Skip to content

Instantly share code, notes, and snippets.

@zchee
Last active August 29, 2018 08:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zchee/0b3555497d6a729ede5f4e07b8bf3f10 to your computer and use it in GitHub Desktop.
Save zchee/0b3555497d6a729ede5f4e07b8bf3f10 to your computer and use it in GitHub Desktop.
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