Go中Gzip與json搭配實(shí)現(xiàn)數(shù)據(jù)壓縮demo
正文
在日常工作中,如果遇到數(shù)據(jù)量大的情況,在db中是不能直接存儲(chǔ)某些字段的,一般會(huì)用json進(jìn)行marshal為 byte存入。但是如果此時(shí)占用空間依舊過(guò)大,則可以考慮再用gzip 還進(jìn)一步壓縮。
demo
package main import ( "bytes" "compress/gzip" "encoding/json" ) func main() { } type anyStruct struct { } // 壓縮 與json搭配使用 func MarshalToJsonWithGzip(jsonData anyStruct) []byte { dataAfterMarshal, _ := json.Marshal(jsonData) dataAfterGzip, err := Encode(dataAfterMarshal) if err != nil { return nil } return dataAfterGzip } // 解壓 與json搭配使用 func UnmarshalDataFromJsonWithGzip(msg []byte) (*anyStruct, error) { dataAfterDecode, err := Decode(msg) if err != nil { return nil, err } data := &anyStruct{} err = json.Unmarshal(dataAfterDecode, data) if err != nil { return nil, err } return data, nil } // Gzip用法 壓縮數(shù)據(jù) func Encode(input []byte) ([]byte, error) { // 創(chuàng)建一個(gè)新的 byte 輸出流 var buf bytes.Buffer // 創(chuàng)建一個(gè)新的 gzip 輸出流 gzipWriter := gzip.NewWriter(&buf) // 將 input byte 數(shù)組寫入到此輸出流中 _, err := gzipWriter.Write(input) if err != nil { _ = gzipWriter.Close() return nil, err } if err := gzipWriter.Close(); err != nil { return nil, err } // 返回壓縮后的 bytes 數(shù)組 return buf.Bytes(), nil } // Gzip用法 解壓數(shù)據(jù) func Decode(input []byte) ([]byte, error) { // 創(chuàng)建一個(gè)新的 gzip.Reader bytesReader := bytes.NewReader(input) gzipReader, err := gzip.NewReader(bytesReader) if err != nil { return nil, err } defer func() { // defer 中關(guān)閉 gzipReader _ = gzipReader.Close() }() buf := new(bytes.Buffer) // 從 Reader 中讀取出數(shù)據(jù) if _, err := buf.ReadFrom(gzipReader); err != nil { return nil, err } return buf.Bytes(), nil }
以上就是Go中Gzip與json搭配實(shí)現(xiàn)數(shù)據(jù)壓縮demo的詳細(xì)內(nèi)容,更多關(guān)于Go 壓縮數(shù)據(jù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Golang語(yǔ)言如何讀取http.Request中body的內(nèi)容
這篇文章主要介紹了Golang語(yǔ)言如何讀取http.Request中body的內(nèi)容問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03golang jwt+token驗(yàn)證的實(shí)現(xiàn)
這篇文章主要介紹了golang jwt+token驗(yàn)證的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10淺談Go語(yǔ)言不提供隱式數(shù)字轉(zhuǎn)換的原因
本文主要介紹了淺談Go語(yǔ)言不提供隱式數(shù)字轉(zhuǎn)換的原因,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03xorm根據(jù)數(shù)據(jù)庫(kù)生成go model文件的操作
這篇文章主要介紹了xorm根據(jù)數(shù)據(jù)庫(kù)生成go model文件的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-12-12Go語(yǔ)言繼承功能使用結(jié)構(gòu)體實(shí)現(xiàn)代碼重用
今天我來(lái)給大家介紹一下在?Go?語(yǔ)言中如何實(shí)現(xiàn)類似于繼承的功能,讓我們的代碼更加簡(jiǎn)潔和可重用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01