bast

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2026 License: MIT Imports: 18 Imported by: 0

README

Bast Logo

Bast

A structured Go framework for building efficient, scalable, and production server-side applications.

Go Reference CI Go version License Version


Philosophy

Explicit over implicit No magic. Every dependency is wired by hand.
Errors as values Handlers return Response. No side effects, no panic.
Structure at scale Module-based organization. Enforced by the framework.
Stdlib at the boundary Bast satisfies http.Handler. The full Go ecosystem works.
Lean core Near-zero dependencies. Batteries are opt-in companion packages.

Features

  • Radix tree router — zero allocations on the hot path, static-wins-over-param priority
  • Pooled *Ctxsync.Pool based, 0 allocs per request for routing and context
  • Module system — portable, self-contained units with dependency injection at main.go
  • Typed error boundary — one ErrorHandler, consistent JSON envelopes everywhere
  • Built-in middlewareRequestID, Logger, Recover, CORS
  • Guards — pre-handler checks with SecuredGuard → OpenAPI security scheme auto-wiring
  • Streaming*StreamCtx for SSE and chunked responses, never pooled
  • Health checks/health (liveness) and /ready (readiness) with dependency checks
  • OpenAPI 3.0 — spec generated from code at startup; Swagger UI at /docs
  • Typed env configLoadConfig[T]() with env, default, required, secret tags
  • Logger — colored [Bast] boot and request logs, fully pluggable
  • bast new CLI — scaffold a working Todo API in seconds
  • basttest — unit and integration test helpers built into the framework

Quick Start

# Install the CLI
go install github.com/bastion-framework/bast/cmd/bast@latest

# Scaffold a new project (generates a working Todo API)
bast new myapp
cd myapp

# Wire the local framework and run
go mod tidy
go run .

Open http://localhost:8080/docs for the Swagger UI.


Installation

go get github.com/bastion-framework/bast@latest

Requires Go 1.22+.


CLI

bast new <appname>                  # Scaffold a new project
bast generate module <name>         # Generate a module (5 files)
bast generate guard  <name>         # Generate a guard
bast generate service <name>        # Generate a shared service

Testing

basttest ships with the framework — no separate install needed.

// Unit test — handler as a pure function
func TestGetUser(t *testing.T) {
    ctx := basttest.NewCtx(
        basttest.WithParam("id", "42"),
        basttest.WithStore("claims", &Claims{Role: "admin"}),
    )
    resp := controller.GetUser(ctx)
    assert.Equal(t, 200, resp.Status())
}

// Integration test — full request lifecycle
func TestCreateUser(t *testing.T) {
    app := basttest.NewApp(users.NewModule(testDB))
    app.Do("POST", "/users",
        basttest.WithJSONBody(CreateUserRequest{Name: "Kasim", Email: "k@suds.ug"}),
    ).Assert(t).StatusIs(201).BodyContains("id")
}

Benchmarks

See BENCH.md for the full suite and regression thresholds.


Companion packages

Package Description
github.com/bastion-framework/bast-pgx pgx/pgxpool repo helpers, transaction utilities
github.com/bastion-framework/bast-gorm Community maintained
github.com/bastion-framework/bast-sqlc Community maintained

Contributing

Contributions are welcome. Please read CONTRIBUTING.md before opening a pull request.


License

Bast is MIT licensed.


Author Kasim Lyee

Documentation

Index

Constants

