Golang gzip response → struct
gzip圧縮されたresponseをhoge struct にいれるまで
import ( "net/http" "compress/gzip" "bytes" "encoding/json" ) func main() { // どこかへGetRequest req, err := http.NewRequest(http.MethodGet, "https://hogehoge/foo/bar.jp", nil) if err != nil { panic(err) } req.Header.Set("Accept-Encoding", "deflate, gzip") client := new(http.Client) resp, err = client.Do(req) if err != nil { panic(err) } if resp.StatusCode != http.StatusOK { panic("なにかしら失敗") } reader, _ = gzip.NewReader(resp.Body) wb := new(bytes.Buffer) io.Copy(wb, reader) var bean *hoge err = json.Unmarshal(wb.Bytes(), &bean) if err != nil { panic(err) } println(bean) } type hoge struct { ... }
Accept-Encoding
Accept-Encoding ヘッダの目的は、クライアントがサポートしている圧縮方式をサーバーに教えることです。 サーバーは送られてきた Accept-Encoding ヘッダの値を見て、クライアントに合う圧縮アルゴリズムでコンテンツを圧縮して返却してあげれば良いというわけです。
今回は gzip 圧縮してresponseちょうだい ということなので、 Accept-Encoding : deflate, gzip