-
Notifications
You must be signed in to change notification settings - Fork 67
/
handler.go
78 lines (67 loc) · 2.48 KB
/
handler.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
package handler
import (
"fmt"
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/render"
"github.com/moira-alert/moira/metric_source"
"github.com/rs/cors"
"github.com/moira-alert/moira"
"github.com/moira-alert/moira/api"
moiramiddle "github.com/moira-alert/moira/api/middleware"
)
var database moira.Database
var searchIndex moira.Searcher
const contactKey moiramiddle.ContextKey = "contact"
const subscriptionKey moiramiddle.ContextKey = "subscription"
// NewHandler creates new api handler request uris based on github.com/go-chi/chi
func NewHandler(db moira.Database, log moira.Logger, index moira.Searcher, config *api.Config, metricSourceProvider *metricSource.SourceProvider, configFile []byte) http.Handler {
database = db
searchIndex = index
router := chi.NewRouter()
router.Use(render.SetContentType(render.ContentTypeJSON))
router.Use(moiramiddle.UserContext)
router.Use(moiramiddle.RequestLogger(log))
router.Use(middleware.NoCache)
router.NotFound(notFoundHandler)
router.MethodNotAllowed(methodNotAllowedHandler)
router.Route("/api", func(router chi.Router) {
router.Use(moiramiddle.DatabaseContext(database))
router.Get("/config", webConfig(configFile))
router.Route("/user", user)
router.Route("/trigger", triggers(metricSourceProvider, searchIndex))
router.Route("/tag", tag)
router.Route("/pattern", pattern)
router.Route("/event", event)
router.Route("/contact", contact)
router.Route("/subscription", subscription)
router.Route("/notification", notification)
router.Route("/health", health)
})
if config.EnableCORS {
return cors.AllowAll().Handler(router)
}
return router
}
func webConfig(content []byte) http.HandlerFunc {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
if content == nil {
render.Render(writer, request, api.ErrorInternalServer(fmt.Errorf("web config file was not loaded")))
return
}
writer.Header().Set("Content-Type", "application/json")
writer.Write(content)
})
}
func notFoundHandler(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("X-Content-Type-Options", "nosniff")
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(404)
render.Render(writer, request, api.ErrNotFound)
}
func methodNotAllowedHandler(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(405)
render.Render(writer, request, api.ErrMethodNotAllowed)
}