github.com/geniusesgroup/libgo@v0.0.0-20220713101832-828057a9d3d4/json/codec.go (about)

     1  /* For license and copyright information please see LEGAL file in repository */
     2  
     3  package json
     4  
     5  import (
     6  	"bytes"
     7  	"io"
     8  
     9  	"../mediatype"
    10  	"../protocol"
    11  )
    12  
    13  // Codec is a wrapper to use anywhere need protocol.Codec interface instead of protocol.JSON interface
    14  type Codec struct {
    15  	json    protocol.JSON
    16  	payload []byte
    17  	len     int
    18  }
    19  
    20  func NewCodec(json protocol.JSON) (codec Codec) {
    21  	codec = Codec{
    22  		json: json,
    23  		len:  json.LenAsJSON(),
    24  	}
    25  	return
    26  }
    27  
    28  /*
    29  ********** protocol.Codec interface **********
    30   */
    31  
    32  // https://www.iana.org/assignments/media-types/application/json
    33  func (c *Codec) MediaType() protocol.MediaType       { return mediatype.JSON }
    34  func (c *Codec) CompressType() protocol.CompressType { return nil }
    35  
    36  func (c *Codec) Decode(reader protocol.Reader) (err protocol.Error) {
    37  	var buf bytes.Buffer
    38  	var _, goErr = buf.ReadFrom(reader)
    39  	if goErr != nil {
    40  		// err =
    41  		return
    42  	}
    43  	c.payload = buf.Bytes()
    44  	err = c.json.FromJSON(c.payload)
    45  	return
    46  }
    47  func (c *Codec) Encode(writer protocol.Writer) (err protocol.Error) {
    48  	var _, goErr = c.WriteTo(writer)
    49  	if goErr != nil {
    50  		// err =
    51  	}
    52  	return
    53  }
    54  func (c *Codec) Len() int { return c.len }
    55  
    56  func (c *Codec) Unmarshal(data []byte) (err protocol.Error) {
    57  	err = c.json.FromJSON(data)
    58  	c.payload = data
    59  	return
    60  }
    61  
    62  func (c *Codec) Marshal() (data []byte) {
    63  	if c.payload == nil {
    64  		c.payload = make([]byte, 0, c.len)
    65  		c.payload = c.json.ToJSON(c.payload)
    66  	}
    67  	return c.payload
    68  }
    69  
    70  func (c *Codec) MarshalTo(data []byte) []byte {
    71  	return c.json.ToJSON(data)
    72  }
    73  
    74  /*
    75  ********** io package interfaces **********
    76   */
    77  
    78  func (c *Codec) ReadFrom(reader io.Reader) (n int64, err error) {
    79  	var buf bytes.Buffer
    80  	n, err = buf.ReadFrom(reader)
    81  	if err != nil {
    82  		return
    83  	}
    84  	c.payload = buf.Bytes()
    85  	err = c.json.FromJSON(c.payload)
    86  	return
    87  }
    88  
    89  func (c *Codec) WriteTo(writer io.Writer) (n int64, err error) {
    90  	if c.payload == nil {
    91  		c.Marshal()
    92  	}
    93  	var writeLength int
    94  	writeLength, err = writer.Write(c.payload)
    95  	n = int64(writeLength)
    96  	return
    97  }