-
Notifications
You must be signed in to change notification settings - Fork 51
/
souin.go
102 lines (87 loc) · 2.39 KB
/
souin.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
90
91
92
93
94
95
96
97
98
99
100
101
102
package beego
import (
"bytes"
"net/http"
"time"
"github.com/darkweak/souin/configurationtypes"
"github.com/darkweak/souin/pkg/middleware"
"github.com/darkweak/souin/plugins/souin/agnostic"
"github.com/beego/beego/v2/server/web"
beegoCtx "github.com/beego/beego/v2/server/web/context"
)
var (
DefaultConfiguration = middleware.BaseConfiguration{
DefaultCache: &configurationtypes.DefaultCache{
TTL: configurationtypes.Duration{
Duration: 10 * time.Second,
},
},
LogLevel: "info",
}
DevDefaultConfiguration = middleware.BaseConfiguration{
API: configurationtypes.API{
BasePath: "/souin-api",
Prometheus: configurationtypes.APIEndpoint{
Enable: true,
},
Souin: configurationtypes.APIEndpoint{
Enable: true,
},
},
DefaultCache: &configurationtypes.DefaultCache{
Regex: configurationtypes.Regex{
Exclude: "/excluded",
},
TTL: configurationtypes.Duration{
Duration: 5 * time.Second,
},
},
LogLevel: "debug",
}
)
// SouinBeegoMiddleware declaration.
type SouinBeegoMiddleware struct {
*middleware.SouinBaseHandler
}
func NewHTTPCache(c middleware.BaseConfiguration) *SouinBeegoMiddleware {
return &SouinBeegoMiddleware{
SouinBaseHandler: middleware.NewHTTPCacheHandler(&c),
}
}
func configurationPropertyMapper(c map[string]interface{}) middleware.BaseConfiguration {
var configuration middleware.BaseConfiguration
agnostic.ParseConfiguration(&configuration, c)
return configuration
}
func NewHTTPCacheFilter() web.FilterChain {
currentConfig := DefaultConfiguration
if v, e := web.AppConfig.DIY("httpcache"); v != nil && e == nil {
currentConfig = configurationPropertyMapper(v.(map[string]interface{}))
}
httpcache := NewHTTPCache(currentConfig)
return httpcache.chainHandleFilter
}
func (s *SouinBeegoMiddleware) chainHandleFilter(next web.HandleFunc) web.HandleFunc {
return func(c *beegoCtx.Context) {
rw := c.ResponseWriter.ResponseWriter
r := c.Request
customCtx := &beegoCtx.Context{
Input: c.Input,
Output: c.Output,
Request: c.Request,
ResponseWriter: &beegoCtx.Response{
ResponseWriter: nil,
},
}
_ = s.SouinBaseHandler.ServeHTTP(rw, r, func(w http.ResponseWriter, r *http.Request) error {
customWriter := &CustomWriter{
ctx: customCtx,
Buf: bytes.NewBuffer([]byte{}),
Rw: w,
}
customCtx.ResponseWriter.ResponseWriter = customWriter
next(customCtx)
return nil
})
}
}