有人可以解释这里发生了什么吗?
package main
import (
"fmt"
"net/http"
"strings"
)
func Verify(req http.Request) string {
return req.FormValue("g-recaptcha-response")
}
func main() {
req, _ := http.NewRequest("POST", "http://www.google.com/search?q=foo&q=bar&both=x&prio=1&empty=not",
strings.NewReader("z=post&both=y&prio=2&empty="))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
Verify(*req)
fmt.Println(req.FormValue("z"))
}
(https://play.golang.org/p/ve4Cc_JTzr)
这将产生一个空的输出。现在,如果我在将请求传递为值之前访问值“ z” ,则它可以正常工作!
package main
import (
"fmt"
"net/http"
"strings"
)
func Verify(req http.Request) string {
return req.FormValue("g-recaptcha-response")
}
func main() {
req, _ := http.NewRequest("POST", "http://www.google.com/search?q=foo&q=bar&both=x&prio=1&empty=not",
strings.NewReader("z=post&both=y&prio=2&empty="))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
Verify(*req)
fmt.Println(req.FormValue("z"))
}
(https://play.golang.org/p/5ALnt-pHTl)
我尝试了从1.5到1.7的几种版本,结果都一样。如果请求是通过引用传递的,则它按预期运行。
这是因为Request的正文为io.Reader
,并且您只能读取io.Reader
一次,因此当您尝试第二次读取内容时,没有更多数据可读取。
方法FormValue
调用ParseForm
,它从读取器读取所有数据。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句