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

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

Adding POST variables to Go test http Request

问题

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

这是我的Go测试代码:

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

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

另一个相关的函数是:

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

我正在使用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:

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

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

The other relevant function is:

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

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

答案1

得分: 12

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

req, _ := http.NewRequest("POST", "/my_url", reader) //顺便检查错误
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:

req, _ := http.NewRequest("POST", "/my_url", reader) //BTW check for error
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:

确定