Skip to content

Commit f4c2c59

Browse files
authored
Add adapter for goframe framework (#588)
1 parent b8d94d1 commit f4c2c59

File tree

7 files changed

+901
-0
lines changed

7 files changed

+901
-0
lines changed

Diff for: pkg/adapters/goframe/doc.go

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Package goframe provides Sentinel middleware for GoFrame.
2+
//
3+
// Users may register SentinelMiddleware to the GoFrame server, like:
4+
//
5+
// import (
6+
// sentinelPlugin "github.com/your-repo/goframe-sentinel-adapter"
7+
// "github.com/gogf/gf/v2/frame/g"
8+
// "github.com/gogf/gf/v2/net/ghttp"
9+
// )
10+
//
11+
// s := g.Server()
12+
// s.Use(ghttp.MiddlewareHandlerFunc(sentinelPlugin.SentinelMiddleware()))
13+
//
14+
// The plugin extracts "HttpMethod:FullPath" as the resource name by default (e.g. GET:/foo/:id).
15+
// Users may provide a customized resource name extractor when creating new SentinelMiddleware (via options).
16+
//
17+
// Fallback logic: the plugin will return "429 Too Many Requests" status code if the current request is blocked by Sentinel rules.
18+
// Users may also provide customized fallback logic via WithBlockFallback(handler) options.
19+
package goframe

Diff for: pkg/adapters/goframe/go.mod

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
module github.com/alibaba/sentinel-golang/pkg/adapters/goframe
2+
3+
go 1.18
4+
5+
require (
6+
github.com/alibaba/sentinel-golang v1.0.4
7+
github.com/gogf/gf/v2 v2.6.4
8+
github.com/stretchr/testify v1.8.2
9+
)
10+
11+
require (
12+
github.com/BurntSushi/toml v1.2.0 // indirect
13+
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d // indirect
14+
github.com/beorn7/perks v1.0.1 // indirect
15+
github.com/cespare/xxhash/v2 v2.1.1 // indirect
16+
github.com/clbanning/mxj/v2 v2.7.0 // indirect
17+
github.com/davecgh/go-spew v1.1.1 // indirect
18+
github.com/fatih/color v1.15.0 // indirect
19+
github.com/fsnotify/fsnotify v1.7.0 // indirect
20+
github.com/go-logr/logr v1.2.4 // indirect
21+
github.com/go-logr/stdr v1.2.2 // indirect
22+
github.com/go-ole/go-ole v1.2.4 // indirect
23+
github.com/golang/protobuf v1.4.3 // indirect
24+
github.com/google/uuid v1.1.1 // indirect
25+
github.com/gorilla/websocket v1.5.0 // indirect
26+
github.com/grokify/html-strip-tags-go v0.0.1 // indirect
27+
github.com/magiconair/properties v1.8.6 // indirect
28+
github.com/mattn/go-colorable v0.1.13 // indirect
29+
github.com/mattn/go-isatty v0.0.20 // indirect
30+
github.com/mattn/go-runewidth v0.0.15 // indirect
31+
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
32+
github.com/olekukonko/tablewriter v0.0.5 // indirect
33+
github.com/pkg/errors v0.9.1 // indirect
34+
github.com/pmezard/go-difflib v1.0.0 // indirect
35+
github.com/prometheus/client_golang v1.9.0 // indirect
36+
github.com/prometheus/client_model v0.2.0 // indirect
37+
github.com/prometheus/common v0.15.0 // indirect
38+
github.com/prometheus/procfs v0.2.0 // indirect
39+
github.com/rivo/uniseg v0.4.4 // indirect
40+
github.com/shirou/gopsutil/v3 v3.21.6 // indirect
41+
github.com/tklauser/go-sysconf v0.3.6 // indirect
42+
github.com/tklauser/numcpus v0.2.2 // indirect
43+
go.opentelemetry.io/otel v1.14.0 // indirect
44+
go.opentelemetry.io/otel/sdk v1.14.0 // indirect
45+
go.opentelemetry.io/otel/trace v1.14.0 // indirect
46+
golang.org/x/net v0.17.0 // indirect
47+
golang.org/x/sys v0.13.0 // indirect
48+
golang.org/x/text v0.13.0 // indirect
49+
google.golang.org/protobuf v1.23.0 // indirect
50+
gopkg.in/yaml.v2 v2.3.0 // indirect
51+
gopkg.in/yaml.v3 v3.0.1 // indirect
52+
)

Diff for: pkg/adapters/goframe/go.sum

+481
Large diffs are not rendered by default.

Diff for: pkg/adapters/goframe/middleware.go

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package goframe
2+
3+
import (
4+
"github.com/alibaba/sentinel-golang/api"
5+
"github.com/alibaba/sentinel-golang/core/base"
6+
"github.com/gogf/gf/v2/net/ghttp"
7+
"net/http"
8+
)
9+
10+
// SentinelMiddleware returns new ghttp.HandlerFunc
11+
// Default resource name is {method}:{path}, such as "GET:/api/users/:id"
12+
// Default block fallback is returning 429 status code
13+
// Define your own behavior by setting options
14+
func SentinelMiddleware(opts ...Option) ghttp.HandlerFunc {
15+
options := evaluateOptions(opts)
16+
return func(r *ghttp.Request) {
17+
resourceName := r.Method + ":" + r.URL.Path
18+
19+
if options.resourceExtract != nil {
20+
resourceName = options.resourceExtract(r)
21+
}
22+
23+
entry, err := api.Entry(
24+
resourceName,
25+
api.WithResourceType(base.ResTypeWeb),
26+
api.WithTrafficType(base.Inbound),
27+
)
28+
29+
if err != nil {
30+
if options.blockFallback != nil {
31+
options.blockFallback(r)
32+
} else {
33+
r.Response.WriteHeader(http.StatusTooManyRequests)
34+
r.Response.Writeln("Too Many Requests")
35+
}
36+
return
37+
}
38+
39+
defer entry.Exit()
40+
41+
r.Middleware.Next()
42+
}
43+
}

Diff for: pkg/adapters/goframe/middleware_example_test.go

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package goframe
2+
3+
import (
4+
"github.com/gogf/gf/v2/frame/g"
5+
"github.com/gogf/gf/v2/net/ghttp"
6+
)
7+
8+
func Example() {
9+
s := g.Server()
10+
s.Use(
11+
SentinelMiddleware(
12+
// customize resource extractor if required
13+
WithResourceExtractor(func(r *ghttp.Request) string {
14+
if res, ok := r.Header["X-Real-IP"]; ok && len(res) > 0 {
15+
return res[0]
16+
}
17+
return ""
18+
}),
19+
// customize block fallback if required
20+
WithBlockFallback(func(r *ghttp.Request) {
21+
r.Response.WriteHeader(400)
22+
r.Response.WriteJson(map[string]interface{}{
23+
"err": "too many requests; the quota used up",
24+
"code": 10222,
25+
})
26+
}),
27+
),
28+
)
29+
30+
s.Group("/", func(group *ghttp.RouterGroup) {
31+
group.GET("/test", func(r *ghttp.Request) {
32+
r.Response.Write("hello sentinel")
33+
})
34+
})
35+
36+
s.SetPort(8199)
37+
}

Diff for: pkg/adapters/goframe/middleware_test.go

+235
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,235 @@
1+
package goframe
2+
3+
import (
4+
sentinel "github.com/alibaba/sentinel-golang/api"
5+
"github.com/alibaba/sentinel-golang/core/flow"
6+
"github.com/gogf/gf/v2/frame/g"
7+
"github.com/gogf/gf/v2/net/ghttp"
8+
"github.com/stretchr/testify/assert"
9+
"io"
10+
"net/http"
11+
"net/http/httptest"
12+
"testing"
13+
)
14+
15+
func initSentinel(t *testing.T) {
16+
err := sentinel.InitDefault()
17+
if err != nil {
18+
t.Fatalf("Unexpected error: %+v", err)
19+
}
20+
21+
_, err = flow.LoadRules([]*flow.Rule{
22+
{
23+
Resource: "GET:/",
24+
Threshold: 1.0,
25+
TokenCalculateStrategy: flow.Direct,
26+
ControlBehavior: flow.Reject,
27+
StatIntervalInMs: 1000,
28+
},
29+
{
30+
Resource: "/api/users/:id",
31+
Threshold: 0.0,
32+
TokenCalculateStrategy: flow.Direct,
33+
ControlBehavior: flow.Reject,
34+
StatIntervalInMs: 1000,
35+
},
36+
{
37+
Resource: "GET:/ping",
38+
Threshold: 0.0,
39+
TokenCalculateStrategy: flow.Direct,
40+
ControlBehavior: flow.Reject,
41+
StatIntervalInMs: 1000,
42+
},
43+
})
44+
if err != nil {
45+
t.Fatalf("Unexpected error: %+v", err)
46+
return
47+
}
48+
}
49+
50+
// go test -run ^TestSentinelMiddlewareDefault -v
51+
func TestSentinelMiddlewareDefault(t *testing.T) {
52+
type args struct {
53+
opts []Option
54+
method string
55+
path string
56+
reqPath string
57+
handler func(r *ghttp.Request)
58+
body io.Reader
59+
}
60+
type want struct {
61+
code int
62+
}
63+
var (
64+
tests = []struct {
65+
name string
66+
args args
67+
want want
68+
}{
69+
{
70+
name: "default get",
71+
args: args{
72+
opts: []Option{
73+
WithResourceExtractor(func(r *ghttp.Request) string {
74+
return r.Router.Uri
75+
}),
76+
},
77+
method: http.MethodPost,
78+
path: "/",
79+
reqPath: "/",
80+
handler: func(r *ghttp.Request) {
81+
r.Response.WriteStatusExit(http.StatusOK, "/")
82+
},
83+
body: nil,
84+
},
85+
want: want{
86+
code: http.StatusOK,
87+
},
88+
},
89+
}
90+
)
91+
92+
initSentinel(t)
93+
94+
for _, tt := range tests {
95+
t.Run(tt.name, func(t *testing.T) {
96+
s := g.Server()
97+
s.SetRouteOverWrite(true)
98+
s.Group("/", func(group *ghttp.RouterGroup) {
99+
group.Middleware(SentinelMiddleware(tt.args.opts...))
100+
group.ALL(tt.args.path, tt.args.handler)
101+
})
102+
s.Start()
103+
104+
r := httptest.NewRequest(tt.args.method, tt.args.reqPath, tt.args.body)
105+
w := httptest.NewRecorder()
106+
s.ServeHTTP(w, r)
107+
108+
assert.Equal(t, tt.want.code, w.Code)
109+
})
110+
}
111+
}
112+
113+
// go test -run ^TestSentinelMiddlewareExtractor -v
114+
func TestSentinelMiddlewareExtractor(t *testing.T) {
115+
type args struct {
116+
opts []Option
117+
method string
118+
path string
119+
reqPath string
120+
handler func(r *ghttp.Request)
121+
body io.Reader
122+
}
123+
type want struct {
124+
code int
125+
}
126+
var (
127+
tests = []struct {
128+
name string
129+
args args
130+
want want
131+
}{
132+
{
133+
name: "customize resource extract",
134+
args: args{
135+
opts: []Option{
136+
WithResourceExtractor(func(r *ghttp.Request) string {
137+
return r.Router.Uri
138+
}),
139+
},
140+
method: http.MethodPost,
141+
path: "/api/users/:id",
142+
reqPath: "/api/users/123",
143+
handler: func(r *ghttp.Request) {
144+
r.Response.WriteStatusExit(http.StatusOK, "/api/users/123")
145+
},
146+
body: nil,
147+
},
148+
want: want{
149+
code: http.StatusTooManyRequests,
150+
},
151+
},
152+
}
153+
)
154+
155+
initSentinel(t)
156+
157+
for _, tt := range tests {
158+
t.Run(tt.name, func(t *testing.T) {
159+
s := g.Server()
160+
s.SetRouteOverWrite(true)
161+
s.Group("/", func(group *ghttp.RouterGroup) {
162+
group.Middleware(SentinelMiddleware(tt.args.opts...))
163+
group.ALL(tt.args.path, tt.args.handler)
164+
})
165+
s.Start()
166+
167+
r := httptest.NewRequest(tt.args.method, tt.args.reqPath, tt.args.body)
168+
w := httptest.NewRecorder()
169+
s.ServeHTTP(w, r)
170+
assert.Equal(t, tt.want.code, w.Code)
171+
})
172+
}
173+
}
174+
175+
// go test -run ^TestSentinelMiddlewareFallback -v
176+
func TestSentinelMiddlewareFallback(t *testing.T) {
177+
type args struct {
178+
opts []Option
179+
method string
180+
path string
181+
reqPath string
182+
handler func(r *ghttp.Request)
183+
body io.Reader
184+
}
185+
type want struct {
186+
code int
187+
}
188+
var (
189+
tests = []struct {
190+
name string
191+
args args
192+
want want
193+
}{
194+
{
195+
name: "customize block fallback",
196+
args: args{
197+
opts: []Option{
198+
WithBlockFallback(func(r *ghttp.Request) {
199+
r.Response.WriteStatus(http.StatusBadRequest, "/ping")
200+
}),
201+
},
202+
method: http.MethodGet,
203+
path: "/ping",
204+
reqPath: "/ping",
205+
handler: func(r *ghttp.Request) {
206+
r.Response.WriteStatus(http.StatusOK, "ping")
207+
},
208+
body: nil,
209+
},
210+
want: want{
211+
code: http.StatusBadRequest,
212+
},
213+
},
214+
}
215+
)
216+
217+
initSentinel(t)
218+
219+
for _, tt := range tests {
220+
t.Run(tt.name, func(t *testing.T) {
221+
s := g.Server()
222+
s.SetRouteOverWrite(true)
223+
s.Group("/", func(group *ghttp.RouterGroup) {
224+
group.Middleware(SentinelMiddleware(tt.args.opts...))
225+
group.ALL(tt.args.path, tt.args.handler)
226+
})
227+
s.Start()
228+
229+
r := httptest.NewRequest(tt.args.method, tt.args.reqPath, tt.args.body)
230+
w := httptest.NewRecorder()
231+
s.ServeHTTP(w, r)
232+
assert.Equal(t, tt.want.code, w.Code)
233+
})
234+
}
235+
}

0 commit comments

Comments
 (0)