package main import ( "context" "errors" "fmt" "log/slog" "net/http" "os" "os/signal" "syscall" "time" "ballet-island/backend/internal/database" "ballet-island/backend/internal/httpapi" "ballet-island/backend/internal/identity" "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() databaseURL := os.Getenv("DATABASE_URL") if databaseURL == "" { for _, key := range []string{"PGHOST", "PGDATABASE", "PGUSER", "PGPASSWORD"} { if os.Getenv(key) == "" { return fmt.Errorf("%s is required when DATABASE_URL is unset", key) } } } // Production uses a URL; local development retains libpq environment variables. pool, err := pgxpool.New(ctx, databaseURL) if err != nil { if databaseURL != "" { // Parser errors can include the URL, so do not log the credential-bearing input. return errors.New("configure database: invalid DATABASE_URL") } return fmt.Errorf("configure database: %w", err) } defer pool.Close() startupCtx, cancel := context.WithTimeout(ctx, 30*time.Second) err = pool.Ping(startupCtx) if err == nil { err = database.Migrate(startupCtx, pool) } 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.NewAppHandler(pool, &identity.WeChat{AppID: os.Getenv("WECHAT_APP_ID"), AppSecret: os.Getenv("WECHAT_APP_SECRET")}, nil), 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 }