LoginSignup
4
3

More than 5 years have passed since last update.

Golangにて"compress/flate"パッケージがflateで圧縮したデータを復元できなかった件について

Last updated at Posted at 2016-10-11

Golangにデータの圧縮と復元のパッケージをいくつ実装しています、"compress/flate" の他、 "compress/gzip" と "compress/zlib" なども提供されています。

ただ、HTTPクライアント Content-Encodingdeflate のリクエストデータを復元できなかった。

import (
    "compress/gzip"
    "compress/flate"
)

// Decode request body by content encoding
func decodeRequestBody(r *http.Request) (string, error) {

    ce, _ := r.Header["Content-Encoding"]

    for _, x := range ce {
        switch x {
        case "gzip":
            gr, e := gzip.NewReader(r.Body)
            defer gr.Close()
            if e != nil {
                return "", e
            }
            return readAll(gr)
        case "deflate":
            fr, e := flate.NewReader(r.Body)
            defer fr.Close()
            if e != nil {
                return "", e
            }
            return readAll(fr)
        }
    }

    // No Content-Encoding header detected
    return readAll(r.Body)
}

// Read from reader to string
func readAll(r io.Reader) (string, error) {
    if body, err := ioutil.ReadAll(r); err != nil {
        return "", err
    } else {
        return string(body), nil
    }
}

これではうまくいかなかった:

panic: flate: corrupt input before offset 5

調べたところ、この スレード のように、入力データは Zlib のストリームなので、 compress/zlib を使うべきだった。

なんでクライアントが Zlib のデータなのに Content-Encodingdeflate 設定したのだろう。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3