blasphem/pkg/server/server.go
2022-09-26 15:00:21 -04:00

84 lines
1.5 KiB
Go

package server
import (
"io/fs"
"log"
"net/http"
"sync"
"dynatron.me/x/blasphem/pkg/bus"
"dynatron.me/x/blasphem/pkg/config"
"dynatron.me/x/blasphem/pkg/frontend"
)
type Server struct {
*bus.Bus
*http.Server
rootFS fs.FS
wg sync.WaitGroup
cfg *config.Config
}
type StatusWriter struct {
http.ResponseWriter
status int
}
func (w *StatusWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func logHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rw := &StatusWriter{ResponseWriter: w}
h.ServeHTTP(rw, r)
logRequest(rw.status, r)
})
}
func logRequest(status int, r *http.Request) {
log.Println(r.Method, status, r.URL.Path)
}
func New(cfg *config.Config) (s *Server, err error) {
mux := http.NewServeMux()
s = &Server{
Bus: bus.New(),
Server: &http.Server{
Addr: cfg.Server.Bind,
Handler: mux,
},
cfg: cfg,
}
s.rootFS, err = fs.Sub(frontend.Root, "frontend/hass_frontend")
if err != nil {
return nil, err
}
mux.HandleFunc("/api/websocket", s.wsHandler)
mux.Handle("/", logHandler(http.FileServer(http.FS(s.rootFS))))
mux.HandleFunc("/auth/authorize", s.authorizeHandler)
mux.HandleFunc("/auth/providers", s.providersHandler)
return s, nil
}
func (s *Server) Go() error {
s.wg.Add(1)
go func() {
err := s.ListenAndServe()
if err != nil {
log.Fatal(err)
}
s.wg.Done()
}()
s.wg.Wait()
return nil
}