dubbo.apache.org/dubbo-go/v3@v3.1.1/protocol/grpc/codec.go (about) 1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package grpc 19 20 import ( 21 "bytes" 22 "encoding/json" 23 ) 24 25 import ( 26 "github.com/golang/protobuf/jsonpb" 27 "github.com/golang/protobuf/proto" 28 29 "google.golang.org/grpc/encoding" 30 ) 31 32 const ( 33 codecJson = "json" 34 codecProto = "proto" 35 ) 36 37 func init() { 38 encoding.RegisterCodec(grpcJson{ 39 Marshaler: jsonpb.Marshaler{ 40 EmitDefaults: true, 41 OrigName: true, 42 }, 43 }) 44 } 45 46 type grpcJson struct { 47 jsonpb.Marshaler 48 jsonpb.Unmarshaler 49 } 50 51 // Name implements grpc encoding package Codec interface method, 52 // returns the name of the Codec implementation. 53 func (_ grpcJson) Name() string { 54 return codecJson 55 } 56 57 // Marshal implements grpc encoding package Codec interface method,returns the wire format of v. 58 func (j grpcJson) Marshal(v interface{}) (out []byte, err error) { 59 if pm, ok := v.(proto.Message); ok { 60 b := new(bytes.Buffer) 61 err := j.Marshaler.Marshal(b, pm) 62 if err != nil { 63 return nil, err 64 } 65 return b.Bytes(), nil 66 } 67 return json.Marshal(v) 68 } 69 70 // Unmarshal implements grpc encoding package Codec interface method,Unmarshal parses the wire format into v. 71 func (j grpcJson) Unmarshal(data []byte, v interface{}) (err error) { 72 if pm, ok := v.(proto.Message); ok { 73 b := bytes.NewBuffer(data) 74 return j.Unmarshaler.Unmarshal(b, pm) 75 } 76 return json.Unmarshal(data, v) 77 }