mirage
mirage

Reputation: 631

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.

Upvotes: 9

Views: 11462

Answers (1)

Not_a_Golfer
Not_a_Golfer

Reputation: 49265

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")

Upvotes: 15

Related Questions