blasphem/pkg/server/server.go

83 lines
1.5 KiB
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"
2022-09-30 14:37:40 -04:00
"github.com/labstack/echo/v4"
"dynatron.me/x/blasphem/pkg/auth"
2022-09-25 11:42:36 -04:00
"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 {
2022-09-30 14:37:40 -04:00
*echo.Echo
2022-09-25 11:42:36 -04:00
*bus.Bus
2022-09-30 14:37:40 -04:00
auth.Authenticator
2022-09-25 21:24:35 -04:00
rootFS fs.FS
2022-09-26 15:00:21 -04:00
wg sync.WaitGroup
cfg *config.Config
2022-09-25 11:42:36 -04:00
}
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) {
s = &Server{
2022-09-30 14:37:40 -04:00
Echo: echo.New(),
cfg: cfg,
2022-09-25 14:07:47 -04:00
}
2022-09-30 23:54:21 -04:00
s.InitAuth()
2022-09-30 14:37:40 -04:00
s.Echo.Debug = true
s.Echo.HideBanner = true
2022-09-25 14:07:47 -04:00
2022-09-30 14:37:40 -04:00
s.GET("/", echo.WrapHandler(frontend.FSHandler))
s.GET("/api/websocket", s.wsHandler)
s.GET("/auth/authorize", s.AuthorizeHandler)
s.GET("/auth/providers", s.ProvidersHandler)
s.POST("/auth/login_flow", s.LoginFlowHandler)
2022-09-30 23:54:21 -04:00
s.POST("/auth/login_flow/:flow_id", s.LoginFlowHandler)
2022-09-25 11:42:36 -04:00
return s, nil
}
func (s *Server) Go() error {
s.wg.Add(1)
go func() {
2022-09-30 14:37:40 -04:00
err := s.Start(s.cfg.Server.Bind)
2022-09-25 11:42:36 -04:00
if err != nil {
log.Fatal(err)
}
s.wg.Done()
}()
s.wg.Wait()
return nil
}