tianyuan-api-server/pkg/response/response.go

54 lines
1.2 KiB
Go
Raw Normal View History

2024-10-02 00:57:17 +08:00
package response
import (
2024-10-04 23:07:49 +08:00
"context"
2024-10-02 00:57:17 +08:00
"github.com/zeromicro/go-zero/rest/httpx"
"net/http"
)
// 定义通用的响应结构
type Response struct {
Code int `json:"code"`
Data interface{} `json:"data,omitempty"`
Message string `json:"message"`
}
2024-10-04 23:07:49 +08:00
type ResponseWithTransactionID struct {
Response
TransactionID string `json:"transaction_id"`
2024-10-02 00:57:17 +08:00
}
// 响应成功
2024-10-04 23:07:49 +08:00
func Success(ctx context.Context, w http.ResponseWriter, data interface{}) {
// 从上下文中获取 TransactionID
transactionID := ctx.Value("TransactionID")
// 判断是否存在 TransactionID
if transactionID != nil {
result := ResponseWithTransactionID{
Response: Response{
Code: http.StatusOK,
Data: data,
Message: "success",
},
TransactionID: transactionID.(string), // 将 TransactionID 添加到响应
}
httpx.OkJsonCtx(ctx, w, result) // 返回带有 TransactionID 的响应
} else {
result := Response{
Code: http.StatusOK,
Data: data,
Message: "success",
}
httpx.OkJsonCtx(ctx, w, result) // 返回没有 TransactionID 的响应
2024-10-02 00:57:17 +08:00
}
}
// 响应失败
2024-10-04 23:07:49 +08:00
func Fail(ctx context.Context, w http.ResponseWriter, err error) {
2024-10-02 00:57:17 +08:00
result := Response{
2024-10-04 23:07:49 +08:00
Code: -1,
Message: err.Error(),
2024-10-02 00:57:17 +08:00
}
2024-10-04 23:07:49 +08:00
httpx.OkJsonCtx(ctx, w, result)
2024-10-02 00:57:17 +08:00
}