-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
64 lines (55 loc) · 1.11 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
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/urfave/cli/v2"
)
var (
dbDSN string
address int
)
func main() {
a := cli.NewApp()
a.Flags = []cli.Flag{
&cli.StringFlag{
Name: "db-dsn",
EnvVars: []string{"DB_DSN"},
Destination: &dbDSN,
Required: true,
},
&cli.IntFlag{
Name: "address",
EnvVars: []string{"SERVER_ADDRESS"},
Required: true,
Destination: &address,
},
}
a.Action = run
if err := a.Run(os.Args); err != nil {
log.Fatal(err)
}
}
func run(c *cli.Context) error {
srv := &http.Server{
Addr: fmt.Sprintf(":%d", address),
Handler: http.DefaultServeMux,
WriteTimeout: 10 * time.Second,
ReadTimeout: 10 * time.Second,
IdleTimeout: 15 * time.Second,
}
go gracefulServerShutdown(c.Context, srv)
return srv.ListenAndServe()
}
func gracefulServerShutdown(ctx context.Context, srv *http.Server) {
<-ctx.Done()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
srv.SetKeepAlivesEnabled(false)
if err := srv.Shutdown(ctx); err != nil {
panic(err)
}
}