官术网_书友最值得收藏!

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)
}
主站蜘蛛池模板: 壶关县| 靖宇县| 营口市| 方正县| 郯城县| 岗巴县| 沙洋县| 龙南县| 万源市| 木里| 樟树市| 宜宾县| 同仁县| 南涧| 阿鲁科尔沁旗| 光泽县| 湟中县| 安图县| 奉新县| 浏阳市| 大厂| 南涧| 若羌县| 玉溪市| 襄垣县| 大渡口区| 永丰县| 南乐县| 平武县| 伊宁县| 涪陵区| 霍林郭勒市| 星子县| 肥城市| 湘西| 龙江县| 道孚县| 包头市| 汝阳县| 黄骅市| 西华县|