-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
83 lines (66 loc) · 2.06 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
package main
import (
"context"
"flag"
"net/http"
"os"
"os/signal"
"time"
"github.com/Ubivius/microservice-template/pkg/database"
"github.com/Ubivius/microservice-template/pkg/handlers"
"github.com/Ubivius/microservice-template/pkg/router"
"github.com/Ubivius/pkg-telemetry/metrics"
"github.com/Ubivius/pkg-telemetry/tracing"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
)
var log = logf.Log.WithName("template-main")
func main() {
// Starting k8s logger
opts := zap.Options{}
opts.BindFlags(flag.CommandLine)
newLogger := zap.New(zap.UseFlagOptions(&opts), zap.WriteTo(os.Stdout))
logf.SetLogger(newLogger.WithName("log"))
// Starting tracer provider
tp := tracing.CreateTracerProvider(os.Getenv("JAEGER_ENDPOINT"), "microservice-template-traces")
// Starting metrics exporter
metrics.StartPrometheusExporterWithName("template")
// Database init
db := database.NewMockProducts()
// Creating handlers
productHandler := handlers.NewProductsHandler(db)
// Router setup
r := router.New(productHandler)
// Server setup
server := &http.Server{
Addr: ":9090",
Handler: r,
IdleTimeout: 120 * time.Second,
ReadTimeout: 1 * time.Second,
}
go func() {
log.Info("Starting server", "port", server.Addr)
err := server.ListenAndServe()
if err != nil {
log.Error(err, "Server error")
}
}()
// Handle shutdown signals from operating system
signalChannel := make(chan os.Signal, 1)
signal.Notify(signalChannel, os.Interrupt)
receivedSignal := <-signalChannel
log.Info("Received terminate, beginning graceful shutdown", "received_signal", receivedSignal.String())
// DB connection shutdown
db.CloseDB()
// Context cancelling
timeoutContext, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Cleanly shutdown and flush telemetry on shutdown
defer func(ctx context.Context) {
if err := tp.Shutdown(ctx); err != nil {
log.Error(err, "Error shutting down tracer provider")
}
}(timeoutContext)
// Server shutdown
_ = server.Shutdown(timeoutContext)
}