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

ServeMux, a basic router in Go

ServeMux is an HTTP request multiplexer. The HandleFunc we used in the preceding section is actually a method of ServeMux. By creating a new ServeMux, we can handle multiple routes. Before that, we can also create our own multiplexer. A multiplexer just handles the logic of separating routes with a function called ServeHTTP. So if we create a new struct with the ServeHTTP method, it can do the job.

Consider a route as a key in a dictionary (map), then the handler as its value. The router finds the handler from the route and tries to execute the ServeHTTP function. Let us create a program called customMux.go and see this implementation in action:

package main
import (
"fmt"
"math/rand"
"net/http"
)
// CustomServeMux is a struct which can be a multiplexer
type CustomServeMux struct {
}
// This is the function handler to be overridden
func (p *CustomServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
giveRandom(w, r)
return
}
http.NotFound(w, r)
return
}
func giveRandom(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Your random number is: %f", rand.Float64())
}
func main() {
// Any struct that has serveHTTP function can be a multiplexer
mux := &CustomServeMux{}
http.ListenAndServe(":8000", mux)
}

In this code, we are creating a custom struct called CustomServeMuxwhich is going to take care of our routing. We implemented a function called ServeHTTP in order to capture the request and write a response back to it. The fmt package is usually used to create strings. Fprinf composes the string out of supplied parameters.

In the main function, we are creating an instance of our CustomServeMux and passing it to the ListenAndServe function on http. "math/rand" is the library that takes care of generating random numbers. This basic foundation is going to be helpful for us when we discuss adding authentication to our API server. 

主站蜘蛛池模板: 彩票| 阜新市| 射阳县| 凤翔县| 讷河市| 阆中市| 苏尼特右旗| 天气| 云霄县| 会泽县| 涞源县| 广丰县| 象州县| 绥德县| 贡嘎县| 东源县| 安化县| 汕头市| 南平市| 长兴县| 右玉县| 拜城县| 江津市| 永吉县| 龙井市| 扎兰屯市| 邵阳市| 云和县| 读书| 阿瓦提县| 盐亭县| 盱眙县| 任丘市| 吴堡县| 洪泽县| 平武县| 东城区| 宁阳县| 邳州市| 华蓥市| 巴林右旗|