- Building RESTful Web services with Go
- Naren Yellavula
- 321字
- 2021-07-02 20:14:07
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 CustomServeMux, which 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.
- 網絡協議工程
- EDA技術與VHDL編程
- C++黑客編程揭秘與防范
- Hands-On Full Stack Development with Spring Boot 2 and React(Second Edition)
- HCNA網絡技術
- WordPress Web Application Development
- 新手易學:新手學淘寶開店
- jQuery Mobile Web Development Essentials
- 紅藍攻防:構建實戰化網絡安全防御體系
- 一本書讀懂TCP/IP
- 物聯網的機遇與利用
- Getting Started with tmux
- 移動互聯網環境下的核心網剖析及演進
- 算力網絡:云網融合2.0時代的網絡架構與關鍵技術
- 萬物互聯:物聯網核心技術與安全