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 {
mu 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 ) {
router . routes [ pattern ] = handle . ServeHTTP
}
func ( router * Router ) HandleFunc ( pattern string , handle func ( http . ResponseWriter , * http . Request ) ) {
router . routes [ pattern ] = handle
}
func ( router * Router ) ServeHTTP ( w http . ResponseWriter , req * http . Request ) {
router . mu . RLock ( )
defer router . mu . RUnlock ( )
2016-12-23 12:35:22 +00:00
2017-01-03 07:47:31 +00:00
if req . URL . Path [ 0 ] != '/' {
w . WriteHeader ( 405 )
w . Write ( [ ] byte ( "" ) )
return
2016-12-23 12:35:22 +00:00
}
// Do something on the path to turn slashes facing the wrong way "\" into "/" slashes. If it's bytes, then alter the bytes in place for the maximum speed
2017-01-03 07:47:31 +00:00
handle , ok := router . routes [ req . URL . Path ]
if ok {
handle ( w , req )
return
2016-12-23 12:35:22 +00:00
}
2017-01-03 07:47:31 +00:00
if req . URL . Path [ len ( req . URL . Path ) - 1 ] == '/' {
2017-02-05 16:36:54 +00:00
NotFound ( w , req )
2017-01-03 07:47:31 +00:00
return
}
handle , ok = router . routes [ req . URL . Path [ : strings . LastIndexByte ( req . URL . Path , '/' ) + 1 ] ]
if ok {
handle ( w , req )
return
}
//fmt.Println(req.URL.Path[:strings.LastIndexByte(req.URL.Path,'/')])
handle , ok = router . routes [ req . URL . Path + "/" ]
if ok {
handle ( w , req )
return
}
2017-02-05 16:36:54 +00:00
NotFound ( w , req )
2017-01-03 07:47:31 +00:00
return
}