-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
98 lines (82 loc) · 2.34 KB
/
server.go
File metadata and controls
98 lines (82 loc) · 2.34 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
package main
import (
"context"
"embed"
"encoding/json"
"fmt"
"log"
"net/http"
)
//go:embed ui/index.html
var uiFS embed.FS
func RunServer(ctx context.Context, state *State) {
mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
data, err := uiFS.ReadFile("ui/index.html")
if err != nil {
http.Error(w, "ui not found", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(data)
})
mux.HandleFunc("GET /api/status", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(state.Status())
})
mux.HandleFunc("GET /api/history", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(state.History(100))
})
mux.HandleFunc("GET /api/threats", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(state.ThreatLog(200))
})
mux.HandleFunc("POST /api/scan", func(w http.ResponseWriter, r *http.Request) {
state.TriggerScan()
w.WriteHeader(http.StatusAccepted)
json.NewEncoder(w).Encode(map[string]string{"status": "scan triggered"})
})
mux.HandleFunc("GET /api/events", func(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming not supported", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
// Send current status immediately
statusJSON, _ := json.Marshal(state.Status())
fmt.Fprintf(w, "event: status\ndata: %s\n\n", statusJSON)
flusher.Flush()
ch := state.Subscribe()
defer state.Unsubscribe(ch)
for {
select {
case <-r.Context().Done():
return
case <-ctx.Done():
return
case msg, ok := <-ch:
if !ok {
return
}
fmt.Fprint(w, msg)
flusher.Flush()
}
}
})
server := &http.Server{
Addr: fmt.Sprintf(":%d", state.port),
Handler: mux,
}
go func() {
<-ctx.Done()
server.Close()
}()
log.Printf("dashboard: http://localhost:%d", state.port)
if err := server.ListenAndServe(); err != http.ErrServerClosed {
log.Printf("server error: %v", err)
}
}