gpt4 book ai didi

go - 如果请求按值传递,则 http 请求值为空

转载 作者:IT王子 更新时间:2023-10-29 01:54:49 29 4
gpt4 key购买 nike

有人能解释一下这里发生了什么吗?

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 )

我尝试了 go 从 1.5 到 1.7 的几个版本,结果都一样奇怪。如果请求通过引用传递,它会按预期工作。

最佳答案

因为Request的body是io.Reader,你只能从io.Reader中读取一次,当你第二次尝试读取内容时,就没有了要读取的数据。

方法 FormValue 调用 ParseForm,它从阅读器读取所有数据。

关于go - 如果请求按值传递,则 http 请求值为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38983089/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com