Search code examples
gohttp-proxy

'Request.RequestURI can't be set in client request' error when resend it through proxy


When I try to resend requests from simple proxy

http.HandleFunc("/",func(w http.ResponseWriter, r *http.Request) {
    log.Printf("proxy rq: %v", r)
    client := &http.Client{}
    proxyRes, err := client.Do(r) // 👈🏻  Get "http://localhost:8097/tmp": http: Request.RequestURI can't be set in client requests
    if err != nil {
        log.Fatalf("err proxy request: %v",err)
    }
    resBody := proxyRes.Body
    defer resBody.Close()
    if _, err := io.Copy(w, resBody); err != nil {
        log.Printf("copy error:%v\n", err)
    }
})
http.ListenAndServe(":8099", nil)

, with set http_proxy ENV (to send requests thought my proxy)

% export http_proxy=http://localhost:8099 
% curl -v http://localhost:8097/tmp

I get an error like

Get "http://localhost:8097/tmp": http: Request.RequestURI can't be set in client requests

What did I miss?


Solution

  • You can't use the client request as a parameter of Do. Create a new request with the same parameter as r, then perform Do on this request