GithubHelp home page GithubHelp logo

Comments (4)

wnanbei avatar wnanbei commented on June 8, 2024

因为 Golang net/http 库的设定,如果在请求头里只指定了 "Accept-Encoding": "gzip" 的话,那么返回的 Body 是不会自动 gzip 解压的,需要手动解压。

解压前把 resp.Contont() 获得的 []byte 转换成 io.Reader 就可以用官方的 compress/gzip 解压了。

package main

import (
	"bytes"
	"compress/gzip"
	"fmt"
	"io/ioutil"

	dw "github.com/wnanbei/direwolf"
)

func main() {
	url := "http://httpbin.org/gzip"
	headers := dw.NewHeaders(
		"User-Agent", "direwolf",
		"Accept-Encoding", "gzip",
	)
	resp, err := dw.Get(url, headers)
	if err != nil {
		fmt.Println(err)
		return
	}

	gr, err := gzip.NewReader(bytes.NewReader(resp.Content()))
	if err != nil {
		fmt.Println(err)
		return
	}
	defer gr.Close()
	data, err := ioutil.ReadAll(gr)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(data))
}

from direwolf.

tablecell avatar tablecell commented on June 8, 2024

from direwolf.

wnanbei avatar wnanbei commented on June 8, 2024

@tablecell
我查了下,造成这个原因是因为,这个网页返回的标头中没有 content-length 这个字段,所以在使用 ioutil.ReadAll() 读取内容的时候,会由于不知道何时结尾,并抛 unexpected EOF 这个异常。

其实内容是已经都读到了的,你可以先加上 Accept-Encoding", "gzip 发起请求,然后在 data, err := ioutil.ReadAll(gr) 这个步骤忽略异常即可。

稍后我会更新一下,在构建 Response 时忽略这个异常。

from direwolf.

wnanbei avatar wnanbei commented on June 8, 2024

@tablecell
在版本 0.5.4 中,已经忽略读取 Response.Body 遇到 Unexpected EOF 这个异常,数据可以正常读取。但如果需要自行手动解压 gzip 数据的话,依然可能会遇到这个问题,需要手动忽略这个 io.ErrUnexpectedEOF 异常。

如无疑问,就关闭这个 Issues 了。

from direwolf.

Related Issues (5)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.