generated from wisdom-oss/microservice-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
92 lines (75 loc) · 2.24 KB
/
main.go
File metadata and controls
92 lines (75 loc) · 2.24 KB
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
package main
import (
"context"
"errors"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/spf13/viper"
"microservice/internal"
"microservice/internal/db"
objectStorage "microservice/internal/minio"
"microservice/router"
)
var headerReadTimeout = 10 * time.Second
var serverShutdownTimeout = 20 * time.Second
var configuration *viper.Viper
// the main function bootstraps the http server and handlers used for this
// microservice.
func main() {
_ = internal.ParseConfiguration() // error ignored as function always returns nil
configuration = internal.Configuration()
// setting up the database connection
err := db.Connect()
if err != nil {
slog.Error("unable to connect to the database", "error", err)
os.Exit(1)
}
// running database migrations stored in resources/migrations
err = db.MigrateDatabase()
if err != nil {
slog.Error("failed to execute database migrations", "error", err)
os.Exit(1)
}
// connect to minio
err = objectStorage.Connect()
if err != nil {
slog.Error("unable to connect to object storage", "error", err)
os.Exit(1)
}
// configure your router
r, err := router.Configure()
if err != nil {
slog.Error("unable to create router", "error", err)
os.Exit(1)
}
// create a http server to handle the requests
server := http.Server{
Addr: net.JoinHostPort(configuration.GetString("http.host"), configuration.GetString("http.port")),
Handler: r.Handler(),
ReadHeaderTimeout: headerReadTimeout,
}
// Start the server and log errors that happen while running it
go func() {
if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
slog.Error("unable to start http server", "error", err)
}
}()
// Set up some the signal handling to allow the server to shut down gracefully
shutdownSignal := make(chan os.Signal, 1)
signal.Notify(shutdownSignal, syscall.SIGINT, syscall.SIGTERM)
// Block further code execution until the shutdown signal was received
<-shutdownSignal
ctx, cancel := context.WithTimeout(context.Background(), serverShutdownTimeout)
defer cancel()
err = server.Shutdown(ctx)
if err != nil {
slog.Error("unable to shutdown api gracefully", "error", err)
slog.Error("forcing shutdown...")
return
}
}