代码之家  ›  专栏  ›  技术社区  ›  Louis Ng

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

  •  4
  • Louis Ng  · 技术社区  · 8 年前

    我尝试这样做是为了转储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)
    }
    

    我得到了一整页的谷歌HTML代码。com而不是谷歌首页。有没有一种方法可以实现类似代理的效果?

    1 回复  |  直到 5 年前
        1
  •  12
  •   Cerise Limón    8 年前

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

    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 type 可能会有帮助。