-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathengine.go
68 lines (61 loc) · 1.32 KB
/
engine.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
package rest
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gozelus/zelus_rest/core"
"github.com/pkg/errors"
"net/http"
"time"
)
type engz struct {
jwtUtils *core.JwtUtils
ginEng *gin.Engine
}
func newEngz() *engz {
ginEng := gin.New()
gin.SetMode(gin.ReleaseMode)
return &engz{
ginEng: ginEng,
}
}
func (e *engz) use(middlrewares ...HandlerFunc) {
for _, m := range middlrewares {
e.ginEng.Use(func(context *gin.Context) {
m(newContext(context))
})
}
}
func (e *engz) addRoute(method, path string, timeout time.Duration, f HandlerFunc) error {
var wrap = func(ctx *gin.Context) {
c := newContext(ctx)
c.setJwtUtils(e.jwtUtils)
if timeout == 0 {
timeout = time.Millisecond * 2000 // 默认2000ms
}
c.setTimeout(timeout)
f(c)
}
switch method {
case http.MethodGet:
e.ginEng.GET(path, wrap)
case http.MethodPost:
e.ginEng.POST(path, wrap)
case http.MethodOptions:
e.ginEng.OPTIONS(path, wrap)
case http.MethodDelete:
e.ginEng.DELETE(path, wrap)
case http.MethodPut:
e.ginEng.PUT(path, wrap)
case http.MethodHead:
e.ginEng.HEAD(path, wrap)
default:
return errors.Errorf("invalid method : %s", method)
}
return nil
}
func (e *engz) setJwtUtils(jwt *core.JwtUtils) {
e.jwtUtils = jwt
}
func (e *engz) run(port int) error {
return e.ginEng.Run(fmt.Sprintf(":%d", port))
}