This repository has been archived by the owner on Aug 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
66 lines (52 loc) · 1.53 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
package apidCounters
import (
"encoding/json"
"net/http"
"strconv"
"github.com/apid/apid-core"
)
var countersBasePath string
func initAPI(services apid.Services) {
countersBasePath = config.GetString(configCountersBasePath)
services.API().HandleFunc(countersBasePath, returnCounters).Methods("GET")
services.API().HandleFunc(countersBasePath+"/{counter}", incrAndReturnCount).Methods("GET", "POST")
}
// called from GET or POST /counters/{counter}
// GET will just returns the counter, POST will also increment the counter
func incrAndReturnCount(w http.ResponseWriter, r *http.Request) {
log.Debugf("incr and return count request: %s", r.URL)
vars := apid.API().Vars(r)
id := vars["counter"]
// send event to increment counter
if r.Method == "POST" {
sendIncrementEvent(id)
}
count, err := getDBCounter(id)
if err != nil {
writeError(w, err)
return
}
w.Header().Add("Content-Type", "application/json")
w.Write([]byte(strconv.Itoa(count)))
}
// called from GET /counters, will return all counters
func returnCounters(w http.ResponseWriter, r *http.Request) {
log.Debugf("return counts request: %s", r.URL)
counters, err := getDBCounters()
if err != nil {
writeError(w, err)
return
}
body, err := json.Marshal(counters)
if err != nil {
writeError(w, err)
return
}
w.Header().Add("Content-Type", "application/json")
w.Write(body)
}
func writeError(w http.ResponseWriter, err error) {
log.Errorf("error handling API request: %s", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
}