登录
首页 >  Golang >  Go问答

POST 请求的 http.NewRequest 失败

来源:stackoverflow

时间:2024-03-21 08:06:37 366浏览 收藏

在使用 Go 语言的 `http.NewRequest` 函数进行 POST 请求时,如果未显式设置 `Content-Type` 标头,则可能会导致无法解析请求正文。这是因为 `http.NewRequest` 不会自动设置该标头,而 `http.PostForm` 会自动设置。因此,在使用 `http.NewRequest` 时,需要手动设置 `Content-Type` 为 `application/x-www-form-urlencoded`,以确保请求正文能够被正确解析。

问题内容

我正在尝试使用 http.newrequest() 将数据从一个 golang 服务传递到另一个 golang 服务。为此,我使用了以下代码:

httpclient := http.client{}

        userserviceurl := "http://user:7071/checkemail"

        form := url.values{}
        form.set("uuid", uuid)
        form.set("email", email)

        b := bytes.newbufferstring(form.encode())
        req, err := http.newrequest("post", userserviceurl, b)
        if err != nil {
            log.println(err)
        }

        opentracing.globaltracer().inject(
            validateemailspan.context(),
            opentracing.httpheaders,
            opentracing.httpheaderscarrier(req.header))

        resp, err := httpclient.do(req)
        //_, err = http.postform("http://user:7071/checkemail", url.values{"uuid": {uuid}, "email": {email}})

        if err != nil {
            log.println("couldnt verify email address user service sends an error : ", err)
        }
        defer resp.body.close()

我从 golang 得到这个:http.newrequest post

当我尝试转储从用户服务接收到的数据时:

req.ParseForm()
    log.Println("Form values : ", req.Form)

我得到一个空的 map[]

这里我只是尝试将跟踪范围注入到我的请求中,之前我已经使用 http.postform() 来传递数据,它工作得很好。但我不知道将 tracing 传递给它。


解决方案


From the docs for ParseForm

[...]当content-type不是application/x-www-form-urlencoded时,不会读取请求body,并且r.postform会初始化为非nil的空值。

postform 自动设置 content-type,但现在您必须自己设置:

req, err := http.NewRequest("POST", userserviceUrl, strings.NewReader(form.Encode()))
// TODO: handle error
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

今天关于《POST 请求的 http.NewRequest 失败》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>