master
nikkiing 2 years ago
parent 1b58396db5
commit 21eab29b83
  1. 41
      transport/v1/http/codec.go

@ -1,7 +1,7 @@
package http package http
import ( import (
"encoding/json" "fmt"
"github.com/go-kratos/kratos/v2/errors" "github.com/go-kratos/kratos/v2/errors"
"github.com/go-kratos/kratos/v2/transport/http" "github.com/go-kratos/kratos/v2/transport/http"
stdhttp "net/http" stdhttp "net/http"
@ -15,42 +15,41 @@ const (
type Response struct { type Response struct {
Code int `json:"code" form:"code"` Code int `json:"code" form:"code"`
Data interface{} `json:"data" form:"data"` Data interface{} `json:"data" form:"data"`
Reason string `json:"reason" form:"reason"`
Message string `json:"message" form:"message"` Message string `json:"message" form:"message"`
} }
func ResponseEncoder(w stdhttp.ResponseWriter, r *stdhttp.Request, data interface{}) error { func ResponseEncoder(w stdhttp.ResponseWriter, r *stdhttp.Request, v interface{}) error {
rsp := &Response{ if v == nil {
Code: 200, return nil
Message: "success",
Data: data,
} }
codec, _ := http.CodecForRequest(r, "Accept")
var dataInterface interface{} codec, _ := http.CodecForRequest(r, "Accept")
{ data, err := codec.Marshal(v)
data, _ := codec.Marshal(data) if err != nil {
_ = json.Unmarshal(data, &dataInterface) return err
rsp.Data = dataInterface
} }
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 { if err != nil {
return err return err
} }
w.Header().Set("Content-Type", ContentType(codec.Name()))
w.WriteHeader(stdhttp.StatusOK)
w.Write(rspJson)
return nil return nil
} }
func ErrorEncoderPro(w stdhttp.ResponseWriter, r *stdhttp.Request, err error) { func ErrorEncoderPro(w stdhttp.ResponseWriter, r *stdhttp.Request, err error) {
// 如果是正式服,则统一抛出服务器错误 se := errors.FromError(err)
if errors.IsInternalServer(err) { if !errors.Is(err, &errors.Error{}) {
err = errors.InternalServer("internal err", "服务出错") se.Reason = "InternalServerError"
se.Code = stdhttp.StatusInternalServerError
se.Message = "internal server error"
} }
se := errors.FromError(err)
codec, _ := http.CodecForRequest(r, "Accept") codec, _ := http.CodecForRequest(r, "Accept")
body, err := codec.Marshal(se) body, err := codec.Marshal(se)
if err != nil { if err != nil {

Loading…
Cancel
Save