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 ) {
2017-02-11 14:51:16 +00:00
router . mu . Lock ( )
2017-01-03 07:47:31 +00:00
router . routes [ pattern ] = handle . ServeHTTP
2017-02-11 14:51:16 +00:00
router . mu . Unlock ( )
2017-01-03 07:47:31 +00:00
}
func ( router * Router ) HandleFunc ( pattern string , handle func ( http . ResponseWriter , * http . Request ) ) {
2017-02-11 14:51:16 +00:00
router . mu . Lock ( )
2017-01-03 07:47:31 +00:00
router . routes [ pattern ] = handle
2017-02-11 14:51:16 +00:00
router . mu . Unlock ( )
2017-01-03 07:47:31 +00:00
}
func ( router * Router ) ServeHTTP ( w http . ResponseWriter , req * http . Request ) {
router . mu . RLock ( )
2016-12-23 12:35:22 +00:00
2017-01-03 07:47:31 +00:00
if req . URL . Path [ 0 ] != '/' {
2017-02-11 14:51:16 +00:00
router . mu . RUnlock ( )
2017-01-03 07:47:31 +00:00
w . WriteHeader ( 405 )
w . Write ( [ ] byte ( "" ) )
return
2016-12-23 12:35:22 +00:00
}
2017-02-11 14:51:16 +00:00
// Do something on the path to turn slashes facing the wrong way "\" into "/" slashes. Like what? Wouldn't that be slow? Might need to move to fasthttp for this
2016-12-23 12:35:22 +00:00
2017-01-03 07:47:31 +00:00
handle , ok := router . routes [ req . URL . Path ]
if ok {
2017-02-11 14:51:16 +00:00
router . mu . RUnlock ( )
2017-01-03 07:47:31 +00:00
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-11 14:51:16 +00:00
router . mu . RUnlock ( )
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 {
2017-02-11 14:51:16 +00:00
router . mu . RUnlock ( )
2017-01-03 07:47:31 +00:00
handle ( w , req )
return
}
//fmt.Println(req.URL.Path[:strings.LastIndexByte(req.URL.Path,'/')])
handle , ok = router . routes [ req . URL . Path + "/" ]
if ok {
2017-02-11 14:51:16 +00:00
router . mu . RUnlock ( )
2017-01-03 07:47:31 +00:00
handle ( w , req )
return
}
2017-02-11 14:51:16 +00:00
router . mu . RUnlock ( )
2017-02-05 16:36:54 +00:00
NotFound ( w , req )
2017-01-03 07:47:31 +00:00
return
}