-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
92 lines (74 loc) · 1.59 KB
/
server.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
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"github.com/aws/aws-sdk-go/service/rekognition"
"github.com/gorilla/websocket"
)
const (
address = ":3000"
staticDir = "static"
)
var face *FaceDetector
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
type Response struct {
FaceDetails []*rekognition.FaceDetail
Command string
}
func websocketHandler(w http.ResponseWriter, r *http.Request) {
// upgrade HTTP connection:
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("upgrade:", err)
return
}
defer conn.Close()
state := FaceState{}
for {
mt, image, err := conn.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
if mt != websocket.BinaryMessage {
log.Println("read expected a binary message")
break
}
faces, err := face.DetectFaces(image)
if err != nil {
log.Println("rekognition:", err)
break
}
cmd := state.AnalyzeFaces(faces.FaceDetails)
resp := Response{
FaceDetails: faces.FaceDetails,
Command: cmd,
}
msg, err := json.Marshal(resp)
if err != nil {
log.Println("marshal:", err)
break
}
// log.Printf("%s\n", msg)
err = conn.WriteMessage(websocket.TextMessage, msg)
if err != nil {
log.Println("write:", err)
break
}
}
}
func main() {
log.SetFlags(0)
_, fakeAPI := os.LookupEnv("FAKE_API")
face = NewFaceDetector(fakeAPI)
fs := http.FileServer(http.Dir(staticDir))
http.Handle("/", fs)
http.HandleFunc("/socket", websocketHandler)
log.Printf("Listening at %v...\n", address)
http.ListenAndServe(address, nil)
}