moira

Форк
0
/
handler.go 
97 строк · 2.8 Кб
1
package handler
2

3
import (
4
	"fmt"
5
	"net/http"
6

7
	"github.com/go-chi/chi"
8
	"github.com/go-chi/chi/middleware"
9
	"github.com/go-chi/render"
10
	"github.com/rs/cors"
11

12
	"go.avito.ru/DO/moira"
13
	"go.avito.ru/DO/moira/api"
14
	moira_middle "go.avito.ru/DO/moira/api/middleware"
15
)
16

17
var database moira.Database
18
var triggerInheritanceDatabase moira.TriggerInheritanceDatabase
19
var superUsers = make(map[string]bool)
20

21
const contactKey moira_middle.ContextKey = "contact"
22
const subscriptionKey moira_middle.ContextKey = "subscription"
23

24
// NewHandler creates new api handler request uris based on github.com/go-chi/chi
25
func NewHandler(
26
	db moira.Database,
27
	triggerInheritanceDb moira.TriggerInheritanceDatabase,
28
	log moira.Logger,
29
	config *api.Config,
30
	configFileContent []byte,
31
	appVersion string,
32
) http.Handler {
33
	database = db
34
	triggerInheritanceDatabase = triggerInheritanceDb
35

36
	router := chi.NewRouter()
37
	router.Use(render.SetContentType(render.ContentTypeJSON))
38
	router.Use(moira_middle.UserContext)
39
	router.Use(moira_middle.RequestLogger(log))
40
	router.Use(moira_middle.AppVersion(appVersion))
41
	router.Use(middleware.NoCache)
42

43
	router.NotFound(notFoundHandler)
44
	router.MethodNotAllowed(methodNotAllowedHandler)
45

46
	router.Route("/api", func(router chi.Router) {
47
		router.Use(moira_middle.DatabaseContext(database))
48
		router.Use(moira_middle.ConfigContext(*config))
49
		router.Get("/config", webConfig(configFileContent))
50
		router.Route("/user", user)
51
		router.Route("/trigger", triggers)
52
		router.Route("/tag", tag)
53
		router.Route("/pattern", pattern)
54
		router.Route("/event", event)
55
		router.Route("/contact", contact)
56
		router.Route("/subscription", subscription)
57
		router.Route("/notification", notification)
58
		router.Route("/silent-pattern", silent)
59
		router.Route("/global-settings", globalSettings)
60
		router.Route("/stats/metrics", metricStats)
61
		router.Route("/maintenance", maintenance)
62
	})
63

64
	if config.EnableCORS {
65
		return cors.AllowAll().Handler(router)
66
	}
67

68
	for _, userLogin := range config.SuperUsers {
69
		superUsers[userLogin] = true
70
	}
71

72
	return router
73
}
74

75
func webConfig(content []byte) http.HandlerFunc {
76
	return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
77
		if content == nil {
78
			render.Render(writer, request, api.ErrorInternalServer(fmt.Errorf("Web config file was not loaded")))
79
			return
80
		}
81
		writer.Header().Set("Content-Type", "application/json")
82
		writer.Write(content)
83
	})
84
}
85

86
func notFoundHandler(writer http.ResponseWriter, request *http.Request) {
87
	writer.Header().Set("X-Content-Type-Options", "nosniff")
88
	writer.Header().Set("Content-Type", "application/json")
89
	writer.WriteHeader(404)
90
	render.Render(writer, request, api.ErrNotFound)
91
}
92

93
func methodNotAllowedHandler(writer http.ResponseWriter, request *http.Request) {
94
	writer.Header().Set("Content-Type", "application/json")
95
	writer.WriteHeader(405)
96
	render.Render(writer, request, api.ErrMethodNotAllowed)
97
}
98

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.