View Source
const (
	// 4xx — client errors
	CodeBadRequest       = "BAD_REQUEST"          // 400 generic bad request
	CodeInvalidBody      = "INVALID_BODY"         // 400 malformed JSON / unreadable body
	CodeUnauthorized     = "UNAUTHORIZED"         // 401
	CodeForbidden        = "FORBIDDEN"            // 403
	CodeNotFound         = "NOT_FOUND"            // 404
	CodeMethodNotAllowed = "METHOD_NOT_ALLOWED"   // 405
	CodeTimeout          = "REQUEST_TIMEOUT"      // 408
	CodeConflict         = "CONFLICT"             // 409
	CodePayloadTooLarge  = "PAYLOAD_TOO_LARGE"    // 413
	CodeUnprocessable    = "UNPROCESSABLE_ENTITY" // 422
	CodeValidation       = "VALIDATION_FAILED"    // 422 field-level validation
	CodeTooManyRequests  = "TOO_MANY_REQUESTS"    // 429

	// 5xx — server errors
	CodeInternal           = "INTERNAL_ERROR"      // 500
	CodeNotImplemented     = "NOT_IMPLEMENTED"     // 501
	CodeServiceUnavailable = "SERVICE_UNAVAILABLE" // 503
	CodeGatewayTimeout     = "GATEWAY_TIMEOUT"     // 504
)

Variables

This section is empty.

Functions

func BenchReleaseCtx

func BenchReleaseCtx(c *Ctx)

func ErrBadRequest

func ErrBadRequest(code, message string) error

ErrBadRequest returns a 400 — generic malformed request.

func ErrConflict

func ErrConflict(code, message string) error

ErrConflict returns a 409 — state conflict (e.g. duplicate resource).

func ErrForbidden

func ErrForbidden(code, message string) error

ErrForbidden returns a 403 — authenticated but not permitted.

func ErrGatewayTimeout

func ErrGatewayTimeout(message string) error

ErrGatewayTimeout returns a 504 — upstream dependency did not respond in time.

func ErrInternal

func ErrInternal(code, message string) error

ErrInternal returns a 500 — server fault; never leaks internals to the client.

func ErrInvalidBody

func ErrInvalidBody(message string) error

ErrInvalidBody returns a 400 — request body could not be parsed.

func ErrMethodNotAllowed

func ErrMethodNotAllowed(message string) error

ErrMethodNotAllowed returns a 405 — HTTP method not supported for this route.

func ErrNotFound

func ErrNotFound(code, message string) error

ErrNotFound returns a 404 — resource does not exist.

func ErrNotImplemented

func ErrNotImplemented(message string) error

ErrNotImplemented returns a 501 — endpoint exists but is not yet implemented.

func ErrPayloadTooLarge

func ErrPayloadTooLarge(message string) error

ErrPayloadTooLarge returns a 413 — request body exceeds the size limit.

func ErrServiceUnavailable

func ErrServiceUnavailable(message string) error

ErrServiceUnavailable returns a 503 — server is temporarily unable to handle requests.

func ErrTimeout

func ErrTimeout(message string) error

ErrTimeout returns a 408 — request took too long.

func ErrTooManyRequests

func ErrTooManyRequests(message string) error

ErrTooManyRequests returns a 429 — client has exceeded its rate limit.

func ErrUnauthorized

func ErrUnauthorized(code, message string) error

ErrUnauthorized returns a 401 — missing or invalid credentials.

func ErrUnprocessable

func ErrUnprocessable(code, message string) error

ErrUnprocessable returns a 422 — request is well-formed but semantically invalid.

func Get

func Get[T any](ctx *Ctx, key string) (T, bool)

Get returns a typed value from the Ctx store. No type assertion needed.

func InitTestCtx

func InitTestCtx(c *Ctx, w http.ResponseWriter, r *http.Request)

InitTestCtx wires a writer and request onto a test Ctx. For basttest only.

func LoadConfig

func LoadConfig[T any]() (T, error)

LoadConfig loads and validates configuration from environment variables. T must be a struct. Reflection runs once at startup — never on the hot path.

Supported tags:

env:"VAR_NAME"    — environment variable name
default:"value"   — used when env var is absent
required:"true"   — app refuses to start if absent and no default
secret:"true"     — value is masked in boot logs

Supported field types: string, int, int64, float64, bool, time.Duration, []string Nested structs: env tag on the struct field acts as a prefix (e.g. env:"DB" → DB_URL).

func MustGet

func MustGet[T any](ctx *Ctx, key string) T

