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

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)
}
主站蜘蛛池模板: 湟源县| 瑞安市| 白玉县| 乐至县| 奉节县| 那坡县| 柞水县| 桑植县| 金阳县| 中超| 东源县| 日照市| 宜阳县| 德格县| 壤塘县| 资阳市| 达尔| 贵阳市| 新余市| 康保县| 九江市| 靖安县| 海城市| 仙桃市| 株洲县| 南汇区| 赞皇县| 娄底市| 普格县| 新平| 尚志市| 阿拉尔市| 青川县| 平泉县| 绩溪县| 文登市| 都昌县| 南汇区| 齐河县| 年辖:市辖区| 于都县|