Kyrux
Back

Views and Context

A view is a func(ctx *router.Context) function.

func PostView(ctx *router.Context) {
    slug := ctx.Param("slug")           // path parameter
    page := ctx.QueryInt("page", 1)     // query string with fallback

    post := models.GetBySlug(slug)
    if post == nil {
        ctx.Error(404)
        return
    }

    render.For("blog").Render(ctx, "post.html", map[string]any{
        "post": post,
        "page": page,
    })
}

⚠️ Never use ctx in goroutines that outlive the handler — the Context goes back to a pool when the handler returns and is reused by another request. For asynchronous work, make a copy:

cp := ctx.Copy() // Params, data, and Request for reading; Writer is nil
go func() { process(cp.Param("id")) }()

Context methods

Path parameters

ctx.Param("slug")             // string — returns "" if absent
ctx.ParamInt("id")            // (int, bool) — (0, false) if invalid

Query string

ctx.Query("q")                // first value, "" if absent
ctx.QueryDefault("order", "asc") // with fallback
ctx.QueryInt("page", 1)       // int with fallback
ctx.QueryAll("tag")           // []string — multiple values for the same parameter

Responses

// Render HTML with a template
render.For("meuapp").Render(ctx, "index.html", map[string]any{
    "titulo": "Hello world",
})

// JSON
ctx.JSON(200, map[string]any{"id": 1, "nome": "Kyrux"})

// Inline HTML
ctx.HTML(200, "<h1>Hello</h1>")

// Redirect
ctx.Redirect("/login/", http.StatusFound)       // 302
ctx.Redirect("/home/", http.StatusMovedPermanently) // 301

// Error page
ctx.Error(404)
ctx.Error(403)
ctx.Error(500)

Internal context data (between middlewares)

// Store
ctx.Set("usuario", usuario)

// Retrieve
v, ok := ctx.Get("usuario")
usuario := v.(*models.Usuario)

Direct access to request and writer

ctx.Request           // *http.Request
ctx.Request.Method    // "GET", "POST", etc.
ctx.Request.Header    // http.Header
ctx.Writer            // http.ResponseWriter