temp
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package response
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/zeromicro/go-zero/rest/httpx"
|
||||
"net/http"
|
||||
)
|
||||
@@ -11,59 +12,42 @@ type Response struct {
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// 定义分页响应结构
|
||||
type PageResult struct {
|
||||
List interface{} `json:"list"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"pageSize"`
|
||||
type ResponseWithTransactionID struct {
|
||||
Response
|
||||
TransactionID string `json:"transaction_id"`
|
||||
}
|
||||
|
||||
// 响应成功
|
||||
func Success(w http.ResponseWriter, data interface{}) {
|
||||
result := Response{
|
||||
Code: http.StatusOK,
|
||||
Data: data,
|
||||
Message: "操作成功",
|
||||
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 的响应
|
||||
}
|
||||
httpx.OkJson(w, result)
|
||||
}
|
||||
|
||||
// 响应失败
|
||||
func Fail(w http.ResponseWriter, code int, message string) {
|
||||
func Fail(ctx context.Context, w http.ResponseWriter, err error) {
|
||||
result := Response{
|
||||
Code: code,
|
||||
Message: message,
|
||||
Code: -1,
|
||||
Message: err.Error(),
|
||||
}
|
||||
httpx.WriteJson(w, code, result)
|
||||
}
|
||||
|
||||
// 无权限
|
||||
func Unauthorized(w http.ResponseWriter, message string) {
|
||||
result := Response{
|
||||
Code: http.StatusUnauthorized,
|
||||
Message: message,
|
||||
}
|
||||
httpx.WriteJson(w, http.StatusUnauthorized, result)
|
||||
}
|
||||
|
||||
// 响应分页数据
|
||||
func Page(w http.ResponseWriter, list interface{}, total int64, page int, pageSize int) {
|
||||
result := Response{
|
||||
Code: http.StatusOK,
|
||||
Data: PageResult{List: list, Total: total, Page: page, PageSize: pageSize},
|
||||
Message: "查询成功",
|
||||
}
|
||||
httpx.OkJson(w, result)
|
||||
}
|
||||
|
||||
// 自定义错误响应
|
||||
func CustomError(w http.ResponseWriter, code int, message string, data interface{}) {
|
||||
result := Response{
|
||||
Code: code,
|
||||
Data: data,
|
||||
Message: message,
|
||||
}
|
||||
httpx.WriteJson(w, code, result)
|
||||
httpx.OkJsonCtx(ctx, w, result)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user