-
Notifications
You must be signed in to change notification settings - Fork 0
/
webserver.go
79 lines (66 loc) · 1.81 KB
/
webserver.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
package main
import (
"log"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/a-h/templ"
"github.com/p0t4t0sandwich/neuralnexus-frontend/components"
"github.com/p0t4t0sandwich/neuralnexus-frontend/middleware"
)
// WebServer - The web server
type WebServer struct {
Address string
UsingUDS bool
}
// NewWebServer - Create a new API server
func NewWebServer(address string, usingUDS bool) *WebServer {
return &WebServer{
Address: address,
UsingUDS: usingUDS,
}
}
// Setup - Setup the web server
func (s *WebServer) Setup() http.Handler {
router := http.NewServeMux()
router.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
router.Handle("/", templ.Handler(components.HomePage()))
router.Handle("/login", templ.Handler(components.LoginPage()))
router.Handle("/projects", templ.Handler(components.ProjectsPage()))
router.Handle("/project/bee-name-generator", templ.Handler(components.BeeNameGeneratorPage()))
router.Handle("/teapot", templ.Handler(components.TeapotPage()))
return middleware.RequestLoggerMiddleware(router)
}
// Run - Start the web server
func (s *WebServer) Run() error {
server := http.Server{
Addr: s.Address,
Handler: s.Setup(),
}
if s.UsingUDS {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
os.Remove(s.Address)
os.Exit(1)
}()
if _, err := os.Stat(s.Address); err == nil {
log.Printf("Removing existing socket file %s", s.Address)
if err := os.Remove(s.Address); err != nil {
return err
}
}
socket, err := net.Listen("unix", s.Address)
if err != nil {
return err
}
log.Printf("WebServer listening on %s", s.Address)
return server.Serve(socket)
} else {
log.Printf("WebServer listening on %s", s.Address)
return server.ListenAndServe()
}
}