dougang5993 2019-04-04 08:22
浏览 48
已采纳

从ReadCloser发送HTTP Put正文永无止境

Target

I want to send to data to my server from a read closer. (In the example a NopCloser, later it will be the Stdout of an exec.Command)

Problem

The Request never ends. Even if I manually close the cmdOut the program nevers ends. Concrete: It never reaches the "Request Done" line and there by never calls wg.Done()

Gotchas

All the data is sent correctly to the server (even with the exec.Command Stdout). But the http.DefaultClient.Do seems to be still listening on the ReadCloser after it is empty (and closed in the main routine)

Code

cmdOut := ioutil.NopCloser(bytes.NewBuffer([]byte("Hallo DU")))

var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done()

    // localhost:1234 is a netcat server: "nc -l -p 1234"
    req, _ := http.NewRequest("PUT", "http://localhost:1234", cmdOut)

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Println(err)
        return
    }

    // Never reaches this line
    log.Println("Request Done")
}()

cmdOut.Close()

log.Println("Wait for go routine")
wg.Wait()
log.Println("DONE")
  • 写回答

1条回答 默认 最新

  • duanaiguang1960 2019-04-04 08:31
    关注

    The problem isn't the sending of your request--it's the receiving of the response.

    You're sending your request to netcat, which simply discards the request, and does nothing else. This leaves the HTTP client library waiting for an HTTP response, which never comes.

    The solution is to talk to an actual HTTP server.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效