Adding multiple handlers using ServeMux

Let us say we have an API requirement that generates random numbers of different types such as int, float, and so on. The custom multiplexer (mux) we developed can be cumbersome when there are multiple endpoints with different functionalities. To add that logic, we need to add multiple if/else conditions to manually check the URL route. To overcome that complex code structure, we can instantiate a new in-built ServeMux object and define many handlers. Let's look at the code with ServeMux:

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 ServeMux and attach multiple handlers to it.

randomFloat and randomInt are the two routes we create for returning a random float and random int, respectively. Now, we pass that to the ListenAndServe function. Int(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.

Let us see a complete example:

  1. Create a file to hold our program and call it multipleHandlers.go in the following path:
touch -p $GOPATH/src/github.com/git-user/chapter2/multipleHandlers/main.go
  1. Now create a main function and add the code for creating the ServeMux object and function handlers.
  2. Finally, run the server with the http.ListenAndServe method:
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)
}
  1. We can run the program directly using the run command:
go run $GOPATH/src/github.com/git-user/chapter2/multipleHandlers/main.go
  1.  Now, let us fire two curl commands and see the output:
curl -X GET http://localhost:8000/randomFloat
curl -X GET http://localhost:8000/randomInt

The responses will be:

0.6046602879796196
87

We saw how we can create a URL router with basic Go constructs. Let us have a look at a few popular URL routing frameworks that are widely used by the Go community for their API servers.