From 1a4803307de61f7a4c2e9a95c59942c759787d86 Mon Sep 17 00:00:00 2001 From: Gerasimos Maropoulos Date: Mon, 5 Mar 2018 20:09:30 +0200 Subject: [PATCH] Add one more example for custom router macro functions, relative to https://github.com/kataras/iris/issues/918 Former-commit-id: 457c1a94dc8d93e614e9da70e1ec2482fe0c5765 --- _examples/routing/dynamic-path/main.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/_examples/routing/dynamic-path/main.go b/_examples/routing/dynamic-path/main.go index b7e78c40..5a3f0b57 100644 --- a/_examples/routing/dynamic-path/main.go +++ b/_examples/routing/dynamic-path/main.go @@ -1,6 +1,7 @@ package main import ( + "regexp" "strconv" "github.com/kataras/iris" @@ -140,6 +141,24 @@ func main() { ctx.Writef("Hello id: %d looking for friend id: ", id, friendid) }) // this will throw e 504 error code instead of 404 if all route's macros not passed. + // Another example using a custom regexp and any custom logic. + latLonExpr := "^-?[0-9]{1,3}(?:\\.[0-9]{1,10})?$" + latLonRegex, err := regexp.Compile(latLonExpr) + if err != nil { + panic(err) + } + + app.Macros().String.RegisterFunc("coordinate", func() func(paramName string) (ok bool) { + // MatchString is a type of func(string) bool, so we can return that as it's. + return latLonRegex.MatchString + }) + + app.Get("/coordinates/{lat:string coordinate() else 502}/{lon:string coordinate() else 502}", func(ctx iris.Context) { + ctx.Writef("Lat: %s | Lon: %s", ctx.Params().Get("lat"), ctx.Params().Get("lon")) + }) + + // + // http://localhost:8080/game/a-zA-Z/level/0-9 // remember, alphabetical is lowercase or uppercase letters only. app.Get("/game/{name:alphabetical}/level/{level:int}", func(ctx iris.Context) {