将POST变量添加到Go测试的HTTP请求中。

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

Adding POST variables to Go test http Request

问题

我正在尝试将表单变量添加到Go的HTTP请求中。

这是我的Go测试代码:

  1. func sample_test(t *testing.T) {
  2. handler := &my_listener_class{}
  3. reader := strings.NewReader("number=2")
  4. req, _ := http.NewRequest("POST", "/my_url", reader)
  5. w := httptest.NewRecorder()
  6. handler.function_to_test(w, req)
  7. if w.Code != http.StatusOK {
  8. t.Errorf("Home page didn't return %v", http.StatusOK)
  9. }
  10. }

问题在于表单数据没有传递给我需要测试的函数。

另一个相关的函数是:

  1. func (listener *my_listener_class) function_to_test(writer http.ResponseWriter, request *http.Request) {
  2. ...
  3. }

我正在使用Go版本go1.3.3 darwin/amd64。

英文:

I am trying to add form variables to a Go http request.

Here's how my Go test looks:

  1. func sample_test(t *testing.T) {
  2. handler := &my_listener_class{}
  3. reader := strings.NewReader("number=2")
  4. req, _ := http.NewRequest("POST", "/my_url", reader)
  5. w := httptest.NewRecorder()
  6. handler.function_to_test(w, req)
  7. if w.Code != http.StatusOK {
  8. t.Errorf("Home page didn't return %v", http.StatusOK)
  9. }
  10. }

The issue is that the form data never gets passed on to the function I need to test.

The other relevant function is:

  1. func (listener *my_listener_class) function_to_test(writer http.ResponseWriter, request *http.Request) {
  2. ...
  3. }

I am using Go version go1.3.3 darwin/amd64.

答案1

得分: 12

你需要在请求中添加一个Content-Type头,这样处理程序才能知道如何处理POST请求的主体数据:

  1. req, _ := http.NewRequest("POST", "/my_url", reader) //顺便检查错误
  2. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
英文:

You need to add a Content-Type header to the request so the handler will know how to treat the POST body data:

  1. req, _ := http.NewRequest("POST", "/my_url", reader) //BTW check for error
  2. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

huangapple
  • 本文由 发表于 2015年6月22日 18:52:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/30978105.html
匿名

发表评论

匿名网友

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

确定