| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- package common
- import (
- "bytes"
- "encoding/json"
- "github.com/golang/protobuf/jsonpb"
- "google.golang.org/protobuf/types/known/structpb"
- "github.com/gogo/protobuf/proto"
- )
- var jsonpbMarshaler *jsonpb.Marshaler
- func init() {
- jsonpbMarshaler = &jsonpb.Marshaler{
- EnumsAsInts: true,
- EmitDefaults: true,
- OrigName: true,
- }
- }
- func MarshalJSON(v interface{}) []byte {
- if _, ok := v.(proto.Message); ok {
- var buf bytes.Buffer
- err := jsonpbMarshaler.Marshal(&buf, v.(proto.Message))
- if err != nil {
- return nil
- }
- return buf.Bytes()
- }
- j, _ := json.Marshal(v)
- return j
- }
- func NewStructValuePB(v interface{}) *structpb.Value {
- s := new(structpb.Value)
- s.UnmarshalJSON(MarshalJSON(v))
- return s
- }
- func NewStructValuePBByBytes(v []byte) *structpb.Value {
- s := new(structpb.Value)
- s.UnmarshalJSON(v)
- return s
- }
|