-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
212 lines (195 loc) · 3.98 KB
/
http.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
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package main
import (
"embed"
"fmt"
"html/template"
"net"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
)
//go:embed template.html
var embedFS embed.FS
var htmlTemplate *template.Template
type clientState int
const (
INITIAL = iota
ACTIVE
)
type client struct {
channel chan string
state clientState
}
var (
clients = make([]*client, 0)
clientMutex sync.Mutex
)
func deleteClient(client *client) {
for i := 0; i < len(clients); i++ {
if clients[i] == client {
clients[i] = clients[len(clients)-1]
clients = clients[:len(clients)-1]
return
}
}
}
func httpServer() error {
htmlTemplate = template.Must(template.ParseFS(embedFS, "template.html"))
http.HandleFunc("/stream", stream)
http.HandleFunc("/", serveRoot)
return http.ListenAndServe(":9090", nil)
}
func getInterfaceBaseIP() string {
iFace, err := net.InterfaceByName(interfaceName)
if err != nil {
return ""
}
addresses, err := iFace.Addrs()
if err != nil {
return ""
}
gua := ""
ula := ""
for _, v := range addresses {
addr := v.String()
if !strings.Contains(addr, ":") {
continue
}
_, anet, err := net.ParseCIDR(addr)
if err != nil {
continue
}
if anet.IP.IsLinkLocalUnicast() {
continue
}
if anet.IP.IsGlobalUnicast() {
gua = strings.Split(anet.String(), "/")[0]
}
if anet.IP.IsPrivate() {
ula = strings.Split(anet.String(), "/")[0]
}
}
if gua != "" {
return gua
} else {
return ula
}
}
func serveRoot(w http.ResponseWriter, r *http.Request) {
if r.RequestURI != "/" {
http.Error(w, "Not found", http.StatusNotFound)
return
}
type pageData struct {
BaseIP string
CanvasWidth int
CanvasHeight int
}
baseIP := getInterfaceBaseIP()
if len(baseIP) == 21 {
baseIP = strings.TrimSuffix(baseIP, ":")
}
err := htmlTemplate.Execute(w, pageData{
BaseIP: baseIP,
CanvasHeight: 512,
CanvasWidth: 512,
})
if err != nil {
fmt.Println("Error executing HTML template:", err)
}
}
var streamServerRunning atomic.Bool
func streamServer() {
if !streamServerRunning.CompareAndSwap(false, true) {
return
}
go func() {
for {
clientMutex.Lock()
if len(clients) == 0 {
streamServerRunning.Store(false)
clientMutex.Unlock()
return
}
requiresInitial := false
requiresUpdate := false
for _, v := range clients {
if v.state == INITIAL {
requiresInitial = true
} else {
requiresUpdate = true
}
if requiresInitial && requiresUpdate {
break
}
}
dataInitial, dataUpdate := getPicture(requiresInitial, requiresUpdate)
tmp := clients[:0]
for _, v := range clients {
if v.state == INITIAL {
v.state = ACTIVE
select {
case v.channel <- dataInitial:
default:
}
} else {
if dataUpdate != "0" {
select {
case v.channel <- dataUpdate:
default:
// Client cannot keep up
close(v.channel)
continue
}
}
}
tmp = append(tmp, v)
}
clients = tmp
clientMutex.Unlock()
time.Sleep(500 * time.Millisecond)
}
}()
}
func stream(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
messageChan := make(chan string, 40)
newClient := &client{
channel: messageChan,
state: INITIAL,
}
clientMutex.Lock()
clients = append(clients, newClient)
clientMutex.Unlock()
streamServer()
// For when clients are removed prior to connection close, to avoid a call to deleteClient()
var channelClosedFirst = false
go func() {
// Listen for connection close
<-r.Context().Done()
clientMutex.Lock()
if !channelClosedFirst {
deleteClient(newClient)
}
close(messageChan)
clientMutex.Unlock()
}()
for {
data, ok := <-messageChan
if !ok {
channelClosedFirst = true
return
}
_, _ = w.Write([]byte(data))
flusher.Flush()
}
}