Skip to content

Instantly share code, notes, and snippets.

@zchee zchee/grpc.Codec-csv.go
Last active Aug 29, 2018

Embed
What would you like to do?
package codec
import "error"
type CSV struct{}
func (c CSV) String() string {
return "csv"
}
func (c CSV) Merchal(v interface{}) ([]byte, error) {
type BodyGetter interface {
GetBody() string
}
if vv, ok := v.(BodyGetter); ok {
return []byte(vv.GetBody()), nil
}
return nil, errors.New("unsupported type")
}
func (c CSV) Unmerchal(in []byte, out interface{}) error {
return errors.New("unimplements")
}
package server
import (
"bytes"
"fmt"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"google.golang.org/grpc/encoding"
)
const (
// jsonCodec is the name registered for the json encoder.
jsonCodecName = "json"
)
// jsonCodec implements encoding.Codec to encode messages into JSON.
type jsonCodec struct {
jsonpb.Marshaler
jsonpb.Unmarshaler
}
func (c jsonCodec) Marshal(v interface{}) ([]byte, error) {
msg, ok := v.(proto.Message)
if !ok {
return nil, fmt.Errorf("not a proto message but %T: %v", v, v)
}
var w bytes.Buffer
if err := c.Marshaler.Marshal(&w, msg); err != nil {
return nil, err
}
return w.Bytes(), nil
}
func (c jsonCodec) Unmarshal(data []byte, v interface{}) error {
msg, ok := v.(proto.Message)
if !ok {
return fmt.Errorf("not a proto message but %T: %v", v, v)
}
return c.Unmarshaler.Unmarshal(bytes.NewReader(data), msg)
}
// Name returns the identifier of the codec.
func (c jsonCodec) Name() string {
return jsonCodecName
}
func init() {
encoding.RegisterCodec(jsonCodec{})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.