Golang NewRequest将POST参数传递给API进行测试

huangapple go评论82阅读模式
英文:

Golang NewRequest passing POST parameter to the API for testing

问题

这是我的测试方法,它创建一个新的请求并传递POST参数。

url1 := "/api/addprospect"
data := url.Values{}
data.Add("customer_name", "value")
b := bytes.NewBuffer([]byte(data.Encode()))
request, err := http.NewRequest("POST", serverHttp.URL+url1, b)
res, err := http.DefaultClient.Do(request)

问题是POST参数没有被URL的处理函数接收到。

你能帮我设置正确的请求吗?

谢谢。

英文:

This is my test method which creates a new request and passes POST param.

url1 := "/api/addprospect"
data := url.Values{}
data.Add("customer_name", "value")
b := bytes.NewBuffer([]byte(data.Encode()))
request, err := http.NewRequest("POST", serverHttp.URL+url1, b)
res, err := http.DefaultClient.Do(request)

The problem is the POST param is not getting picked up by the function handler of the url.

Can you please help me with setting up right request?

Thanks

答案1

得分: 1

你需要为你的请求正确设置content-type头。

request, err := http.NewRequest("POST", serverHttp.URL+url1, b)

request.Header.Set("Content-Type", "application/x-www-form-urlencoded")

res, err := http.DefaultClient.Do(request)
英文:

You need to properly set the content-type header for your request.

request, err := http.NewRequest("POST", serverHttp.URL+url1, b)

request.Header.Set("Content-Type", "application/x-www-form-urlencoded")

res, err := http.DefaultClient.Do(request)

huangapple
  • 本文由 发表于 2016年1月18日 15:41:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/34849475.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定