MustGet returns a typed value and panics if missing or wrong type.

func SetTestBody

func SetTestBody(c *Ctx, b []byte)

SetTestBody pre-loads the body buffer on a test Ctx so readBody() is skipped. For basttest only.

func SetTestParam

func SetTestParam(c *Ctx, key, value string)

SetTestParam sets a route param on a test Ctx. For basttest only.

Types

type App

type App struct {
	// contains filtered or unexported fields
}

App is the Bast application. Satisfies http.Handler.

func New

func New(cfg Config) *App

New creates a new Bast app with the given config.

func (*App) Guard

func (a *App) Guard(guards ...Guard) *App

Guard registers global guards. Runs for every request before the handler.

func (*App) Listen

func (a *App) Listen() error

Listen starts the HTTP server on the configured port. Uses net.Listen so OnReady fires after the port is bound, before first connections.

func (*App) LivenessHandler

func (a *App) LivenessHandler() HandlerFunc

LivenessHandler returns a HandlerFunc for the liveness probe. Always returns 200 as long as the process is alive — never checks dependencies.

func (*App) OpenAPISpec

func (a *App) OpenAPISpec() map[string]any

OpenAPISpec returns the built OpenAPI spec, or nil if docs are not configured. The spec is built once when this method is first called — safe to call multiple times.

func (*App) ReadinessHandler

func (a *App) ReadinessHandler() HandlerFunc

ReadinessHandler returns a HandlerFunc for the readiness probe. Returns 200 if all checks pass, 503 if any check fails.

func (*App) Register

func (a *App) Register(modules ...Module) *App

Register mounts one or more modules onto the app.

func (*App) ServeHTTP

func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP satisfies http.Handler.

func (*App) Shutdown

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

Shutdown gracefully shuts down the server.

func (*App) Use

func (a *App) Use(mw ...MiddlewareFunc) *App

Use registers global middleware. Runs for every request.

type BastError

type BastError struct {
	Status  int    `json:"-"`
	Code    string `json:"code"`
	Message string `json:"message"`
}

BastError is the typed error Bast understands. Use the constructors — never instantiate directly.

func (*BastError) Error

func (e *BastError) Error() string

func (*BastError) JSON

func (e *BastError) JSON() []byte

JSON serializes BastError into the standard error envelope.

type BodySchema

type BodySchema struct {
	Example any
}

BodySchema holds a reflected type for OpenAPI schema generation. Populated via Body[T]() — reflection runs once at startup, never on hot path.

func Body

func Body[T any]() *BodySchema

Body captures a type for OpenAPI schema generation. Reflection runs once at startup — zero cost at request time.

type Config

type Config struct {
	Port            int
	ReadTimeout     time.Duration
	WriteTimeout    time.Duration
	IdleTimeout     time.Duration
	MaxBodySize     int64
	HandlerTimeout  time.Duration
	ShutdownTimeout time.Duration
	HookTimeout     time.Duration
	TrustedProxies  []string
	ErrorHandler    ErrorHandler
	Validator       Validator
	Health          *HealthConfig
	Docs            *DocsConfig
	Logger          Logger
}

Config holds app-level settings.

type Controller

type Controller interface {
	Routes() []Route
}

Controller is the interface every controller must satisfy. Routes() declares the handler mappings. That is the only contract.

type Ctx

type Ctx struct {

	// Raw stdlib request.
	Request *http.Request
	// contains filtered or unexported fields
}

Ctx is the request context passed to every Bast handler. Pooled via sync.Pool — reset and reused after every request.

CRITICAL: *Ctx does NOT implement context.Context intentionally. This means you cannot pass *Ctx where context.Context is expected. The compiler enforces correct usage, always call ctx.Context() for passing to services, goroutines, or DB calls.

func BenchAcquireCtx

func BenchAcquireCtx(w http.ResponseWriter, r *http.Request) *Ctx

BenchAcquireCtx and BenchReleaseCtx expose the pool for benchmark tests.

