package main import ( "net/http" "net/http/httptest" "testing" ) func helloWorld(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("Hello World!")) } func TestHelloWorldHandler(t *testing.T) { req, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } recorder := httptest.NewRecorder() handler := http.HandlerFunc(helloWorld) handler.ServeHTTP(recorder, req) if status := recorder.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } expected := "Hello World!" if recorder.Body.String() != expected { t.Errorf("handler returned unexpected body: got %v want %v", recorder.Body.String(), expected) } }
package main import ( "io/ioutil" "net/http" "net/http/httptest" "testing" ) func TestHTTPClient(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("Hello World!")) })) defer ts.Close() res, err := http.Get(ts.URL) if err != nil { t.Fatal(err) } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { t.Fatal(err) } expected := "Hello World!" if string(body) != expected { t.Errorf("handler returned unexpected body: got %v want %v", string(body), expected) } }This example creates an HTTP client using the http.Get method to send a GET request to an httptest server. The httptest.NewServer creates a new in-memory HTTP server using a HandlerFunc that returns "Hello World!" message. The http.Get method sends the GET request to the server and receives the response. The expected response is checked using the test function.