Help us shape the future of Go! Take the 2026 Go Developer Survey

vukem

package module
v0.18.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 49 Imported by: 0

README

Vukem

Tests CI/CD Version Go Reference License

Introduction

Vukem is a complete Model-View-Controller (MVC) web framework for Go built on net/http and the standard library to build APIs and FullStack Web Applications.

Summary

  • HTTP: net/http-native router with named routes, resources and groups; middleware is func(http.Handler) http.Handler.
  • Validation: Zod-style typed schemas (z) for every input, exportable as JSON Schema, TypeScript and Zod.
  • Database: SQLite built in, PostgreSQL driver module, generic query builder, relations, migrations, factories and seeders.
  • Auth: sessions, API tokens, social login (OAuth2/OIDC), email verification, password reset, gates and policies.
  • APIs: JSON resources, pagination, RFC 9457 errors, rate limiting, idempotency keys, typed handlers, OpenAPI 3.1 and a Scalar API reference.
  • Background work: typed queue jobs (sync, memory, database), queued mail and listeners, cron scheduler.
  • Frontend: HTMX-first server-rendered views, with Inertia + React on the way.
  • More: mail (SMTP, Resend), cache, storage, events, Telegram logging, SSRF-safe HTTP client, signed URLs and webhooks.

Why Vukem

  • Standard library first. Handlers are plain net/http; any http.Handler works.
  • No magic. No globals, no init() registration, no reflection-based dependency injection. Generators write code you own.
  • Typed end to end. Inputs parse into Go types, outputs are checked, and the same types produce your OpenAPI and TypeScript.
  • Opt-in batteries. Heavy drivers (PostgreSQL, Redis, MongoDB) are separate modules, so you only download what you use.
  • Secure by default. CSRF, security headers, Argon2id, safe SQL, fail-closed authorization, mapped to the OWASP Top 10:2025.
  • Windows is first-class. Pure Go, no C compiler, tested on Windows, Linux and macOS.

Agentic development

Vukem's predictable structure and conventions (generators, typed schemas, named routes, no magic) make it a natural fit for AI coding agents like Claude Code, Cursor and GitHub Copilot. Install Vukem Boost in your project to supercharge your AI workflow:

vukem boost:install

Boost adds Vukem guidelines to AGENTS.md, framework skills to .claude/skills/ and the vukem-boost MCP server to .mcp.json (plus .cursor/ and .vscode/ when present). The server gives your agent tools to inspect the running app: application info, routes, commands, the database schema, read-only SQL queries, absolute URLs for named routes and a documentation search.

Contributing

Thank you for considering contributing to Vukem! Read the contribution guide to get started.

Code of conduct

To keep the community welcoming to everyone, please review and follow the Code of Conduct.

Security vulnerabilities

If you discover a security vulnerability, please follow the security policy instead of opening a public issue.

License

Vukem is open-source software licensed under the MIT license.

Documentation

Overview

Package vukem is a full-stack web framework for Go inspired by Laravel and AdonisJS, built on net/http and the standard library.

Vukem is in its prototype phase; see PLAN.md for the roadmap.

Index

Constants

View Source
const (
	DefaultReadHeaderTimeout = 10 * time.Second
	DefaultReadTimeout       = 30 * time.Second
	DefaultWriteTimeout      = 60 * time.Second
	DefaultIdleTimeout       = 120 * time.Second
	DefaultMaxHeaderBytes    = 1 << 20
)

Server timeouts applied by NewHTTPServer. Zero timeouts are never used (Slowloris protection, docs/security.md A02).

View Source
const MailJobKind = "vukem.mail"

MailJobKind is the queue job that sends queued mail (App.MailLater).

Variables

View Source
var ErrNoFailedStore = errors.New("vukem: the queue driver does not keep failed jobs (use QUEUE_CONNECTION=database)")

ErrNoFailedStore is returned by the failed-job commands for drivers that do not keep failed jobs.

Functions

func APIMiddleware added in v0.10.0

func APIMiddleware(app *App, r *router.Router) error

APIMiddleware installs the stack of JSON-only apps: recover, request id, logging and security headers on the server; the body limit on routes. There are no sessions or CSRF: API clients authenticate with tokens (see auth.TokenGuard), and CORS is configured by the routes.

func DefaultMiddleware

func DefaultMiddleware(app *App, r *router.Router) error

DefaultMiddleware installs Vukem's recommended stacks on r:

  • server: Recover, RequestID, Logger, SecureHeaders, MethodOverride;
  • router: BodyLimit(10 MiB), sessions, CSRF (CrossOriginProtection, trusted origins from CSRF_TRUSTED_ORIGINS), and the i18n locale resolver when WithTranslations was given.

It returns configuration errors (insecure production cookies, bad origins) so they fail at boot. Starters call it from bootstrap.

func Main

func Main(build BuildFunc) int

Main runs the application from os.Args and the process environment and returns the exit code. Use it as: func main() { os.Exit(vukem.Main(bootstrap.New)) }.

