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

如何使用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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程