duanke9540 2013-11-04 15:31
浏览 87
已采纳

如何在Go中执行HTTP双工处理程序?

I heard here that

once you write anything in the response, the request body will be closed which prevents you from reading anything from it

If that is true, how can I write a proper duplex handler that is able to read from the request body, make some kind of transformation, and then write to the response body, in a streaming fashion just like people do in node.js ?

  • 写回答

2条回答 默认 最新

  • drbii0359 2013-11-06 11:10
    关注

    I ended up managing to do this with http.Hijacker.

    After the request is made and the request headers are parsed, I can read from *http.Request.Body, then hijack the connection and write to it, at the same time, like this:

    hj, ok := w.(http.Hijacker)
    if !ok {
        http.Error(w, "hijacking not supported", 500)
        return
    }
    
    conn, bufrw, err := hj.Hijack()
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }
    defer conn.Close()
    

    And then conn is a net.Conn which is the underlying TCP connection to the client, bufrw is a *bufio.ReadWriter, and to write the response without closing the body all I have to do is

    _, err = bufrw.WriteString("HTTP/1.1 200 OK
    
    ")
    _, err = bufrw.WriteString("this")
    _, err = bufrw.WriteString("is")
    _, err = bufrw.WriteString("the")
    _, err = bufrw.WriteString("response")
    _, err = bufrw.WriteString("body")
    

    And then I'm not sure about this but maybe someone can complete the answer, it's a good idea to flush the buffers down the connection once in a while with

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

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?