英文:
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首页。有没有办法实现类似代理的效果?
英文:
I am trying to do it to dump the response of an HTTP GET request and write the very same response in an http.ResponseWriter
. Here is my code:
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)
}
I get a full page of HTML code of google.com instead of the Google front page. Is there a way I can achieve a proxy-like effect?
答案1
得分: 13
将请求的头部、状态和响应体复制到响应写入器中:
resp, err := http.Get("http://google.com")
if err != nil {
// 处理错误
}
defer resp.Body.Close()
// 头部
for name, values := range resp.Header {
w.Header()[name] = values
}
// 状态(必须在设置头部之后、复制响应体之前)
w.WriteHeader(resp.StatusCode)
// 响应体
io.Copy(w, resp.Body)
如果你正在创建一个代理服务器,那么 net/http/httputil ReverseProxy 类型 可能会有所帮助。
英文:
Copy the headers, status and response body to the response writer:
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)
If you are creating a proxy server, then the net/http/httputil ReverseProxy type might be of help.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论