我从服务器转储请求[]byte并用于ReadRequest使用Client.Do方法发出请求.我收到一个错误:
http:Request.RequestURI无法在客户端请求中设置.
你能解释一下为什么我得到这个错误吗?
ANi*_*sus 11
错误很明显:在执行客户端请求时,不允许设置RequestURI.
在文档中http.Request.RequestURI,它说(我的重点):
RequestURI是
客户端发送
到服务器的Request-Line(RFC 2616,第5.1节)的未修改Request-URI .通常应该使用URL字段.
在HTTP客户端请求中设置此字段是错误的.
设置它的原因是因为这是ReadRequest在解析请求流时所做的事情.
因此,如果要发送,则需要设置URL并清除RequestURI.在尝试之后,我注意到从ReadRequest返回的请求中的URL对象将不具有所有信息集,例如scheme和host.由于这一点,你需要自己设置它,或者只是使用解析一个新的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)
}
Run Code Online (Sandbox Code Playgroud)
PS.play.golang.org会惊慌失措,因为我们没有权限做http请求.
| 归档时间: |
|
| 查看次数: |
4984 次 |
| 最近记录: |