我正在尝试使用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 .
最佳答案
[...] 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/