trpc.group/trpc-go/trpc-go@v1.0.2/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. 33 type JSONPBSerialization struct{} 34 35 // Unmarshal deserialize the in bytes into body. 36 func (s *JSONPBSerialization) Unmarshal(in []byte, body interface{}) error { 37 input, ok := body.(proto.Message) 38 if !ok { 39 return JSONAPI.Unmarshal(in, body) 40 } 41 return Unmarshaler.Unmarshal(in, input) 42 } 43 44 // Marshal returns the serialized bytes in jsonpb protocol. 45 func (s *JSONPBSerialization) Marshal(body interface{}) ([]byte, error) { 46 input, ok := body.(proto.Message) 47 if !ok { 48 return JSONAPI.Marshal(body) 49 } 50 return Marshaler.Marshal(input) 51 }