February 2020
Intermediate to advanced
404 pages
8h 42m
English
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) ...Read now
Unlock full access