-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
75 lines (57 loc) · 1.27 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
)
func main() {
log.Printf("Starting on port 8081")
http.Handle("/memory", handler(decodeMemory))
http.Handle("/stream", handler(decodeStream))
log.Fatal(http.ListenAndServe(":8081", nil))
}
type handler func(http.ResponseWriter, *http.Request) error
func (fn handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := fn(w, r); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func decodeMemory(w http.ResponseWriter, r *http.Request) error {
decoder := json.NewDecoder(r.Body)
var action struct {
Results []struct {
DeviceName string `json:"device_name"`
} `json:"results"`
}
if err := decoder.Decode(&action); err != nil {
return err
}
w.WriteHeader(200)
for _, r := range action.Results {
fmt.Fprint(w, "%s <br />", r.DeviceName)
}
return nil
}
func decodeStream(w http.ResponseWriter, r *http.Request) error {
decoder := json.NewDecoder(r.Body)
w.WriteHeader(200)
for {
token, err := decoder.Token()
if err == io.EOF {
break
}
if err != nil {
return err
}
if token == "device_name" {
name, errName := decoder.Token()
if errName != nil {
return err
}
fmt.Fprint(w, "%s <br />", name)
}
}
return nil
}