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 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型