62 lines
1.4 KiB
Go
62 lines
1.4 KiB
Go
// Command api is the HTTP entrypoint of the messenger backend.
|
|||
|
|
//
|
||
|
|
// It wires configuration, logging and the HTTP server together and
|
||
|
|
// supports graceful shutdown on SIGINT/SIGTERM.
|
||
|
|
package main
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"errors"
|
||
|
|
"net/http"
|
||
|
|
"os"
|
||
|
|
"os/signal"
|
||
|
|
"syscall"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"messenger/internal/platform/config"
|
||
|
|
"messenger/internal/platform/logger"
|
||
|
|
"messenger/internal/server"
|
||
|
|
)
|
||
|
|
|
||
|
|
func main() {
|
||
|
|
log := logger.New()
|
||
|
|
|
||
|
|
cfg, err := config.Load()
|
||
|
|
if err != nil {
|
||
|
|
log.Error("invalid configuration", "error", err)
|
||
|
|
os.Exit(1)
|
||
|
|
}
|
||
|
|
|
||
|
|
httpServer := server.New(cfg, log)
|
||
|
|
|
||
|
|
// Run the server in a goroutine so that shutdown can be triggered
|
||
|
|
// from the signal handler below.
|
||
|
|
go func() {
|
||
|
|
log.Info("http server listening",
|
||
|
|
"addr", cfg.HTTPAddr,
|
||
|
|
"static_dir", cfg.StaticDir,
|
||
|
|
"env", cfg.Environment,
|
||
|
|
)
|
||
|
|
if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||
|
|
log.Error("http server failed", "error", err)
|
||
|
|
os.Exit(1)
|
||
|
|
}
|
||
|
|
}()
|
||
|
|
|
||
|
|
// Wait for a termination signal, then drain in-flight requests.
|
||
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||
|
|
defer stop()
|
||
|
|
|
||
|
|
<-ctx.Done()
|
||
|
|
log.Info("shutting down")
|
||
|
|
|
||
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||
|
|
defer cancel()
|
||
|
|
|
||
|
|
if err := httpServer.Shutdown(shutdownCtx); err != nil {
|
||
|
|
log.Error("graceful shutdown failed", "error", err)
|
||
|
|
os.Exit(1)
|
||
|
|
}
|
||
|
|
log.Info("server stopped cleanly")
|
||
|
|
}
|