dosf40815
dosf40815
采纳率100%
2014-03-01 00:41

如何使用Golang的net / http包读取流式响应正文?

已采纳

我正在尝试连接到一个执行json数据流的端点。我想知道如何使用Go的net/http包执行基本请求,并在响应出现时读取响应?目前,我只能在连接关闭时读取响应。

resp, err := http.Get("localhost:8080/stream")
if err != nil {
    ...
}
...
// perform work while connected and getting data

任何帮助都将不胜感激!谢谢!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • doure8758 doure8758 7年前

    The way to do streaming JSON parsing is with a Decoder:

    json.NewDecoder(resp.Body).Decode(&yourStuff)
    

    For a streaming API where it's a bunch of objects coming back (a la Twitter), that should stream great with this model and the built-in encoding/json API. But if it's a large response where you have an object that's got a giant array with 10MB of stuff, you probably need to write your own Decoder to pull those inner pieces out and return them. I'm running into that problem with a library I've written.

    点赞 评论 复制链接分享
  • dtrotfd1012 dtrotfd1012 7年前

    The answer provided by Eve Freeman is the correct way to read json data. For reading any type of data, you can use the method below:

    resp, err := http.Get("http://localhost:3000/stream")
    ...
    
    reader := bufio.NewReader(resp.Body)
    for {
        line, err := reader.ReadBytes('
    ')
        ...
    
        log.Println(string(line))
    }
    
    点赞 评论 复制链接分享

相关推荐