...

Source file src/google.golang.org/grpc/encoding/proto/proto.go

Documentation: google.golang.org/grpc/encoding/proto

     1  /*
     2   *
     3   * Copyright 2018 gRPC authors.
     4   *
     5   * Licensed under the Apache License, Version 2.0 (the "License");
     6   * you may not use this file except in compliance with the License.
     7   * You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   *
    17   */
    18  
    19  // Package proto defines the protobuf codec. Importing this package will
    20  // register the codec.
    21  package proto
    22  
    23  import (
    24  	"fmt"
    25  
    26  	"google.golang.org/grpc/encoding"
    27  	"google.golang.org/protobuf/proto"
    28  	"google.golang.org/protobuf/protoadapt"
    29  )
    30  
    31  // Name is the name registered for the proto compressor.
    32  const Name = "proto"
    33  
    34  func init() {
    35  	encoding.RegisterCodec(codec{})
    36  }
    37  
    38  // codec is a Codec implementation with protobuf. It is the default codec for gRPC.
    39  type codec struct{}
    40  
    41  func (codec) Marshal(v any) ([]byte, error) {
    42  	vv := messageV2Of(v)
    43  	if vv == nil {
    44  		return nil, fmt.Errorf("failed to marshal, message is %T, want proto.Message", v)
    45  	}
    46  
    47  	return proto.Marshal(vv)
    48  }
    49  
    50  func (codec) Unmarshal(data []byte, v any) error {
    51  	vv := messageV2Of(v)
    52  	if vv == nil {
    53  		return fmt.Errorf("failed to unmarshal, message is %T, want proto.Message", v)
    54  	}
    55  
    56  	return proto.Unmarshal(data, vv)
    57  }
    58  
    59  func messageV2Of(v any) proto.Message {
    60  	switch v := v.(type) {
    61  	case protoadapt.MessageV1:
    62  		return protoadapt.MessageV2Of(v)
    63  	case protoadapt.MessageV2:
    64  		return v
    65  	}
    66  
    67  	return nil
    68  }
    69  
    70  func (codec) Name() string {
    71  	return Name
    72  }
    73  

View as plain text