func NewTestCtx

func NewTestCtx() *Ctx

NewTestCtx is the exported form for basttest only.

func NewTestCtxWithPath

func NewTestCtxWithPath(path string) *Ctx

NewTestCtxWithPath builds a test Ctx with a specific URL path set.

func (*Ctx) Bind

func (c *Ctx) Bind(v any) error

Bind decodes and validates the request body into v. Returns a 400 BastError on malformed JSON, or a ValidationError on failed struct validation — both flow cleanly through the error boundary.

func (*Ctx) BindForm

func (c *Ctx) BindForm(v any) error

BindForm binds a multipart or url-encoded form into a struct. Uses reflection — only called by user, never on the hot path.

func (*Ctx) BindJSON

func (c *Ctx) BindJSON(v any) error

BindJSON decodes JSON body into v without running validation. Returns a 400 BastError on malformed JSON so the error boundary produces a proper Bad Request response instead of a 500.

func (*Ctx) Context

func (c *Ctx) Context() context.Context

Context returns a detached context.Context safe to pass anywhere.

func (*Ctx) Cookie

func (c *Ctx) Cookie(name string) (*http.Cookie, error)

Cookie retrieves a named cookie from the request.

func (*Ctx) Cookies

func (c *Ctx) Cookies() []*http.Cookie

Cookies returns all cookies from the request.

func (*Ctx) Created

func (c *Ctx) Created(data any) Response

Created returns a 201 response with a JSON envelope.

func (*Ctx) Error

func (c *Ctx) Error(err error) Response

Error returns a response carrying an error for the boundary.

func (*Ctx) File

func (c *Ctx) File(field string) (*multipart.FileHeader, error)

File retrieves a single uploaded file by field name.

func (*Ctx) Files

func (c *Ctx) Files(field string) ([]*multipart.FileHeader, error)

Files retrieves multiple uploaded files from one field.

func (*Ctx) FormValue

func (c *Ctx) FormValue(key string) string

FormValue reads a form field (multipart or url-encoded).

func (*Ctx) Get

func (c *Ctx) Get(key string) (any, bool)

Get retrieves a value from the request-scoped store.

func (*Ctx) Header

func (c *Ctx) Header(key string) string

Header returns a request header value by name.

func (*Ctx) IP

func (c *Ctx) IP() string

IP returns the real client IP, respecting X-Forwarded-For and X-Real-IP only when the request comes from a trusted proxy.

func (*Ctx) Method

func (c *Ctx) Method() string

Method returns the HTTP method of the request.

func (*Ctx) MustGet

func (c *Ctx) MustGet(key string) any

MustGet retrieves a value and panics if not found. Use only when a guard guarantees the value was set.

func (*Ctx) NoContent

func (c *Ctx) NoContent() Response

NoContent returns a 204 response with no body.

func (*Ctx) OK

func (c *Ctx) OK(data any) Response

OK returns a 200 response with a JSON envelope.

func (*Ctx) Paginated

func (c *Ctx) Paginated(data any, meta PaginationMeta) Response

Paginated returns a 200 response with data and pagination metadata.

func (*Ctx) Param

func (c *Ctx) Param(key string) string

Param returns a URL path parameter by name.

func (*Ctx) Path

func (c *Ctx) Path() string

Path returns the request URL path.

func (*Ctx) Query

func (c *Ctx) Query(key string) string

Query returns a URL query parameter by name.

func (*Ctx) QueryDefault

func (c *Ctx) QueryDefault(key, fallback string) string

QueryDefault returns a query param or a fallback if missing.

func (*Ctx) Raw

func (c *Ctx) Raw(status int, contentType string, body []byte) Response

Raw returns a response with a raw body. Used for escape-hatch streaming.

func (*Ctx) RawBody

func (c *Ctx) RawBody() ([]byte, error)

RawBody reads and returns the request body bytes. Safe to call multiple times.

func (*Ctx) Redirect

