github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/util/codec/json/json.go (about) 1 // Licensed under the Apache License, Version 2.0 (the "License"); 2 // you may not use this file except in compliance with the License. 3 // You may obtain a copy of the License at 4 // 5 // https://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, 9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 // See the License for the specific language governing permissions and 11 // limitations under the License. 12 // 13 // Original source: github.com/micro/go-micro/v3/codec/json/json.go 14 15 // Package json provides a json codec 16 package json 17 18 import ( 19 "encoding/json" 20 "io" 21 22 "github.com/golang/protobuf/jsonpb" 23 "github.com/golang/protobuf/proto" 24 "github.com/tickoalcantara12/micro/v3/util/codec" 25 ) 26 27 type Codec struct { 28 Conn io.ReadWriteCloser 29 Encoder *json.Encoder 30 Decoder *json.Decoder 31 } 32 33 func (c *Codec) ReadHeader(m *codec.Message, t codec.MessageType) error { 34 return nil 35 } 36 37 func (c *Codec) ReadBody(b interface{}) error { 38 if b == nil { 39 return nil 40 } 41 if pb, ok := b.(proto.Message); ok { 42 return jsonpb.UnmarshalNext(c.Decoder, pb) 43 } 44 return c.Decoder.Decode(b) 45 } 46 47 func (c *Codec) Write(m *codec.Message, b interface{}) error { 48 if b == nil { 49 return nil 50 } 51 return c.Encoder.Encode(b) 52 } 53 54 func (c *Codec) Close() error { 55 return c.Conn.Close() 56 } 57 58 func (c *Codec) String() string { 59 return "json" 60 } 61 62 func NewCodec(c io.ReadWriteCloser) codec.Codec { 63 return &Codec{ 64 Conn: c, 65 Decoder: json.NewDecoder(c), 66 Encoder: json.NewEncoder(c), 67 } 68 }