Skip to content

HTTP Requests

kstola2 edited this page Sep 22, 2019 · 2 revisions

The goal here is to give an example of a simple HTTP request.

First make a package in GOPATH:src called requestTut/, with two files requestTut.go and requestTut_test.go.

Next, let's head on over to requestTut_test.go to write our test function. We follow the AAA unit test format and first arrange our test space:

package requestTut

import (
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestMyGETRequest(t *testing.T) {

	// Arrange
	endpoint := ""

	// This recorder will capture responses from our test handler
	rr := httptest.NewRecorder()

	// This is our test handler.
	// It is simple and just responds with everything being OK
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})
}

Next we will Act. Since we are testing an HTTP Request, our Act stage should involve making the HTTP request and sending it off:

func TestMyGETRequest(t *testing.T) {
...
	// Act
	// We create our get request here
	req, err := MyGETRequest(endpoint)
	if err != nil {
		t.Errorf(err.Error())
	}
	// Here we bind the response recorder and request
	// to the hander. This essentially means req
	// will be sent to the handler, and rr will
	// record what the handler send back
	handler.ServeHTTP(rr, req)
}

Finally, we make our Assertions:

func TestMyGETRequest(t *testing.T) {
...
	// Assert
	// Our handler should respond with a StatusOK response
	// Here we make that assertion
	if status := rr.Code; status != http.StatusOK {
		t.Errorf("Wanted %d, got %d", http.StatusOK, status)
	}
}

Now that we're done with the test part, let's make the actual MyGETRequest function to pass it in requestTut.go:

package requestTut

import (
	"fmt"
	"net/http"
)

// This builds a new Get Request
// It will use the GET HTTP Method and the target
// is the endpoint parameter
func MyGETRequest(endpoint string) (*http.Request, error) {
	req, err := http.NewRequest(http.MethodGet, endpoint, nil)
	if err != nil {
		panic(err)
	}
	return req, nil
}

Clone this wiki locally