2015-06-22 80 views
1

我想添加表单变量到Go http请求。添加POST变量去测试http请求

这里是我去考试的样子:

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) { 
    ... 
} 

我使用转到版本go1.3.3达尔文/ AMD64。

回答

1

你需要一个Content-Type头添加到请求,以便处理程序就知道如何处理POST体数据:

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

我试过了,而且...... KABOOM! (RAN去检验) 恐慌:运行时错误:无效的内存地址或零指针引用[回收] \t恐慌:运行时错误:无效的内存地址或零指针引用 [信号0XB代码=为0x1 ADDR =为0x0 PC = 0x1271d0] – mirage

+0

@mirage这可能是你的处理程序中的一个问题,你没有给出足够的上下文来看看它是什么。但至少我们知道我的回答对于您的具体问题是正确的。 –

+0

是的,工作。我还有其他一些问题。修正了那些现在。非常感谢。 – mirage