簡體   English   中英

用Go解碼gZip json

[英]Decoding gZip json with Go

作為Go新手,我很難確定問題區域,但希望能給你一些事實會有所幫助。

我正在使用API​​將其Content-Encoding作為gzip返回。 我寫了以下內容來編碼我的響應結構:

reader, err = gzip.NewReader(resp.Body)
defer reader.Close()

// print to standard out
//_, err = io.Copy(os.Stdout, reader)
//if err != nil {
//  log.Fatal(err)
//}

// Decode the response into our tescoResponse struct
var response TescoResponse
err := json.NewDecoder(reader).Decode(&response)

為簡潔起見,我刪除了錯誤處理,但感興趣的是,如果我將打印取消注釋到stdout,我會得到預期的結果。 但是,解碼並不能滿足我的期望。 有什么指針嗎? 結構必須精確映射到響應嗎?

以下是完整示例: https//play.golang.org/p/4eCuXxXm3T

從文件

DisableCompression,如果為true,則當請求不包含現有的Accept-Encoding值時,阻止傳輸使用“Accept-Encoding:gzip”請求標頭請求壓縮。 如果傳輸單獨請求gzip並獲得一個gzip壓縮響應,它將在Response.Body中透明地解碼。 但是,如果用戶明確請求gzip,則不會自動解壓縮。

建議的解決方案:

type gzreadCloser struct {
    *gzip.Reader
    io.Closer
}

func (gz gzreadCloser) Close() error {
    return gz.Closer.Close()
}

//然后在你的http電話....

    if resp.Header.Get("Content-Encoding") == "gzip" {
        resp.Header.Del("Content-Length")
        zr, err := gzip.NewReader(resp.Body)
        if err != nil {
            return nil, err
        }
        resp.Body = gzreadCloser{zr, resp.Body}
    }

// then you will be able to decode the json transparently

if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {

}

來自您的代碼的改編解決方案: https//play.golang.org/p/Vt07y_xgak

正如@icza在評論中提到的那樣,不需要解碼,因為gzip閱讀器在您使用它時會自動解碼。 也許試試:

ubs := make([]byte, len) // check Content-Length header to set len
n, err := reader.Read(ubs)
err := json.Unmarshal(ubs, &response)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM