-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
84 lines (73 loc) · 2.12 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
package main
import (
"context"
"errors"
"io/fs"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"github.com/oklog/ulid/v2"
configuration "github.com/oktalz/present/config"
"github.com/oktalz/present/data"
"github.com/oktalz/present/handlers"
)
func configureServer(config configuration.Config) {
wsServer := data.NewServer()
data.Init(wsServer, &config)
iframeHandler := handlers.IFrame(config)
http.Handle("/{$}", handlers.Homepage(iframeHandler, config))
http.Handle("POST /cast", handlers.CastSSE(wsServer, config))
http.Handle("/print", handlers.NoLayout(config))
http.Handle("/iframe", iframeHandler)
http.Handle("/login", handlers.Login(loginPage))
http.Handle("/stats", handlers.Stats(statsPage, config))
http.Handle("/events", handlers.SSE(wsServer, config))
http.Handle("GET /api/login", handlers.APILogin(config))
http.Handle("GET /api/users", handlers.APIUsers(config))
http.Handle("GET /api/cmd/", handlers.APICmd(config))
sub, err := fs.Sub(dist, "ui/static")
if err != nil {
panic(err)
}
wd, err := os.Getwd()
if err != nil {
panic(err)
}
handler := &fallbackFileServer{
primary: http.FileServer(http.FS(sub)),
secondary: http.FileServer(http.Dir(wd)),
eTag: ulid.Make().String(),
}
http.Handle("/", handler)
}
func startServer(config configuration.Config) {
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, syscall.SIGTERM, os.Interrupt)
configureServer(config)
server := &http.Server{
Addr: config.Address + ":" + strconv.Itoa(config.Port),
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
IdleTimeout: 5 * time.Second,
}
go func() {
log.Println("Listening on", server.Addr)
err := server.ListenAndServe()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Printf("HTTP server error: %s\n", err)
}
}()
<-signalCh
// Shutdown the server gracefully
log.Println("Shutting down...")
shutdownCtx, cancelShutdown := context.WithTimeout(context.Background(), 3*time.Second)
defer cancelShutdown()
err := server.Shutdown(shutdownCtx)
if err != nil {
log.Printf("HTTP server shutdown error: %s\n", err)
}
}