summaryrefslogtreecommitdiff
path: root/cmd/api/main.go
diff options
context:
space:
mode:
Diffstat (limited to 'cmd/api/main.go')
-rw-r--r--cmd/api/main.go75
1 files changed, 51 insertions, 24 deletions
diff --git a/cmd/api/main.go b/cmd/api/main.go
index f64b43c..796837b 100644
--- a/cmd/api/main.go
+++ b/cmd/api/main.go
@@ -3,54 +3,82 @@ package main
import (
"context"
"flag"
- "log"
"net/http"
"os"
"os/signal"
- "go.neonxp.dev/djson/internal/api"
- "go.neonxp.dev/djson/internal/storage"
- "go.neonxp.dev/djson/internal/tree"
+ "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"
-)
-var (
- cluster = flag.String("cluster", "", "Master node address (ex: 192.168.1.10:5657)")
- clusterAddr = flag.String("cluster_addr", ":5657", "Self address for cluster")
- apiAddr = flag.String("api_addr", ":5656", "API address")
+ "go.neonxp.dev/djson/internal/handler"
+ "go.neonxp.dev/djson/internal/storage"
+ "go.neonxp.dev/djson/internal/tree"
)
func main() {
flag.Parse()
+
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
defer cancel()
+ logger := httplog.NewLogger("djson", httplog.Options{
+ JSON: true,
+ LogLevel: "debug",
+ })
+
+ // TBD raft cluster initialization
if cluster != nil {
- log.Printf("Connecting to cluster %s", *cluster)
+ logger.Info().Str("cluster connect", *cluster).Send()
} else {
- log.Printf("Creating cluster at %s", *clusterAddr)
+ logger.Info().Str("cluster create", *clusterAddr).Send()
}
- storage, err := storage.NewFileStorage("test.wal")
+
+ // Tree storage
+ storage, err := storage.New(*dbPath, logger)
if err != nil {
- log.Fatal(err)
+ panic(err)
}
- service := tree.New(
+
+ // Tree engine
+ core := tree.New(
storage,
)
+ if err := core.Init(); err != nil {
+ panic(err)
+ }
- server := http.Server{
+ // Tree HTTP wrapper
+ treeHandler := handler.New(core)
+
+ // HTTP router
+ r := chi.NewRouter()
+
+ r.Use(httplog.RequestLogger(logger))
+ r.Use(middleware.RequestID)
+ r.Use(middleware.RealIP)
+ r.Use(middleware.Recoverer)
+
+ r.Get("/health", treeHandler.Hearthbeat)
+ r.Route("/tree", treeHandler.Handle)
+
+ server := &http.Server{
Addr: *apiAddr,
- Handler: api.NewHandler(service),
+ Handler: r,
}
- eg, ctx := errgroup.WithContext(ctx)
+ if err := run(ctx, logger, server, storage); err != nil {
+ panic(err)
+ }
+}
- eg.Go(func() error {
- return service.Run(ctx)
- })
+func run(ctx context.Context, logger zerolog.Logger, server *http.Server, storage storage.Storage) error {
+ eg, ctx := errgroup.WithContext(ctx)
eg.Go(func() error {
- log.Printf("Server started at %s", *apiAddr)
+ logger.Info().Str("server listen", *apiAddr).Send()
if err := server.ListenAndServe(); err != http.ErrServerClosed {
return err
}
@@ -59,10 +87,9 @@ func main() {
eg.Go(func() error {
<-ctx.Done()
+ storage.Close()
return server.Close()
})
- if err := eg.Wait(); err != nil {
- log.Fatal(err)
- }
+ return eg.Wait()
}