初始化
This commit is contained in:
38
internal/response/response.go
Normal file
38
internal/response/response.go
Normal file
@@ -0,0 +1,38 @@
|
||||
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 状态仍为 200,code 用于表达业务错误。
|
||||
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})
|
||||
}
|
||||
Reference in New Issue
Block a user