由于只是写一个博客,自定义一个路由器没(wo
)有(hai)必(bu)要(hui),实现一个简单的路由即可
package router
import (
"net/http"
"zhfblog/controller"
"regexp"
"fmt"
)
// 路由定义
type routeInfo struct {
pattern string // 正则表达式
f func(w http.ResponseWriter, r *http.Request) //Controller函数
}
// 路由添加
var routePath = []routeInfo{
routeInfo{"^/a/$", controller.Index},
}
// 使用正则路由转发
func Route(w http.ResponseWriter, r *http.Request) {
isFound := false
for _, p := range routePath {
// 这里循环匹配Path,先添加的先匹配
reg, err := regexp.Compile(p.pattern)
if err != nil {
continue
}
if reg.MatchString(r.URL.Path) {
isFound = true
p.f(w, r)
}
}
if !isFound {
// 未匹配到路由
fmt.Fprint(w, "404 Page Not Found!")
}
}
func init() {
// 使用"/"匹配所有路由到自定义的正则路由函数Route
// 只需在main包导入该路由包即可
// import _ "zhfblog/router"
http.HandleFunc("/", Route)
}