package jsonpb import ( "bytes" "encoding/json" "reflect" "github.com/gogo/protobuf/proto" "github.com/golang/protobuf/jsonpb" "github.com/go-kratos/kratos/v2/encoding" ) // Name is the name registered for the json codec. const Name = "jsonpb" var jsonpbMarshaler *jsonpb.Marshaler func init() { jsonpbMarshaler = &jsonpb.Marshaler{ EnumsAsInts: true, EmitDefaults: true, OrigName: true, } encoding.RegisterCodec(codec{}) } // codec is a Codec implementation with json. type codec struct{} func (codec) Marshal(v interface{}) ([]byte, error) { if _, ok := v.(proto.Message); ok { var buf bytes.Buffer err := jsonpbMarshaler.Marshal(&buf, v.(proto.Message)) if err != nil { return nil, err } return buf.Bytes(), nil } return json.Marshal(v) } func (codec) Unmarshal(data []byte, v interface{}) error { rv := reflect.ValueOf(v) for rv.Kind() == reflect.Ptr { if rv.IsNil() && rv.CanInterface() { rv.Set(reflect.New(rv.Type().Elem())) v = rv.Interface() } rv = rv.Elem() } return json.Unmarshal(data, v) } func (codec) Name() string { return Name }