POST data faild using http.NewRequest

空扰寡人 提交于 2020-01-21 19:15:09

问题


I am trying to pass data from one golang service to another using http.NewRequest(). To do it I used following code:

        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()

I got this from Golang: http.NewRequest POST

When I try to dump received data from user service:

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

I get an empty map[]

Here I just try to inject tracing span to my request, previously I have used http.PostForm() to pass data, it worked perfectly. But I have no idea to pass tracing to it.


回答1:


From the docs for ParseForm:

[...] when the Content-Type is not application/x-www-form-urlencoded, the request Body is not read, and r.PostForm is initialized to a non-nil, empty value.

PostForm sets the Content-Type automatically, but now you have to do it yourself:

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


来源:https://stackoverflow.com/questions/58696512/post-data-faild-using-http-newrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!