使用http.NewRequest的POST数据失败 [英] POST data faild using http.NewRequest
问题描述
我正在尝试使用http.NewRequest()
将数据从一个golang服务传递到另一服务.为此,我使用了以下代码:
I am trying to pass data from one golang service to another using http.NewRequest()
. To do it I used following code:
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
当我尝试转储从用户服务接收到的数据时:
When I try to dump received data from user service:
req.ParseForm()
log.Println("Form values : ", req.Form)
我得到一个空的map[]
在这里,我只是尝试将跟踪范围插入到我的请求中,之前我已经使用过http.PostForm()
来传递数据,它工作得很好.但是我不知道将tracing
传递给它.
Here I just try to inject tracing span to my request, previously I have used http.PostForm()
to pass data, it worked perfectly. But I have no idea to pass tracing
to it.
推荐答案
[...]当Content-Type不是application/x-www-form-urlencoded时,不读取请求主体,并且r.PostForm初始化为非空值.
[...] 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,但是现在您必须自己做:
PostForm sets the Content-Type automatically, but now you have to do it yourself:
req, err := http.NewRequest("POST", userserviceUrl, strings.NewReader(form.Encode()))
// TODO: handle error
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
这篇关于使用http.NewRequest的POST数据失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!