-
Notifications
You must be signed in to change notification settings - Fork 3
/
web.go
100 lines (86 loc) · 2.1 KB
/
web.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
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
package cmd
import (
"context"
"fmt"
"log"
"net/http"
cfg "github.com/slotopol/server/config"
"github.com/slotopol/server/spi"
"golang.org/x/sync/errgroup"
"github.com/gin-gonic/gin"
"github.com/spf13/cobra"
)
const webShort = "Starts web-server"
const webLong = ``
const webExmp = `
%s web`
var exitctx context.Context
// webCmd represents the web command
var webCmd = &cobra.Command{
Use: "web",
Short: webShort,
Long: webLong,
Example: fmt.Sprintf(webExmp, cfg.AppName),
RunE: func(cmd *cobra.Command, args []string) (err error) {
if cfg.DevMode {
gin.SetMode(gin.DebugMode)
} else {
gin.SetMode(gin.ReleaseMode)
}
if exitctx, err = Init(); err != nil {
return
}
var r = gin.New()
r.SetTrustedProxies(Cfg.TrustedProxies)
spi.Router(r)
// starts HTTP listeners
var wg errgroup.Group
for _, addr := range Cfg.PortHTTP {
log.Printf("start http on %s\n", addr)
var srv = http.Server{
Addr: addr,
Handler: r.Handler(),
ReadTimeout: Cfg.ReadTimeout,
ReadHeaderTimeout: Cfg.ReadHeaderTimeout,
WriteTimeout: Cfg.WriteTimeout,
IdleTimeout: Cfg.IdleTimeout,
MaxHeaderBytes: Cfg.MaxHeaderBytes,
}
wg.Go(func() (err error) {
var ctx, cancel = context.WithCancel(context.Background())
go func() {
defer cancel()
// service connections
if err = srv.ListenAndServe(); err != nil {
if err != http.ErrServerClosed {
err = fmt.Errorf("failed to serve on %s: %w", addr, err)
return
}
err = nil
}
log.Printf("stop http on %s\n", addr)
}()
select {
case <-ctx.Done():
case <-exitctx.Done():
// create a deadline to wait for.
var ctx, cancel = context.WithTimeout(context.Background(), Cfg.ShutdownTimeout)
defer cancel()
if err = srv.Shutdown(ctx); err != nil {
err = fmt.Errorf("shutdown http on %s: %w", addr, err)
return
}
}
return
})
}
if err = wg.Wait(); err != nil {
log.Println(err.Error())
return
}
return nil
},
}
func init() {
rootCmd.AddCommand(webCmd)
}