trpc.group/trpc-go/trpc-go@v1.0.3/codec/serialization_jsonpb.go (about) 1 // 2 // 3 // Tencent is pleased to support the open source community by making tRPC available. 4 // 5 // Copyright (C) 2023 THL A29 Limited, a Tencent company. 6 // All rights reserved. 7 // 8 // If you have downloaded a copy of the tRPC source code from Tencent, 9 // please note that tRPC source code is licensed under the Apache 2.0 License, 10 // A copy of the Apache 2.0 License is included in this file. 11 // 12 // 13 14 package codec 15 16 import ( 17 "google.golang.org/protobuf/encoding/protojson" 18 "google.golang.org/protobuf/proto" 19 ) 20 21 func init() { 22 RegisterSerializer(SerializationTypeJSON, &JSONPBSerialization{}) 23 } 24 25 // Marshaler is jsonpb marshal object, users can change its params. 26 var Marshaler = protojson.MarshalOptions{EmitUnpopulated: true, UseProtoNames: true, UseEnumNumbers: true} 27 28 // Unmarshaler is jsonpb unmarshal object, users can chang its params. 29 var Unmarshaler = protojson.UnmarshalOptions{DiscardUnknown: false} 30 31 // JSONPBSerialization provides jsonpb serialization mode. It is based on 32 // protobuf/jsonpb. This serializer will firstly try jsonpb's serialization. If 33 // object does not conform to protobuf proto.Message interface, json-iterator 34 // will be used. 35 type JSONPBSerialization struct{} 36 37 // Unmarshal deserialize the in bytes into body. 38 func (s *JSONPBSerialization) Unmarshal(in []byte, body interface{}) error { 39 input, ok := body.(proto.Message) 40 if !ok { 41 return JSONAPI.Unmarshal(in, body) 42 } 43 return Unmarshaler.Unmarshal(in, input) 44 } 45 46 // Marshal returns the serialized bytes in jsonpb protocol. 47 func (s *JSONPBSerialization) Marshal(body interface{}) ([]byte, error) { 48 input, ok := body.(proto.Message) 49 if !ok { 50 return JSONAPI.Marshal(body) 51 } 52 return Marshaler.Marshal(input) 53 }