func (c *Ctx) Redirect(url string, code int) Response

Redirect returns a redirect response.

func (*Ctx) Set

func (c *Ctx) Set(key string, val any)

Set stores a value in the request-scoped store.

func (*Ctx) WithCookie

func (c *Ctx) WithCookie(cookie *http.Cookie) Response

WithCookie chains a cookie onto a response.

func (*Ctx) WithValue

func (c *Ctx) WithValue(key, val any) *Ctx

WithValue returns a shallow copy of Ctx with a value injected.

type Doc

type Doc struct {
	Summary       string
	Description   string
	Tags          []string
	Params        []Param
	Body          *BodySchema
	Returns       Returns
	Deprecated    bool
	DeprecatedMsg string
}

Doc holds human-readable documentation for a route, used to build OpenAPI specs.

type DocsConfig

type DocsConfig struct {
	Enabled     bool
	Path        string // Swagger UI path, e.g. "/docs"
	JSONPath    string // Raw OpenAPI JSON path, e.g. "/openapi.json"
	Title       string
	Version     string
	Description string
}

DocsConfig configures the built-in OpenAPI documentation endpoints.

type ErrorHandler

type ErrorHandler func(ctx *Ctx, err error) Response

ErrorHandler maps an error to a Response.

type Guard

type Guard interface {
	Check(ctx *Ctx) error
}

Guard is a pre-handler check. Return nil to allow, return an error to block. Guards run before the handler and short-circuit on the first non-nil error.

type GuardFunc

type GuardFunc func(ctx *Ctx) error

GuardFunc is a function adapter for Guard.

func (GuardFunc) Check

func (f GuardFunc) Check(ctx *Ctx) error

type HandlerFunc

type HandlerFunc func(ctx *Ctx) Response

HandlerFunc is the signature every Bast handler must have. No variadic args, no interface{}, no side effects.

type HealthCheck

type HealthCheck struct {
	Name string
	// contains filtered or unexported fields
}

HealthCheck is a named dependency check run on the readiness endpoint.

func CustomCheck

func CustomCheck(name string, fn func(ctx context.Context) error) HealthCheck

CustomCheck builds a HealthCheck from a name and a check function.

type HealthConfig

type HealthConfig struct {
	LivePath  string        // liveness probe path, e.g. "/health"
	ReadyPath string        // readiness probe path, e.g. "/ready"
	Checks    []HealthCheck // dependency checks run on /ready
}

HealthConfig configures the built-in health check endpoints.

type Hooks

type Hooks interface {
	OnInit(ctx context.Context) error
	OnReady()
	OnShutdown(ctx context.Context) error
}

Hooks is an optional interface modules may implement to hook into the app lifecycle.

type Logger

type Logger interface {
	OnBoot(version string)
	OnModuleRegistered(name, prefix string)
	OnRouteRegistered(method, path string, guards []string)
	OnServiceExported(serviceType string, fromModule string)
	OnServiceResolved(serviceType string, toModule string)
	OnListening(port int)
	OnShutdown()
	OnRequest(method, path string, status int, dur time.Duration, ip string)
	OnError(ctx *Ctx, err error)
	Info(msg string, args ...any)
	Warn(msg string, args ...any)
	Error(msg string, args ...any)
	Debug(msg string, args ...any)
}

Logger is the pluggable logging interface for the Bast framework. The default implementation produces colored output to stdout. Swap it out via Config.Logger for Zap, Zerolog, or any other backend.

func NewDefaultLogger

func NewDefaultLogger() Logger

NewDefaultLogger returns the default Bast logger writing to stdout.

type MiddlewareFunc

type MiddlewareFunc func(next HandlerFunc) HandlerFunc

MiddlewareFunc wraps a HandlerFunc to form a pipeline. Call next(ctx) to pass control to the next middleware or handler. Do not call next to short-circuit (e.g. auth failure) — return a Response directly.

type Module

