如何转储HTTP GET请求的响应并将其写入http.ResponseWriter

Lou*_* Ng 3 proxy go http-proxy

我正在尝试这样做以转储HTTP GET请求的响应,并将相同的响应写入http.ResponseWriter。这是我的代码:

package main

import (
    "net/http"
    "net/http/httputil"
)

func handler(w http.ResponseWriter, r *http.Request) {
    resp, _ := http.Get("http://google.com")
    dump, _ := httputil.DumpResponse(resp,true)
    w.Write(dump)
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}
Run Code Online (Sandbox Code Playgroud)

我得到了一整页的google.com的HTML代码,而不是Google的首页。有没有办法可以达到类似代理的效果?

Cer*_*món 6

将标头,状态和响应主体复制到响应编写器:

resp, err :=http.Get("http://google.com")
if err != nil {
    // handle error
}
defer resp.Body.Close()

// headers

for name, values := range resp.Header {
    w.Header()[name] = values
}

// status (must come after setting headers and before copying body)

w.WriteHeader(resp.StatusCode)

// body

io.Copy(w, resp.Body)
Run Code Online (Sandbox Code Playgroud)

如果要创建代理服务器,则net / http / httputil ReverseProxy类型可能会有所帮助。

  • 我很难理解为什么 io.Copy 必须在 w.WriteHeader 之后。查看http文档,我发现:“如果尚未调用WriteHeader,Write会在写入数据之前调用WriteHeader(http.StatusOK)。如果标头不包含Content-Type行,Write会添加一个Content-Type集将初始 512 字节写入数据传递给 DetectContentType 的结果。此外,如果所有写入数据的总大小低于几 KB 并且没有 Flush 调用,则会自动添加 Content-Length 标头。https://golang.org/pkg/net/http/ (2认同)