func TestMyHandler(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(MyHandler)) defer server.Close() // Perform HTTP requests against the server and test the responses }
func TestServerClose(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) // Perform HTTP requests against the server server.Close() _, err := http.Get(server.URL) if err == nil { t.Error("Expected error after server is closed.") } }In this example, a test is being written to ensure that the server is properly shut down when the `Close` method is called. A new `httptest.Server` is created with a simple handler that returns a 200 status code. After making some HTTP requests against the server, `server.Close()` is called. Then, another HTTP request is made against the server to verify that an error is returned because the server is closed.