mirror of https://github.com/zhufuyi/sponge
40 lines
820 B
Go
40 lines
820 B
Go
package proto
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/zhufuyi/sponge/pkg/encoding"
|
|
|
|
"google.golang.org/protobuf/proto"
|
|
)
|
|
|
|
// Name is the name registered for the proto compressor.
|
|
const Name = "proto"
|
|
|
|
func init() {
|
|
encoding.RegisterCodec(codec{})
|
|
}
|
|
|
|
// codec is a Codec implementation with protobuf. It is the default codec for gRPC.
|
|
type codec struct{}
|
|
|
|
func (codec) Marshal(v interface{}) ([]byte, error) {
|
|
vv, ok := v.(proto.Message)
|
|
if !ok {
|
|
return nil, fmt.Errorf("failed to marshal, message is %T, want proto.Message", v)
|
|
}
|
|
return proto.Marshal(vv)
|
|
}
|
|
|
|
func (codec) Unmarshal(data []byte, v interface{}) error {
|
|
vv, ok := v.(proto.Message)
|
|
if !ok {
|
|
return fmt.Errorf("failed to unmarshal, message is %T, want proto.Message", v)
|
|
}
|
|
return proto.Unmarshal(data, vv)
|
|
}
|
|
|
|
func (codec) Name() string {
|
|
return Name
|
|
}
|