Files
xk-of-api/internal/response/response.go
2026-07-18 05:58:41 +08:00

39 lines
1.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package response
import (
"context"
"github.com/gogf/gf/v2/frame/g"
)
// Payload 是所有接口统一返回结构。
// HTTP 状态码统一保持 200前端通过 code 判断业务成功或失败。
type Payload struct {
Code int `json:"code"`
Message string `json:"message"`
Result interface{} `json:"result"`
}
// write 写出统一 JSON 并立即结束请求,避免 GF 默认响应中间件二次包装。
func write(ctx context.Context, payload Payload) {
r := g.RequestFromCtx(ctx)
r.Response.Status = 200
r.Response.WriteJsonExit(payload)
}
// Success 返回统一成功响应result 字段承载业务数据。
func Success(ctx context.Context, result interface{}) {
write(ctx, Payload{Code: 0, Message: "ok", Result: result})
}
// Error 返回统一失败响应HTTP 状态仍为 200code 用于表达业务错误。
func Error(ctx context.Context, code int, message string) {
if code == 0 {
code = 500
}
if message == "" {
message = "服务器开小差了,请稍后重试"
}
write(ctx, Payload{Code: code, Message: message, Result: nil})
}