github.com/binbinly/pkg@v0.0.11-0.20240321014439-f4fbf666eb0f/codec/json_codec.go (about) 1 package codec 2 3 import ( 4 "bytes" 5 "compress/gzip" 6 "encoding/json" 7 "fmt" 8 "io" 9 ) 10 11 // JSONEncoding json格式 12 type JSONEncoding struct{} 13 14 // Marshal json encode 15 func (j JSONEncoding) Marshal(v any) ([]byte, error) { 16 return json.Marshal(v) 17 } 18 19 // Unmarshal json decode 20 func (j JSONEncoding) Unmarshal(data []byte, value any) error { 21 return json.Unmarshal(data, value) 22 } 23 24 // JSONGzipEncoding json and gzip 25 type JSONGzipEncoding struct{} 26 27 // Marshal json encode and gzip 28 func (jz JSONGzipEncoding) Marshal(v any) ([]byte, error) { 29 buf, err := json.Marshal(v) 30 if err != nil { 31 return nil, err 32 } 33 // var bufSizeBefore = len(buf) 34 35 buf, err = GzipEncode(buf) 36 // log.Infof("gzip_json_compress_ratio=%d/%d=%.2f", bufSizeBefore, len(buf), float64(bufSizeBefore)/float64(len(buf))) 37 return buf, err 38 } 39 40 // Unmarshal json encode and gzip 41 func (jz JSONGzipEncoding) Unmarshal(data []byte, value any) error { 42 jsonData, err := GzipDecode(data) 43 if err != nil { 44 return err 45 } 46 47 err = json.Unmarshal(jsonData, value) 48 if err != nil { 49 return err 50 } 51 return nil 52 } 53 54 // GzipEncode 编码 55 func GzipEncode(in []byte) ([]byte, error) { 56 var ( 57 buffer bytes.Buffer 58 out []byte 59 err error 60 ) 61 writer, err := gzip.NewWriterLevel(&buffer, gzip.BestCompression) 62 if err != nil { 63 return nil, err 64 } 65 66 _, err = writer.Write(in) 67 if err != nil { 68 err = writer.Close() 69 if err != nil { 70 return out, err 71 } 72 return out, err 73 } 74 err = writer.Close() 75 if err != nil { 76 return out, err 77 } 78 79 return buffer.Bytes(), nil 80 } 81 82 // GzipDecode 解码 83 func GzipDecode(in []byte) ([]byte, error) { 84 reader, err := gzip.NewReader(bytes.NewReader(in)) 85 if err != nil { 86 var out []byte 87 return out, err 88 } 89 defer func() { 90 err = reader.Close() 91 if err != nil { 92 fmt.Printf("reader close err: %+v", err) 93 } 94 }() 95 96 return io.ReadAll(reader) 97 }