-
Notifications
You must be signed in to change notification settings - Fork 35
/
routes.go
103 lines (90 loc) · 2.54 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package routes
import (
"encoding/json"
"html/template"
"net/http"
"strings"
"github.com/Sirupsen/logrus"
"github.com/elazarl/go-bindata-assetfs"
"github.com/gorilla/mux"
"github.com/klarna/eremetic/assets"
"github.com/klarna/eremetic/handler"
"github.com/klarna/eremetic/types"
"github.com/prometheus/client_golang/prometheus"
)
// Create is used to create a new router
func Create(scheduler types.Scheduler) *mux.Router {
routes := types.Routes{
types.Route{
Name: "AddTask",
Method: "POST",
Pattern: "/task",
Handler: handler.AddTask(scheduler),
},
types.Route{
Name: "Status",
Method: "GET",
Pattern: "/task/{taskId}",
Handler: handler.GetTaskInfo(scheduler),
},
types.Route{
Name: "ListRunningTasks",
Method: "GET",
Pattern: "/task",
Handler: handler.ListRunningTasks(scheduler),
},
}
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(prometheus.InstrumentHandler(route.Name, route.Handler))
}
router.
Methods("GET").
Path("/metrics").
Name("Metrics").
Handler(prometheus.Handler())
router.
Methods("GET").
Path("/").
Name("Index").
HandlerFunc(indexHandler)
router.PathPrefix("/static/").
Handler(
http.StripPrefix(
"/static/", http.FileServer(
&assetfs.AssetFS{Asset: assets.Asset, AssetDir: assets.AssetDir, AssetInfo: assets.AssetInfo, Prefix: "static"})))
router.NotFoundHandler = http.HandlerFunc(notFound)
return router
}
func notFound(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.Header.Get("Accept"), "text/html") {
src, _ := assets.Asset("templates/error_404.html")
tpl, err := template.New("404").Parse(string(src))
if err == nil {
tpl.Execute(w, nil)
return
}
logrus.WithError(err).WithField("template", "error_404.html").Error("Unable to load template")
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(nil)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.Header.Get("Accept"), "text/html") {
src, _ := assets.Asset("templates/index.html")
tpl, err := template.New("index").Parse(string(src))
if err == nil {
tpl.Execute(w, nil)
return
}
logrus.WithError(err).WithField("template", "index.html").Error("Unable to load template")
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusNoContent)
json.NewEncoder(w).Encode(nil)
}