54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
package response
|
|
|
|
import (
|
|
"context"
|
|
"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"`
|
|
}
|
|
type ResponseWithTransactionID struct {
|
|
Response
|
|
TransactionID string `json:"transaction_id"`
|
|
}
|
|
|
|
// 响应成功
|
|
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 的响应
|
|
}
|
|
}
|
|
|
|
// 响应失败
|
|
func Fail(ctx context.Context, w http.ResponseWriter, err error) {
|
|
result := Response{
|
|
Code: -1,
|
|
Message: err.Error(),
|
|
}
|
|
httpx.OkJsonCtx(ctx, w, result)
|
|
}
|