Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding POST variables to Go test http Request

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.

like image 446
mirage Avatar asked Jun 22 '15 10:06

mirage


Video Answer


1 Answers

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")
like image 159
Not_a_Golfer Avatar answered Sep 25 '22 13:09

Not_a_Golfer