-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
101 lines (82 loc) · 1.88 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
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
package gifttt
import (
"encoding/json"
"net/http"
"github.com/drtoful/gifttt/Godeps/_workspace/src/github.com/codegangsta/negroni"
"github.com/drtoful/gifttt/Godeps/_workspace/src/github.com/gorilla/mux"
)
type APIServer struct {
ip, port string
handler *negroni.Negroni
}
var (
internalVars = []string{
"time:second",
"time:minute",
"time:hour",
"date:day",
"date:month",
"date:year",
}
)
func postVar(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
vars := mux.Vars(r)
varname := vars["var"]
for _, c := range internalVars {
if c == varname {
w.WriteHeader(http.StatusForbidden)
return
}
}
var value Value
if err := json.NewDecoder(r.Body).Decode(&value); err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
vm := GetManager()
if err := vm.Set(varname, value.Value); err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(http.StatusOK)
}
func getVar(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
varname := vars["var"]
vm := GetManager()
v, err := vm.Get(varname)
if err != nil {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(err.Error()))
return
}
val := &Value{Value: v}
b, err := json.Marshal(val)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(http.StatusOK)
w.Write(b)
}
func NewAPIServer(ip, port string) *APIServer {
router := mux.NewRouter()
api := router.PathPrefix("/v").Subrouter()
api = api.StrictSlash(true)
api.Path("/{var}").Methods("POST").HandlerFunc(postVar)
api.Path("/{var}").Methods("GET").HandlerFunc(getVar)
n := negroni.New(negroni.NewRecovery())
n.UseHandler(router)
return &APIServer{
ip: ip,
port: port,
handler: n,
}
}
func (a *APIServer) Run() {
a.handler.Run(a.ip + ":" + a.port)
}