Documentation
¶
Overview ¶
Package kora provides a small, batteries-included foundation for Go HTTP applications while preserving standard library types and conventions.
Applications are built around App:
app := kora.New()
app.Get("/health", func(ctx *kora.Context) error {
return ctx.JSON(http.StatusOK, map[string]string{"status": "ok"})
}).Named("health")
Kora includes routing, middleware, typed errors, request binding, validation, environment configuration, structured logging, lifecycle hooks, and explicit constructor-based dependency wiring. The underlying http.Handler, http.Request, http.ResponseWriter, context.Context, error, and slog APIs remain directly accessible.
Index ¶
- func Instance[T any](app *App, value T) error
- func JSON(w http.ResponseWriter, status int, value any) error
- func LoadConfig[T any]() (T, error)
- func LoadConfigFromEnv[T any](lookup EnvLookup) (T, error)
- func LoadEnvFile(path string) error
- func LoadEnvFileIfExists(path string) error
- func LoggerFromContext(ctx context.Context) *slog.Logger
- func ProvideAs[T any](app *App, constructor any, options ...ServiceOption) error
- func RequestIDFromContext(ctx context.Context) string
- func Resolve[T any](app *App) (T, error)
- type App
- func (a *App) Delete(pattern string, handler HandlerFunc) *Route
- func (a *App) Get(pattern string, handler HandlerFunc) *Route
- func (a *App) Group(prefix string, configure func(*Router))
- func (a *App) Handle(method, pattern string, handler HandlerFunc) *Route
- func (a *App) HandleHTTP(method, pattern string, handler http.Handler) *Route
- func (a *App) HandleHTTPFunc(method, pattern string, handler http.HandlerFunc) *Route
- func (a *App) Handler() http.Handler
- func (a *App) Logger() *slog.Logger
- func (a *App) NamedRoute(name string) (Route, bool)
- func (a *App) OnStart(hooks ...LifecycleHook)
- func (a *App) OnStop(hooks ...LifecycleHook)
- func (a *App) Patch(pattern string, handler HandlerFunc) *Route
- func (a *App) Post(pattern string, handler HandlerFunc) *Route
- func (a *App) Provide(constructor any, options ...ServiceOption) error
- func (a *App) Put(pattern string, handler HandlerFunc) *Route
- func (a *App) Routes() []Route
- func (a *App) Run(address string) error
- func (a *App) RunContext(ctx context.Context, address string) error
- func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (a *App) Services() *Container
- func (a *App) SetErrorHandler(handler ErrorHandler)
- func (a *App) SortedRoutes() []Route
- func (a *App) Start(ctx context.Context) error
- func (a *App) Stop(ctx context.Context) error
- func (a *App) URL(name string, params map[string]string) (string, error)
- func (a *App) Use(middleware ...Middleware)
- type Container
- type Context
- func (c *Context) BindJSON(target any) error
- func (c *Context) Context() context.Context
- func (c *Context) JSON(status int, value any) error
- func (c *Context) Logger() *slog.Logger
- func (c *Context) NoContent(status int) error
- func (c *Context) Param(name string) string
- func (c *Context) RequestID() string
- type EnvLookup
- type ErrorHandler
- type HTTPError
- func BadRequest(code, message string) *HTTPError
- func Conflict(code, message string) *HTTPError
- func Forbidden(code, message string) *HTTPError
- func NewHTTPError(status int, code, message string) *HTTPError
- func NotFound(code, message string) *HTTPError
- func Unauthorized(code, message string) *HTTPError
- type HandlerFunc
- type LifecycleHook
- type Lifetime
- type Middleware
- type Option
- type Route
- type Router
- func (r *Router) Delete(pattern string, handler HandlerFunc) *Route
- func (r *Router) Get(pattern string, handler HandlerFunc) *Route
- func (r *Router) Group(prefix string, configure func(*Router))
- func (r *Router) Handle(method, pattern string, handler HandlerFunc) *Route
- func (r *Router) HandleHTTP(method, pattern string, handler http.Handler) *Route
- func (r *Router) HandleHTTPFunc(method, pattern string, handler http.HandlerFunc) *Route
- func (r *Router) Patch(pattern string, handler HandlerFunc) *Route
- func (r *Router) Post(pattern string, handler HandlerFunc) *Route
- func (r *Router) Put(pattern string, handler HandlerFunc) *Route
- func (r *Router) Use(middleware ...Middleware)
- type ServiceOption
- type Validatable
- type ValidationError
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func JSON ¶
func JSON(w http.ResponseWriter, status int, value any) error
JSON writes value as a JSON response with the provided status code. The value is encoded before headers are committed, so serialization errors can still be handled by the caller.
func LoadConfig ¶
LoadConfig loads a typed configuration struct from environment variables. Fields opt in with `env:"KEY"`. The optional `default` tag supplies a fallback, and `required:"true"` rejects missing or empty values.
func LoadConfigFromEnv ¶
LoadConfigFromEnv is LoadConfig with a replaceable environment lookup function. It is useful for tests and custom environment sources.
func LoadEnvFile ¶ added in v0.2.0
LoadEnvFile loads KEY=VALUE entries into the process environment.
Existing environment variables take precedence over file values. Blank lines and comments are ignored. Values may be unquoted, single-quoted, or double-quoted.
func LoadEnvFileIfExists ¶ added in v0.2.0
LoadEnvFileIfExists loads an environment file when it exists.
func LoggerFromContext ¶
LoggerFromContext returns the request-scoped logger when available. It falls back to slog.Default for contexts not created by Kora.
func ProvideAs ¶
func ProvideAs[T any](app *App, constructor any, options ...ServiceOption) error
ProvideAs registers a constructor under T, commonly an interface implemented by the constructor's concrete return type.
func RequestIDFromContext ¶
RequestIDFromContext returns the Kora request ID stored in a standard context.Context. It is useful from native net/http handlers and lower-level application code.
Types ¶
type App ¶
type App struct {
// contains filtered or unexported fields
}
App is the root Kora application.
func (*App) Delete ¶
func (a *App) Delete(pattern string, handler HandlerFunc) *Route
Delete registers a DELETE route.
func (*App) Get ¶
func (a *App) Get(pattern string, handler HandlerFunc) *Route
Get registers a GET route.
func (*App) Handle ¶
func (a *App) Handle(method, pattern string, handler HandlerFunc) *Route
Handle registers a Kora handler for an HTTP method and route pattern. Route patterns use the Go standard library ServeMux syntax.
func (*App) HandleHTTP ¶
HandleHTTP registers an ordinary http.Handler without wrapping it in a Kora Context. Application-wide middleware still applies.
func (*App) HandleHTTPFunc ¶
func (a *App) HandleHTTPFunc(method, pattern string, handler http.HandlerFunc) *Route
HandleHTTPFunc registers an ordinary http.HandlerFunc.
func (*App) Handler ¶
Handler returns the final HTTP handler including Kora request context and application middleware.
func (*App) NamedRoute ¶
NamedRoute returns a copy of the route registered with name.
func (*App) OnStart ¶
func (a *App) OnStart(hooks ...LifecycleHook)
OnStart registers startup hooks. Hooks run in registration order.
func (*App) OnStop ¶
func (a *App) OnStop(hooks ...LifecycleHook)
OnStop registers shutdown hooks. Hooks run in reverse registration order.
func (*App) Patch ¶
func (a *App) Patch(pattern string, handler HandlerFunc) *Route
Patch registers a PATCH route.
func (*App) Post ¶
func (a *App) Post(pattern string, handler HandlerFunc) *Route
Post registers a POST route.
func (*App) Provide ¶
func (a *App) Provide(constructor any, options ...ServiceOption) error
Provide registers a constructor in the application's service container.
func (*App) Put ¶
func (a *App) Put(pattern string, handler HandlerFunc) *Route
Put registers a PUT route.
func (*App) RunContext ¶
RunContext starts an HTTP server and gracefully shuts it down when ctx is cancelled.
func (*App) ServeHTTP ¶
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP lets App satisfy http.Handler.
func (*App) SetErrorHandler ¶
func (a *App) SetErrorHandler(handler ErrorHandler)
SetErrorHandler replaces the application error handler. Passing nil restores Kora's default JSON error handler.
func (*App) SortedRoutes ¶
SortedRoutes returns routes sorted by pattern and method for deterministic output.
func (*App) Stop ¶
Stop runs all registered shutdown hooks in reverse order. All hooks are attempted and their errors are joined.
func (*App) Use ¶
func (a *App) Use(middleware ...Middleware)
Use registers application-wide middleware. Middleware executes in the same order it is registered.
type Container ¶
type Container struct {
// contains filtered or unexported fields
}
Container stores application service providers and resolves their dependency graph.
type Context ¶
type Context struct {
Response http.ResponseWriter
Request *http.Request
}
Context exposes Kora conveniences while keeping the underlying net/http types available.
func NewContext ¶
func NewContext(w http.ResponseWriter, r *http.Request) *Context
NewContext creates a Kora request context around standard library HTTP types.
func (*Context) BindJSON ¶
BindJSON decodes a JSON request body into target. Unknown JSON fields are rejected. If target implements Validatable, validation runs automatically after a successful decode.
func (*Context) Logger ¶
Logger returns the request-scoped slog logger. The logger includes request_id, method, and path attributes.
type ErrorHandler ¶
ErrorHandler converts handler errors into HTTP responses.
type HTTPError ¶
HTTPError represents an expected HTTP failure.
func BadRequest ¶
BadRequest creates a 400 HTTP error.
func NewHTTPError ¶
NewHTTPError creates an expected HTTP error.
func Unauthorized ¶
Unauthorized creates a 401 HTTP error.
type HandlerFunc ¶
HandlerFunc is a Kora handler. Returning an error delegates response handling to the application's ErrorHandler.
type LifecycleHook ¶
LifecycleHook runs during application startup or shutdown.
type Middleware ¶
Middleware wraps an HTTP handler with additional behavior.
type Option ¶
type Option func(*App)
Option configures an App during construction.
func WithLogger ¶
WithLogger configures the application's base slog logger.
func WithRequestIDGenerator ¶
WithRequestIDGenerator replaces the request ID generator. This is useful when applications need a specific ID format.
func WithRequestIDHeader ¶
WithRequestIDHeader changes the HTTP header used for request IDs.
func WithShutdownTimeout ¶
WithShutdownTimeout configures the timeout used for graceful HTTP shutdown and lifecycle stop hooks.
type Route ¶
type Route struct {
Method string
Pattern string
Name string
// contains filtered or unexported fields
}
Route describes a registered HTTP route.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router represents a route group with a shared prefix and middleware stack.
func (*Router) Handle ¶
func (r *Router) Handle(method, pattern string, handler HandlerFunc) *Route
Handle registers a Kora handler on the group.
func (*Router) HandleHTTP ¶
HandleHTTP registers an ordinary http.Handler on the group.
func (*Router) HandleHTTPFunc ¶
func (r *Router) HandleHTTPFunc(method, pattern string, handler http.HandlerFunc) *Route
HandleHTTPFunc registers an ordinary http.HandlerFunc on the group.
func (*Router) Use ¶
func (r *Router) Use(middleware ...Middleware)
Use registers middleware for routes declared on this group and its child groups.
type ServiceOption ¶
type ServiceOption func(*serviceOptions)
ServiceOption configures a service registration.
func Singleton ¶
func Singleton() ServiceOption
Singleton explicitly configures a provider as a singleton. Singleton is also the default lifetime.
func Transient ¶
func Transient() ServiceOption
Transient configures a provider to build a new value on every resolution.
type Validatable ¶
type Validatable interface {
Validate() error
}
Validatable can be implemented by request DTOs that want BindJSON to run explicit application validation after decoding.
type ValidationError ¶
ValidationError contains field-level validation messages.
func NewValidationError ¶
func NewValidationError() *ValidationError
NewValidationError creates an empty validation error collection.
func (*ValidationError) Add ¶
func (e *ValidationError) Add(field, message string) *ValidationError
Add appends a validation message for field and returns the same collection.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Error implements the error interface.
func (*ValidationError) OrNil ¶
func (e *ValidationError) OrNil() error
OrNil returns nil when no validation messages were added.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
kora
command
|
|
|
Package data composes Kora's database application commands.
|
Package data composes Kora's database application commands. |
|
Package database integrates standard library database/sql connections with Kora configuration, dependency injection, and application lifecycle.
|
Package database integrates standard library database/sql connections with Kora configuration, dependency injection, and application lifecycle. |
|
examples
|
|
|
basic
command
Command basic demonstrates a minimal Kora HTTP application.
|
Command basic demonstrates a minimal Kora HTTP application. |
|
crud
command
Command crud runs the complete in-memory Kora CRUD example.
|
Command crud runs the complete in-memory Kora CRUD example. |
|
Package factory builds deterministic test data without requiring an ORM.
|
Package factory builds deterministic test data without requiring an ORM. |
|
internal
|
|
|
cli
Package cli implements the Kora developer command.
|
Package cli implements the Kora developer command. |
|
Package migrate provides dialect-aware, transactional SQL migrations on top of database/sql.
|
Package migrate provides dialect-aware, transactional SQL migrations on top of database/sql. |
|
Package seed executes ordered, transactional database seeders.
|
Package seed executes ordered, transactional database seeders. |