December 2017
Intermediate to advanced
316 pages
6h 58m
English
The preceding custom Mux that we created can be cumbersome when we have different endpoints with different functionalities. To add that logic, we need to add many if/else conditions to manually check the URL route. We can instantiate a new ServeMux and define many handlers like this:
newMux := http.NewServeMux()newMux.HandleFunc("/randomFloat", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, rand.Float64())})newMux.HandleFunc("/randomInt", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, rand.Int(100))})
This code snippet shows how to create a ServerMux and attach multiple handlers to it. randomFloat and randomInt are the two routes we created for returning a random float ...