diff options
Diffstat (limited to 'cmd/api/main.go')
-rw-r--r-- | cmd/api/main.go | 64 |
1 files changed, 38 insertions, 26 deletions
diff --git a/cmd/api/main.go b/cmd/api/main.go index 3d2f587..f6d0166 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -3,6 +3,7 @@ package main import ( "context" "flag" + "log" "net/http" "os" "os/signal" @@ -10,39 +11,54 @@ import ( "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" "github.com/go-chi/httplog" - "github.com/rs/zerolog" "golang.org/x/sync/errgroup" + badger "github.com/dgraph-io/badger/v3" + + "go.neonxp.dev/djson/internal/config" + "go.neonxp.dev/djson/internal/core" "go.neonxp.dev/djson/internal/events" "go.neonxp.dev/djson/internal/handler" - "go.neonxp.dev/djson/internal/storage" - "go.neonxp.dev/djson/internal/tree" + "go.neonxp.dev/djson/internal/logger" ) +var configFile = flag.String("config", "/etc/djson/config.json", "Path to config file") + func main() { flag.Parse() ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill) defer cancel() - logger := httplog.NewLogger("djson", httplog.Options{ + cfg, err := config.Parse(*configFile) + if err != nil { + panic(err) + } + + baseLogger := httplog.NewLogger("djson", httplog.Options{ JSON: true, - LogLevel: *logLevel, + LogLevel: cfg.Log.Level, }) - // Tree storage - storage, err := storage.New(*dbPath, logger) + appLogger := logger.Logger{ + Logger: baseLogger, + } + + dbOpts := badger.DefaultOptions(cfg.DB) + dbOpts.Logger = appLogger + + db, err := badger.Open(dbOpts) if err != nil { - panic(err) + log.Fatal(err) } + defer db.Close() + eventsDispatcher := events.New() - // Tree engine - core := tree.New( - storage, - eventsDispatcher, - ) - if err := core.Init(); err != nil { - panic(err) + + // Tree core + core := core.New(db) + if err := core.Init(ctx); err != nil { + log.Fatal(err) } // Tree HTTP wrapper @@ -51,7 +67,7 @@ func main() { // HTTP router r := chi.NewRouter() - r.Use(httplog.RequestLogger(logger)) + r.Use(httplog.RequestLogger(appLogger.Logger)) r.Use(middleware.RequestID) r.Use(middleware.RealIP) r.Use(middleware.Recoverer) @@ -61,20 +77,14 @@ func main() { r.Route("/events", treeHandler.HandleEvents) server := &http.Server{ - Addr: *apiAddr, + Addr: cfg.Listen, Handler: r, } - if err := run(ctx, logger, server, storage); err != nil { - panic(err) - } -} - -func run(ctx context.Context, logger zerolog.Logger, server *http.Server, storage storage.Storage) error { eg, ctx := errgroup.WithContext(ctx) eg.Go(func() error { - logger.Info().Str("server listen", *apiAddr).Send() + appLogger.Info().Str("server listen", cfg.Listen).Send() if err := server.ListenAndServe(); err != http.ErrServerClosed { return err } @@ -83,9 +93,11 @@ func run(ctx context.Context, logger zerolog.Logger, server *http.Server, storag eg.Go(func() error { <-ctx.Done() - storage.Close() + db.Close() return server.Close() }) - return eg.Wait() + if err := eg.Wait(); err != nil { + panic(err) + } } |