繁体   English   中英

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

[英]How to dump a response of an HTTP GET request and write it in http.ResponseWriter

我试图这样做来转储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)
}

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

将标题,状态和响应正文复制到响应编写器:

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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM