dosf40815
2014-03-01 00:41
采纳率: 100%
浏览 336
已采纳

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

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

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

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

图片转代码服务由CSDN问答提供 功能建议

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

  resp,err:= http.Get(“ localhost:8080 / stream”)
if err!= nil {
 ... 
} 
 ..  。
 //在连接并获取数据的同时执行工作
   
 
 

任何见识将不胜感激!

谢谢!< / p>

-RC

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doure8758 2014-03-01 14:23
    已采纳

    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 2014-03-04 16:39

    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))
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题