mirror of
https://github.com/go-kratos/kratos.git
synced 2026-05-16 09:48:28 +02:00
add protojson (#952)
This commit is contained in:
@@ -5,11 +5,24 @@ import (
|
|||||||
"reflect"
|
"reflect"
|
||||||
|
|
||||||
"github.com/go-kratos/kratos/v2/encoding"
|
"github.com/go-kratos/kratos/v2/encoding"
|
||||||
|
"google.golang.org/protobuf/encoding/protojson"
|
||||||
|
"google.golang.org/protobuf/proto"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Name is the name registered for the json codec.
|
// Name is the name registered for the json codec.
|
||||||
const Name = "json"
|
const Name = "json"
|
||||||
|
|
||||||
|
var (
|
||||||
|
// MarshalOptions is a configurable JSON format marshaler.
|
||||||
|
MarshalOptions = protojson.MarshalOptions{
|
||||||
|
EmitUnpopulated: true,
|
||||||
|
}
|
||||||
|
// UnmarshalOptions is a configurable JSON format parser.
|
||||||
|
UnmarshalOptions = protojson.UnmarshalOptions{
|
||||||
|
DiscardUnknown: true,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
encoding.RegisterCodec(codec{})
|
encoding.RegisterCodec(codec{})
|
||||||
}
|
}
|
||||||
@@ -18,6 +31,9 @@ func init() {
|
|||||||
type codec struct{}
|
type codec struct{}
|
||||||
|
|
||||||
func (codec) Marshal(v interface{}) ([]byte, error) {
|
func (codec) Marshal(v interface{}) ([]byte, error) {
|
||||||
|
if m, ok := v.(proto.Message); ok {
|
||||||
|
return MarshalOptions.Marshal(m)
|
||||||
|
}
|
||||||
return json.Marshal(v)
|
return json.Marshal(v)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -29,6 +45,11 @@ func (codec) Unmarshal(data []byte, v interface{}) error {
|
|||||||
}
|
}
|
||||||
rv = rv.Elem()
|
rv = rv.Elem()
|
||||||
}
|
}
|
||||||
|
if m, ok := v.(proto.Message); ok {
|
||||||
|
return UnmarshalOptions.Unmarshal(data, m)
|
||||||
|
} else if m, ok := reflect.Indirect(reflect.ValueOf(v)).Interface().(proto.Message); ok {
|
||||||
|
return UnmarshalOptions.Unmarshal(data, m)
|
||||||
|
}
|
||||||
return json.Unmarshal(data, v)
|
return json.Unmarshal(data, v)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -134,6 +134,7 @@ func testEchoClient(t *testing.T, addr string) {
|
|||||||
if din.Body.ValueField.GetStringValue() != dout.Body.ValueField.GetStringValue() {
|
if din.Body.ValueField.GetStringValue() != dout.Body.ValueField.GetStringValue() {
|
||||||
t.Fatalf("EchoPatch expected %s got %s", din, dout)
|
t.Fatalf("EchoPatch expected %s got %s", din, dout)
|
||||||
}
|
}
|
||||||
|
fmt.Println("echo test success!")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestJSON(t *testing.T) {
|
func TestJSON(t *testing.T) {
|
||||||
|
|||||||
Reference in New Issue
Block a user