-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
99 lines (84 loc) · 2.36 KB
/
main.go
File metadata and controls
99 lines (84 loc) · 2.36 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
93
94
95
96
97
98
99
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
_ "github.com/go-modkit/modkit/examples/hello-mysql/docs"
"github.com/go-modkit/modkit/examples/hello-mysql/internal/httpserver"
"github.com/go-modkit/modkit/examples/hello-mysql/internal/lifecycle"
configmodule "github.com/go-modkit/modkit/examples/hello-mysql/internal/modules/config"
"github.com/go-modkit/modkit/examples/hello-mysql/internal/platform/logging"
modkithttp "github.com/go-modkit/modkit/modkit/http"
"github.com/go-modkit/modkit/modkit/module"
)
// @title hello-mysql API
// @version 0.1
// @description Example modkit service with MySQL.
// @BasePath /api/v1
func main() {
boot, handler, err := httpserver.BuildAppHandler()
if err != nil {
log.Fatalf("bootstrap failed: %v", err)
}
addr, err := module.Get[string](boot, configmodule.TokenHTTPAddr)
if err != nil {
log.Fatalf("config load failed: %v", err)
}
logger := logging.New()
logStartup(logger, addr)
server := &http.Server{
Addr: addr,
Handler: handler,
}
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
defer func() {
signal.Stop(sigCh)
close(sigCh)
}()
errCh := make(chan error, 1)
go func() {
errCh <- server.ListenAndServe()
}()
hooks := buildShutdownHooks(boot)
if err := runServer(modkithttp.ShutdownTimeout, server, sigCh, errCh, hooks); err != nil {
log.Fatalf("server failed: %v", err)
}
}
type shutdownServer interface {
ListenAndServe() error
Shutdown(context.Context) error
}
type appLifecycle interface {
CleanupHooks() []func(context.Context) error
CloseContext(context.Context) error
}
func buildShutdownHooks(app appLifecycle) []lifecycle.CleanupHook {
hooks := lifecycle.FromFuncs(app.CleanupHooks())
return append([]lifecycle.CleanupHook{app.CloseContext}, hooks...)
}
func runServer(shutdownTimeout time.Duration, server shutdownServer, sigCh <-chan os.Signal, errCh <-chan error, hooks []lifecycle.CleanupHook) error {
select {
case err := <-errCh:
if err == http.ErrServerClosed {
return nil
}
return err
case <-sigCh:
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
shutdownErr := lifecycle.ShutdownServer(ctx, server, hooks)
err := <-errCh
if err == http.ErrServerClosed {
err = nil
}
if shutdownErr != nil {
return shutdownErr
}
return err
}
}