1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
package main
import (
"context"
"flag"
"net/http"
"os"
"os/signal"
"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"
"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 {
logger.Info().Str("cluster connect", *cluster).Send()
} else {
logger.Info().Str("cluster create", *clusterAddr).Send()
}
// Tree storage
storage, err := storage.New(*dbPath, logger)
if err != nil {
panic(err)
}
// Tree engine
core := tree.New(
storage,
)
if err := core.Init(); err != nil {
panic(err)
}
// 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: 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()
if err := server.ListenAndServe(); err != http.ErrServerClosed {
return err
}
return nil
})
eg.Go(func() error {
<-ctx.Done()
storage.Close()
return server.Close()
})
return eg.Wait()
}
|