POST 使用 http.NewRequest 数据失败

POST data faild using http.NewRequest

我正在尝试使用 http.NewRequest() 将数据从一个 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()

我从

那里得到了这个

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

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

我得到一个空的map[]

这里我只是尝试将跟踪跨度注入到我的请求中,之前我使用 http.PostForm() 来传递数据,它工作得很好。但是我有 no idea to pass tracing to it.

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 会自动设置 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")