Skip to content

URL Path Parameters

Learn how to handle URL path parameters in Iris.

Basic Path Parameters

go
package main

import "github.com/kataras/iris/v12"

func main() {
    app := iris.New()

    // GET /users/42
    app.Get("/users/{id}", func(ctx iris.Context) {
        id := ctx.Params().Get("id")
        ctx.JSON(iris.Map{
            "id": id,
        })
    })

    app.Listen(":8080")
}

Multiple Parameters

go
app.Get("/users/{userID}/posts/{postID}", func(ctx iris.Context) {
    userID := ctx.Params().Get("userID")
    postID := ctx.Params().Get("postID")

    ctx.JSON(iris.Map{
        "userID": userID,
        "postID": postID,
    })
})

Type Parameters

go
// Integer parameter
app.Get("/users/{id:int}", func(ctx iris.Context) {
    id := ctx.Params().GetIntDefault("id", 0)
    ctx.JSON(iris.Map{
        "id": id,
    })
})

// String parameter (alphabetical only)
app.Get("/categories/{name:string}", func(ctx iris.Context) {
    name := ctx.Params().Get("name")
    ctx.JSON(iris.Map{
        "name": name,
    })
})

// UUID parameter
app.Get("/resources/{id:uuid}", func(ctx iris.Context) {
    id := ctx.Params().Get("id")
    ctx.JSON(iris.Map{
        "id": id,
    })
})

Optional Parameters

go
app.Get("/files/{directory:string}/{name:string}", func(ctx iris.Context) {
    directory := ctx.Params().GetStringDefault("directory", "default")
    name := ctx.Params().Get("name")

    ctx.JSON(iris.Map{
        "directory": directory,
        "name": name,
    })
})

Wildcard Parameters

go
app.Get("/assets/{path:path}", func(ctx iris.Context) {
    path := ctx.Params().Get("path")
    ctx.JSON(iris.Map{
        "path": path,
    })
})

Best Practices

  1. Parameter Types:

    • Use appropriate types
    • Validate input
    • Handle conversions
    • Set defaults
    • Document requirements
  2. Security:

    • Validate parameters
    • Prevent injection
    • Escape values
    • Check lengths
    • Monitor usage
  3. Performance:

    • Cache parsed values
    • Optimize routing
    • Handle large paths
    • Monitor performance
    • Clean resources
  4. Implementation:

    • Use descriptive names
    • Handle missing values
    • Document patterns
    • Test edge cases
    • Follow conventions

Built with excellence by Hellenic Development, delivering enterprise-grade solutions.