package http import ( "encoding/json" "github.com/go-kratos/kratos/v2/errors" "github.com/go-kratos/kratos/v2/transport/http" stdhttp "net/http" "strings" ) const ( baseContentType = "application" ) type Response struct { Code int `json:"code" form:"code"` Data interface{} `json:"data" form:"data"` Message string `json:"message" form:"message"` } func ResponseEncoder(w stdhttp.ResponseWriter, r *stdhttp.Request, data interface{}) error { rsp := &Response{ Code: 200, Message: "success", Data: data, } codec, _ := http.CodecForRequest(r, "Accept") var dataInterface interface{} { data, _ := codec.Marshal(data) _ = json.Unmarshal(data, &dataInterface) rsp.Data = dataInterface } rspJson, err := codec.Marshal(rsp) if err != nil { return err } w.Header().Set("Content-Type", ContentType(codec.Name())) w.WriteHeader(stdhttp.StatusOK) w.Write(rspJson) return nil } func ErrorEncoderPro(w stdhttp.ResponseWriter, r *stdhttp.Request, err error) { // 如果是正式服,则统一抛出服务器错误 if errors.IsInternalServer(err) { err = errors.InternalServer("internal err", "服务出错") } se := errors.FromError(err) codec, _ := http.CodecForRequest(r, "Accept") body, err := codec.Marshal(se) if err != nil { w.WriteHeader(stdhttp.StatusInternalServerError) return } w.Header().Set("Content-Type", ContentType(codec.Name())) w.WriteHeader(int(se.Code)) _, _ = w.Write(body) } // ContentType returns the content-type with base prefix. func ContentType(subtype string) string { return strings.Join([]string{baseContentType, subtype}, "/") }