router.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package main
  2. import (
  3. "github.com/gorilla/mux"
  4. "github.com/rs/cors"
  5. "net/http"
  6. "rate-it-api/controllers"
  7. "strings"
  8. )
  9. // APIRouter handle routes
  10. func APIRouter() *mux.Router {
  11. router := mux.NewRouter().StrictSlash(true)
  12. c := cors.New(cors.Options{
  13. AllowedOrigins: []string{"*"},
  14. AllowCredentials: true,
  15. AllowedHeaders: strings.Split("Access-Control-Allow-Methods,Access-Control-Allow-Origin,Content-Type", ","),
  16. ExposedHeaders: strings.Split("*", ","),
  17. OptionsPassthrough: true,
  18. Debug: false,
  19. })
  20. for _, route := range routes {
  21. var handler http.Handler
  22. handler = route.HandlerFunc
  23. handler = Logger(handler, route.Name)
  24. handler = c.Handler(handler)
  25. // route.Method += ",OPTIONS"
  26. router.
  27. Methods(strings.Split(route.Method, ",")...).
  28. Path(route.Pattern).
  29. Name(route.Name).
  30. Handler(handler)
  31. }
  32. for _, route := range routesJwt {
  33. var handler http.Handler
  34. handler = route.HandlerFunc
  35. handler = cors.Default().Handler(handler)
  36. handler = Logger(handler, route.Name)
  37. handler = controllers.JwtMiddleware.Handler(handler)
  38. route.Method += ",OPTIONS"
  39. router.
  40. Methods(strings.Split(route.Method, ",")...).
  41. Path(route.Pattern).
  42. Name(route.Name).
  43. Handler(handler)
  44. }
  45. return router
  46. }