test a http server in go

To test a HTTP server in Go, you can create a new instance of httptest.Server which provides a mock HTTP server. This allows you to send requests to the server and verify the responses.

Here's an example of how you can use httptest.Server to test a simple HTTP server:

main.go
func TestServer(t *testing.T) {
    // create a new instance of the server you want to test
    server := NewMyServer()

    // create a new mock HTTP server
    mockServer := httptest.NewServer(server.Handler())

    defer mockServer.Close()

    // send a GET request to the mock server
    resp, err := http.Get(mockServer.URL + "/path/to/endpoint")

    if err != nil {
        t.Fatalf("Error sending request to server: %v", err)
    }

    // verify the response
    if resp.StatusCode != http.StatusOK {
        t.Errorf("Received unexpected status code %v", resp.StatusCode)
    }
}
591 chars
22 lines

In this example, NewMyServer() creates a new instance of the HTTP server you want to test. mockServer is a instance of httptest.Server that provides a mock server for testing purposes. We send a GET request to this mock server using the http.Get function and verify the response using standard Go testing assertions.

Remember to start your function with Test so that Go knows it's a test function.

gistlibby LogSnag