blasphem/pkg/server/server.go

59 lines
852 B
Go
Raw Normal View History

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
wg sync.WaitGroup
cfg *config.Config
}
func New(cfg *config.Config) (*Server, error) {
mux := http.NewServeMux()
s := &Server{
Bus: bus.New(),
Server: &http.Server{
Addr: cfg.Server.Bind,
Handler: mux,
},
cfg: cfg,
}
2022-09-25 14:07:47 -04:00
rootFS, err := fs.Sub(frontend.Root, "frontend/hass_frontend")
if err != nil {
return nil, err
}
2022-09-25 11:42:36 -04:00
mux.HandleFunc("/api/websocket", s.wsHandler)
2022-09-25 14:07:47 -04:00
mux.Handle("/", http.FileServer(http.FS(rootFS)))
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
}