我将请求从服务器转储到 []byte
并使用 ReadRequest
通过 Client.Do
方法发出请求。我收到一个错误:
http: Request.RequestURI can't be set in client requests.
你能解释一下为什么我会收到这个错误吗?
最佳答案
错误很明显:您不允许在执行客户端请求时设置 RequestURI。
在 http.Request.RequestURI
的文档中,它说(我强调):
RequestURI is the unmodified Request-URI of the
Request-Line (RFC 2616, Section 5.1) as sent by the client
to a server. Usually the URL field should be used instead.
It is an error to set this field in an HTTP client request.
设置它的原因是因为这是 ReadRequest 在解析请求流时所做的。
因此,如果要发送,则需要设置URL并清除RequestURI。经过尝试,我发现ReadRequest返回的请求中的URL对象并没有设置所有的信息,比如scheme和host。因此,您需要自己设置,或者使用 Parse 解析新的 URL。在 net/url
包中:
这是一些适合您的工作代码:
package main
import (
"fmt"
"strings"
"bufio"
"net/http"
"net/url"
)
var rawRequest = `GET /pkg/net/http/ HTTP/1.1
Host: golang.org
Connection: close
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X; de-de) AppleWebKit/523.10.3 (KHTML, like Gecko) Version/3.0.4 Safari/523.10
Accept-Encoding: gzip
Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7
Cache-Control: no-cache
Accept-Language: de,en;q=0.7,en-us;q=0.3
`
func main() {
b := bufio.NewReader(strings.NewReader(rawRequest))
req, err := http.ReadRequest(b)
if err != nil {
panic(err)
}
// We can't have this set. And it only contains "/pkg/net/http/" anyway
req.RequestURI = ""
// Since the req.URL will not have all the information set,
// such as protocol scheme and host, we create a new URL
u, err := url.Parse("http://golang.org/pkg/net/http/")
if err != nil {
panic(err)
}
req.URL = u
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
fmt.Printf("%#v\n", resp)
}
附言。 play.golang.org 会 panic ,因为我们没有做 http 请求的权限。
关于http.Request RequestURI字段在go中发出请求时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19595860/