如果请求通过值传递,则http请求值为空

重力:

有人可以解释这里发生了什么吗?

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章