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的首页。有没有办法可以达到类似代理的效果?
将标头,状态和响应主体复制到响应编写器:
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类型可能会有所帮助。
归档时间: |
|
查看次数: |
1680 次 |
最近记录: |