How to Test HTTP Handlers in Go with httptest

Web
Test Go HTTP handlers instantly using httptest.NewRequest and httptest.NewRecorder to mock requests and capture responses.

Use net/http/httptest to create a mock server and client that execute your handler without starting a real network listener.

package main

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

func TestHandler(t *testing.T) {
	req := httptest.NewRequest("GET", "/", nil)
	rr := httptest.NewRecorder()
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("OK"))
	})
	handler.ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)
	}
}