Create & Init Project...
This commit is contained in:
33
library/net/rpc/warden/encoding/json/BUILD
Normal file
33
library/net/rpc/warden/encoding/json/BUILD
Normal file
@ -0,0 +1,33 @@
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
load(
|
||||
"@io_bazel_rules_go//go:def.bzl",
|
||||
"go_library",
|
||||
)
|
||||
|
||||
go_library(
|
||||
name = "go_default_library",
|
||||
srcs = ["json.go"],
|
||||
importpath = "go-common/library/net/rpc/warden/encoding/json",
|
||||
tags = ["automanaged"],
|
||||
visibility = ["//visibility:public"],
|
||||
deps = [
|
||||
"@com_github_gogo_protobuf//jsonpb:go_default_library",
|
||||
"@com_github_gogo_protobuf//proto:go_default_library",
|
||||
"@org_golang_google_grpc//encoding:go_default_library",
|
||||
],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "package-srcs",
|
||||
srcs = glob(["**"]),
|
||||
tags = ["automanaged"],
|
||||
visibility = ["//visibility:private"],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "all-srcs",
|
||||
srcs = [":package-srcs"],
|
||||
tags = ["automanaged"],
|
||||
visibility = ["//visibility:public"],
|
||||
)
|
53
library/net/rpc/warden/encoding/json/json.go
Normal file
53
library/net/rpc/warden/encoding/json/json.go
Normal file
@ -0,0 +1,53 @@
|
||||
package codec
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/gogo/protobuf/jsonpb"
|
||||
"github.com/gogo/protobuf/proto"
|
||||
"google.golang.org/grpc/encoding"
|
||||
)
|
||||
|
||||
//Reference https://jbrandhorst.com/post/grpc-json/
|
||||
func init() {
|
||||
encoding.RegisterCodec(JSON{
|
||||
Marshaler: jsonpb.Marshaler{
|
||||
EmitDefaults: true,
|
||||
OrigName: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// JSON is impl of encoding.Codec
|
||||
type JSON struct {
|
||||
jsonpb.Marshaler
|
||||
jsonpb.Unmarshaler
|
||||
}
|
||||
|
||||
// Name is name of JSON
|
||||
func (j JSON) Name() string {
|
||||
return "json"
|
||||
}
|
||||
|
||||
// Marshal is json marshal
|
||||
func (j JSON) Marshal(v interface{}) (out []byte, err error) {
|
||||
if pm, ok := v.(proto.Message); ok {
|
||||
b := new(bytes.Buffer)
|
||||
err := j.Marshaler.Marshal(b, pm)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
return json.Marshal(v)
|
||||
}
|
||||
|
||||
// Unmarshal is json unmarshal
|
||||
func (j JSON) Unmarshal(data []byte, v interface{}) (err error) {
|
||||
if pm, ok := v.(proto.Message); ok {
|
||||
b := bytes.NewBuffer(data)
|
||||
return j.Unmarshaler.Unmarshal(b, pm)
|
||||
}
|
||||
return json.Unmarshal(data, v)
|
||||
}
|
Reference in New Issue
Block a user