diff --git a/macro/handler/handler.go b/macro/handler/handler.go index 24b6367a..e3f10859 100644 --- a/macro/handler/handler.go +++ b/macro/handler/handler.go @@ -11,10 +11,9 @@ import ( // If the template does not contain any dynamic attributes and a special handler is NOT required // then it returns a nil handler and false as its second output value, // the caller should check those two values before any further action. -func MakeHandler(tmpl *macro.Template) (context.Handler, bool) { - needsMacroHandler := len(tmpl.Params) > 0 - if !needsMacroHandler { - return nil, false +func MakeHandler(tmpl *macro.Template) (handler context.Handler, needsMacroHandler bool) { + if len(tmpl.Params) == 0 { + return } // check if we have params like: {name:string} or {name} or {anything:path} without else keyword or any functions used inside these params. @@ -29,10 +28,10 @@ func MakeHandler(tmpl *macro.Template) (context.Handler, bool) { } if !needsMacroHandler { - return nil, false + return } - handler := func(ctx context.Context) { + handler = func(ctx context.Context) { for _, p := range tmpl.Params { if !p.CanEval() { continue // allow. @@ -48,5 +47,5 @@ func MakeHandler(tmpl *macro.Template) (context.Handler, bool) { ctx.Next() } - return handler, true + return } diff --git a/macro/handler/handler_test.go b/macro/handler/handler_test.go new file mode 100644 index 00000000..c22ed663 --- /dev/null +++ b/macro/handler/handler_test.go @@ -0,0 +1,41 @@ +package handler + +import ( + "testing" + + "github.com/kataras/iris/macro" +) + +func TestMakeHandlerNeeds(t *testing.T) { + tests := []struct { + src string + needsHandler bool + }{ + {"/static/static", false}, + {"/{myparam}", false}, + {"/{myparam min(1)}", true}, + {"/{myparam else 500}", true}, + {"/{myparam else 404}", false}, + {"/{myparam:string}/static", false}, + {"/{myparam:int}", true}, + {"/static/{myparam:int}/static", true}, + {"/{myparam:path}", false}, + {"/{myparam:path min(1) else 404}", true}, + } + + availableMacros := *macro.Defaults + for i, tt := range tests { + tmpl, err := macro.Parse(tt.src, availableMacros) + if err != nil { + t.Fatalf("[%d] '%s' failed to be parsed: %v", i, tt.src, err) + } + if _, got := MakeHandler(tmpl); got != tt.needsHandler { + if tt.needsHandler { + t.Fatalf("[%d] '%s' expected to be able to generate an evaluator handler instead of a nil one", i, tt.src) + } else { + t.Fatalf("[%d] '%s' should not need an evaluator handler", i, tt.src) + } + + } + } +}