-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
78 lines (68 loc) · 1.67 KB
/
api.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
package acrouter
import (
"strconv"
"github.com/gin-gonic/gin"
)
type ApiServer struct {
Engine *gin.Engine
ipAddr string
port int
certFile string
keyFile string
}
func NewApiServer(ipAddr string, port int) *ApiServer {
gin.SetMode(gin.ReleaseMode)
s := &ApiServer{
ipAddr: ipAddr,
port: port,
Engine: gin.New(),
}
s.setMiddleware()
return s
}
func NewApiTlsServer(ipAddr string, port int, certFile, keyFile string) *ApiServer {
s := NewApiServer(ipAddr, port)
s.keyFile = keyFile
s.certFile = certFile
return s
}
// Initialize middleware and use zap to record log
// Recovery can record log and recover when the request crashes
func (aps *ApiServer) setMiddleware() {
/*
aps.Engine.Use(func(c *gin.Context) {
start := time.Now()
c.Next()
end := time.Now()
latency := end.Sub(start)
path := c.Request.URL.Path
clientIP := c.ClientIP()
method := c.Request.Method
statusCode := c.Writer.Status()
logger.Info("api request",
zap.Int("status_code", statusCode),
zap.Duration("latency", latency),
zap.String("client_ip", clientIP),
zap.String("method", method),
zap.String("path", path),
)
})
*/
aps.Engine.Use(gin.Recovery())
}
// Turn on debug mode
func (aps *ApiServer) SetDebug() {
gin.SetMode(gin.DebugMode)
}
// Set no route handle
func (aps *ApiServer) SetNoRoute(handlerFunc gin.HandlerFunc) {
aps.Engine.NoRoute(handlerFunc)
}
// Run api server
func (aps *ApiServer) Run() error {
return aps.Engine.Run(aps.ipAddr + ":" + strconv.Itoa(aps.port))
}
// Run api tls server
func (aps *ApiServer) RunTLS() error {
return aps.Engine.RunTLS(aps.ipAddr+":"+strconv.Itoa(aps.port), aps.certFile, aps.keyFile)
}