github.com/emcfarlane/larking@v0.0.0-20220605172417-1704b45ee6c3/codec.go (about)

     1  // Copyright 2021 Edward McFarlane. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package larking
     6  
     7  import (
     8  	"fmt"
     9  
    10  	"google.golang.org/grpc/encoding"
    11  	"google.golang.org/protobuf/encoding/protojson"
    12  	"google.golang.org/protobuf/proto"
    13  )
    14  
    15  func init() {
    16  	encoding.RegisterCodec(protoCodec{})
    17  	encoding.RegisterCodec(jsonCodec{})
    18  }
    19  
    20  func errInvalidType(v any) error {
    21  	return fmt.Errorf("marshal invalid type %T", v)
    22  }
    23  
    24  type protoCodec struct{}
    25  
    26  func (protoCodec) Marshal(v interface{}) ([]byte, error) {
    27  	m, ok := v.(proto.Message)
    28  	if !ok {
    29  		return nil, errInvalidType(v)
    30  	}
    31  	return proto.Marshal(m)
    32  }
    33  
    34  func (protoCodec) Unmarshal(data []byte, v interface{}) error {
    35  	m, ok := v.(proto.Message)
    36  	if !ok {
    37  		return errInvalidType(v)
    38  	}
    39  	return proto.Unmarshal(data, m)
    40  }
    41  
    42  // Name == "proto" overwritting internal proto codec
    43  func (protoCodec) Name() string { return "proto" }
    44  
    45  type jsonCodec struct{}
    46  
    47  func (jsonCodec) Marshal(v interface{}) ([]byte, error) {
    48  	m, ok := v.(proto.Message)
    49  	if !ok {
    50  		return nil, errInvalidType(v)
    51  	}
    52  	return protojson.Marshal(m)
    53  }
    54  
    55  func (jsonCodec) Unmarshal(data []byte, v interface{}) error {
    56  	m, ok := v.(proto.Message)
    57  	if !ok {
    58  		return errInvalidType(v)
    59  	}
    60  	return protojson.Unmarshal(data, m)
    61  }
    62  
    63  func (jsonCodec) Name() string { return "json" }