Files
ballet-server/backend/cmd/server/main.go
T

85 lines
1.9 KiB
Go
Raw Normal View History

package main
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"ballet-island/backend/internal/httpapi"
"github.com/jackc/pgx/v5/pgxpool"
)
func main() {
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil)))
if err := run(); err != nil {
slog.Error("server stopped", "error", err)
os.Exit(1)
}
}
func run() error {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
for _, key := range []string{"PGHOST", "PGDATABASE", "PGUSER", "PGPASSWORD"} {
if os.Getenv(key) == "" {
return fmt.Errorf("%s is required", key)
}
}
// Use libpq environment variables so passwords need no URL escaping.
pool, err := pgxpool.New(ctx, "")
if err != nil {
return fmt.Errorf("configure database: %w", err)
}
defer pool.Close()
startupCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
err = pool.Ping(startupCtx)
cancel()
if err != nil {
return fmt.Errorf("connect database: %w", err)
}
addr := os.Getenv("HTTP_ADDR")
if addr == "" {
addr = "127.0.0.1:8080"
}
server := &http.Server{
Addr: addr,
Handler: httpapi.NewHandler(pool.Ping),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 60 * time.Second,
}
serverErr := make(chan error, 1)
go func() {
slog.Info("server starting", "address", addr)
serverErr <- server.ListenAndServe()
}()
select {
case err := <-serverErr:
if !errors.Is(err, http.ErrServerClosed) {
return err
}
case <-ctx.Done():
slog.Info("server shutting down")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
_ = server.Close()
return fmt.Errorf("shutdown server: %w", err)
}
}
return nil
}