Go语言 通过代理重新发送时出现“无法在客户端请求中设置请求.RequestURI”错误

iovurdzv  于 2022-12-16  发布在  Go
关注(0)|答案(2)|浏览(189)

当我尝试从简单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)

,设置http_proxy ENV(通过我的代理发送请求)

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

我得到一个error,就像

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

我错过了什么?

bhmjp9jg

bhmjp9jg1#

不能将客户端请求用作Do的参数。请使用与r相同的参数创建新请求,然后对此请求执行Do

qyzbxkaa

qyzbxkaa2#

../src/net/http/client.go:217https://go.dev/src/net/http/client.go)中的误差定义为:

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

如果在发送HTTP请求之前设置r.RequestURI = "",则应该能够重用现有的r *http.Request

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

相关问题