解决kratos and proto3 返回字段为空不显示问题
处理返回信息
func ResponseEncoder() http.ServerOption {
return http.ResponseEncoder(func(
w httpNet.ResponseWriter,
r *httpNet.Request,
i interface{},
) error {
json.MarshalOptions.EmitUnpopulated = true
json.MarshalOptions.UseProtoNames = true
json.MarshalOptions.UseEnumNumbers = true
json.MarshalOptions.AllowPartial = true
b,_:=json.MarshalOptions.Marshal(i.(proto.Message))
m := make(map[string]interface{})
err := json2.Unmarshal(b, &m)
if err != nil {
return err
}
type response struct {
Code int `json:"code"`
Data interface{}`json:"data"`
Message string `json:"message"`
Ts string `json:"ts"`
}
reply := &response{
Code: 1,
Data: m,
Message:"成功",
Ts: helpers.TimeNow(),
}
b1, err := json2.Marshal(reply)
if err != nil {
return err
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Write(b1)
return nil
})
}
修改 http.go 添加
opts = append(opts, ResponseEncoder())
完事儿