forked from owenthereal/gundam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
68 lines (53 loc) · 1.28 KB
/
api.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
package main
import (
"net/http"
"regexp"
"strconv"
"github.com/codegangsta/martini"
)
func NewApi(sphero Sphero) Api {
return &ApiMartini{sphero}
}
type Api interface {
Handler() http.Handler
}
type ApiPlain struct {
S Sphero
}
func (a *ApiPlain) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
rgbRegexp := regexp.MustCompile(`/rgb/(\d+),(\d+),(\d+)`)
path := req.URL.Path
if req.Method == "PUT" && rgbRegexp.MatchString(path) {
match := rgbRegexp.FindStringSubmatch(path)
setRGB(a.S, match[1], match[2], match[3])
resp.WriteHeader(201)
} else {
http.NotFound(resp, req)
}
}
func (a *ApiPlain) Handler() http.Handler {
return a
}
type ApiMartini struct {
S Sphero
}
func (a *ApiMartini) Handler() http.Handler {
m := martini.Classic()
m.Put("/rgb/:rgb", func(params martini.Params) (int, string) {
rgb := params["rgb"]
rgbRegexp := regexp.MustCompile(`^(\d+),(\d+),(\d+)$`)
if !rgbRegexp.MatchString(params["rgb"]) {
return 400, "Invalid format of rgb"
}
match := rgbRegexp.FindStringSubmatch(rgb)
setRGB(a.S, match[1], match[2], match[3])
return 201, "ok"
})
return m
}
func setRGB(s Sphero, r, g, b string) {
rr, _ := strconv.Atoi(r)
gg, _ := strconv.Atoi(g)
bb, _ := strconv.Atoi(b)
s.SetRGB((uint8)(rr), (uint8)(gg), (uint8)(bb))
}