英文:
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论