package httpext import ( "encoding/json" "github.com/go-kratos/kratos/v2/errors" "github.com/go-kratos/kratos/v2/transport/http" "github.com/spf13/cast" netHttp "net/http" ) type HttpResponseBody struct { Code int `json:"code"` Message string `json:"message"` Data interface{} `json:"data"` } func Encoder(w http.ResponseWriter, r *http.Request, v interface{}) error { // 重定向处理 //if rd, ok := v.(http.Redirector); ok { // url, code := rd.Redirect() // netHttp.Redirect(w, r, url, code) // return nil //} success := &HttpResponseBody{ Code: 0, Message: "success", Data: v, } data, err := json.Marshal(success) if err != nil { return err } w.Header().Set("Content-Type", "application/json; charset=utf-8") _, err = w.Write(data) if err != nil { return err } return nil } func ErrorEncoder(w http.ResponseWriter, r *http.Request, err error) { // 拿到error并转换成kratos Error实体 se := errors.FromError(err) body, err := json.Marshal(se) if err != nil { w.WriteHeader(netHttp.StatusInternalServerError) w.Write([]byte(cast.ToString(err.Error()))) return } w.Header().Set("Content-Type", "application/json; charset=utf-8") // 设置HTTP Status Code //w.WriteHeader(int(se.Code)) w.WriteHeader(netHttp.StatusOK) // http 统一200状态码 w.Write(body) }