From 84bc7bc6192214b57cb2a5878b4ce226796073a2 Mon Sep 17 00:00:00 2001 From: Eden Kirin Date: Mon, 23 Oct 2023 23:48:18 +0200 Subject: [PATCH] Separate router --- app/main.go | 62 +++++++++++++++++++++++++++-------------------------- 1 file changed, 32 insertions(+), 30 deletions(-) diff --git a/app/main.go b/app/main.go index ec787c7..434cf16 100644 --- a/app/main.go +++ b/app/main.go @@ -37,6 +37,37 @@ var users = []User{ }, } +func createRouter(app *iris.Application) { + app.Get("/", func(ctx iris.Context) { + params1 := []string{"param 1", "param 2", "param 3"} + ctx.ViewData("params1", params1) + ctx.ViewData("users", users) + + if err := ctx.View("pages/index.jet"); err != nil { + ctx.HTML("

%s

", err.Error()) + return + } + }) + + app.Get("/redirect/{namedRoute}", func(ctx iris.Context) { + routeName := ctx.Params().Get("namedRoute") + r := app.GetRoute(routeName) + if r == nil { + ctx.StatusCode(iris.StatusNotFound) + ctx.Writef("Route with name %s not found", routeName) + return + } + + println("The path of " + routeName + "is: " + r.Path) + // if routeName == "my-page1" + // prints: The path of of my-page1 is: /mypath + // if it's a path which takes named parameters + // then use "r.ResolvePath(paramValuesHere)" + ctx.Redirect(r.Path) + // http://localhost:8080/redirect/my-page1 will redirect to -> http://localhost:8080/mypath + }) +} + func main() { cfg.Init() logging.Init() @@ -65,36 +96,7 @@ func main() { // mypath6Route := app.Get("/mypath6/{paramfirst}/{paramsecond}/statichere/{paramThirdAfterStatic}", writePathHandler) // mypath6Route.Name = "my-page6" - app.Get("/", func(ctx iris.Context) { - // templateContext := map[string]string{} - - params1 := []string{"param 1", "param 2", "param 3"} - ctx.ViewData("params1", params1) - ctx.ViewData("users", users) - - if err := ctx.View("pages/index.jet"); err != nil { - ctx.HTML("

%s

", err.Error()) - return - } - }) - - app.Get("/redirect/{namedRoute}", func(ctx iris.Context) { - routeName := ctx.Params().Get("namedRoute") - r := app.GetRoute(routeName) - if r == nil { - ctx.StatusCode(iris.StatusNotFound) - ctx.Writef("Route with name %s not found", routeName) - return - } - - println("The path of " + routeName + "is: " + r.Path) - // if routeName == "my-page1" - // prints: The path of of my-page1 is: /mypath - // if it's a path which takes named parameters - // then use "r.ResolvePath(paramValuesHere)" - ctx.Redirect(r.Path) - // http://localhost:8080/redirect/my-page1 will redirect to -> http://localhost:8080/mypath - }) + createRouter(app) // http://localhost:8080 // http://localhost:8080/redirect/my-page1