This repository has been archived by the owner on Sep 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-rest.go
89 lines (65 loc) · 1.99 KB
/
service-rest.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 service
import (
"fmt"
"sync"
ginzap "github.com/gin-contrib/zap"
"github.com/gin-gonic/gin"
"github.com/itbasis/go-service/v2/rest"
"github.com/juju/zaputil/zapctx"
"go.uber.org/zap/zapcore"
)
type HTTPController struct {
Method string
Path string
Handler gin.HandlerFunc
}
func (receiver *Service) GetGin() *gin.Engine {
if receiver.gin == nil {
receiver.initGinServer()
}
return receiver.gin
}
func (receiver *Service) AddHTTPControllers(httpControllers ...HTTPController) {
log := zapctx.Default.Sugar()
log.Debugf("REST controllers for adding: %v", httpControllers)
receiver.ginControllers = append(receiver.ginControllers, httpControllers...)
log.Debugf("REST controllers: %v", receiver.ginControllers)
log.Debugf("gin: %v", receiver.gin)
if receiver.gin != nil {
for _, restController := range httpControllers {
log.Debugf("adding REST controller: %v", restController)
receiver.gin.Handle(restController.Method, restController.Path, restController.Handler)
}
}
}
func (receiver *Service) initGinServer() {
log := zapctx.Default
receiver.gin = gin.New()
receiver.gin.Use(
gin.Recovery(),
ginzap.RecoveryWithZap(zapctx.Default, true),
)
if log.Core().Enabled(zapcore.DebugLevel) {
log.Info("enable REST request tracing")
receiver.gin.Use(rest.LoggingRequest)
}
log.Debug(fmt.Sprintf("REST controllers: %v", receiver.ginControllers))
for _, restController := range receiver.ginControllers {
log.Debug(fmt.Sprintf("adding REST controller: %v", restController))
receiver.gin.Handle(restController.Method, restController.Path, restController.Handler)
}
}
func (receiver *Service) runGinServer(wg *sync.WaitGroup) {
log := zapctx.Default
engine := receiver.GetGin()
if engine == nil {
wg.Done()
return
}
listen := fmt.Sprintf("%s:%d", receiver.config.RestServerHost, receiver.config.RestServerPort)
log.Debug(fmt.Sprintf("rest listen address: %s", listen))
if err := engine.Run(listen); err != nil {
log.Panic(err.Error())
}
wg.Done()
}