liveBook · Manning

Http.HandleFunc

As explained in Learn Go with Pocket-Sized Projects

HandleFunc is a ServeMux method that registers a function as the handler for a specified HTTP pattern.

A ServeMux’s HandleFunc method registers a handler function for an HTTP pattern. The mux routes matching requests to that function and can itself be passed to http.ListenAndServe because it implements http.Handler. section 8.2.1 section 11.1.1

The method takes a pattern string and a function with the signature func(http.ResponseWriter, *http.Request). The handler can be an ordinary function or a method. Patterns can include an HTTP method, such as "POST /games" or "GET /". section 8.2.1 section 11.1.1

Register two routes

Save as main.go and run go run main.go: ```go package main import ( "io" "log" "net/http" ) func main() { mux := http.NewServeMux() mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { _, _ = io.WriteString(w, "Hello, world!") }) mux.HandleFunc("POST /games", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) _, _ = io.WriteString(w, "Creating a new game") }) log.Fatal(http.ListenAndServe(":8080", mux)) } ``` Try curl -v localhost:8080/ and curl -v -X POST localhost:8080/games. The POST handler sets 201 before writing the response body; writing the body first would send the default 200 status. section 8.2.1 section 11.1.1

Listing 11.3 server.go: Server struct
// Server serves all the HTML routes on this service.
type Server struct {} #1

func New() *Server... #2

// Router returns an HTTP handler that listens to all the proper paths.
func (s *Server) Router() http.Handler {
    r := http.NewServeMux() #3

    // Register each endpoint.
    r.HandleFunc(http.MethodGet+" "+"/", s.index) #4

    return r
}

A Server method can be registered directly as the handler for a method-qualified route. section 11.1.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains the function signature and router construction, then implements handlers and tests their responses.
Examples
Uses a POST game-creation endpoint and a GET index page, with curl requests and handler tests.
What you can do after
Apply it via Go’s net/http package to register routes and serve them with ListenAndServe.
How it connects
Connects ServeMux routing with the Handler interface, HandlerFunc, and HTTP methods.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.