refactor: web server returns *http.Server for shutdown control

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-25 17:36:15 +09:00
parent a38cf804ef
commit 6e78d8a073
2 changed files with 21 additions and 9 deletions

10
main.go
View File

@@ -5,6 +5,7 @@ import (
"log"
"log/slog"
"os"
"time"
"github.com/tolelom/catacombs/config"
"github.com/tolelom/catacombs/game"
@@ -41,12 +42,9 @@ func main() {
sshAddr := fmt.Sprintf("0.0.0.0:%d", cfg.Server.SSHPort)
webAddr := fmt.Sprintf(":%d", cfg.Server.HTTPPort)
// Start web terminal server in background
go func() {
if err := web.Start(webAddr, cfg.Server.SSHPort); err != nil {
slog.Error("web server error", "error", err)
}
}()
startTime := time.Now()
webServer := web.Start(webAddr, cfg.Server.SSHPort, lobby, db, startTime)
_ = webServer // used later for graceful shutdown
slog.Info("server starting", "ssh_port", cfg.Server.SSHPort, "http_port", cfg.Server.HTTPPort)
if err := server.Start(sshAddr, lobby, db); err != nil {

View File

@@ -8,9 +8,12 @@ import (
"log/slog"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
"golang.org/x/crypto/ssh"
"github.com/tolelom/catacombs/game"
"github.com/tolelom/catacombs/store"
)
//go:embed static
@@ -26,8 +29,8 @@ type resizeMsg struct {
Rows int `json:"rows"`
}
// Start launches the HTTP server for the web terminal.
func Start(addr string, sshPort int) error {
// Start launches the HTTP server for the web terminal and returns the server handle.
func Start(addr string, sshPort int, lobby *game.Lobby, db *store.DB, startTime time.Time) *http.Server {
mux := http.NewServeMux()
// Serve static files from embedded FS
@@ -38,8 +41,19 @@ func Start(addr string, sshPort int) error {
handleWS(w, r, sshPort)
})
// Admin endpoint
mux.Handle("/admin", AdminHandler(lobby, db, startTime))
srv := &http.Server{Addr: addr, Handler: mux}
slog.Info("starting web terminal", "addr", addr)
return http.ListenAndServe(addr, mux)
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
slog.Error("web server error", "error", err)
}
}()
return srv
}
func handleWS(w http.ResponseWriter, r *http.Request, sshPort int) {