-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
95 lines (88 loc) · 2.3 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
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"context"
"errors"
"fmt"
"log"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
config "github.com/rbroggi/streamingconfig"
appcfg "github.com/rbroggi/streamingconfig/example/config"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
port := os.Getenv("HTTP_PORT")
if port == "" {
port = "8080"
}
runnableCtx, cancelRunnables := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancelRunnables()
repo, done := initRepo(runnableCtx)
s := &server{repo: repo, lgr: slog.Default()}
mux := http.NewServeMux()
mux.HandleFunc("GET /configs/latest", s.latestConfigHandler)
mux.HandleFunc("PUT /configs/latest", s.putConfigHandler)
mux.HandleFunc("GET /configs", s.listConfigsHandler)
// Create a new server
srv := &http.Server{
Addr: fmt.Sprintf(":%s", port),
Handler: mux,
}
// Start the server in a goroutine
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}()
fmt.Printf("Server listening on port %s\n", port)
// until shutdown signal is sent
<-runnableCtx.Done()
// Graceful shutdown
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer func() {
cancel()
}()
if err := srv.Shutdown(ctx); err != nil {
log.Println("Error during shutdown:", err)
}
log.Println("Server stopped")
<-done
}
func initRepo(ctx context.Context) (*config.WatchedRepo[*appcfg.Conf], <-chan struct{}) {
lgr := slog.Default()
db := getDb()
repo, err := config.NewWatchedRepo[*appcfg.Conf](
config.Args{
Logger: lgr,
DB: db,
})
if err != nil {
log.Fatal(err)
}
done, err := repo.Start(ctx)
if err != nil {
log.Fatal(err)
}
return repo, done
}
func getDb() *mongo.Database {
ctx, cnl := context.WithTimeout(context.Background(), 5*time.Second)
defer cnl()
// use test name as db name to parallel tests.
opts := options.Client()
opts.ApplyURI("mongodb://localhost:27017/?connect=direct")
client, err := mongo.Connect(ctx, opts)
if err != nil {
panic(fmt.Errorf("run `make dependencies_up` before, error: %w", err))
}
err = client.Ping(ctx, nil)
if err != nil {
panic(fmt.Errorf("error %v\nrun `make dependencies_up` before running main\n", err))
}
return client.Database("test")
}