12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- 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")
- }
- }
- }
|