doumengjing1500 2015-04-02 15:59
浏览 95
已采纳

在Go中请求多个URL

I have the following Go program: https://play.golang.org/p/-TUtJ7DIhi

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "strconv"
)

func main() {
    body, err := get("https://hacker-news.firebaseio.com/v0/topstories.json")

    if err != nil {
        panic(err)
    }

    var ids [500]int
    if err = json.Unmarshal(body, &ids); err != nil {
        panic(err)
    }

    var contents []byte
    for _, value := range ids[0:10] {
        body, err := get("https://hacker-news.firebaseio.com/v0/item/" + strconv.Itoa(value) + ".json")

        if err != nil {
            fmt.Println(err)
        } else {
            contents = append(contents, body...)
        }
    }

    fmt.Println(contents)
}

func get(url string) ([]byte, error) {
    res, err := http.Get(url)
    if err != nil {
        return nil, err
    }

    body, err := ioutil.ReadAll(res.Body)
    res.Body.Close()

    return body, err
}

When run it throws EOF json errors on the iterative get requests, but when I hit the URLs individually they do not appear to be malformed.

What am I missing?

  • 写回答

1条回答 默认 最新

  • drqj8605 2015-04-02 16:42
    关注

    It looks like there's something wrong with their server, and it's closing connections without sending a Connection: close header. The client therefore tries to reuse the connection per the HTTP/1.1 specification.

    You can work around this by creating your own request, and setting Close = true, or using a custom Transport with DisableKeepAlives = true

    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        return nil, err
    }
    req.Close = true
    
    res, err := http.DefaultClient.Do(req)
    if err != nil {
        return nil, err
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探