Skip to content

Go Test Httptest Server

DodaTech 1 min read

In this tutorial, you'll learn about Go Test: httptest.Server. We cover key concepts, practical examples, and best practices.

httptest.Server -- Use httptest.NewServer to create test HTTP servers for integration testing handlers.

The Problem

httptest.NewServer starts a real HTTP server on a random port. Use it to test HTTP clients, middleware, and handlers end-to-end.

Wrong

func TestHandler(t *testing.T) {
    handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("OK"))
    })
    // How to test handler? Manual http.ListenAndServe?

Output:

// Complex setup without httptest
func TestHandler(t *testing.T) {
    handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("OK"))
    })
    server := httptest.NewServer(handler)
    defer server.Close()
    resp, _ := http.Get(server.URL)
    body, _ := io.ReadAll(resp.Body)
    resp.Body.Close()
    if string(body) != "OK" {
        t.Errorf("got %s, want OK", body)
    }
}

Output:

// Test passes. Server auto-assigns port.

Prevention

  • httptest.NewServer creates real HTTP server
  • Use server.URL for the listening address
  • HTTPS version: httptest.NewTLSServer
  • Server closes on Close() call
  • Use t.Cleanup(server.Close) for safe teardown

Common Mistakes with test httptest server

  1. Using foldl instead of foldl' causing stack overflow on large lists
  2. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  3. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**What port does httptest use?**

Random available port. No conflicts with parallel tests.

Can I test TLS?

Yes. httptest.NewTLSServer for HTTPS.

How to test client-side timeouts?

Use httptest.NewServer with slow handler + context timeout.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro