将POST变量添加到Go测试http请求。

9

我将尝试在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。

1个回答

14

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

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

我尝试了一下,结果...炸了!(运行go test)恐慌:运行时错误:无效的内存地址或空指针解引用[已恢复] 恐慌:运行时错误:无效的内存地址或空指针解引用 [信号0xb代码=0x1 addr=0x0 pc=0x1271d0] - mirage
@mirage 这可能是你的处理程序出了问题,你没有提供足够的上下文来看清楚是什么问题。但至少我们知道我的答案对于你的具体问题是正确的。 - Not_a_Golfer
是的,那行了。我还有一些其他问题。现在解决了。非常感谢。 - mirage

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接