-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb_server.go
86 lines (69 loc) · 1.74 KB
/
web_server.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
package main
import (
"context"
"log"
"net/http"
"time"
"github.com/blockassets/bam_agent/controller"
"github.com/blockassets/bam_agent/tool"
"github.com/jpillora/overseer"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"go.uber.org/fx"
)
type WebServer struct {
echo *echo.Echo
ctrl controller.Manager
state overseer.State
staticRiceBox tool.StaticRiceBox
}
func NewWebServer(e *echo.Echo, ctrl controller.Manager, state overseer.State, staticRiceBox tool.StaticRiceBox) *WebServer {
return &WebServer{
echo: e,
ctrl: ctrl,
state: state,
staticRiceBox: staticRiceBox,
}
}
func (server *WebServer) Start() {
go func() {
go run(server.echo, server.state, server.staticRiceBox)
// Blocks until we receive a shutdown notice
<-server.state.GracefulShutdown
stop(server)
}()
}
func (server *WebServer) Stop() {
server.state.GracefulShutdown <- true
}
func stop(server *WebServer) {
// After 10 seconds we gracefully shutdown the server
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := server.echo.Shutdown(ctx); err != nil {
server.echo.Logger.Fatal(err)
} else {
log.Println("Shutdown")
}
}
func run(e *echo.Echo, state overseer.State, staticRiceBox tool.StaticRiceBox) {
e.HideBanner = true
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.GET("/favicon.ico", echo.WrapHandler(http.FileServer((*staticRiceBox).HTTPBox())))
// Start server
if state.Listener != nil {
e.Listener = state.Listener
}
e.Logger.Fatal(e.Start(state.Address))
}
func NewEcho() *echo.Echo {
return echo.New()
}
var WebServerModule = fx.Options(
controller.Module,
fx.Provide(
NewEcho,
NewWebServer,
),
)