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
100
101
102
|
package server
import (
"context"
"fmt"
"net/http"
"time"
"github.com/grindlemire/gothem-stack/pkg/nodes/config"
"github.com/grindlemire/gothem-stack/pkg/nodes/router"
"go.uber.org/zap"
"github.com/grindlemire/graft"
"github.com/pkg/errors"
)
const ID = graft.ID("server")
type Output struct {
Err error
}
func init() {
graft.Register(graft.Node[Output]{
ID: ID,
Cacheable: true,
DependsOn: []graft.ID{config.ID, router.ID},
Run: run,
})
}
func run(ctx context.Context) (Output, error) {
config, err := graft.Dep[config.Output](ctx)
if err != nil {
return Output{}, errors.Wrap(err, "getting config")
}
router, err := graft.Dep[router.Output](ctx)
if err != nil {
return Output{}, errors.Wrap(err, "getting router")
}
if config.Server.LocalCerts {
if !hasCerts() {
_, err := generateCerts()
if err != nil {
return Output{}, errors.Wrap(err, "generating certs")
}
}
}
server := &http.Server{
Addr: fmt.Sprintf(":%d", config.Server.Port),
Handler: router,
}
err = start(ctx, server, config)
if err != nil {
return Output{
Err: errors.Wrap(err, "starting server"),
}, nil
}
return Output{
Err: nil,
}, nil
}
func start(ctx context.Context, server *http.Server, config config.Output) (err error) {
errCh := make(chan error, 1)
go func() {
zap.S().Infof("started listening on :%d", config.Server.Port)
if config.Server.LocalCerts {
zap.S().Debug(ctx, "listening with tls")
err := server.ListenAndServeTLS(publicKeyFile, privateKeyFile)
errCh <- errors.Wrap(err, "starting server")
return
}
err := server.ListenAndServe()
errCh <- errors.Wrap(err, "starting server")
}()
for {
select {
case <-ctx.Done():
shutdownCTX, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err = server.Shutdown(shutdownCTX)
if err != nil {
return err
}
return ctx.Err()
case err := <-errCh:
return err
}
}
}
|