-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathhttp_server.go
71 lines (59 loc) · 1.53 KB
/
http_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
package mybench
import (
"embed"
"encoding/json"
"fmt"
"io/fs"
"net/http"
"time"
)
//go:embed webui
var webuiFiles embed.FS
type StatusData struct {
CurrentTime float64
Note string
Workloads []string
DataSnapshots []*DataSnapshot
}
type HttpServer struct {
benchmark *Benchmark
note string
mux *http.ServeMux
port int
}
func NewHttpServer(benchmark *Benchmark, note string, port int) *HttpServer {
s := &HttpServer{
benchmark: benchmark,
note: note,
mux: http.NewServeMux(),
port: port,
}
subFS, err := fs.Sub(webuiFiles, "webui")
if err != nil {
panic(err)
}
s.mux.Handle("/", http.FileServer(http.FS(subFS)))
s.mux.HandleFunc("/api/status", s.apiStatus)
return s
}
func (s *HttpServer) apiStatus(w http.ResponseWriter, req *http.Request) {
var statusData StatusData
statusData.DataSnapshots = s.benchmark.DataSnapshots()
statusData.Note = s.note
statusData.Workloads = make([]string, 0, len(s.benchmark.workloads))
for workloadName := range s.benchmark.workloads {
statusData.Workloads = append(statusData.Workloads, workloadName)
}
statusData.CurrentTime = time.Since(s.benchmark.startTime).Seconds()
w.Header().Add("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(statusData)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
}
}
func (h *HttpServer) Run() {
host := fmt.Sprintf("localhost:%d", h.port)
fmt.Printf("Starting HTTP server at http://%s\n", host)
http.ListenAndServe(host, h.mux)
}