-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.go
86 lines (69 loc) · 1.59 KB
/
routes.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package routes
import (
"go-graphql-mongo-server/auth"
"go-graphql-mongo-server/gqlhandler"
"net/http"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
type Route struct {
Method string
Pattern string
Handler http.HandlerFunc
Middleware []mux.MiddlewareFunc
}
var routes []Route
func initializeRoutes() {
createLimiterMiddleware()
setAllRoutes()
}
func registerAPIRoute(method, pattern string, handler http.HandlerFunc, middleware []mux.MiddlewareFunc) {
pattern = "/api" + pattern
registerCommonRoute(method, pattern, handler, middleware)
}
func registerCommonRoute(method, pattern string, handler http.HandlerFunc, middleware []mux.MiddlewareFunc) {
routes = append(routes, Route{method, pattern, handler, middleware}, Route{"OPTIONS", pattern, handler, middleware})
}
func setAllRoutes() {
registerAPIRoute(
"POST",
"/graphql",
gqlhandler.GraphqlHandler,
[]mux.MiddlewareFunc{
limiterMiddleware.Handle,
auth.Middleware,
})
registerAPIRoute(
"GET",
"/graphiql",
gqlhandler.GraphiqlHandler,
nil,
)
registerCommonRoute(
"GET",
"/metrics",
promhttp.Handler().ServeHTTP,
nil,
)
registerCommonRoute(
"GET",
"/health",
healthCheckHandler,
nil,
)
}
func NewRouter() (router *mux.Router) {
initializeRoutes()
router = mux.NewRouter()
for _, route := range routes {
r := router.
Methods(route.Method).
Path(route.Pattern)
var handler http.Handler = route.Handler
for i := len(route.Middleware) - 1; i >= 0; i-- {
handler = route.Middleware[i](handler)
}
r.Handler(handler)
}
return
}