diff --git a/transport/v1/http/codec.go b/transport/v1/http/codec.go index b90c68e..62f01d7 100644 --- a/transport/v1/http/codec.go +++ b/transport/v1/http/codec.go @@ -1,7 +1,7 @@ package http import ( - "encoding/json" + "fmt" "github.com/go-kratos/kratos/v2/errors" "github.com/go-kratos/kratos/v2/transport/http" stdhttp "net/http" @@ -15,42 +15,41 @@ const ( type Response struct { Code int `json:"code" form:"code"` Data interface{} `json:"data" form:"data"` + Reason string `json:"reason" form:"reason"` 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, +func ResponseEncoder(w stdhttp.ResponseWriter, r *stdhttp.Request, v interface{}) error { + if v == nil { + return nil } - codec, _ := http.CodecForRequest(r, "Accept") - var dataInterface interface{} - { - data, _ := codec.Marshal(data) - _ = json.Unmarshal(data, &dataInterface) - rsp.Data = dataInterface + codec, _ := http.CodecForRequest(r, "Accept") + data, err := codec.Marshal(v) + if err != nil { + return err } + application := strings.Join([]string{baseContentType, codec.Name()}, "/") + + w.Header().Set("Content-Type", application) - rspJson, err := codec.Marshal(rsp) + d := fmt.Sprintf(`{"code": 0,"data": %s,"reason": "","message": ""}`, string(data)) + + _, err = w.Write([]byte(d)) 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) + if !errors.Is(err, &errors.Error{}) { + se.Reason = "InternalServerError" + se.Code = stdhttp.StatusInternalServerError + se.Message = "internal server error" } - se := errors.FromError(err) codec, _ := http.CodecForRequest(r, "Accept") body, err := codec.Marshal(se) if err != nil {