func RunMain

func RunMain(ctx context.Context, args []string, getenv func(string) (string, bool), build BuildFunc,
	opts ...Option,
) error

RunMain is the testable body of main: it builds the app with the given environment and runs the command in args (default "serve").

func ServeOpenAPI added in v0.15.0

func ServeOpenAPI(app *App, r *router.Router, path string) *router.Route

ServeOpenAPI registers GET path (e.g. "/openapi.json") serving the document. In production it registers nothing (and returns nil) unless OPENAPI_IN_PRODUCTION=true: the document maps the whole API surface.

Types

type App

type App struct {
	// Config is the core configuration.
	Config Config
	// Source gives access to every configuration value (for module configs).
	Source *config.Source
	// Key is the decoded APP_KEY; derive purpose-specific keys from it.
	Key config.Key
	// Crypt encrypts with a key derived from APP_KEY and still decrypts
	// values sealed with APP_PREVIOUS_KEYS. DB() hands it to orm.Encrypted.
	Crypt *crypt.Encrypter
	// Log is the application logger.
	Log *slog.Logger
	// Kind is the runtime kind (web, console, test).
	Kind Kind
	// Router holds the HTTP routes; /up is registered by default.
	Router *router.Router
	// Views renders templates when WithViews was given (nil otherwise).
	Views *view.Engine
	// Vite renders asset tags when WithVite was given (nil otherwise).
	Vite *vite.Vite
	// Inertia is the Inertia adapter when WithInertia was given (nil
	// otherwise).
	Inertia *inertia.Inertia
	// I18n holds the translations when WithTranslations was given (nil
	// otherwise); DefaultMiddleware then resolves the request locale.
	I18n *i18n.Bundle

	// Telegram is the Telegram log handler when TELEGRAM_* is set (nil
	// otherwise); use it for Contact and Send.
	Telegram *telegram.Handler

	// Events is the application event bus (WithListeners registers listeners).
	Events *events.Bus
	// contains filtered or unexported fields
}

App is a Vukem application: configuration, logger, providers and the long-running runners (HTTP server, workers). Services added by providers live in typed fields of the structs that embed or reference the App.

func New

func New(opts ...Option) (*App, error)

New builds an App: it loads and validates configuration and registers providers. It refuses insecure configuration (see docs/security.md, A02).

func (*App) AddCommand

func (a *App) AddCommand(cmds ...Command)

AddCommand registers commands. Call it from a provider's Register.

func (*App) AddHealthCheck

func (a *App) AddHealthCheck(name string, check HealthCheck)

AddHealthCheck registers a check reported by GET /up?checks=1.

func (*App) AddRunner

func (a *App) AddRunner(name string, r Runner)

AddRunner adds a long-running component. Call it from Register or Boot.

func (*App) Addr

func (a *App) Addr() string

Addr returns the HTTP listen address from HOST and PORT.

func (*App) Boot

func (a *App) Boot(ctx context.Context) error

Boot runs every provider's Boot hook once, in order.

func (*App) Cache added in v0.11.0

func (a *App) Cache() (*cache.Cache, error)

Cache returns the application cache, built from CACHE_* on first use. The database store creates its table if needed.

func (*App) Call added in v0.16.0

func (a *App) Call(ctx context.Context, name string, args []string) error

Call runs the app command name with args inside the current process (the app is already booted), e.g. from a scheduled task.

func (*App) Commands

func (a *App) Commands() []Command

Commands returns registered commands sorted by name, built-ins included.

func (*App) DB

func (a *App) DB() (*database.DB, error)

DB opens the default database from DATABASE_URL on first use, with app.Crypt as its encrypter (orm.Encrypted columns), adds a "db" health check and closes it on shutdown.

func (*App) Handler

func (a *App) Handler() (http.Handler, error)

Handler returns the compiled HTTP handler.

func (*App) MailLater added in v0.16.0

func (a *App) MailLater(ctx context.Context, mailable mail.Mailable, opts ...queue.Option) error

