【问题标题】:POST data faild using http.NewRequest使用 http.NewRequest POST 数据失败
【发布时间】:2019-11-05 01:01:11
【问题描述】:

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

【问题讨论】:

    标签: forms go http-headers microservices distributed-tracing


    【解决方案1】:

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

    【讨论】:

    • 我错过了什么req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    猜你喜欢
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    相关资源
    最近更新 更多