Kyrux
Back

Quick Reference

Context — all methods

// Path params
ctx.Param("name")              // string
ctx.ParamInt("id")             // (int, bool)

// Query string
ctx.Query("q")                 // string
ctx.QueryDefault("order","asc")// string with fallback
ctx.QueryInt("page", 1)        // int with fallback
ctx.QueryAll("tag")            // []string

// Responses
ctx.JSON(status, v)
ctx.HTML(status, html)
ctx.Redirect(url, status)
ctx.Error(code)

// Internal data
ctx.Set("key", value)
ctx.Get("key")                 // (any, bool)

// Direct access
ctx.Request                    // *http.Request
ctx.Writer                     // http.ResponseWriter
ctx.Params                     // map[string]string

ORM — all methods

// Reading
orm.FromDB[T](db).All()                          // ([]T, error)
orm.FromDB[T](db).Each(func(t *T) error {...})   // streaming, O(1) memory
orm.FromDB[T](db).First()                        // (*T, error) — sql.ErrNoRows if empty
orm.FromDB[T](db).Last()                         // (*T, error) — reversed ordering
orm.FromDB[T](db).Exists()                       // (bool, error)
orm.FromDB[T](db).Count()                        // (int64, error)
orm.FromDB[T](db).Sum("col")                     // (float64, error) — also Avg/Min/Max

// Typed filters (return *Query[T]) — preferred: column is validated
.WhereEq("col", val)          // col = ?      (also OrWhereEq)
.WhereNe("col", val)          // col <> ?
.WhereGt/.WhereGte/.WhereLt/.WhereLte("col", val)  // col >, >=, <, <= ?
.WhereLike("col", "%term%")   // col LIKE ?   (also OrWhereLike)
.WhereNull("col") / .WhereNotNull("col")

// Free-form SQL filters — never concatenate values into the string, only args
.Where("col = ?", val)        // identical to WhereSQL
.OrWhere("col = ?", val)      // identical to OrWhereSQL
.WhereIn("id", ids)           // expands a slice into placeholders (max 5000 values)
.Join("users", "users.id = posts.user_id")     // filter by relation
.LeftJoin("users", "users.id = posts.user_id")
.OrderBy("col DESC", "id")    // multiple columns — or orm.Desc("col")/orm.Asc("col")
.Select("id", "titulo")       // restricts SELECT columns (default: *)
.Distinct()
.Limit(n)
.Offset(n)

// Relations (loading without N+1)
orm.Prefetch[Comentario](db, "post_id", ids, func(c *Comentario) int64 { return c.PostID })
// → (map[int64][]Comentario, error)

// Pagination
orm.FromDB[T](db).Where(...).OrderBy("id DESC").Paginate(page, 20)     // pageSize capped at 1000
orm.FromDB[T](db).OrderBy("id DESC").PaginateNoCount(page, 20)         // no COUNT(*)
// → (Page[T], error)
// Page[T]: Items, Total, Page, PageSize, TotalPages, HasNext, HasPrev

orm.FromDB[T](db).PaginateAfter("id", cursor, false, 20) // keyset — cost doesn't grow with the page
// → (KeysetPage[T], error) — KeysetPage[T]: Items, NextCursor, HasNext

// Writing
orm.Create(db, &model)                         // error — fills in the PK
orm.CreateAll(db, []*T{...})                   // bulk: a single multi-VALUES INSERT
orm.FromDB[T](db).Where(...).Update(map[string]any{...}) // error
orm.FromDB[T](db).Where(...).Delete()            // error
orm.FromDB[T](db).Where(...).GetOrCreate(&defaults)      // (*T, created, error) — recovers from a race via UNIQUE
orm.FromDB[T](db).Where(...).UpdateOrCreate(values, &defaults) // (created, error) — same

// Transactions (atomic — automatic commit/rollback)
fw.DB.Use().Transaction(func(tx *database.Tx) error {
    orm.CreateTx(tx, &model)
    return orm.FromTx[T](tx).Where(...).Update(...)
})

// Multi-tenant
db := fw.DB.Use().WithSchema("tenant_abc")
orm.FromDB[T](db).All()  // → SELECT * FROM tenant_abc.table

ORM — model tags

Tag Effect
kyrux:"pk" Primary key — ignored on INSERT, filled in after creation
kyrux:"column:name" Overrides the SQL column name
kyrux:"size:N" VARCHAR(N) in makemigrations
kyrux:"unique" CREATE UNIQUE INDEX in makemigrations (migration only)
kyrux:"default:value" SQL literal used on INSERT if the field is the Go zero value
kyrux:"hash" Automatic Argon2id+pepper hashing on write; never reversed
kyrux:"encrypt" AES-256-GCM: encrypts on write, decrypts on read
kyrux:"login" Exclusive to auth.User — sets the login field; immutable after migrate
kyrux:"autonow" Automatic CURRENT_TIMESTAMP on every Update; fills in on Create if zero
kyrux:"fk:table" REFERENCES table(id) + index in the migration

