-
Notifications
You must be signed in to change notification settings - Fork 454
/
router_engine.go
76 lines (62 loc) · 2.58 KB
/
router_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
69
70
71
72
73
74
75
76
package krakend
import (
"encoding/json"
"github.com/gin-gonic/gin"
botdetector "github.com/krakendio/krakend-botdetector/v2/gin"
httpsecure "github.com/krakendio/krakend-httpsecure/v2/gin"
lua "github.com/krakendio/krakend-lua/v2/router/gin"
opencensus "github.com/krakendio/krakend-opencensus/v2/router/gin"
"github.com/luraproject/lura/v2/config"
"github.com/luraproject/lura/v2/core"
luragin "github.com/luraproject/lura/v2/router/gin"
"github.com/luraproject/lura/v2/transport/http/server"
)
// NewEngine creates a new gin engine with some default values and a secure middleware
func NewEngine(cfg config.ServiceConfig, opt luragin.EngineOptions) *gin.Engine {
engine := luragin.NewEngine(cfg, opt)
engine.NoRoute(opencensus.HandlerFunc(&config.EndpointConfig{Endpoint: "NoRoute"}, defaultHandler, nil))
engine.NoMethod(opencensus.HandlerFunc(&config.EndpointConfig{Endpoint: "NoMethod"}, defaultHandler, nil))
if v, ok := cfg.ExtraConfig[luragin.Namespace]; ok && v != nil {
var ginOpts ginOptions
if b, err := json.Marshal(v); err == nil {
json.Unmarshal(b, &ginOpts)
}
if ginOpts.ErrorBody.Err404 != nil {
engine.NoRoute(opencensus.HandlerFunc(&config.EndpointConfig{Endpoint: "NoRoute"}, jsonHandler(404, ginOpts.ErrorBody.Err404), nil))
}
if ginOpts.ErrorBody.Err405 != nil {
engine.NoMethod(opencensus.HandlerFunc(&config.EndpointConfig{Endpoint: "NoMethod"}, jsonHandler(405, ginOpts.ErrorBody.Err405), nil))
}
}
logPrefix := "[SERVICE: Gin]"
if err := httpsecure.Register(cfg.ExtraConfig, engine); err != nil && err != httpsecure.ErrNoConfig {
opt.Logger.Warning(logPrefix+"[HTTPsecure]", err)
} else if err == nil {
opt.Logger.Debug(logPrefix + "[HTTPsecure] Successfully loaded module")
}
lua.Register(opt.Logger, cfg.ExtraConfig, engine)
botdetector.Register(cfg, opt.Logger, engine)
return engine
}
func defaultHandler(c *gin.Context) {
c.Header(core.KrakendHeaderName, core.KrakendHeaderValue)
c.Header(server.CompleteResponseHeaderName, server.HeaderIncompleteResponseValue)
}
func jsonHandler(status int, v interface{}) gin.HandlerFunc {
return func(c *gin.Context) {
defaultHandler(c)
c.JSON(status, v)
}
}
type engineFactory struct{}
func (engineFactory) NewEngine(cfg config.ServiceConfig, opt luragin.EngineOptions) *gin.Engine {
return NewEngine(cfg, opt)
}
type ginOptions struct {
// ErrorBody sets the json body to return to handlers like NoRoute (404) and NoMethod (405)
// Example: "404": { "error": "Not Found", "status": 404 }
ErrorBody struct {
Err404 interface{} `json:"404"`
Err405 interface{} `json:"405"`
} `json:"error_body"`
}