github.com/geniusesgroup/libgo@v0.0.0-20220713101832-828057a9d3d4/json/codec-runtime.go (about) 1 /* For license and copyright information please see LEGAL file in repository */ 2 3 package json 4 5 import ( 6 "encoding/json" 7 8 "../protocol" 9 ) 10 11 /* 12 ********************PAY ATTENTION:******************* 13 We don't suggest use these codec instead use Codec and autogenerate needed code before compile time 14 and reduce runtime proccess to improve performance of the app and gain better performance from this protocol! 15 */ 16 17 /* 18 Field int `json:"{Name},{Option}"` 19 Options: 20 - Name Other name than field name. Must be first option. 21 - dash(-) Don't encode||decode field! 22 - omitempty Encode||Decode only field not nil! 23 - string base64 string! Use when array||slice numbers is not represent meaningful data. Also encode|decode numbers as string with "". 24 - tuple must assign to all fields to encode|decode as tuple array instead key-value object! 25 26 Examples of struct field tags and their meanings: 27 Field int `json:"myName"` // Field appears in JSON as key "myName". 28 Field int `json:"myName,omitempty"` // Field appears in JSON as key "myName" and the field is omitted from the object if its value is empty. 29 Field int `json:",omitempty"` // Field appears in JSON as key "Field" (the default), but the field is skipped if empty. 30 Field int `json:"-"` // Field is ignored by this package. 31 Field int `json:"-,"` // Field appears in JSON as key "-". 32 */ 33 34 // Marshal encodes the value of s to the payload buffer in runtime. 35 func Marshal(s interface{}) (p []byte, err protocol.Error) { 36 // TODO::: make better algorithm instead of below 37 var goErr error 38 p, goErr = json.Marshal(s) 39 if goErr != nil { 40 return nil, ErrEncodedCorrupted 41 } 42 return 43 } 44 45 // Unmarshal decode payload and stores the result in the value pointed to by s in runtime. 46 func Unmarshal(p []byte, s interface{}) (err protocol.Error) { 47 // TODO::: make better algorithm instead of below 48 var goErr error = json.Unmarshal(p, s) 49 if goErr != nil { 50 return ErrEncodedCorrupted 51 } 52 return 53 } 54 55 // RunTimeCodec is a wrapper to use anywhere need protocol.Codec interface instead of protocol.JSON interface 56 type RunTimeCodec struct { 57 t interface{} 58 decoder interface{} 59 encoder interface{} 60 len int 61 } 62 63 func NewRunTimeCodec(t interface{}) (codec *RunTimeCodec) { 64 codec = &RunTimeCodec{ 65 t: t, 66 // len: json.LenAsJSON(), 67 } 68 // codec.encoder.buf = make([]byte, 0, codec.len) 69 return 70 }