http - 使用 Go http 客户端的意外 EOF

标签 http error-handling go

我正在学习 Go 并遇到了这个问题。

我只是使用 HTTP 客户端下载网页内容:

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

func main() {
    client := &http.Client{}

    req, err := http.NewRequest("GET", "https://mail.ru/", nil)
    req.Close = true

    response, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }

    defer response.Body.Close()

    content, err := ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(string(content)[:100])
}

我在读取响应正文时收到 unexpected EOF 错误。同时内容变量具有整页内容。

此错误仅在我下载 https://mail.ru/ 内容时出现。使用其他 URL 一切正常 - 没有任何错误。

我使用 curl 下载此页面内容 - 一切正常。

我有点困惑 - 这里发生了什么?

Go v1.2,在 Ubuntu 和 MacOS X 上试用

最佳答案

看起来该服务器(Apache 1.3,哇!)正在提供截断的 gzip 响应。如果您明确请求 identity 编码(阻止 Go 传输添加 gzip 本身),您将不会得到 ErrUnexpectedEOF:

req.Header.Add("Accept-Encoding", "identity")

关于http - 使用 Go http 客户端的意外 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21147562/

相关文章:

python - Flask 和传输编码 : chunked

c++ - 如何使用libevent在C++中发出HEAD请求

python - 在 Python CGI 中返回 http 状态代码

c++ - 尽管有错误,glDebugMessageCallback 不会被调用

c# - DLL 未找到错误

mysql - 无法连接到 DB : database is closed

json - 从键值对中提取 "filtering"JSON 对象的最有效方法是什么?

http - 登录详细信息(ID、密码)在浏览器开发人员工具中以纯文本形式显示

multithreading - 使用 Go 1.2 的线程 CGO

c++ - 做组合时被零除