dragon19720808 2014-09-19 15:26
浏览 38
已采纳

多次从阅读器读取

I'm building a simple caching proxy that intercepts HTTP requests, grabs the content in response.Body, then writes it back to the client. The problem is, as soon as I read from response.Body, the write back to the client contains an empty body (everything else, like the headers, are written as expected).

Here's the current code:

func requestHandler(w http.ResponseWriter, r *http.Request) {
    client := &http.Client{}
    r.RequestURI = ""
    response, err := client.Do(r)
    defer response.Body.Close()
    if err != nil {
        log.Fatal(err)
    }
    content, _ := ioutil.ReadAll(response.Body)
    cachePage(response.Request.URL.String(), content)
    response.Write(w)
}

If I remove the content, _ and cachePage lines, it works fine. With the lines included, requests return and empty body. Any idea how I can get just the Body of the http.Response and still write out the response in full to the http.ResponseWriter?

  • 写回答

3条回答 默认 最新

  • duan02143 2014-09-19 16:32
    关注

    You do not need to read from the response a second time. You already have the data in hand and can write it directly to the response writer.

    The call

    response.Write(w)
    

    writes the response in wire format to the server's response body. This is not what you want for a proxy. You need to copy the headers, status and body to the server response individually.

    I have noted other issues in the code comments below.

    I recommend using the standard library's ReverseProxy or copying it and modifying it to meet your needs.

    func requestHandler(w http.ResponseWriter, r *http.Request) {
    
        // No need to make a client, use the default
        // client := &http.Client{} 
    
        r.RequestURI = ""
        response, err := http.DefaultClient.Do(r)
    
        // response can be nil, close after error check
        // defer response.Body.Close() 
    
        if err != nil {
            log.Fatal(err)
        }
        defer response.Body.Close() 
    
        // Check errors! Always.
        // content, _ := ioutil.ReadAll(response.Body)
        content, err := ioutil.ReadAll(response.Body)
        if err != nil {
             // handle error
        }
        cachePage(response.Request.URL.String(), content)
    
        // The Write method writes the response in wire format to w.
        // Because the server handles the wire format, you need to do
        // copy the individual pieces.
        // response.Write(w)
    
        // Copy headers
        for k, v := range response.Header {
           w.Header()[k] = v
        }
        // Copy status code
        w.WriteHeader(response.StatusCode)
    
        // Write the response body.
        w.Write(content)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据