HTTP server with WebSockets.
All checks were successful
Linting and tests / Linting (push) Successful in 5s

This commit is contained in:
2025-09-20 09:59:09 +05:00
parent cc5d010204
commit f1617efb0f
6 changed files with 71 additions and 8 deletions

View File

@@ -9,6 +9,8 @@ import (
"os"
"time"
"bunker/server/internal/services/core"
"github.com/coder/websocket"
)
@@ -35,12 +37,15 @@ func (h *httpServer) configureHTTPServer() error {
return fmt.Errorf("configure HTTP server: validate HTTP server address: %w", errHTTPServerAddrInvalid)
}
mux := new(http.ServeMux)
mux.HandleFunc("GET /api/v1/socket", h.handleWebsocketRequest)
h.httpMux = new(http.ServeMux)
// Default catch-all handler.
h.RegisterHandler("", "/", h.defaultHandler)
h.RegisterHandler(http.MethodGet, "/api/v1/socket", h.handleWebsocketRequest)
h.httpSrv = &http.Server{
Addr: httpSrvAddr,
Handler: mux,
Handler: h.httpMux,
ReadHeaderTimeout: time.Second * 3,
}
@@ -66,6 +71,20 @@ func (h *httpServer) handleWebsocketRequest(w http.ResponseWriter, r *http.Reque
}()
}
func (h *httpServer) RegisterHandler(method, path string, handler http.HandlerFunc) {
h.httpMux.HandleFunc(fmt.Sprintf("%s %s", method, path), func(w http.ResponseWriter, r *http.Request) {
for i := len(h.middlewares) - 1; i >= 0; i-- {
handler = h.middlewares[i](handler)
}
handler(w, r)
})
}
func (h *httpServer) RegisterMiddleware(middleware core.HTTPMiddlewareFunc) {
h.middlewares = append(h.middlewares, middleware)
}
func (h *httpServer) startHTTPServer() {
h.logger.Info("Starting listening for HTTP requests.", "address", h.httpSrv.Addr)