Skip to content

Commit

Permalink
provide access to underlying *json.Decoder from JSONPb.NewDecoder
Browse files Browse the repository at this point in the history
  • Loading branch information
jhump committed May 1, 2018
1 parent c2b051d commit 25508bd
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
3 changes: 3 additions & 0 deletions runtime/marshal_json.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ import (
// with the standard "encoding/json" package of Golang.
// Although it is generally faster for simple proto messages than JSONPb,
// it does not support advanced features of protobuf, e.g. map, oneof, ....
//
// The NewEncoder and NewDecoder types return *json.Encoder and
// *json.Decoder respectively.
type JSONBuiltin struct{}

// ContentType always Returns "application/json".
Expand Down
17 changes: 14 additions & 3 deletions runtime/marshal_jsonpb.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ import (
// JSONPb is a Marshaler which marshals/unmarshals into/from JSON
// with the "github.com/golang/protobuf/jsonpb".
// It supports fully functionality of protobuf unlike JSONBuiltin.
//
// The NewDecoder method returns a DecoderWrapper, so the underlying
// *json.Decoder methods can be used.
type JSONPb jsonpb.Marshaler

// ContentType always returns "application/json".
Expand Down Expand Up @@ -84,16 +87,24 @@ func (j *JSONPb) marshalNonProtoField(v interface{}) ([]byte, error) {
}

// Unmarshal unmarshals JSON "data" into "v"
// Currently it can marshal only proto.Message.
// TODO(yugui) Support fields of primitive types in a message.
func (j *JSONPb) Unmarshal(data []byte, v interface{}) error {
return unmarshalJSONPb(data, v)
}

// NewDecoder returns a Decoder which reads JSON stream from "r".
func (j *JSONPb) NewDecoder(r io.Reader) Decoder {
d := json.NewDecoder(r)
return DecoderFunc(func(v interface{}) error { return decodeJSONPb(d, v) })
return DecoderWrapper{Decoder: d}
}

// DecoderWrapper is a wrapper around a *json.Decoder that adds
// support for protos to the Decode method.
type DecoderWrapper struct {
*json.Decoder
}

func (d DecoderWrapper) Decode(v interface{}) error {
return decodeJSONPb(d.Decoder, v)
}

// NewEncoder returns an Encoder which writes JSON stream into "w".
Expand Down

0 comments on commit 25508bd

Please # to comment.