package server import ( "context" "embed" "fmt" "html/template" "log/slog" "net/http" "os" "os/signal" "time" "git.lastassault.de/speatzle/morffix/config" ) var conf config.Config var templates *template.Template func Start(_conf config.Config, tmplFS embed.FS, staticFS embed.FS) { conf = _conf // Static Files staticServer := http.FS(staticFS) fs := http.FileServer(staticServer) // Templates t, err := template.ParseFS(tmplFS, "tmpl/*.tmpl") if err != nil { panic(fmt.Errorf("Parsing templates: %w", err)) } templates = t mux := http.NewServeMux() mux.HandleFunc("/worker", handleWorkerWebsocket) mux.Handle("/static/", fs) mux.HandleFunc("/", handleIndex) server := &http.Server{ Addr: conf.Server.Address, Handler: mux, ReadTimeout: 1 * time.Second, WriteTimeout: 1 * time.Second, IdleTimeout: 30 * time.Second, ReadHeaderTimeout: 2 * time.Second, } serverClose := make(chan bool) go func() { slog.Info("Listening...", "Address", conf.Server.Address) err := server.ListenAndServe() if err != http.ErrServerClosed { slog.Error("Listen Failed", "err", err) } else { slog.Info("Server Closed") } serverClose <- true }() stopCleanup := make(chan bool, 1) go cleanupDeadWorkers(stopCleanup) sigs := make(chan os.Signal, 1) signal.Notify(sigs, os.Interrupt) select { case <-serverClose: slog.Info("Exiting due to Listen Failure") case sig := <-sigs: slog.Info("Stopping Server...", "signal", sig) stopCtx, cancel := context.WithTimeout(context.Background(), time.Second*10) server.Shutdown(stopCtx) cancel() stopCleanup <- true slog.Info("Done") } }