@@ -2,13 +2,56 @@ package castle
2
2
3
3
import "net/http"
4
4
5
+ type middlewareOpts struct {
6
+ methodFilter string
7
+ pathFilter string
8
+ ignoreEmpty bool
9
+ }
10
+
11
+ type MiddlewareOpt func (* middlewareOpts )
12
+
13
+ func WithMethodFilter (method string ) MiddlewareOpt {
14
+ return func (o * middlewareOpts ) {
15
+ o .methodFilter = method
16
+ }
17
+ }
18
+
19
+ func WithPathFilter (path string ) MiddlewareOpt {
20
+ return func (o * middlewareOpts ) {
21
+ o .pathFilter = path
22
+ }
23
+ }
24
+
25
+ func WithIgnoreEmpty (ignore bool ) MiddlewareOpt {
26
+ return func (o * middlewareOpts ) {
27
+ o .ignoreEmpty = ignore
28
+ }
29
+ }
30
+
5
31
// Middleware is a function that wraps an http.Handler to inject the Castle context into the request.
6
32
// If ignoreEmpty is true, it will skip the middleware if the request token is empty.
7
- func Middleware (ignoreEmpty bool ) func (next http.Handler ) http.Handler {
33
+ func Middleware (opts ... MiddlewareOpt ) func (next http.Handler ) http.Handler {
34
+ options := & middlewareOpts {
35
+ methodFilter : "POST" ,
36
+ ignoreEmpty : true ,
37
+ }
38
+
39
+ for _ , opt := range opts {
40
+ opt (options )
41
+ }
42
+
8
43
return func (next http.Handler ) http.Handler {
9
44
return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
45
+ if options .methodFilter != "" && r .Method != options .methodFilter {
46
+ next .ServeHTTP (w , r )
47
+ return
48
+ }
49
+ if options .pathFilter != "" && r .URL .Path != options .pathFilter {
50
+ next .ServeHTTP (w , r )
51
+ return
52
+ }
10
53
castleCtx := FromHTTPRequest (r )
11
- if ignoreEmpty && castleCtx .RequestToken == "" {
54
+ if options . ignoreEmpty && castleCtx .RequestToken == "" {
12
55
next .ServeHTTP (w , r )
13
56
return
14
57
}
0 commit comments