-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.go
132 lines (111 loc) · 2.19 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/fatih/color"
"github.com/gorilla/mux"
)
// Logger function for http requests
func Logger(inner http.Handler, name string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
log.Printf(
"%s\t%s\t%s\t%s",
r.Method,
r.RequestURI,
name,
time.Since(start),
)
})
}
// Route holds inforamation about which action to perform for a given route.
// TODO: make local
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
// Routes hold information for all route elements.
// Therefore a Routes is a collection of Route structs
type Routes []Route
// Create a router for the http.ListenAndServe.
// The routes for the router come from the router collection below.
func NewRouter() *mux.Router {
if Debug {
fmt.Println("[Creating Router]")
}
router := mux.NewRouter()
for _, route := range routes {
var handler http.Handler
handler = route.HandlerFunc
handler = Logger(handler, route.Name)
if Debug {
fmt.Println("Endpoint: ", route.Name, route.Pattern)
}
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
}
// Add static file routing
router.PathPrefix("/").Handler(http.FileServer(http.Dir(Conf.HTMLPath)))
if Debug {
fmt.Println("[Creating Router]")
}
if Debug {
color.Green("[Router: OK]")
}
return router
}
var prefix = "/api"
var routes = Routes{
// Device based routes
Route{
"CreateDevice",
"CREATE",
prefix + "/device/add",
DeviceCreateHandler,
},
Route{
"DeleteDevice",
"DELETE",
prefix + "/device/delete",
DeviceDeleteHandler,
},
Route{
"ListDevices",
"GET",
prefix + "/devices/list",
DeviceListHandler,
},
Route{
"GetDevice",
"GET",
prefix + "/device/{deviceID}",
DeviceGetHandler,
},
Route{
"ControlDevice",
"POST",
prefix + "/device/{deviceID}",
DeviceControlHandler,
},
// Room based routes
Route{
"CreateRoom",
"POST",
prefix + "/rooms/add",
RoomCreateHandler,
},
Route{
"ListRooms",
"GET",
prefix + "/rooms/list",
RoomListHandler,
},
}