Golang: HTTP Testing

HTTP GET

func TestPingRoute(t *testing.T) {

	w := httptest.NewRecorder()
	req := httptest.NewRequest("GET", "/ping", nil)

	PingRoute(w, req)

	if w.Code != 201 {
		t.Error("Return code expected", 201, "got", w.Code)
	}

	if w.Body.String() != "world" {
		t.Errorf("Response body expected %s got %s", "world", w.Body.String())
	}
}

func PingRoute(w http.ResponseWriter, r *http.Request) {

	w.Write([]byte("hello"))
}

Run it with:

$ go test

HTTP GET with Query String

func TestPingRoute(t *testing.T) {

	req := httptest.NewRequest("GET", "/ping?foo=bar", nil)
	w := httptest.NewRecorder()

	handlePingWithQueryString(w, req)

	if w.Code != 201 {
		t.Error("Return code expected", 201, "got", w.Code)
	}

	if w.Body.String() != "world" {
		t.Errorf("Response body expected %s got %s", "world", w.Body.String())
	}
}

func handlePingWithQueryString(w http.ResponseWriter, r *http.Request) {

	fmt.Println("Query strings:", r.URL.Query())
	w.Write([]byte(r.URL.Query().Get("foo")))
}

Run it with:

$ go test

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *