Skip to Content
Building RESTful Web services with Go
book

Building RESTful Web services with Go

by Naren Yellavula
December 2017
Intermediate to advanced
316 pages
6h 58m
English
Packt Publishing
Content preview from Building RESTful Web services with Go

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Hands-On RESTful Web Services with Go - Second Edition

Hands-On RESTful Web Services with Go - Second Edition

Naren Yellavula
Microservices with Go

Microservices with Go

Alexander Shuiskov

Publisher Resources

ISBN: 9781788294287Supplemental Content