Standard library patterns · 3 MIN READ

http.Handler is one method, like Reader

Serve /hello from an in-memory request, with no listen.

Go's own "Writing Web Applications" tutorial and the Tour's "where to go next" both land on http.Handler. It is one method:

text
ServeHTTP(http.ResponseWriter, *http.Request)

http.HandlerFunc turns a function into that type. http.ServeMux is a Handler that dispatches to others. The sandbox has no network, so this lesson uses httptest: the types are real, the listen is not. A function that accepts http.Handler can be tested the same way in any Go module.

SEE THE IDEA

A handler can be exercised without opening a socket

  1. 01

    Request

    go
    httptest.NewRequest(...)

    Builds an in-memory request

  2. 02

    Recorder

    go
    httptest.NewRecorder()

    Captures status, headers and body

  3. 03

    Handler

    go
    handler.ServeHTTP(w, r)

    Writes status, headers and body into the recorder

The lesson tests real handler behavior with an in-memory transport.

In practice

Keep HTTP behavior separate from business logic so handler tests can check methods, paths and invalid input directly. Set headers and status before writing a body; the first Write otherwise commits status 200. In GopherForge’s Wasm sandbox, httptest is the supported way to exercise these routes.

Watch out

Passing an in-memory handler test does not claim that the Wasm program can bind a network socket.

Official reference ↗

Work through the exercise

go
package main

import "net/http"

// Hello answers GET /hello with "hi" and 404 for anything else.
func Hello() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
}

func main() {}
Try it yourself

Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.

Progress stays in this browser. No account needed.