package routes import ( "fmt" "log" "net/http" "github.com/andreanidouglas/auth/model" ) type Method string const ( GET Method = "GET" POST Method = "POST" ) type Route struct { Path string Handler http.HandlerFunc Authentication bool Method Method } type Routes struct { Pool model.Db logger *log.Logger Routes []Route } func New(log *log.Logger, db model.Db) Routes { return Routes{ Pool: db, logger: log, Routes: make([]Route, 0, 5), } } func (r *Routes) RegisterRoute(path string, method Method, authenticated bool, handler func(http.ResponseWriter, *http.Request)) { if authenticated { handler = AuthMiddleware(handler) } switch method { case GET: { handler = r.Get(handler) } case POST: { handler = r.Post(handler) } } r.Routes = append(r.Routes, Route{ Path: path, Authentication: authenticated, Method: method, Handler: handler, }) } func (self *Routes) Post(next http.HandlerFunc) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { self.logger.Printf("[%s: %s]: 200 [POST]", r.RemoteAddr, r.RequestURI) next.ServeHTTP(w, r) } else { self.logger.Printf("[%s: %s]: 405 [Invalid method]", r.RemoteAddr, r.RequestURI) w.WriteHeader(405) fmt.Fprintln(w, "Invalid Method") } } } func (self *Routes) Get(next http.HandlerFunc) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { if r.Method == "Get" { self.logger.Printf("[%s: %s]: 200 [GET]", r.RemoteAddr, r.RequestURI) next.ServeHTTP(w, r) } else { self.logger.Printf("[%s: %s]: 405 [Invalid method]", r.RemoteAddr, r.RequestURI) w.WriteHeader(405) fmt.Fprintln(w, "Invalid Method") } } }