dongreng9864 2017-12-22 20:25
浏览 150
已采纳

使用分块传输编码处理请求

Does golang's net/http package support requests with chunked transfer-encoding? Thus far I have been able to use the Hijacker interface (https://golang.org/src/net/http/server.go?s=6173:6875#L156) to at least not close the connection and receive the full chunked request, but not yet parsing the chunks and suspect I may be going down the wrong path with this.

From https://golang.org/src/net/http/httputil/httputil.go?s=688:732#L10, I see there is a chunked reader, but appears to be for internal use.

Essentially, I'm trying to accept an HTTP PUT with 'chunked' transfer-encoding and send it off to a backend server 'on-the-fly' (i.e. without buffering the full request in golang). I have no control over the upstream request. Is there a recommended way to handle such a request, or is Hijacker the way to do it?

  • 写回答

1条回答 默认 最新

  • dongwubao4785 2017-12-22 20:34
    关注

    The net/http client and server transparently read and write chunked bodies.

    To accept a chunked request and send it to another HTTP server, pass the server request body as the client request body. Here's now to forward the body to another server as a PUT:

     func handler(w http.ResponseWriter, r *http.Request) {
        creq, err := http.NewRequest("PUT", url, r.Body)
        if err != nil {
           // handle error
        }
        if ct := r.Header.Get("Content-Type"); ct != "" {
            creq.Header.Set("Content-Type", ct)
        }
        cresp, err := http.DefaultClient.Do(creq)
        if err != nil {
            // handle error
        }
        ... do something with cresp.
     }
    

    If you want to copy to a file, then io.Copy the request body to the file.

     func handler(w http.ResponseWriter, r *http.Request) {
         f, err := os.Create("fname")
         if err != nil {
             // handle error
         }
         _, err := io.Copy(f, r.Body)
         if err != nil {
              // handle error
         }
         ...
      }
    

    These snippets copy the body 'on the fly'.

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

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题