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
|
package server
import (
"context"
"fmt"
"net/http"
"time"
"github.com/kelseyhightower/envconfig"
"github.com/pkg/errors"
"go.uber.org/zap"
)
type ServerConfig struct {
Port int `envconfig:"PORT" default:"4433"`
LocalCerts bool `envconfig:"LOCAL_CERTS" default:"false" split_words:"true"`
}
func Run(ctx context.Context) error {
var config ServerConfig
err := envconfig.Process("", &config)
if err != nil {
return errors.Wrap(err, "loading environment")
}
addr := fmt.Sprintf(":%d", config.Port)
if config.LocalCerts {
if !hasCerts() {
_, err := generateCerts()
if err != nil {
return err
}
}
}
httpRouter := http.NewServeMux()
webMux, err := NewRouter(ctx)
if err != nil {
return err
}
httpRouter.Handle("/", webMux)
server := &http.Server{Addr: addr, Handler: httpRouter}
errCh := make(chan error, 1)
go func() {
zap.S().Infof("started listening on %s", addr)
if config.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
}
}
}
|