kozmo
kozmo

Reputation: 4491

'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?

Upvotes: 2

Views: 2094

Answers (2)

daliborp
daliborp

Reputation: 171

The error is defined in the ../src/net/http/client.go:217 (https://go.dev/src/net/http/client.go) as:

if req.RequestURI != "" {
    req.closeBody()
    return nil, alwaysFalse, errors.New("http: Request.RequestURI can't be set in client requests")
}

You should be able to reuse existing r *http.Request if you set r.RequestURI = "" before sending a HTTP request:

r.RequestURI = ""
proxyRes, err := client.Do(r)

Upvotes: 1

aureliar
aureliar

Reputation: 1614

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

Upvotes: 3

Related Questions