-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
84 lines (67 loc) · 1.58 KB
/
main.go
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
package main
import (
"context"
"log/slog"
"net/http"
"os"
"os/signal"
"github.com/spf13/pflag"
twicmdhttp "github.com/twipi/twipi/twicmd/http"
"github.com/twipi/twittt/service"
"golang.org/x/sync/errgroup"
"libdb.so/hserve"
)
var (
listenAddr = ":8080"
)
func init() {
pflag.StringVarP(&listenAddr, "listen-addr", "l", listenAddr, "address to listen on")
pflag.Parse()
}
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
logger := slog.Default()
slog.SetLogLoggerLevel(slog.LevelDebug)
os.Exit(start(ctx, logger))
}
func start(ctx context.Context, logger *slog.Logger) int {
errg, ctx := errgroup.WithContext(ctx)
svc := service.NewService(logger)
errg.Go(func() error { return svc.Start(ctx) })
handler := twicmdhttp.NewHandler(svc, logger.With("component", "http"))
errg.Go(func() error {
<-ctx.Done()
if err := handler.Close(); err != nil {
logger.Error(
"failed to close http service handler",
"err", err)
}
return ctx.Err()
})
errg.Go(func() error {
r := http.NewServeMux()
r.Handle("GET /health", http.HandlerFunc(healthCheck))
r.Handle("/", handler)
logger.Info(
"listening via HTTP",
"addr", listenAddr)
if err := hserve.ListenAndServe(ctx, listenAddr, r); err != nil {
logger.Error(
"failed to listen and serve",
"err", err)
return err
}
return ctx.Err()
})
if err := errg.Wait(); err != nil {
logger.Error(
"service error",
"err", err)
return 1
}
return 0
}
func healthCheck(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}