/
app.go
83 lines (73 loc) · 1.77 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
package uci_master
import (
"context"
"fmt"
"github.com/cheerego/uci/app/uci-master/internal/config"
"github.com/cheerego/uci/app/uci-master/internal/provider"
"github.com/cheerego/uci/app/uci-master/internal/service"
"github.com/cheerego/uci/pkg/http"
signal2 "github.com/cheerego/uci/pkg/signal"
"github.com/cheerego/uci/pkg/uerror"
"github.com/cockroachdb/errors"
"github.com/go-playground/validator"
"github.com/labstack/echo/v4"
"golang.org/x/sync/errgroup"
http2 "net/http"
)
type Application struct {
engine *echo.Echo
}
func NewApplication() *Application {
return &Application{}
}
func (a *Application) Start() error {
err := config.Register()
if err != nil {
return err
}
err = provider.Register()
if err != nil {
return err
}
err = service.Register()
if err != nil {
return err
}
ctx, cancel := context.WithCancel(context.Background())
g, gctx := errgroup.WithContext(ctx)
g.Go(a.startHttp)
g.Go(func() error {
<-gctx.Done()
return a.engine.Shutdown(gctx)
})
//
//waiting exit signal
g.Go(func() error {
quit := signal2.KillSignal()
select {
case <-gctx.Done():
return gctx.Err()
case <-quit:
cancel()
return errors.New("ErrExitSignal1")
}
})
return g.Wait()
}
func (a *Application) startHttp() error {
engine := http.NewEcho()
a.engine = engine
engine.Validator = &CustomValidator{validator: validator.New()}
Routes(engine)
engine.HTTPErrorHandler = uerror.JSONHttpErrorHandler(engine)
return engine.Start(fmt.Sprintf(":%d", config.Configs.HttpPort))
}
type CustomValidator struct {
validator *validator.Validate
}
func (cv *CustomValidator) Validate(i interface{}) error {
if err := cv.validator.Struct(i); err != nil {
return echo.NewHTTPError(http2.StatusBadRequest, err.Error()).SetInternal(err)
}
return nil
}