MailLater renders mailable now and sends it from a queue job (retried with the queue's backoff; the message ID stays the same across retries, so providers that deduplicate by it send it once).

func (*App) Mailer added in v0.7.0

func (a *App) Mailer() (*mail.Mailer, error)

Mailer returns the app mailer, built from MAIL_* on first use. Views come from the app's view engine (WithViews).

func (*App) Migrator

func (a *App) Migrator() (*schema.Migrator, error)

Migrator returns a migrator over DB() with the registered migrations.

func (*App) Now

func (a *App) Now() time.Time

Now returns the current time from the app clock (see WithClock).

func (*App) OnShutdown

func (a *App) OnShutdown(fn func(context.Context) error)

OnShutdown registers fn to run during Shutdown, in reverse registration order, after runners stop and before providers shut down.

func (*App) OpenAPI added in v0.15.0

func (a *App) OpenAPI() (*openapi.Document, error)

OpenAPI returns the OpenAPI 3.1 document of the app's routes (title APP_NAME, version API_VERSION, filtered by OPENAPI_PREFIX).

func (*App) Queue added in v0.16.0

func (a *App) Queue() (*queue.Queue, error)

Queue returns the application queue, built from QUEUE_* on first use.

func (*App) Run

func (a *App) Run(ctx context.Context) error

Run boots the app, starts every runner and blocks until ctx is cancelled or a runner fails; then it shuts everything down gracefully within SHUTDOWN_TIMEOUT. A cancelled ctx is a clean exit (nil error).

func (*App) Schedule added in v0.16.0

func (a *App) Schedule() (*schedule.Schedule, error)

Schedule returns the application schedule, built on first use. Locks for WithoutOverlapping use App.Cache (set CACHE_STORE=database or Redis when several servers run the schedule).

func (*App) Seed added in v0.4.0

func (a *App) Seed(ctx context.Context) error

Seed runs every registered seeder in order; the first error stops it.

func (*App) Sessions

func (a *App) Sessions() (*session.Manager, error)

Sessions returns the session manager, building it from SESSION_* on first use. Use SetSessionStore before the first call to change the store.

func (*App) SetSessionStore

func (a *App) SetSessionStore(store session.Store)

SetSessionStore makes sessions server-side with store (call it from a provider's Register, before Sessions is first used).

func (*App) Shutdown

func (a *App) Shutdown(ctx context.Context) error

Shutdown runs shutdown hooks and providers' Shutdown in reverse order. It is idempotent.

type Booter

type Booter interface {
	Boot(ctx context.Context, app *App) error
}

Booter is implemented by providers that need a boot phase. Boot runs after every provider registered.

type BuildFunc

type BuildFunc func(opts ...Option) (*App, error)

BuildFunc builds the application; bootstrap.New implements it.

type CacheConfig added in v0.11.0

type CacheConfig struct {
	// Store is "memory" (default) or "database" (table CACHE_TABLE).
	Store  string `env:"CACHE_STORE"  default:"memory"`
	Prefix string `env:"CACHE_PREFIX" default:"vukem:"`
	Table  string `env:"CACHE_TABLE"  default:"cache"`
	// MaxEntries bounds the memory store.
	MaxEntries int `env:"CACHE_MAX_ENTRIES" default:"10000"`
}

CacheConfig is read from CACHE_* variables.

type Command

type Command interface {
	// Name is "namespace:action", e.g. "reports:send".
	Name() string
	// Description is shown by "list".
	Description() string
	// Flags defines flags on fs; it may be a no-op.
	Flags(fs *flag.FlagSet)
	// Run executes the command with the remaining positional args.
	Run(ctx context.Context, app *App, args []string) error
}

Command is an application command compiled into the app binary (migrate, queue:work, user commands). The global `vukem` CLI delegates unknown commands to the app binary.

type CommandFunc

type CommandFunc struct {
	CommandName string
	Desc        string
	DefineFlags func(fs *flag.FlagSet)
	Fn          func(ctx context.Context, app *App, args []string) error
}

CommandFunc builds a Command from a function.

func (CommandFunc) Description

func (c CommandFunc) Description() string

Description implements Command.

func (CommandFunc) Flags

func (c CommandFunc) Flags(set *flag.FlagSet)

Flags implements Command.

func (CommandFunc) Name

func (c CommandFunc) Name() string

Name implements Command.

func (CommandFunc) Run

func (c CommandFunc) Run(ctx context.Context, app *App, args []string) error

Run implements Command.

type Config

type Config struct {
	Name  string        `env:"APP_NAME"  default:"Vukem"`
	Env   config.Env    `env:"APP_ENV"   default:"development"`
	Debug bool          `env:"APP_DEBUG"`
	URL   string        `env:"APP_URL"   default:"http://localhost:3000"`
	Key   config.Secret `env:"APP_KEY"`
	// PreviousKeys are former APP_KEY values (comma-separated, same format)
	// that still decrypt app.Crypt tokens after a key rotation.
	PreviousKeys    config.Secret `env:"APP_PREVIOUS_KEYS"`
	Host            string        `env:"HOST"              default:"localhost"`
	Port            int           `env:"PORT"              default:"3000"`
	ShutdownTimeout time.Duration `env:"SHUTDOWN_TIMEOUT"  default:"15s"`
	LogLevel        string        `env:"LOG_LEVEL"         default:"info"`
	LogFormat       string        `env:"LOG_FORMAT"`
	// APIVersion is info.version of the OpenAPI document.
	APIVersion string `env:"API_VERSION" default:"1.0.0"`
	// OpenAPIPrefix keeps only routes under it in the document (e.g. /api).
	OpenAPIPrefix string `env:"OPENAPI_PREFIX"`
	// OpenAPIInProduction serves /openapi.json in production too.
	OpenAPIInProduction bool `env:"OPENAPI_IN_PRODUCTION"`
}

Config is the core application configuration, loaded from the environment.

func (*Config) IsProduction

func (c *Config) IsProduction() bool

IsProduction reports whether APP_ENV is production.

type DatabaseConfig

type DatabaseConfig struct {
	URL     string `env:"DATABASE_URL" default:"file:storage/database.sqlite"`
	MaxOpen int    `env:"DB_MAX_OPEN"  default:"10"`
	MaxIdle int    `env:"DB_MAX_IDLE"  default:"5"`
}

DatabaseConfig is loaded from DB_* variables.

type HTTPServer

type HTTPServer struct {
	Server *http.Server
	// ShutdownTimeout bounds the graceful drain of in-flight requests.
	ShutdownTimeout time.Duration
	// Listener, when set, is used instead of listening on Server.Addr.
	Listener net.Listener
	// Ready, when set, receives the bound address once listening.
	Ready chan<- string
}

HTTPServer runs an *http.Server as a Runner with graceful shutdown.

func NewHTTPServer

func NewHTTPServer(addr string, handler http.Handler) *HTTPServer

NewHTTPServer returns an HTTPServer for handler on addr with secure timeouts.

func (*HTTPServer) Run

func (s *HTTPServer) Run(ctx context.Context) error

Run listens and serves until ctx is done, then drains in-flight requests.

type HealthCheck

type HealthCheck func(ctx context.Context) error

HealthCheck reports whether a dependency (database, cache...) is healthy.

type Kind

type Kind string

Kind is the runtime in which the application is running. Providers can be limited to some kinds (see KindFilter).

const (
	KindWeb     Kind = "web"
	KindConsole Kind = "console"
	KindTest    Kind = "test"
	// KindWarmup builds the app (config, Register, routes) but never runs
	// providers' Boot or Shutdown, so no connection is opened. Commands that
	// only read the route table (codegen:routes) run in it.
	KindWarmup Kind = "warmup"
)

Runtime kinds.

type KindFilter

type KindFilter interface {
	Kinds() []Kind
}

KindFilter limits a provider to some runtime kinds. Providers that do not implement it run everywhere.

type MailConfig added in v0.7.0

type MailConfig struct {
	// Mailer is "smtp", "resend", "log" or "array" (tests). Production
	// must choose explicitly; elsewhere it defaults to "log".
	Mailer string `env:"MAIL_MAILER"`
	From   string `env:"MAIL_FROM"   default:"Vukem <hello@example.com>"`

	SMTPHost     string        `env:"SMTP_HOST"     default:"localhost"`
	SMTPPort     int           `env:"SMTP_PORT"     default:"587"`
	SMTPUsername string        `env:"SMTP_USERNAME"`
	SMTPPassword config.Secret `env:"SMTP_PASSWORD"`
	// SMTPInsecure allows servers without STARTTLS (local catchers only).
	SMTPInsecure bool `env:"SMTP_INSECURE"`

	ResendAPIKey config.Secret `env:"RESEND_API_KEY"`
}

MailConfig is read from MAIL_* (and SMTP_* / RESEND_*) variables.

type Option

type Option func(*options) error

Option configures New.

func WithCacheStore added in v0.17.0

func WithCacheStore(s cache.Store) Option

WithCacheStore replaces the store chosen by CACHE_STORE (e.g. Redis: vukem.WithCacheStore(redisClient.CacheStore("cache:"))).

func WithClock

func WithClock(now func() time.Time) Option

WithClock sets the clock used by sessions and other time-based features (tests use vukemtest.FakeClock).

func WithDatabaseDrivers

func WithDatabaseDrivers(drivers ...database.Driver) Option

WithDatabaseDrivers makes extra drivers (e.g. postgres.Driver()) available to DB().

func WithEnv

func WithEnv(fsys fs.FS, getenv func(string) (string, bool)) Option

WithEnv loads configuration from fsys (.env files) and getenv.

func WithInertia added in v0.18.0

func WithInertia(cfg inertia.Config) Option

WithInertia enables the Inertia adapter (app.Inertia); add app.Inertia.Middleware to the routes that render pages. Version and the SSR dev endpoint default to app.Vite when WithVite is given.

func WithJobs added in v0.16.0

func WithJobs(regs ...queue.Registration) Option

WithJobs registers job handlers on the application queue (generated apps pass jobs.All(); vukem make:job appends there).

func WithKind

func WithKind(k Kind) Option

WithKind sets the runtime kind (web by default).

func WithListeners added in v0.11.0

func WithListeners(regs ...events.Registration) Option

WithListeners registers event listeners on App.Events (generated apps pass listeners.All(); vukem make:listener appends there).

func WithLogOutput

func WithLogOutput(w io.Writer) Option

WithLogOutput sets where the default logger writes (stderr by default).

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the logger instead of building one from configuration.

func WithMailTransport added in v0.7.0

func WithMailTransport(t mail.Transport) Option

WithMailTransport replaces the transport chosen by MAIL_MAILER.

func WithMigrations

func WithMigrations(migrations []schema.Migration) Option

WithMigrations registers the application's migrations used by the migrate commands (migrate, migrate:rollback, migrate:reset, migrate:fresh, migrate:status).

func WithProviders

func WithProviders(p ...Provider) Option

WithProviders appends providers, registered and booted in order.

func WithQueueDriver added in v0.16.0

func WithQueueDriver(d queue.Driver) Option

WithQueueDriver replaces the driver chosen by QUEUE_CONNECTION (tests pass a queue.Fake).

func WithReady

func WithReady(ch chan<- string) Option

WithReady receives the HTTP listen address once the server is listening.

func WithRoutes

func WithRoutes(fn func(r *router.Router, app *App) error) Option

WithRoutes registers routes (and router middleware) after providers registered, so handlers can use the services they added. An error stops New.

func WithRunner

func WithRunner(name string, r Runner) Option

WithRunner adds a long-running component started by Run.

func WithSchedule added in v0.16.0

func WithSchedule(fn func(s *schedule.Schedule, app *App)) Option

WithSchedule declares scheduled tasks (generated apps pass routes.Schedule).

func WithSeeders added in v0.4.0

func WithSeeders(seeders ...Seeder) Option

WithSeeders registers the seeders run by `db:seed` (generated apps pass seeders.All()).

func WithSessionStore added in v0.17.0

func WithSessionStore(s session.Store) Option

WithSessionStore replaces the store chosen by SESSION_DRIVER (e.g. Redis: vukem.WithSessionStore(redisClient.SessionStore(""))).

func WithSource

func WithSource(src *config.Source) Option

WithSource uses an already resolved configuration source.

func WithStdin added in v0.18.0

func WithStdin(r io.Reader) Option

WithStdin sets where commands read input (os.Stdin by default).

func WithStdout

func WithStdout(w io.Writer) Option

WithStdout sets where commands print (os.Stdout by default).

func WithTranslations added in v0.18.0

func WithTranslations(fsys fs.FS) Option

WithTranslations loads the JSON catalogs at the root of fsys (os.DirFS("resources/lang") or an embed.FS) into App.I18n, with APP_LOCALE (default "en") as the fallback locale. Views get the "t" and "locale" functions, and DefaultMiddleware installs i18n.Middleware.

func WithViews

func WithViews(fsys fs.FS) Option

WithViews renders html/template views from fsys (os.DirFS("resources/views") or an embed.FS). Views reload on every request outside production.

func WithVite added in v0.18.0

func WithVite(fsys fs.FS) Option

WithVite enables the "vite" and "viteReactRefresh" view functions over the public directory fsys (os.DirFS("public") or an embed.FS). The dev server "hot" file is honoured only outside production.

func WithoutHTTP

func WithoutHTTP() Option

WithoutHTTP disables the HTTP server runner (workers-only processes).

type Provider

type Provider interface {
	Register(app *App) error
}

Provider registers services into the App. Register must not perform I/O; use Boot for work that needs other services.

type ProviderFunc

type ProviderFunc func(app *App) error

ProviderFunc adapts a function to a Provider with only a Register phase.

func (ProviderFunc) Register

func (f ProviderFunc) Register(app *App) error

Register calls f.

type QueueConfig added in v0.16.0

type QueueConfig struct {
	// Connection is "sync" (default: jobs run during Dispatch), "memory"
	// (in process, run by a worker inside serve) or "database".
	Connection string `env:"QUEUE_CONNECTION" default:"sync"`
	// Queues lists the queues workers poll, in priority order.
	Queues string `env:"QUEUE_NAMES" default:"default"`
	// Concurrency is the number of parallel workers.
	Concurrency int `env:"QUEUE_CONCURRENCY" default:"4"`
	// Table and FailedTable are the database driver's tables.
	Table       string `env:"QUEUE_TABLE"        default:"jobs"`
	FailedTable string `env:"QUEUE_FAILED_TABLE" default:"failed_jobs"`
}

QueueConfig is read from QUEUE_* variables.

func (QueueConfig) QueueNames added in v0.16.0

func (c QueueConfig) QueueNames() []string

QueueNames returns Queues as a list.

type Runner

type Runner interface {
	Run(ctx context.Context) error
}

Runner is a long-running component (HTTP server, queue worker, scheduler). Run blocks until ctx is done or the runner fails, and must return after releasing its resources.

type RunnerFunc

type RunnerFunc func(ctx context.Context) error

RunnerFunc adapts a function to a Runner.

func (RunnerFunc) Run

func (f RunnerFunc) Run(ctx context.Context) error

Run calls f.

type ScheduleConfig added in v0.16.0

type ScheduleConfig struct {
	// Timezone of the expressions (IANA name, default UTC).
	Timezone string `env:"SCHEDULE_TIMEZONE" default:"UTC"`
}

ScheduleConfig is read from SCHEDULE_* variables.

type Seeder added in v0.4.0

type Seeder interface {
	Seed(ctx context.Context, db *database.DB) error
}

Seeder fills the database with data (demo content, reference tables). `vukem db:seed` runs every seeder given to WithSeeders, in order.

type SeederFunc added in v0.4.0

type SeederFunc func(ctx context.Context, db *database.DB) error

SeederFunc adapts a function to Seeder.

func (SeederFunc) Seed added in v0.4.0

func (f SeederFunc) Seed(ctx context.Context, db *database.DB) error

Seed implements Seeder.

type SessionConfig

type SessionConfig struct {
	// Driver is "cookie" (encrypted cookie, default) or "memory"; the
	// database driver is installed by the database provider.
	Driver      string        `env:"SESSION_DRIVER"       default:"cookie"`
	Lifetime    time.Duration `env:"SESSION_LIFETIME"     default:"24h"`
	IdleTimeout time.Duration `env:"SESSION_IDLE_TIMEOUT" default:"2h"`
	CookieName  string        `env:"SESSION_COOKIE"       default:"vukem_session"`
	// Secure defaults to true in production or when APP_URL is https.
	Secure string `env:"SESSION_SECURE" default:"auto"`
}

SessionConfig is loaded from SESSION_* variables.

type Shutdowner

type Shutdowner interface {
	Shutdown(ctx context.Context, app *App) error
}

Shutdowner is implemented by providers that release resources. Shutdown runs in reverse provider order.

type TelegramConfig added in v0.12.0

type TelegramConfig struct {
	BotToken config.Secret `env:"TELEGRAM_BOT_TOKEN"`
	ChatID   string        `env:"TELEGRAM_CHAT_ID"`
	// MinLevel is debug, info, warn or error (default error).
	MinLevel string `env:"TELEGRAM_MIN_LEVEL" default:"error"`
	ThreadID int    `env:"TELEGRAM_THREAD_ID"`
}

TelegramConfig is read from TELEGRAM_* variables.

Directories

Path Synopsis
Package api holds REST helpers on top of web and orm: resource transformers, pagination envelopes, allowlisted query conventions (filter, sort, fields, include, pagination) and deprecation headers.
Package api holds REST helpers on top of web and orm: resource transformers, pagination envelopes, allowlisted query conventions (filter, sort, fields, include, pagination) and deprecation headers.
Package apidocs serves an API reference for the app's OpenAPI document with Scalar (https://scalar.com).
Package apidocs serves an API reference for the app's OpenAPI document with Scalar (https://scalar.com).
Package auth authenticates requests: guards (session for browsers, access tokens for APIs), user providers, middleware and password hashing (auth/hash).
Package auth authenticates requests: guards (session for browsers, access tokens for APIs), user providers, middleware and password hashing (auth/hash).
hash
Package hash hashes and verifies passwords: argon2id by default (PHC string format), bcrypt for compatibility.
Package hash hashes and verifies passwords: argon2id by default (PHC string format), bcrypt for compatibility.
jwt
Package jwt issues and verifies JSON Web Tokens (RFC 7519) with the standard library: HS256, RS256, ES256 and EdDSA, an algorithm allowlist tied to each key (no algorithm confusion, never "none"), key ids with static or remote (JWKS) key sets that rotate, strict claim checks, a Guard for package auth, and rotating refresh tokens with reuse detection.
Package jwt issues and verifies JSON Web Tokens (RFC 7519) with the standard library: HS256, RS256, ES256 and EdDSA, an algorithm allowlist tied to each key (no algorithm confusion, never "none"), key ids with static or remote (JWKS) key sets that rotate, strict claim checks, a Guard for package auth, and rotating refresh tokens with reuse detection.
totp
Package totp implements time-based one-time passwords (RFC 6238, the codes of authenticator apps) for two-factor authentication: secrets, otpauth:// enrolment URIs with an SVG QR code, validation with one step of clock skew and replay protection, and hashed single-use recovery codes.
Package totp implements time-based one-time passwords (RFC 6238, the codes of authenticator apps) for two-factor authentication: secrets, otpauth:// enrolment URIs with an SVG QR code, validation with one step of clock skew and replay protection, and hashed single-use recovery codes.
Package authz decides what an authenticated user may do: gates (named abilities) and policies (abilities on a model type).
Package authz decides what an authenticated user may do: gates (named abilities) and policies (abilities on a model type).
Package cache stores values with a TTL behind a Store (memory, database; Redis in drivers/redis).
Package cache stores values with a TTL behind a Store (memory, database; Redis in drivers/redis).
cachetest
Package cachetest is the conformance suite every cache.Store passes (memory and database in core, Redis in drivers/redis).
Package cachetest is the conformance suite every cache.Store passes (memory and database in core, Redis in drivers/redis).
cmd
vukem command
Command vukem is the Vukem CLI: generators, the dev server, builds and delegation of app commands to the project's binary.
Command vukem is the Vukem CLI: generators, the dev server, builds and delegation of app commands to the project's binary.
Package config loads typed application configuration from environment variables and .env files.
Package config loads typed application configuration from environment variables and .env files.
contrib
graphql module
grpc module
imaging module
stripe module
Package crypt encrypts and authenticates values with AES-256-GCM and supports key rotation: one current key encrypts, previous keys only decrypt.
Package crypt encrypts and authenticates values with AES-256-GCM and supports key rotation: one current key encrypts, previous keys only decrypt.
Package csrf protects state-changing requests from cross-site request forgery using Go's http.CrossOriginProtection (Fetch Metadata and Origin checks, no tokens needed in modern browsers), with an optional session-token fallback for clients that send neither header.
Package csrf protects state-changing requests from cross-site request forgery using Go's http.CrossOriginProtection (Fetch Metadata and Origin checks, no tokens needed in modern browsers), with an optional session-token fallback for clients that send neither header.
Package database manages SQL connections for Vukem: dialects, SQLite defaults (WAL, busy timeout, foreign keys, a single-connection writer pool beside a reader pool), PostgreSQL through driver modules, and transactions that roll back on error or panic.
Package database manages SQL connections for Vukem: dialects, SQLite defaults (WAL, busy timeout, foreign keys, a single-connection writer pool beside a reader pool), PostgreSQL through driver modules, and transactions that roll back on error or panic.
dbtest
Package dbtest is the database conformance suite: the same schema, ORM, transaction and migration checks run against every dialect (SQLite in core, Postgres and others in their driver modules).
Package dbtest is the database conformance suite: the same schema, ORM, transaction and migration checks run against every dialect (SQLite in core, Postgres and others in their driver modules).
drivers
mongo module
mysql module
otel module
postgres module
redis module
s3 module
websocket module
Package errs defines the error values handlers return.
Package errs defines the error values handlers return.
Package events dispatches typed events to listeners registered by type.
Package events dispatches typed events to listeners registered by type.
Package factory builds models with fake data for tests and seeders:
Package factory builds models with fake data for tests and seeders:
Package htmx provides helpers for htmx 4: reading htmx request headers, building response headers, and rendering <hx-partial> and out-of-band fragments.
Package htmx provides helpers for htmx 4: reading htmx request headers, building response headers, and rendering <hx-partial> and out-of-band fragments.
Package httpclient builds outbound HTTP clients for URLs that users control (webhooks, link previews, avatars by URL).
Package httpclient builds outbound HTTP clients for URLs that users control (webhooks, link previews, avatars by URL).
Package i18n translates messages from JSON catalogs: one file per locale (resources/lang/en.json, pt-BR.json...), nested or dotted keys, {name} placeholders, CLDR plural categories, a locale fallback chain (pt-BR → pt → default), a locale-resolving middleware and translated validation messages.
Package i18n translates messages from JSON catalogs: one file per locale (resources/lang/en.json, pt-BR.json...), nested or dotted keys, {name} placeholders, CLDR plural categories, a locale fallback chain (pt-BR → pt → default), a locale-resolving middleware and translated validation messages.
Package inertia is a server-side adapter for the Inertia.js v3 protocol (https://inertiajs.com/docs/v3/core-concepts/the-protocol).
Package inertia is a server-side adapter for the Inertia.js v3 protocol (https://inertiajs.com/docs/v3/core-concepts/the-protocol).
internal
cli
Package cli implements the global `vukem` command: project scaffolding, generators, the dev server and delegation of app commands to the project's own binary (cmd/app).
Package cli implements the global `vukem` command: project scaffolding, generators, the dev server and delegation of app commands to the project's own binary (cmd/app).
cli/starter/app/jobs
Package jobs holds the queued jobs.
Package jobs holds the queued jobs.
codemod
Package codemod edits Go source the way a developer would: it appends an element to the slice literal returned by a known function and adds the imports it needs.
Package codemod edits Go source the way a developer would: it appends an element to the slice literal returned by a known function and adds the imports it needs.
naming
Package naming converts identifiers between Go and database/file conventions.
Package naming converts identifiers between Go and database/file conventions.
tools/commitlint command
Command commitlint validates a commit message file against Conventional Commits 1.0.
Command commitlint validates a commit message file against Conventional Commits 1.0.
tools/release command
Command release cuts a release at the end of a PLAN.md task group:
Command release cuts a release at the end of a PLAN.md task group:
logging
telegram
Package telegram is a log/slog handler that sends records to Telegram chats, ported from the maintainer's TypeScript telegram-logger.
Package telegram is a log/slog handler that sends records to Telegram chats, ported from the maintainer's TypeScript telegram-logger.
Package mail sends email.
Package mail sends email.
Package middleware provides Vukem's built-in net/http middleware.
Package middleware provides Vukem's built-in net/http middleware.
Package openapi generates an OpenAPI 3.1 document from the router: typed routes (api.Register) are described from their input and output types and `validate` tags; plain routes get a generic entry.
Package openapi generates an OpenAPI 3.1 document from the router: typed routes (api.Register) are described from their input and output types and `validate` tags; plain routes get a generic entry.
Package orm is a generic query builder and model mapper over database/sql.
Package orm is a generic query builder and model mapper over database/sql.
Package queue runs typed background jobs.
Package queue runs typed background jobs.
queuetest
Package queuetest is the conformance suite for queue drivers:
Package queuetest is the conformance suite for queue drivers:
Package ratelimit limits requests per key (token, user, IP) with GCRA, a smooth token bucket that needs one timestamp per key.
Package ratelimit limits requests per key (token, user, IP) with GCRA, a smooth token bucket that needs one timestamp per key.
Package router is a thin layer over net/http.ServeMux (Go 1.22+ patterns) adding route groups, named routes with URL generation, resource controllers and three middleware stacks:
Package router is a thin layer over net/http.ServeMux (Go 1.22+ patterns) adding route groups, named routes with URL generation, resource controllers and three middleware stacks:
Package schedule runs recurring tasks: functions, app commands and queue jobs, on cron expressions or helpers such as DailyAt.
Package schedule runs recurring tasks: functions, app commands and queue jobs, on cron expressions or helpers such as DailyAt.
Package schema builds DDL with a fluent, dialect-aware API (SQLite and PostgreSQL) and runs versioned migrations with batches and checksums.
Package schema builds DDL with a fluent, dialect-aware API (SQLite and PostgreSQL) and runs versioned migrations with batches and checksums.
Package security defines the security event dispatched for every security-relevant decision (failed logins, denied authorization, CSRF rejections, rate limits, invalid signatures).
Package security defines the security event dispatched for every security-relevant decision (failed logins, denied authorization, CSRF rejections, rate limits, invalid signatures).
Package session provides server-side and cookie sessions with flash messages, old input, regeneration (anti-fixation) and idle/absolute timeouts.
Package session provides server-side and cookie sessions with flash messages, old input, regeneration (anti-fixation) and idle/absolute timeouts.
Package signed creates and verifies signed URLs: links that carry an expiry and an HMAC-SHA256 signature over their path and query, for email verification, unsubscribe links or temporary downloads.
Package signed creates and verifies signed URLs: links that carry an expiry and an HMAC-SHA256 signature over their path and query, for email verification, unsubscribe links or temporary downloads.
Package social signs users in with OAuth2 / OpenID Connect providers (GitHub, Google, GitLab, Discord, Microsoft and any compliant provider), in the spirit of AdonisJS Ally, using only the standard library.
Package social signs users in with OAuth2 / OpenID Connect providers (GitHub, Google, GitLab, Discord, Microsoft and any compliant provider), in the spirit of AdonisJS Ally, using only the standard library.
Package sse streams server-sent events (text/event-stream).
Package sse streams server-sent events (text/event-stream).
Package storage reads and writes files on disks: the local filesystem (through os.Root, so paths can never escape the disk) and memory (tests); S3-compatible storage arrives in BETA (drivers/s3).
Package storage reads and writes files on disks: the local filesystem (through os.Root, so paths can never escape the disk) and memory (tests); S3-compatible storage arrives in BETA (drivers/s3).
storagetest
Package storagetest is the conformance suite every storage.Disk passes (local and memory in core, S3 in drivers/s3).
Package storagetest is the conformance suite every storage.Disk passes (local and memory in core, S3 in drivers/s3).
Package view renders html/template views with layouts, partials and fragments (single blocks, for htmx), plus request-aware helpers: route, asset, csrfField, old, errors, flash, cspNonce, t and locale.
Package view renders html/template views with layouts, partials and fragments (single blocks, for htmx), plus request-aware helpers: route, asset, csrfField, old, errors, flash, cspNonce, t and locale.
Package vite renders the tags that load a Vite frontend, following the Laravel "hot file" model.
Package vite renders the tags that load a Vite frontend, following the Laravel "hot file" model.
Package vukemtest is Vukem's testing toolkit: boot an app for a test with an isolated in-memory database, send in-process HTTP requests with a fluent client, and assert on responses, sessions and the database.
Package vukemtest is Vukem's testing toolkit: boot an app for a test with an isolated in-memory database, send in-process HTTP requests with a fluent client, and assert on responses, sessions and the database.
Package web provides the request context (*Ctx) used by Vukem handlers: request helpers, typed input, responses, and the central error handler.
Package web provides the request context (*Ctx) used by Vukem handlers: request helpers, typed input, responses, and the central error handler.
Package webhook verifies signed incoming webhooks (HMAC-SHA256 over the raw body), the scheme used by GitHub, Shopify, Resend/Svix-style providers and your own integrations.
Package webhook verifies signed incoming webhooks (HMAC-SHA256 over the raw body), the scheme used by GitHub, Shopify, Resend/Svix-style providers and your own integrations.
z
Package z parses untrusted input into typed Go values with Zod-inspired schemas, and checks outgoing values against the same contracts.
Package z parses untrusted input into typed Go values with Zod-inspired schemas, and checks outgoing values against the same contracts.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL