-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathrouter.go
120 lines (104 loc) · 2.34 KB
/
router.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package backend
import (
"fmt"
"net/http"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/spf13/viper"
)
const (
// APIVersion defines the compatability version of the API and is appended to each API route
APIVersion = "1"
endpointFormat = "/api/v%s/%s"
)
// getEndpoint returns a properly formatted API endpoint
func getEndpoint(suffix string) string {
return fmt.Sprintf(endpointFormat, APIVersion, suffix)
}
// Route defines a route passed to our mux
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
// Routes holds a list of Routes
type Routes []Route
// all defined server endpoints
var routes = Routes{
// API endpoints
Route{
"Version",
"GET",
getEndpoint("version"),
handlerVersion,
},
Route{
"Refresh",
"POST",
getEndpoint("refresh"),
handlerRefresh,
},
Route{
"EnvAll",
"GET",
getEndpoint("env/{group:summary|details}"),
handlerEnvAll,
},
Route{
"EnvSingle",
"GET",
getEndpoint("env/{env-id}/{group:summary|details}"),
handlerEnvSingle,
},
Route{
"EnvPowerToggle",
"POST",
getEndpoint("env/{env-id}/{state:start|stop}"),
handlerEnvPowerToggle,
},
Route{
"InstancePowerToggle",
"POST",
getEndpoint("instance/{instance-id}/{state:start|stop}"),
handlerInstancePowerToggle,
},
Route{
"Config",
"GET",
getEndpoint("config"),
handlerConfig,
},
}
func newRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
// add compression support to handler if enabled
var handler http.Handler
handler = route.HandlerFunc
if viper.GetBool("server.compression") {
handler = handlers.CompressHandler(route.HandlerFunc)
}
// add routes to mux
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
}
// add route to mux to handle frontend UI static files (generated by npm)
staticPath := viper.GetString("server.static_files_dir")
if staticPath == "" {
staticPath = "./frondent/dist"
}
handlerStatic := http.StripPrefix("/", http.FileServer(http.Dir(staticPath)))
// add compression support to handler if enabled
if viper.GetBool("server.compression") {
handlerStatic = handlers.CompressHandler(handlerStatic)
}
router.
Methods("GET").
PathPrefix("/").
Handler(handlerStatic)
return router
}