Auth — all methods

// Model
user.SetPassword("password")       // Argon2id + pepper hash
user.CheckPassword("password")     // bool
user.FullName()                    // "First Last"

// Login field (determined by the kyrux:"login" tag on the User model)
auth.LoginFieldName()                              // string — "Username" or "Email"

// SSR (session)
auth.Login(db, store, w, r, loginValue, password)  // (*session.Session, error)
auth.Logout(store, r, w)                           // removes the session + expires the cookie
auth.GetUser(db, store, r)                         // (*User, error)
auth.NextURL(r, fallback)                          // string — reads ?next=, validates against open redirect

// JWT
fw.Auth.GenerateToken(userID, ttl)  // (string, error)
fw.Auth.ValidateToken(token)        // (*Claims, error)

// SSR errors
auth.ErrUserNotFound
auth.ErrWrongPassword
auth.ErrInactiveUser
auth.ErrAuthDisabled  // returned when DB_ENABLED=false

Realtime — all methods

fw.Realtime.Replace("target", html)   // innerHTML = html
fw.Realtime.Append("target", html)    // appends to the end
fw.Realtime.Prepend("target", html)   // prepends to the beginning
fw.Realtime.Remove("target")          // removes the element
fw.Realtime.Broadcast("event", data)  // publishes to the EventBus

EventBus — all methods

fw.Events.Subscribe("event", handler)   // subscribe
fw.Events.Publish("event", payload)     // publish
fw.Events.Unsubscribe("event")          // unsubscribe

DB Manager — all methods

fw.DB.Add("name", "driver", "dsn")          // add a connection
fw.DB.Use()                                 // "default" connection
fw.DB.Use("name")                           // named connection
fw.DB.Use().WithSchema("schema")            // copy with schema set (multi-tenant)
fw.DB.Use().Transaction(func(tx) error { ... })
fw.DB.Close()                               // close all of them

Render — global functions and processors

// Custom functions for templates (available globally)
render.AddFunc("name", function)
render.AddFunc("formatarData", func(t time.Time) string {
    return t.Format("02/01/2006")
})

// ContextProcessors — variables injected into every template of every app
render.AddDefaultProcessor(func(ctx *router.Context) map[string]any {
    return map[string]any{"ano": time.Now().Year()}
})

// Render a fragment to a string (used with Realtime)
html, err := render.Partial("appName", "partials/lista.html", data)

Crypton — security utilities

// Setup (called automatically by bootstrap)
crypton.SetPepper(pepper)
crypton.SetEncryptionKey(key)

// Passwords (Argon2id — PHC format)
crypton.HashPassword("password")               // (string, error) — $argon2id$...
crypton.CheckPassword("password", hash)        // bool — constant-time comparison

// Symmetric encryption (AES-256-GCM)
crypton.Encrypt("sensitive data")              // (string, error) — $enc$<base64>
crypton.Decrypt("$enc$<base64>")              // (string, error)

// HMAC-SHA256 signing
crypton.Sign("payload", "secret")             // (string, error) — <b64>.<sig>
crypton.Verify("token", "secret")             // (string, error) — payload or error

// Cryptographically secure randomness
crypton.RandomBytes(32)                        // ([]byte, error)

Errors — customizing error pages

import kyerrors "kyrux/core/errors"

// Register a custom handler for an HTTP code
kyerrors.Set(404, func(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(404)
    json.NewEncoder(w).Encode(map[string]string{"error": "not found"})
})

kyerrors.Set(500, func(w http.ResponseWriter, r *http.Request) {
    // render a custom 500 error template
})

Registered handlers take priority over the default behavior in any environment.

Session — low-level API

import "kyrux/core/security/session"

// Create a session manually
sess, err := fw.Sessions.New()
sess.Set("chave", valor)
session.SetCookie(ctx.Writer, sess.ID, ctx.Request.TLS != nil)

// Read the session from the request
sess, ok := session.FromRequest(ctx.Request, fw.Sessions)
if !ok { /* no session */ }

// Access values (safe for concurrent requests)
val, ok := sess.Get("chave")

// End the session
fw.Sessions.Delete(sess.ID)

Kyrux — execution at the right time. Built by Müller Nocciolli · MIT License with mandatory attribution.