/
app.go
89 lines (72 loc) · 1.9 KB
/
app.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
package app
import (
"context"
"net/http"
"strings"
"time"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/sirupsen/logrus"
"github.com/typical-go/typical-rest-server/internal/app/domain/mylibrary"
"github.com/typical-go/typical-rest-server/internal/app/domain/mymusic"
"github.com/typical-go/typical-rest-server/internal/app/infra"
"github.com/typical-go/typical-rest-server/internal/app/infra/log"
"github.com/typical-go/typical-rest-server/pkg/logruskit"
"github.com/typical-go/typical-rest-server/pkg/typrest"
"go.uber.org/dig"
// enable `/debug/vars`
_ "expvar"
// enable `/debug/pprof` API
_ "net/http/pprof"
)
const (
healthCheckPath = "/application/health"
)
type (
app struct {
dig.In
Config *infra.AppCfg
Library mylibrary.Router
Album mymusic.Router
HealthCheck infra.HealthCheck
}
)
// Start app
func Start(a app) (err error) {
e := echo.New()
defer shutdown(e)
e.HideBanner = true
e.Debug = a.Config.Debug
logger := log.SetDebug(a.Config.Debug)
e.Logger = logruskit.EchoLogger(logger)
setMiddleware(a, e)
setRoute(a, e)
return e.StartServer(&http.Server{
Addr: a.Config.Address,
ReadTimeout: a.Config.ReadTimeout,
WriteTimeout: a.Config.WriteTimeout,
})
}
func setMiddleware(a app, e *echo.Echo) {
e.Use(log.Middleware)
e.Use(middleware.Recover())
}
func setRoute(a app, e *echo.Echo) {
typrest.SetRoute(e,
&a.Library,
&a.Album,
)
e.GET(healthCheckPath, a.HealthCheck.Handle)
e.HEAD(healthCheckPath, a.HealthCheck.Handle)
e.GET("/debug/*", echo.WrapHandler(http.DefaultServeMux))
e.GET("/debug/*/*", echo.WrapHandler(http.DefaultServeMux))
if a.Config.Debug {
logrus.Debugf("Print routes:\n %s\n\n",
strings.Join(typrest.DumpEcho(e), "\n "))
}
}
func shutdown(e *echo.Echo) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
e.Shutdown(ctx)
}