2022-09-25 11:42:36 -04:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2022-09-25 14:07:47 -04:00
|
|
|
"io/fs"
|
2022-09-25 11:42:36 -04:00
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"dynatron.me/x/blasphem/pkg/bus"
|
|
|
|
"dynatron.me/x/blasphem/pkg/config"
|
2022-09-25 14:07:47 -04:00
|
|
|
"dynatron.me/x/blasphem/pkg/frontend"
|
2022-09-25 11:42:36 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
type Server struct {
|
|
|
|
*bus.Bus
|
|
|
|
*http.Server
|
2022-09-25 21:24:35 -04:00
|
|
|
rootFS fs.FS
|
2022-09-25 11:42:36 -04:00
|
|
|
wg sync.WaitGroup
|
|
|
|
cfg *config.Config
|
|
|
|
}
|
|
|
|
|
2022-09-25 21:24:35 -04:00
|
|
|
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) {
|
|
|
|
|
2022-09-25 11:42:36 -04:00
|
|
|
mux := http.NewServeMux()
|
|
|
|
|
2022-09-25 21:24:35 -04:00
|
|
|
s = &Server{
|
2022-09-25 11:42:36 -04:00
|
|
|
Bus: bus.New(),
|
|
|
|
Server: &http.Server{
|
|
|
|
Addr: cfg.Server.Bind,
|
|
|
|
Handler: mux,
|
|
|
|
},
|
|
|
|
cfg: cfg,
|
|
|
|
}
|
|
|
|
|
2022-09-25 21:24:35 -04:00
|
|
|
s.rootFS, err = fs.Sub(frontend.Root, "frontend/hass_frontend")
|
2022-09-25 14:07:47 -04:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-09-25 11:42:36 -04:00
|
|
|
mux.HandleFunc("/api/websocket", s.wsHandler)
|
2022-09-25 21:24:35 -04:00
|
|
|
mux.Handle("/", logHandler(http.FileServer(http.FS(s.rootFS))))
|
|
|
|
mux.HandleFunc("/auth/authorize", s.authorizeHandler)
|
|
|
|
mux.HandleFunc("/auth/providers", s.providersHandler)
|
2022-09-25 11:42:36 -04:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|