-
Notifications
You must be signed in to change notification settings - Fork 448
Add adapter for echo framework #95
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| package echo | ||
|
|
||
| import ( | ||
| "net/http" | ||
|
|
||
| sentinel "github.com/alibaba/sentinel-golang/api" | ||
| "github.com/alibaba/sentinel-golang/core/base" | ||
| "github.com/labstack/echo/v4" | ||
| ) | ||
|
|
||
| // SentinelMiddleware | ||
| func SentinelMiddleware(opts ...Option) echo.MiddlewareFunc { | ||
|
|
||
| options := evaluateOptions(opts) | ||
| return func(next echo.HandlerFunc) echo.HandlerFunc { | ||
| return func(c echo.Context) (err error) { | ||
| resourceName := c.Request().Method + ":" + c.Path() | ||
| if options.resourceExtract != nil { | ||
| resourceName = options.resourceExtract(c) | ||
| } | ||
| entry, errEntry := sentinel.Entry( | ||
| resourceName, | ||
| sentinel.WithResourceType(base.ResTypeWeb), | ||
| sentinel.WithTrafficType(base.Inbound), | ||
| ) | ||
|
|
||
| if errEntry != nil { | ||
| if options.blockFallback != nil { | ||
| err = options.blockFallback(c) | ||
| } else { | ||
| err = c.JSON(http.StatusTooManyRequests, "error") | ||
| } | ||
| return err | ||
| } | ||
| defer entry.Exit() | ||
| err = next(c) | ||
| return err | ||
| } | ||
|
|
||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| package echo | ||
|
|
||
| import ( | ||
| "github.com/labstack/echo/v4" | ||
| "github.com/labstack/echo/v4/middleware" | ||
| ) | ||
|
|
||
| func Example() { | ||
| r := echo.New() | ||
| r.Use(middleware.Logger()) | ||
| r.Use( | ||
| SentinelMiddleware( | ||
| // customize resource extractor if required | ||
| // method_path by default | ||
| WithResourceExtractor(func(ctx echo.Context) string { | ||
| if res, ok := ctx.Get("X-Real-IP").(string); ok { | ||
| return res | ||
| } | ||
| return "" | ||
| }), | ||
| // customize block fallback if required | ||
| // abort with status 429 by default | ||
| WithBlockFallback(func(ctx echo.Context) error{ | ||
| return ctx.JSON(400, map[string]interface{}{ | ||
| "err": "too many request; the quota used up", | ||
| "code": 10222, | ||
| }) | ||
| }), | ||
| ), | ||
| ) | ||
|
|
||
| r.GET("/test", func(c echo.Context) error { | ||
| return nil | ||
| }) | ||
| r.Logger.Fatal(r.Start(":1323")) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| package echo | ||
|
|
||
| import ( | ||
| "github.com/labstack/echo/v4" | ||
| "io" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "testing" | ||
|
|
||
| sentinel "github.com/alibaba/sentinel-golang/api" | ||
| "github.com/alibaba/sentinel-golang/core/flow" | ||
| "github.com/stretchr/testify/assert" | ||
| ) | ||
|
|
||
| func initSentinel(t *testing.T) { | ||
| err := sentinel.InitDefault() | ||
| if err != nil { | ||
| t.Fatalf("Unexpected error: %+v", err) | ||
| } | ||
|
|
||
| _, err = flow.LoadRules([]*flow.FlowRule{ | ||
| { | ||
| Resource: "GET:/ping", | ||
| MetricType: flow.QPS, | ||
| Count: 1, | ||
| ControlBehavior: flow.Reject, | ||
| }, | ||
| { | ||
| Resource: "/api/:uid", | ||
| MetricType: flow.QPS, | ||
| Count: 0, | ||
| ControlBehavior: flow.Reject, | ||
| }, | ||
| }) | ||
| if err != nil { | ||
| t.Fatalf("Unexpected error: %+v", err) | ||
| return | ||
| } | ||
| } | ||
|
|
||
| func TestSentinelMiddleware(t *testing.T) { | ||
| type args struct { | ||
| opts []Option | ||
| method string | ||
| path string | ||
| reqPath string | ||
| handler func(ctx echo.Context) error | ||
| body io.Reader | ||
| } | ||
| type want struct { | ||
| code int | ||
| } | ||
| var ( | ||
| tests = []struct { | ||
| name string | ||
| args args | ||
| want want | ||
| }{ | ||
| { | ||
| name: "default get", | ||
| args: args{ | ||
| opts: []Option{}, | ||
| method: http.MethodGet, | ||
| path: "/ping", | ||
| reqPath:"/ping", | ||
| handler: echo.HandlerFunc(func(ctx echo.Context) error { | ||
| return ctx.String(http.StatusOK, "ping") | ||
| }), | ||
| body: nil, | ||
| }, | ||
| want: want{ | ||
| code:http.StatusOK, | ||
| }, | ||
| }, | ||
| { | ||
| name: "customize resource extract", | ||
| args: args{ | ||
| opts: []Option{ | ||
| WithResourceExtractor(func(ctx echo.Context) string { | ||
| return ctx.Path() | ||
| }), | ||
| }, | ||
| method: http.MethodGet, | ||
| path: "/api/:uid", | ||
| reqPath:"/api/123", | ||
| handler: func(ctx echo.Context) error { | ||
| return ctx.JSON(http.StatusOK, "ping") | ||
| }, | ||
| body: nil, | ||
| }, | ||
| want: want{ | ||
| code:http.StatusTooManyRequests, | ||
| }, | ||
| }, | ||
| { | ||
| name: "customize block fallback", | ||
| args: args{ | ||
| opts: []Option{ | ||
| WithBlockFallback(func(ctx echo.Context) error { | ||
| return ctx.JSON(http.StatusBadRequest, "block") | ||
| }), | ||
| }, | ||
| method: http.MethodGet, | ||
| path: "/ping", | ||
| reqPath:"/ping", | ||
| handler: func(ctx echo.Context) error { | ||
| return ctx.JSON(http.StatusOK, "ping") | ||
| }, | ||
| body: nil, | ||
| }, | ||
| want: want{ | ||
| code:http.StatusBadRequest, | ||
| }, | ||
| }, | ||
| } | ||
| ) | ||
| initSentinel(t) | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| router := echo.New() | ||
| router.Use(SentinelMiddleware(tt.args.opts...)) | ||
| router.Add(tt.args.method, tt.args.path, tt.args.handler) | ||
| r := httptest.NewRequest(tt.args.method, tt.args.reqPath, nil) | ||
| w := httptest.NewRecorder() | ||
| router.ServeHTTP(w, r) | ||
|
|
||
| assert.Equal(t, tt.want.code, w.Code) | ||
| }) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| package echo | ||
|
|
||
| import ( | ||
| "github.com/labstack/echo/v4" | ||
| ) | ||
|
|
||
| type ( | ||
| Option func(*options) | ||
| options struct { | ||
| resourceExtract func(echo.Context) string | ||
| blockFallback func(echo.Context) error | ||
| } | ||
| ) | ||
|
|
||
| func evaluateOptions(opts []Option) *options { | ||
| optCopy := &options{} | ||
| for _, opt := range opts { | ||
| opt(optCopy) | ||
| } | ||
|
|
||
| return optCopy | ||
| } | ||
|
|
||
| // WithResourceExtractor set resourceExtract | ||
| func With(handlerFunc echo.HandlerFunc) Option { | ||
zhangmingke marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| return func(opts *options) { | ||
| return | ||
| } | ||
| } | ||
|
|
||
| func WithResourceExtractor(fn func(ctx echo.Context) string) Option { | ||
| return func(opts *options) { | ||
| opts.resourceExtract = fn | ||
| } | ||
| } | ||
|
|
||
| // WithBlockFallback set blockFallback | ||
| func WithBlockFallback(fn func(ctx echo.Context) error) Option { | ||
| return func(opts *options) { | ||
| opts.blockFallback = fn | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.