Skip to content

Commit

Permalink
refactor(router): use mux instead to make it middleware friendly
Browse files Browse the repository at this point in the history
  • Loading branch information
adhocore committed Oct 3, 2020
1 parent 1e388a2 commit 0e25641
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions router/router.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
package router

import (
"github.com/adhocore/urlsh/middleware"
"net/http"

"github.com/adhocore/urlsh/controller"
)

type handler func(res http.ResponseWriter, req *http.Request)

var routes = map[string]handler{
var routes = map[string]http.HandlerFunc{
"GET /": controller.Index,
"POST /api/urls": controller.CreateShortUrl,
"GET /api/admin/urls": controller.ListUrl,
}

func locateHandler(route string) handler {
func locateHandler(route string) http.HandlerFunc {
handlerFunc, ok := routes[route]

if !ok {
Expand All @@ -24,10 +23,15 @@ func locateHandler(route string) handler {
return handlerFunc
}

func RegisterHandlers() {
http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
func RegisterHandlers() *http.ServeMux {
handler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
route := req.Method + " " + req.URL.Path

locateHandler(route)(res, req)
})

mux := http.NewServeMux()
mux.Handle("/", middleware.AdminAuth(handler))

return mux
}

0 comments on commit 0e25641

Please sign in to comment.