Go http.NewServerMux()
How to use http.NewServeMux in Go to create a custom request multiplexer with types that implement the http.Handler interface.
This program demonstrates how to create a custom HTTP request multiplexer using http.NewServeMux() instead of relying on the default mux. It defines two custom types (pageDog and pageCat) that each implement the http.Handler interface by providing a ServeHTTP method. The custom mux routes /dogs/ and /cats to their respective handlers.
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
mux := http.NewServeMux()
mux.Handle("/dogs/", dogs)
mux.Handle("/cats", cats)
http.ListenAndServe(":8080", mux)
}
This post is licensed under CC BY 4.0 by the author.