package main
import (
"fmt"
"net/http"
"regexp"
"strings"
)
type pathResolver struct {
handers map[string]http.HandlerFunc
cache map[string]*regexp.Regexp
}
func newPathResolver() *pathResolver {
return &pathResolver{make(map[string]http.HandlerFunc),
make(map[string]*regexp.Regexp)}
}
func (p *pathResolver) Add(path string, handler http.HandlerFunc) {
p.handers[path] = handler
cache, _ := regexp.Compile(path)
p.cache[path] = cache
}
func (p *pathResolver) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
check := request.Method + " " + request.URL.Path
for pattern, handlerFun := range p.handers {
if p.cache[pattern].MatchString(check) == true {
handlerFun(writer, request)
return
}
}
http.NotFound(writer, request)
}
func hello(writer http.ResponseWriter, request *http.Request) {
query := request.URL.Query()
name := query.Get("name")
if name == "" {
name = "WMJ"
}
fmt.Fprint(writer, "Hello, my name is ", name)
}
func goodbye(writer http.ResponseWriter, request *http.Request) {
path := request.URL.Path
parts := strings.Split(path, "/")
name := ""
if len(parts) > 2 {
name = parts[2]
}
if name == "" {
name = "WMJ"
}
fmt.Fprint(writer, "Goodby ", name)
}
func main() {
pr := newPathResolver()
pr.Add("GET /hello", hello)
pr.Add("(GET|HEAD) /goodbye(/?[A-Za-z0-9]*)?", goodbye)
http.ListenAndServe(":8080", pr)
}
go语言web服务器URL路由正则匹配
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 知识点: 1)装饰器特点: 只要整个模块被导入服务器,装饰器就会立马执行,只要一执行,字典里就有东西了,后面就可以...
- 上一节我们介绍了搭建一个Web服务器需要了解的基础知识,本节我们来看看怎么用Go语言搭建一个Web服务器,Go语...
- 最近用ios开发一个简单的app,先写一个简单的接口,简单人做简单事。之前看过java,被各种框架绕得不行,后来看...
- 请从github下载配套代码: https://github.com/shuningzhang/learn_gol...