Post

Go using DefaultMux with nil

Using Go's DefaultServeMux by passing nil to http.ListenAndServe and registering custom handler types with http.Handle.

This example demonstrates how to use Go’s DefaultServeMux by passing nil as the handler to http.ListenAndServe. Two custom types (pageDog and pageCat) implement the http.Handler interface via the ServeHTTP method. These handlers are registered with http.Handle on the default mux, which routes requests based on URL path patterns.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package main

import (
	"io"
	"net/http"
)

type pageDog int

func (pd pageDog) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "This is the web about dogs!\n")
}

type pageCat []string

func (pc pageCat) ServeHTTP(w http.ResponseWriter, r *http.Request)  {
	io.WriteString(w, "This is the web about cats!\n")
}

func main() {

	var dogs pageDog
	var cats pageCat

	http.Handle("/dogs/", dogs)
	http.Handle("/cats", cats)

	http.ListenAndServe(":8080", nil)

}

This post is licensed under CC BY 4.0 by the author.