Documentation
¶
Overview ¶
Package sinatra is a pure-Go (no cgo) reimplementation of the deterministic core of Ruby's Sinatra web framework (Sinatra 4.x) — the route table, the Mustermann-style pattern compiler, the request dispatcher (before/after filters, halt/pass/redirect, not_found/error handlers) and the assembly of the Rack [status, headers, body] tuple — matching the MRI sinatra gem.
It is built on github.com/go-ruby-rack/rack, reusing rack.Request to read the incoming environment and rack.Response to shape the outgoing tuple, and it is a sibling of the other go-ruby-* front-ends (go-ruby-regexp, go-ruby-erb, go-ruby-yaml, go-ruby-rack).
What it is — and isn't ¶
Compiling a route pattern to a matcher, extracting params (named captures, splats, query merge), ordering the filters, and the halt/pass control flow are all fully deterministic and need no interpreter, so they live here as pure Go. The action bodies (the `do…end` blocks of a Ruby route), the session store, and template rendering (ERB/Haml) are SEAMS the embedding runtime (go-embedded-ruby's rbgo) supplies. The HTTP server — the socket accept loop, TLS, Rack::Handler — is the host's job and is out of scope.
An action body is modelled as an Action: a Go func given a *Context that returns a body (or invokes Halt/Pass/Redirect on the context). rbgo binds a Ruby block to an Action; a Go caller can supply one directly.
Index ¶
- func MimeType(sym string) string
- func StatusText(code int) string
- type Action
- type Context
- func (c *Context) App() *Sinatra
- func (c *Context) Body(s string)
- func (c *Context) ContentType(typeArg string)
- func (c *Context) ContentTypeCharset(typeArg, charset string)
- func (c *Context) CurrentStatus() int
- func (c *Context) Halt(args ...any)
- func (c *Context) Header(key string, value string)
- func (c *Context) Headers(h map[string]string)
- func (c *Context) Param(key string) (any, bool)
- func (c *Context) ParamKeys() []string
- func (c *Context) ParamString(key string) string
- func (c *Context) Params() []ParamPair
- func (c *Context) Pass()
- func (c *Context) Redirect(target string, status ...int)
- func (c *Context) Request() *rack.Request
- func (c *Context) Response() *rack.Response
- func (c *Context) Session() any
- func (c *Context) Settings() *Settings
- func (c *Context) Status(code int)
- func (c *Context) URI(path string) string
- type MatchResult
- type ParamPair
- type Pattern
- type Settings
- type Sinatra
- func (s *Sinatra) After(pat string, action Action)
- func (s *Sinatra) Before(pat string, action Action)
- func (s *Sinatra) Call(env rack.Env) *rack.Response
- func (s *Sinatra) CallTuple(env rack.Env) (int, *rack.Headers, []string)
- func (s *Sinatra) Delete(pat string, action Action)
- func (s *Sinatra) Error(status int, action Action)
- func (s *Sinatra) Get(pat string, action Action)
- func (s *Sinatra) Head(pat string, action Action)
- func (s *Sinatra) NotFound(action Action)
- func (s *Sinatra) Options(pat string, action Action)
- func (s *Sinatra) Patch(pat string, action Action)
- func (s *Sinatra) Post(pat string, action Action)
- func (s *Sinatra) Put(pat string, action Action)
- func (s *Sinatra) Route(verb, pat string, action Action)
- func (s *Sinatra) RoutePattern(verb string, p *Pattern, action Action)
- func (s *Sinatra) Settings() *Settings
- type UnknownMediaType
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func MimeType ¶
MimeType resolves a Sinatra mime symbol or extension to a media type, like Sinatra::Base.mime_type. A value already containing a "/" is returned as is (Sinatra treats a full media type as itself). It returns "" when unknown.
func StatusText ¶
StatusText returns the canonical reason phrase for an HTTP status code, from rack's status table (e.g. 404 -> "Not Found"). It is "" for an unknown code.
Types ¶
type Action ¶
Action is the body of a route (or a filter): the Ruby `do…end` block as a Go func. It receives the live *Context and returns the body. The embedding runtime (rbgo) binds a Ruby block to an Action; a Go caller supplies one directly. Control-flow helpers — Halt, Pass, Redirect — are invoked on the context and unwind via panic, exactly like Sinatra's throw :halt/:pass.
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context carries the per-request dispatch state and exposes the Sinatra DSL helpers an action body uses: Params, Request, Response, Status, Body, ContentType, Headers, Redirect, Halt and Pass. It wraps go-ruby-rack's Request and Response.
func (*Context) ContentType ¶
ContentType sets the Content-Type, resolving a Sinatra mime symbol/extension and appending a charset per Sinatra's add_charset rule, like the `content_type` helper. It panics (HaltError 500-style) for an unknown type, matching Sinatra raising on an unknown media type — callers using rbgo see the raise; Go callers should pass known types or a full media type.
func (*Context) ContentTypeCharset ¶
ContentTypeCharset is Context.ContentType with an explicit charset (content_type :json, charset: 'utf-8').
func (*Context) CurrentStatus ¶
CurrentStatus returns the response status.
func (*Context) Halt ¶
Halt stops processing immediately, like Sinatra's `halt`. With no argument it keeps the current status; an int sets the status; a string sets the body; (int, string) sets both. Extra/!typed arguments are ignored.
func (*Context) Param ¶
Param returns the named param value and whether it is present. The value is a string for a scalar, or a []string for "splat"/"captures".
func (*Context) ParamString ¶
ParamString returns the string value of a scalar param, or "" if absent or not a string.
func (*Context) Params ¶
Params returns a snapshot of the params as an ordered key/value list, preserving Sinatra's deterministic ordering (route params, then splat, then query). The values are strings or []string.
func (*Context) Pass ¶
func (c *Context) Pass()
Pass abandons the current route and tells the dispatcher to try the next matching route for the request method, like Sinatra's `pass`. If no further route matches, the not_found handler runs.
func (*Context) Redirect ¶
Redirect performs a Sinatra redirect: it sets the Location header (resolving a relative target against the request URL) and halts with status 302 (or the given status). Like Sinatra, it unwinds the action immediately.
func (*Context) Session ¶
Session returns the session store seam (the rack.session env value). The store itself is supplied by the host; Sinatra only shapes access to it.
type MatchResult ¶
type MatchResult struct {
// Named maps each :name token to its URI-decoded captured value, in the
// order the tokens appear. A nil capture (an absent optional :name?) is
// omitted, matching Sinatra dropping the key.
Named *orderedParams
// Splat is the ordered list of URI-decoded "*" captures (or, for a regexp
// pattern, its numbered captures).
Splat []string
// FromRegexp reports whether Splat came from a raw regexp pattern, so the
// dispatcher knows to file it under params["captures"] not params["splat"].
FromRegexp bool
}
MatchResult holds the outcome of matching a path against a Pattern.
type Pattern ¶
type Pattern struct {
// contains filtered or unexported fields
}
Pattern is a compiled Sinatra route pattern. It is produced by Compile from a Mustermann-style string ("/hello/:name", "/say/*/to/*", "/posts/:id?") or wrapped around a raw regexp by CompileRegexp.
Matching a path yields the ordered named captures and the ordered list of splat ("*") values, mirroring how Sinatra populates params: a :name token becomes params["name"], every * (and a regexp group) feeds the params["splat"] / params["captures"] array, and all captured values are URI-decoded.
func Compile ¶
Compile turns a Mustermann-style Sinatra pattern into a Pattern. The grammar handled is the Sinatra default: ":name" named captures, "*" splats, a trailing "?" making the preceding token optional, and literal text (with regexp metacharacters escaped). It mirrors Mustermann's compiled regexp: :name -> (?P<n>[^/?#]+), :name? -> (?:(?P<n>[^/?#]+))? and * -> (.*?), all anchored with \A…\z.
Every token in the grammar emits a valid regexp fragment — names are [A-Za-z0-9_], literals are quoted, and the structural pieces are fixed — so the assembled regexp always compiles; Compile therefore never returns a pattern error. A raw user regexp, which can be malformed, goes through CompileRegexp instead.
func CompileRegexp ¶
CompileRegexp wraps a raw regexp source as a Pattern. Its numbered captures feed params["captures"], matching Sinatra's `get %r{…}` form. The source is anchored with \A…\z if not already.
func (*Pattern) Match ¶
func (p *Pattern) Match(path string) (MatchResult, bool)
Match tests path against the pattern. It returns the extracted captures and true on a match, or a zero MatchResult and false otherwise. Captured values are URI-decoded (Mustermann/Sinatra decode each segment).
type Settings ¶
type Settings struct {
// contains filtered or unexported fields
}
Settings is the per-application registry behind Sinatra's set/enable/disable. Values are arbitrary; the dispatcher reads a handful of well-known keys (default_content_type, default_encoding). It is insertion-ordered so a caller can enumerate settings deterministically.
func (*Settings) Bool ¶
Bool returns the boolean value of key, or false if unset or non-bool. It mirrors Sinatra treating a truthy setting (used by enable?/disable?).
type Sinatra ¶
type Sinatra struct {
// contains filtered or unexported fields
}
Sinatra is an application: the route table per HTTP verb, the before/after filters, the not_found and error handlers, and the settings registry. Build one with New, register routes with Get/Post/…, then serve a Rack env with Sinatra.Call.
func (*Sinatra) Before ¶
Before registers a before-filter. With an empty pattern it runs on every request; otherwise only when pat matches the path (and its captures merge into params, like Sinatra).
func (*Sinatra) Call ¶
Call serves a Rack environment, returning the [status, headers, body] tuple as a rack.Response. It runs the before filters, finds the first matching route for the request method (honouring pass), runs the action, runs the after filters, and applies the not_found / error handlers.
func (*Sinatra) CallTuple ¶
CallTuple is a convenience returning the SPEC [status, headers, body] tuple directly, the form a Rack server consumes.
func (*Sinatra) Error ¶
Error registers a handler for a specific HTTP status (Sinatra's error(code)).
func (*Sinatra) NotFound ¶
NotFound registers the handler for an unmatched request (Sinatra's not_found), run with status 404.
func (*Sinatra) Route ¶
Route registers an action for an arbitrary HTTP verb and Mustermann pattern.
func (*Sinatra) RoutePattern ¶
RoutePattern registers an action for verb against an already-compiled Pattern (e.g. a regexp route from CompileRegexp).
type UnknownMediaType ¶
type UnknownMediaType struct{ Type string }
UnknownMediaType is raised by ContentType for an unrecognised media type, mirroring Sinatra's "Unknown media type" error.
func (*UnknownMediaType) Error ¶
func (e *UnknownMediaType) Error() string
