golang的http.HandleFunc使用正则匹配路由
由于只是写一个博客,自定义一个路由器没(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) }
原文地址:https://my.oschina.net/watcher/blog/758864
相关推荐
-
linux 最简单安装NIGNX 服务器
2019-8-29
-
MyCAT实现MySQL的读写分离 服务器
2019-3-21
-
Trafodion null 问题的源码级剖析 服务器
2020-6-22
-
为自己搭建一个分布式 IM(即时通讯) 系统 服务器
2020-6-21
-
MySQL约束条件 服务器
2019-8-15
-
一小时快速搭建基于阿里云容器服务-Kubernetes的Web应用 服务器
2020-6-24
-
亿级 ELK 日志平台构建实践 服务器
2019-9-10
-
Centos6安装配置Zookeeper 服务器
2019-3-15
-
vagrant安装和使用 服务器
2019-8-29
-
Nodejs Express 连接Mongodb 服务器
2019-3-22