64 lines
1.6 KiB
Go
64 lines
1.6 KiB
Go
// Command server starts the messenger API over PostgreSQL.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"net"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
|
|
"messenger/internal/app"
|
|
"messenger/internal/platform/config"
|
|
"messenger/internal/platform/postgres"
|
|
"messenger/internal/server"
|
|
)
|
|
|
|
func main() {
|
|
cfg, err := config.Load(os.LookupEnv)
|
|
if err != nil {
|
|
fmt.Fprintln(os.Stderr, "configuration error:", err)
|
|
os.Exit(2)
|
|
}
|
|
log := newLogger(cfg)
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
|
defer stop()
|
|
|
|
if err := run(ctx, log, cfg); err != nil {
|
|
log.Error("server stopped with error", "error", err.Error())
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
// run connects the dependencies before it listens, so the port accepts
|
|
// connections only once the schema is in place.
|
|
func run(ctx context.Context, log *slog.Logger, cfg config.Config) error {
|
|
pool, err := postgres.NewPool(ctx, cfg.DatabaseURL)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer pool.Close()
|
|
if err := postgres.Migrate(ctx, pool); err != nil {
|
|
return err
|
|
}
|
|
|
|
ln, err := net.Listen("tcp", cfg.Addr())
|
|
if err != nil {
|
|
return fmt.Errorf("listen on %s: %w", cfg.Addr(), err)
|
|
}
|
|
log.Info("starting", "env", cfg.Env, "addr", cfg.Addr(), "shutdown_timeout", cfg.ShutdownTimeout.String())
|
|
a := app.New(app.Deps{Log: log, DB: pool, MaxBodyBytes: cfg.MaxBodyBytes})
|
|
return server.Run(ctx, log, ln, a.Engine, a.Health, cfg.ShutdownTimeout)
|
|
}
|
|
|
|
func newLogger(cfg config.Config) *slog.Logger {
|
|
opts := &slog.HandlerOptions{Level: cfg.LogLevel}
|
|
if cfg.Env == "dev" {
|
|
return slog.New(slog.NewTextHandler(os.Stdout, opts))
|
|
}
|
|
return slog.New(slog.NewJSONHandler(os.Stdout, opts))
|
|
}
|