type Module struct {
	// Prefix is the URL prefix for all routes in this module.
	Prefix string

	// Controller declares this module's routes.
	Controller Controller

	// Middleware scoped to every route in this module.
	// Runs after global middleware, before route-level middleware.
	Middleware []MiddlewareFunc

	// Guards scoped to every route in this module.
	// Runs after global guards, before route-level guards.
	Guards []Guard

	// Nested sub-modules. Inherits parent prefix.
	Modules []Module

	// Doc metadata for Swagger tag group.
	Doc ModuleDoc
}

Module is a portable, self-contained unit of functionality. It owns its routes, guards, middleware, and optionally sub-modules.

type ModuleDoc

type ModuleDoc struct {
	Name        string
	Description string
}

ModuleDoc holds human-readable metadata for OpenAPI tag groups.

type PaginationMeta

type PaginationMeta struct {
	Page    int `json:"page"`
	PerPage int `json:"per_page"`
	Total   int `json:"total"`
	Pages   int `json:"pages"`
}

PaginationMeta holds standard pagination information.

type Param

type Param struct {
	In          string // "path", "query", "header"
	Name        string
	Description string
	Required    bool
}

Param describes a single route parameter for OpenAPI docs.

func PathParam

func PathParam(name, description string) Param

PathParam constructs a path parameter descriptor.

func QueryParam

func QueryParam(name, description string) Param

QueryParam constructs a query parameter descriptor.

type Response

type Response struct {
	// contains filtered or unexported fields
}

Response is an immutable value representing what the framework should write. Constructed via Ctx methods — never directly instantiated by user code. All methods use value receivers and return new Response values — never mutate.

Internal constructors below are used by Ctx methods and basttest.

func DefaultErrorHandler

func DefaultErrorHandler(ctx *Ctx, err error) Response

DefaultErrorHandler is the built-in error boundary. Maps BastError and ValidationError to structured JSON responses. Unknown errors become 500 without leaking internals.

func NewErrorResponse

func NewErrorResponse(err error) Response

NewErrorResponse is the exported form used by basttest and response tests.

func NewRawResponse

func NewRawResponse(status int, contentType string, body []byte) Response

NewRawResponse is the exported form used by basttest and response tests.

func (Response) Body

func (r Response) Body() []byte

Body returns the raw response body bytes.

func (Response) ContentType

func (r Response) ContentType() string

ContentType returns the Content-Type header value.

func (Response) Cookies

func (r Response) Cookies() []*http.Cookie

Cookies returns cookies to be set on the response.

func (Response) Err

func (r Response) Err() error

Err returns the underlying error, if any.

func (Response) Headers

func (r Response) Headers() map[string]string

Headers returns the response headers map.

func (Response) IsError

func (r Response) IsError() bool

IsError reports whether this response carries an error.

func (Response) Redirect

func (r Response) Redirect() string

Redirect returns the redirect URL, if any.

func (Response) Status

func (r Response) Status() int

Status returns the HTTP status code.

func (Response) WithCookie

func (r Response) WithCookie(cookie *http.Cookie) Response

WithCookie returns a new Response with an additional cookie attached.

func (Response) WithHeader

func (r Response) WithHeader(key, value string) Response

WithHeader returns a new Response with an additional header set.

func (Response) WithStatus

func (r Response) WithStatus(code int) Response

WithStatus returns a new Response with a different status code.

type Returns

type Returns map[int]*BodySchema

Returns maps HTTP status codes to response body schemas.

type Route

type Route struct {
	Method      string
	Pattern     string
	Handler     HandlerFunc
	Stream      StreamHandlerFunc // non-nil when this is a streaming route
	Middleware  []MiddlewareFunc
	Guards      []Guard
	Timeout     time.Duration
	MaxBodySize int64
	Doc         Doc
}

Route binds an HTTP method + path pattern to a handler.

func DELETE

func DELETE(pattern string, handler HandlerFunc, opts ...RouteOption) Route

DELETE constructs a DELETE route.

func GET

