temp
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"github.com/zeromicro/go-zero/rest/httpx"
|
||||
"net/http"
|
||||
"tianyuan-api/pkg/errs"
|
||||
)
|
||||
|
||||
// 定义通用的响应结构
|
||||
@@ -13,41 +14,43 @@ type Response struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
type ResponseWithTransactionID struct {
|
||||
Response
|
||||
TransactionID string `json:"transaction_id"`
|
||||
Code int `json:"code"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
Message string `json:"message"`
|
||||
TransactionID string `json:"transaction_id"`
|
||||
}
|
||||
|
||||
// 发送响应(公用函数)
|
||||
func sendResponse(ctx context.Context, w http.ResponseWriter, code int, message string, data interface{}) {
|
||||
// 从上下文中获取 TransactionID
|
||||
transactionID, _ := ctx.Value("transactionID").(string)
|
||||
if transactionID != "" {
|
||||
result := ResponseWithTransactionID{
|
||||
Code: code,
|
||||
Data: data,
|
||||
Message: message,
|
||||
TransactionID: transactionID,
|
||||
}
|
||||
httpx.OkJsonCtx(ctx, w, result)
|
||||
} else {
|
||||
result := Response{
|
||||
Code: code,
|
||||
Data: data,
|
||||
Message: message,
|
||||
}
|
||||
httpx.OkJsonCtx(ctx, w, result)
|
||||
}
|
||||
}
|
||||
|
||||
// 响应成功
|
||||
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 的响应
|
||||
}
|
||||
ctx = context.WithValue(ctx, "status", "success")
|
||||
sendResponse(ctx, w, 0, "success", data)
|
||||
}
|
||||
|
||||
// 响应失败
|
||||
func Fail(ctx context.Context, w http.ResponseWriter, err error) {
|
||||
result := Response{
|
||||
Code: -1,
|
||||
Message: err.Error(),
|
||||
}
|
||||
httpx.OkJsonCtx(ctx, w, result)
|
||||
func Fail(ctx context.Context, w http.ResponseWriter, err *errs.AppError) {
|
||||
ctx = context.WithValue(ctx, "status", "failed")
|
||||
ctx = context.WithValue(ctx, "remark", err.Message)
|
||||
sendResponse(ctx, w, err.Code, err.Message, nil)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user