trpc.group/trpc-go/trpc-go@v1.0.3/codec/serialization_proto.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  	"errors"
    18  
    19  	"google.golang.org/protobuf/proto"
    20  )
    21  
    22  func init() {
    23  	RegisterSerializer(SerializationTypePB, &PBSerialization{})
    24  }
    25  
    26  // PBSerialization provides protobuf serialization mode.
    27  type PBSerialization struct{}
    28  
    29  // Unmarshal deserializes the in bytes into body.
    30  func (s *PBSerialization) Unmarshal(in []byte, body interface{}) error {
    31  	msg, ok := body.(proto.Message)
    32  	if !ok {
    33  		return errors.New("unmarshal fail: body not protobuf message")
    34  	}
    35  	return proto.Unmarshal(in, msg)
    36  }
    37  
    38  // Marshal returns the serialized bytes in protobuf protocol.
    39  func (s *PBSerialization) Marshal(body interface{}) ([]byte, error) {
    40  	msg, ok := body.(proto.Message)
    41  	if !ok {
    42  		return nil, errors.New("marshal fail: body not protobuf message")
    43  	}
    44  	return proto.Marshal(msg)
    45  }