我就直接上代码了:
main.go
package main
import (
"fmt"
"net/http"
"regexp"
)
type Router struct {
routes []*Route
}
type Route struct {
pattern *regexp.Regexp
handler http.HandlerFunc
}
func (r *Router) HandleFunc(pattern string, handler http.HandlerFunc) {
route := &Route{
pattern: regexp.MustCompile(pattern),
handler: handler,
}
r.routes = append(r.routes, route)
}
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
for _, route := range r.routes {
if route.pattern.MatchString(req.URL.Path) {
route.handler(w, req)
return
}
}
http.NotFound(w, req)
}
func main() {
router := &Router{}
router.HandleFunc("^/$", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Hello, world!")
})
router.HandleFunc("^/users/([0-9]+)$", func(w http.ResponseWriter, req *http.Request) {
matches := router.routes[1].pattern.FindStringSubmatch(req.URL.Path)
fmt.Fprintf(w, "User ID: %s", matches[1])
})
http.ListenAndServe(":8080", router)
}
运行:
go run .