routes.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package routes
  2. import (
  3. "fmt"
  4. "log"
  5. "net/http"
  6. "github.com/andreanidouglas/auth/model"
  7. )
  8. type Method string
  9. const (
  10. GET Method = "GET"
  11. POST Method = "POST"
  12. )
  13. type Route struct {
  14. Path string
  15. Handler http.HandlerFunc
  16. Authentication bool
  17. Method Method
  18. }
  19. type Routes struct {
  20. Pool model.Db
  21. logger *log.Logger
  22. Routes []Route
  23. }
  24. func New(log *log.Logger, db model.Db) Routes {
  25. return Routes{
  26. Pool: db,
  27. logger: log,
  28. Routes: make([]Route, 0, 5),
  29. }
  30. }
  31. func (r *Routes) RegisterRoute(path string, method Method, authenticated bool, handler func(http.ResponseWriter, *http.Request)) {
  32. if authenticated {
  33. handler = AuthMiddleware(handler)
  34. }
  35. switch method {
  36. case GET:
  37. {
  38. handler = r.Get(handler)
  39. }
  40. case POST:
  41. {
  42. handler = r.Post(handler)
  43. }
  44. }
  45. r.Routes = append(r.Routes, Route{
  46. Path: path,
  47. Authentication: authenticated,
  48. Method: method,
  49. Handler: handler,
  50. })
  51. }
  52. func (self *Routes) Post(next http.HandlerFunc) func(http.ResponseWriter, *http.Request) {
  53. return func(w http.ResponseWriter, r *http.Request) {
  54. if r.Method == "POST" {
  55. self.logger.Printf("[%s: %s]: 200 [POST]", r.RemoteAddr, r.RequestURI)
  56. next.ServeHTTP(w, r)
  57. } else {
  58. self.logger.Printf("[%s: %s]: 405 [Invalid method]", r.RemoteAddr, r.RequestURI)
  59. w.WriteHeader(405)
  60. fmt.Fprintln(w, "Invalid Method")
  61. }
  62. }
  63. }
  64. func (self *Routes) Get(next http.HandlerFunc) func(http.ResponseWriter, *http.Request) {
  65. return func(w http.ResponseWriter, r *http.Request) {
  66. if r.Method == "Get" {
  67. self.logger.Printf("[%s: %s]: 200 [GET]", r.RemoteAddr, r.RequestURI)
  68. next.ServeHTTP(w, r)
  69. } else {
  70. self.logger.Printf("[%s: %s]: 405 [Invalid method]", r.RemoteAddr, r.RequestURI)
  71. w.WriteHeader(405)
  72. fmt.Fprintln(w, "Invalid Method")
  73. }
  74. }
  75. }