-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
39 lines (32 loc) · 728 Bytes
/
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
package lights
import (
"encoding/json"
"net/http"
"github.com/bmizerany/pat"
)
type Router struct {
lights map[string]*Light
m *pat.PatternServeMux
}
func NewRouter() *Router {
r := &Router{
lights: make(map[string]*Light),
m: pat.New(),
}
r.m.Get("/", http.HandlerFunc(r.listLightsHandler))
return r
}
func (r *Router) Add(l *Light) {
r.lights[l.Name()] = l
r.m.Get("/"+l.Name()+"/:action", l)
}
func (r *Router) listLightsHandler(w http.ResponseWriter, req *http.Request) {
var ret []string
for _, light := range r.lights {
ret = append(ret, light.Name())
}
json.NewEncoder(w).Encode(ret)
}
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
r.m.ServeHTTP(w, req)
}