liveBook · Manning

Http.HandlerFunc

As explained in Go by Example

http.HandlerFunc is a Go function type that adapts a function with an HTTP handler signature to the http.Handler interface.

http.HandlerFunc is a Go function type that adapts a function with the HTTP handler signature to the http.Handler interface. The adapter lets a regular function or closure serve requests wherever an http.Handler is required. section 8.10 section 8.3.2

Its ServeHTTP method receives a ResponseWriter and Request, then calls the wrapped function. This preserves the simple function implementation while satisfying the interface expected by HTTP servers and test servers. section 8.3.2

Serve a function with ListenAndServe

A named Health function can be converted directly when starting a server: http.ListenAndServe("localhost:8080", http.HandlerFunc(Health)). The server calls Health for each incoming request through ServeHTTP. section 8.3.2

Create a closure-backed handler

A function such as Shorten can return http.HandlerFunc around a closure that uses injected dependencies. The closure processes the request, writes a response, and returns immediately after an error to prevent further side effects. section 8.4.1

Test with httptest.Server

Wrap a closure with http.HandlerFunc and pass it to httptest.NewServer. The server invokes the closure for incoming requests; use server.URL to address it and server.Close to release resources. section 7.6.1

How Go by Example covers it

How deep it goes
Defines the adapter and its delegating ServeHTTP method, then applies it to production and testing examples.
Examples
Uses Health serving, a dependency-injected Shorten closure, and an httptest.Server closure.
What it assumes
Assumes familiarity with Go functions, closures, interfaces, HTTP requests, and ResponseWriter; demonstrates the adapter relationship explicitly.
What you can do after
Build HTTP services and tests by converting functions or closures with http.HandlerFunc for ListenAndServe and httptest.NewServer.
How it connects
Connects http.Handler with httptest.Server, http.ListenAndServe, closures, dependency injection, and HTTP error handling.

Also explained in

Compare how 2 books explain http.HandlerFunc →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.