go语言web服务器URL路由正则匹配

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路由正则匹配)