- Building RESTful Web services with Go
- Naren Yellavula
- 186字
- 2021-07-02 20:14:08
Adding multiple handlers using ServeMux
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 and random int, respectively. Now we can pass this to the ListenAndServe function. Intn(100) returns a random integer number from the range 0-100. For more details on random functions, visit the Go random package page at http://golang.org.
http.ListenAndServe(":8000", newMux)
The complete code looks like this:
package main
import (
"fmt"
"math/rand"
"net/http"
)
func main() {
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.Intn(100))
})
http.ListenAndServe(":8000", newMux)
}