- Hands-On RESTful Web Services with Go
- Naren Yellavula
- 340字
- 2021-06-24 17:04:25
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.
Let us see a complete example:
- 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
- Now create a main function and add the code for creating the ServeMux object and function handlers.
- 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)
}
- We can run the program directly using the run command:
go run $GOPATH/src/github.com/git-user/chapter2/multipleHandlers/main.go
- 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.
- 微信公眾平臺與小程序開發:從零搭建整套系統
- Mastering OpenCV Android Application Programming
- 軟件界面交互設計基礎
- Visual Basic編程:從基礎到實踐(第2版)
- 深入理解Java7:核心技術與最佳實踐
- 網店設計看這本就夠了
- 名師講壇:Java微服務架構實戰(SpringBoot+SpringCloud+Docker+RabbitMQ)
- 軟件測試技術指南
- 移動界面(Web/App)Photoshop UI設計十全大補
- Nginx Lua開發實戰
- 常用工具軟件立體化教程(微課版)
- 深入淺出Go語言編程
- 30天學通C#項目案例開發
- Android應用程序設計
- C語言程序設計實驗指導