-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb.go
93 lines (79 loc) · 1.77 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
package service
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"time"
"github.com/labstack/echo/v4"
)
var (
_ WebApplication = &WebApp{}
)
// WebApplication interface represents a web application
type WebApplication interface {
Application
GetRouter() *echo.Echo
SetRouter(*echo.Echo)
ListenAndServe()
}
// WebApp is the concrete type of WebApplication
type WebApp struct {
App
Router *echo.Echo
}
// NewWebApp returns a new web app
func NewWebApp() *WebApp {
app := &WebApp{
App: NewApp(),
Router: echo.New(),
}
app.Set("app.web", app, new(WebApplication))
return app
}
// Initialize web application
func (app *WebApp) Initialize() {
app.RegisterHook(LoggerHook, initRouterLogger)
initialize(app)
}
// SetRouter sets router
func (app *WebApp) SetRouter(r *echo.Echo) {
app.Router = r
}
// GetRouter gets router
func (app *WebApp) GetRouter() *echo.Echo {
return app.Router
}
// ListenAndServe the web application
func (app *WebApp) ListenAndServe() {
graceStart(app)
runHooks(ShutdownHook, app)
}
func graceStart(app *WebApp) error {
// Start server
go func() {
if err := app.Router.Start(fmt.Sprintf("%s:%d", app.Config.Host, app.Config.Port)); err != nil {
log.Fatal(err)
}
}()
// Wait for interrupt signal to gracefully shutdown the server with
// a timeout of 3 seconds.
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := app.Router.Shutdown(ctx); err != nil {
log.Println(err)
return err
}
return nil
}
func initRouterLogger(app Application) error {
if webApp, ok := app.(*WebApp); ok {
webApp.GetRouter().Logger = app.DefaultLogger()
return nil
}
return fmt.Errorf("initializing Echo.Logger: app is not *WebApp")
}