2016-12-23 12:35:22 +00:00
|
|
|
package main
|
2017-01-03 07:47:31 +00:00
|
|
|
//import "fmt"
|
|
|
|
import "strings"
|
|
|
|
import "sync"
|
2016-12-23 12:35:22 +00:00
|
|
|
import "net/http"
|
|
|
|
|
|
|
|
type Router struct {
|
2017-04-12 13:39:03 +00:00
|
|
|
sync.RWMutex
|
2017-01-03 07:47:31 +00:00
|
|
|
routes map[string]func(http.ResponseWriter, *http.Request)
|
2016-12-23 12:35:22 +00:00
|
|
|
}
|
|
|
|
|
2017-01-03 07:47:31 +00:00
|
|
|
func NewRouter() *Router {
|
|
|
|
return &Router{
|
|
|
|
routes: make(map[string]func(http.ResponseWriter, *http.Request)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (router *Router) Handle(pattern string, handle http.Handler) {
|
2017-04-12 13:39:03 +00:00
|
|
|
router.Lock()
|
2017-01-03 07:47:31 +00:00
|
|
|
router.routes[pattern] = handle.ServeHTTP
|
2017-04-12 13:39:03 +00:00
|
|
|
router.Unlock()
|
2017-01-03 07:47:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (router *Router) HandleFunc(pattern string, handle func(http.ResponseWriter, *http.Request)) {
|
2017-04-12 13:39:03 +00:00
|
|
|
router.Lock()
|
2017-01-03 07:47:31 +00:00
|
|
|
router.routes[pattern] = handle
|
2017-04-12 13:39:03 +00:00
|
|
|
router.Unlock()
|
2017-01-03 07:47:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (router *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
|
|
|
if req.URL.Path[0] != '/' {
|
|
|
|
w.WriteHeader(405)
|
|
|
|
w.Write([]byte(""))
|
|
|
|
return
|
2016-12-23 12:35:22 +00:00
|
|
|
}
|
|
|
|
|
2017-04-12 10:10:36 +00:00
|
|
|
var /*extra_data, */prefix string
|
|
|
|
if req.URL.Path[len(req.URL.Path) - 1] != '/' {
|
|
|
|
//extra_data = req.URL.Path[strings.LastIndexByte(req.URL.Path,'/') + 1:]
|
|
|
|
prefix = req.URL.Path[:strings.LastIndexByte(req.URL.Path,'/') + 1]
|
|
|
|
} else {
|
|
|
|
prefix = req.URL.Path
|
2017-01-03 07:47:31 +00:00
|
|
|
}
|
|
|
|
|
2017-04-12 13:39:03 +00:00
|
|
|
router.RLock()
|
2017-04-12 10:10:36 +00:00
|
|
|
handle, ok := router.routes[prefix]
|
2017-05-02 17:24:33 +00:00
|
|
|
router.RUnlock()
|
|
|
|
|
2017-01-03 07:47:31 +00:00
|
|
|
if ok {
|
|
|
|
handle(w,req)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
//fmt.Println(req.URL.Path[:strings.LastIndexByte(req.URL.Path,'/')])
|
2017-02-05 16:36:54 +00:00
|
|
|
NotFound(w,req)
|
2017-04-12 10:10:36 +00:00
|
|
|
}
|