forms - 使用 http.NewRequest POST 数据失败

标签 forms go http-headers microservices distributed-tracing

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

这里我只是尝试将跟踪范围注入(inject)到我的请求中,之前我使用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")

关于forms - 使用 http.NewRequest POST 数据失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58696512/

相关文章:

java - 带有 header 列表的 REST 调用

forms - 如何使用 EXT : Form in TYPO3 8. 7.1 将数据保存到数据库?

javascript - 使用语言获取数组值 Multipart/form-data

php - 表格问题

pointers - 为什么 Go 禁止获取 (&) map 成员的地址,而允许 (&) slice 元素?

php - 来自 PHP 脚本的 HTML5 音频

php - 如何从 CakePHP 列表数组返回一个值以在表单中使用?

go - 在哪里以及如何记录项目维护者

r - 如何在每日时间序列数据中获得每周的最大高点或最小低点然后使其成为每周时间序列?

HTTP - 我应该使用 Last-Modified 作为 Etag 吗?