kratos的http.Context中内置了JSON的方法具体如下:
func (c *wrapper) JSON(code int, v interface{}) error {
c.res.Header().Set("Content-Type", "application/json")
c.res.WriteHeader(code)
return json.NewEncoder(c.res).Encode(v)
}
可以看到第一个参数是http状态码,通常是200,第二个参数是interface,会将其json编码后写入响应中。
在前后端分离的业务中,通常是使用自定义的业务状态码来判断业务状态,不使用http状态码,例如:
{"code":500,"message":"服务器错误"}
这里直接使用JSON方法需要写大量重复的定义代码,可以优化提取代码编写一个公共方法:
先重新实现一个自定义的error对象
package ecode
const (
StatusCode200 = 200
StatusCode400 = 400
StatusCode404 = 404
Code500 = 500
Code0 = 0
)
type ECode struct {
StatusCode int
Code int
Message string
}
func (e *ECode) Error() string {
return e.Message
}
func New(Code int, M