-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
180 lines (157 loc) · 4.62 KB
/
server.go
File metadata and controls
180 lines (157 loc) · 4.62 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package main
import (
"bytes"
"context"
"log"
"mime/multipart"
"net/http"
"net/textproto"
"path"
"strconv"
"sync"
"text/template"
"time"
)
type FrameClient struct {
li chan *bytes.Buffer
}
type route struct {
Path string
Description string
handler http.HandlerFunc
}
type RouteTable struct {
Routes []route
}
type IndexInfo struct {
RouteTable
Version string
}
// HandleRoot simple http handler to render our index.html sitemap
func (rt *RouteTable) HandleRoot(w http.ResponseWriter, r *http.Request) {
ii := IndexInfo{}
ii.Routes = rt.Routes
ii.Version = Version
t, err := template.ParseFiles("./templates/index.html")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Println(err)
return
}
if err := t.Execute(w, ii); err != nil {
log.Println(err)
}
}
// HandleStream returns a stream of jpeg frames
func (fc *FrameClient) HandleStream(w http.ResponseWriter, r *http.Request) {
// Remove stale image
<-fc.li
const boundary = `frame`
w.Header().Set("Content-Type", `multipart/x-mixed-replace;boundary=`+boundary)
multipartWriter := multipart.NewWriter(w)
multipartWriter.SetBoundary(boundary)
for {
img := <-fc.li
image := img.Bytes()
iw, err := multipartWriter.CreatePart(textproto.MIMEHeader{
"Content-type": []string{"image/jpeg"},
"Content-length": []string{strconv.Itoa(len(image))},
})
if err != nil {
log.Println(err)
return
}
_, err = iw.Write(image)
if err != nil {
log.Println(err)
return
}
}
}
// HandleSnapshot returns a single jpeg frame
func (fc *FrameClient) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
// Remove stale image
<-fc.li
img := <-fc.li
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "image/jpeg")
if _, err := w.Write(img.Bytes()); err != nil {
log.Println(err)
return
}
}
// ServeHttp start the http server
func ServeHttp(ctx context.Context, errCh chan error, wg *sync.WaitGroup, port string, li chan *bytes.Buffer) {
// This is guaranteed to run as the last thing before this function returns
defer wg.Done()
log.Printf("Starting http server on port %s", port)
fc := FrameClient{
li: li,
}
/*
Register some routes with our global routes table. This is just a neat way to
update our index.html without modifying the template, so it generates the
sitemap at runtime. I added this because I wanted a way for index.html to
automatically add new routes to the sitemap without me having to edit anything.
Structure is subject to change.
*/
rt := RouteTable{
Routes: []route{
{
Path: "/snap",
Description: "view a still image of the camera",
handler: fc.HandleSnapshot,
},
{
Path: "/stream",
Description: "view a livestream of the camera",
handler: fc.HandleStream,
},
{
Path: "/timelapse",
Description: "view a timelapse video",
handler: func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, path.Join(TimelapseOutputDir, "timelapse.mp4"))
},
},
},
}
/*
Here we create a new http mux. You can alternatively just use `http.HandleFunc`
instead of `mux.HandleFunc` but then all http servers started by this program
will use that handling rule. Instead of using the global http mux, I like to
make my own for every http server in the program even though it doesn't really
matter when there is only one http server, as in this case.
*/
mux := http.NewServeMux()
mux.HandleFunc("/", rt.HandleRoot)
for _, route := range rt.Routes {
mux.HandleFunc(route.Path, route.handler)
}
server := &http.Server{
Addr: ":" + port,
Handler: mux,
ReadTimeout: ReadTimeout,
}
// Receives a signal from the done channel to close the server
go func() {
<-ctx.Done()
log.Println("Gracefully shutting down http server")
// We give the server a few seconds to allow requests to finish and shutdown
ctx, cancel := context.WithTimeout(context.TODO(), time.Duration(GracefulTimeoutSecs-1))
server.Shutdown(ctx)
cancel()
}()
/*
`server.ListenAndServe()` blocks until an error, then returns it. We report
any errors to the main synchronization goroutine via the `errCh` channel.
Note that nil errors may return and be sent over the `errCh` channel as
well as ErrServerClosed which occurs as as result of the above `Shutdown()`
call. This isn't an issue, however, since `errCh` is buffered and therefore
this line will never hang. Also, we always want the program to begin its
shutdown procedure if it hasn't already which is why it makes sense to just
always send it because it is harmless.
*/
errCh <- server.ListenAndServe()
log.Println("Stopped http server")
}