response_encoder.go 1.32 KB
Newer Older
kzkzzzz's avatar
kzkzzzz committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
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)
}