func GET(pattern string, handler HandlerFunc, opts ...RouteOption) Route

GET constructs a GET route.

func PATCH

func PATCH(pattern string, handler HandlerFunc, opts ...RouteOption) Route

PATCH constructs a PATCH route.

func POST

func POST(pattern string, handler HandlerFunc, opts ...RouteOption) Route

POST constructs a POST route.

func PUT

func PUT(pattern string, handler HandlerFunc, opts ...RouteOption) Route

PUT constructs a PUT route.

func STREAM

func STREAM(pattern string, handler StreamHandlerFunc, opts ...RouteOption) Route

STREAM constructs a streaming route. The handler owns the connection for its lifetime.

type RouteOption

type RouteOption func(*Route)

RouteOption applies optional config to a route at construction time.

func WithDoc

func WithDoc(doc Doc) RouteOption

WithDoc attaches documentation to a route.

func WithGuards

func WithGuards(guards ...Guard) RouteOption

WithGuards attaches guards to a specific route.

func WithMaxBody

func WithMaxBody(n int64) RouteOption

WithMaxBody sets a per-route request body size limit in bytes.

func WithMiddleware

func WithMiddleware(mw ...MiddlewareFunc) RouteOption

WithMiddleware attaches middleware to a specific route.

func WithTimeout

func WithTimeout(d time.Duration) RouteOption

WithTimeout sets a per-route handler timeout.

type SecuredGuard

type SecuredGuard interface {
	Guard
	SecurityScheme() SecurityScheme
}

SecuredGuard is a Guard that also declares its OpenAPI security scheme. Bast uses this to populate securitySchemes in the OpenAPI spec automatically.

type SecurityScheme

type SecurityScheme struct {
	Type         string // "http", "apiKey", "oauth2"
	Scheme       string // "bearer", "basic"
	BearerFormat string // "JWT"
	Description  string
}

SecurityScheme describes an OpenAPI security scheme declared by a guard.

type StreamCtx

type StreamCtx struct {
	context.Context
	Request *http.Request
	// contains filtered or unexported fields
}

StreamCtx is the context for streaming handlers. Unlike *Ctx, it is NOT pooled — allocated per connection, GC'd when done. It embeds context.Context directly — safe to pass anywhere, for any duration.

func (*StreamCtx) Closed

func (s *StreamCtx) Closed() <-chan struct{}

Closed returns a channel that is closed when the client disconnects. Equivalent to StreamCtx.Done() via the embedded context.

func (*StreamCtx) Flush

func (s *StreamCtx) Flush()

Flush flushes buffered data to the client immediately.

func (*StreamCtx) Send

func (s *StreamCtx) Send(event, data string) error

Send writes a Server-Sent Event to the client.

func (*StreamCtx) SetHeader

func (s *StreamCtx) SetHeader(key, value string)

SetHeader sets a response header. Must be called before first Write or Send.

func (*StreamCtx) Write

func (s *StreamCtx) Write(p []byte) (int, error)

Write writes raw bytes to the client.

type StreamHandlerFunc

type StreamHandlerFunc func(ctx *StreamCtx)

StreamHandlerFunc is the signature for streaming handlers. Does not return a Response, the handler owns the wire for its full duration.

type ValidationError

type ValidationError struct {
	Fields map[string]string
}

ValidationError is returned by ctx.Bind() when struct validation fails. The error boundary detects it and produces field-level 422 responses automatically.

func (*ValidationError) BastStatus

func (e *ValidationError) BastStatus() int

BastStatus satisfies a convention checked by the error boundary.

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) JSON

func (e *ValidationError) JSON() []byte

JSON serializes ValidationError into the validation error envelope.

type Validator

type Validator interface {
	Validate(v any) error
}

Validator is a pluggable struct validation interface.

Directories

Path Synopsis
Package basttest provides test helpers for Bast handlers and apps.
Package basttest provides test helpers for Bast handlers and apps.
cmd
bast command
internal

Jump to

Keyboard shortcuts

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