使用http.NewRequest的POST数据失败

我正在尝试使用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()

我从Golang: http.NewRequest POST那里得到了

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

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

我得到一个空的map[]

在这里,我只是尝试将跟踪范围插入到我的请求中,之前我曾经使用过http.PostForm()来传递数据,但效果很好。但是我有no idea to pass tracing to it

huangchaoqi 回答:使用http.NewRequest的POST数据失败

From the docs for ParseForm

  

[...]当Content-Type不是application / x-www-form-urlencoded时,不读取请求主体,并且r.PostForm初始化为非空值。

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")
本文链接:https://www.f2er.com/3165589.html

大家都在问