|
| 1 | +// Package main an example on how to naming your routes & use the custom 'url path' Jet Template Engine. |
| 2 | +package main |
| 3 | + |
| 4 | +import ( |
| 5 | + "github.com/kataras/iris/v12" |
| 6 | +) |
| 7 | + |
| 8 | +func main() { |
| 9 | + app := iris.New() |
| 10 | + app.RegisterView(iris.Jet("./views", ".jet").Reload(true)) |
| 11 | + |
| 12 | + mypathRoute := app.Get("/mypath", writePathHandler) |
| 13 | + mypathRoute.Name = "my-page1" |
| 14 | + |
| 15 | + mypath2Route := app.Get("/mypath2/{paramfirst}/{paramsecond}", writePathHandler) |
| 16 | + mypath2Route.Name = "my-page2" |
| 17 | + |
| 18 | + mypath3Route := app.Get("/mypath3/{paramfirst}/statichere/{paramsecond}", writePathHandler) |
| 19 | + mypath3Route.Name = "my-page3" |
| 20 | + |
| 21 | + mypath4Route := app.Get("/mypath4/{paramfirst}/statichere/{paramsecond}/{otherparam}/{something:path}", writePathHandler) |
| 22 | + // same as: app.Get("/mypath4/:paramfirst/statichere/:paramsecond/:otherparam/*something", writePathHandler) |
| 23 | + mypath4Route.Name = "my-page4" |
| 24 | + |
| 25 | + // same with Handle/Func |
| 26 | + mypath5Route := app.Handle("GET", "/mypath5/{paramfirst}/statichere/{paramsecond}/{otherparam}/anything/{something:path}", writePathHandler) |
| 27 | + mypath5Route.Name = "my-page5" |
| 28 | + |
| 29 | + mypath6Route := app.Get("/mypath6/{paramfirst}/{paramsecond}/statichere/{paramThirdAfterStatic}", writePathHandler) |
| 30 | + mypath6Route.Name = "my-page6" |
| 31 | + |
| 32 | + app.Get("/", func(ctx iris.Context) { |
| 33 | + // for /mypath6... |
| 34 | + paramsAsArray := []string{"theParam1", "theParam2", "paramThirdAfterStatic"} |
| 35 | + ctx.ViewData("ParamsAsArray", paramsAsArray) |
| 36 | + if err := ctx.View("page.jet"); err != nil { |
| 37 | + panic(err) |
| 38 | + } |
| 39 | + }) |
| 40 | + |
| 41 | + app.Get("/redirect/{namedRoute}", func(ctx iris.Context) { |
| 42 | + routeName := ctx.Params().Get("namedRoute") |
| 43 | + r := app.GetRoute(routeName) |
| 44 | + if r == nil { |
| 45 | + ctx.StatusCode(iris.StatusNotFound) |
| 46 | + ctx.Writef("Route with name %s not found", routeName) |
| 47 | + return |
| 48 | + } |
| 49 | + |
| 50 | + println("The path of " + routeName + "is: " + r.Path) |
| 51 | + // if routeName == "my-page1" |
| 52 | + // prints: The path of of my-page1 is: /mypath |
| 53 | + // if it's a path which takes named parameters |
| 54 | + // then use "r.ResolvePath(paramValuesHere)" |
| 55 | + ctx.Redirect(r.Path) |
| 56 | + // http://localhost:8080/redirect/my-page1 will redirect to -> http://localhost:8080/mypath |
| 57 | + }) |
| 58 | + |
| 59 | + // http://localhost:8080 |
| 60 | + // http://localhost:8080/redirect/my-page1 |
| 61 | + app.Run(iris.Addr(":8080")) |
| 62 | +} |
| 63 | + |
| 64 | +func writePathHandler(ctx iris.Context) { |
| 65 | + ctx.Writef("Hello from %s.", ctx.Path()) |
| 66 | +} |
0 commit comments