package response import ( "encoding/json" "net/http" "github.com/go-kratos/kratos/v2/errors" ) // Response 统一响应格式 type Response struct { Code int `json:"code"` Msg string `json:"msg"` Data interface{} `json:"data,omitempty"` } // Encoder 响应编码器,包装响应为 {code, msg, data} 格式 func Encoder(w http.ResponseWriter, r *http.Request, v interface{}) error { if v == nil { v = struct{}{} } reply := Response{ Code: 0, Msg: "success", Data: v, } w.Header().Set("Content-Type", "application/json") return json.NewEncoder(w).Encode(reply) } // ErrorEncoder 错误编码器,统一错误响应格式 func ErrorEncoder(w http.ResponseWriter, r *http.Request, err error) { se := errors.FromError(err) code := int(se.Code) if code >= 400 && code < 500 { code = 7 } else if code >= 500 { code = 7 } reply := Response{ Code: code, Msg: se.Message, } w.Header().Set("Content-Type", "application/json") w.WriteHeader(int(se.Code)) json.NewEncoder(w).Encode(reply) }