Documentation
¶
Index ¶
Constants ¶
const Version = "2.0.0-beta.2"
Version is the library version.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type App ¶
type App interface {
Router
// Run starts the HTTP server and blocks until it stops. Each optional arg
// may be:
// - a string "host:port" or ":port" listen address (default ":8080"), or
// - a pre-bound net.Listener.
// http.ErrServerClosed from a graceful stop is not reported as an error.
Run(args ...any) error
// Shutdown gracefully stops the server (see http.Server.Shutdown), waiting
// for active connections to finish or ctx to expire. Call it from another
// goroutine while Run is blocking.
Shutdown(ctx context.Context) error
}
App is a self-contained HTTP application: a Router plus a Run entry point. Create one with New.
type Config ¶
type Config struct {
// Addr is the listen address (default ":8080"; a string passed to Run
// overrides it).
Addr string
// Timeouts; defaults are Read/Write 60s, ReadHeader 10s. Set WriteTimeout
// to a large value (or use streaming) for long responses.
ReadTimeout time.Duration
WriteTimeout time.Duration
ReadHeaderTimeout time.Duration
// MaxHeaderBytes caps request header size (default 1 MiB).
MaxHeaderBytes int
}
Config holds server settings, applied at construction via WithConfig. Zero fields keep the defaults set in New.
type Ctx ¶
type Ctx interface {
// Request / Response
Request() *http.Request
Response() http.ResponseWriter
// SetResponse replaces the response writer for the remainder of the chain.
// Intended for middleware that wraps the writer (e.g. compression); route
// handlers normally do not need it.
SetResponse(w http.ResponseWriter)
// Identity
Method() string
Path() string
IP() string
// BaseURL returns (protocol + host + base path).
BaseURL() string
// Locale returns the request locale (set by the AcceptLanguage middleware),
// falling back to the i18n default, then "".
Locale() string
// Input
Params(key string) string
Query(key string, def ...string) string
Header(key string, def ...string) string // request header
Body() []byte
FormValue(key string, def ...string) string // body form field (urlencoded or multipart)
Bind(out any) error // JSON body -> out (json.Unmarshal)
//
Translate(locale, key string, args ...any) string // i18n lookup (requires WithI18n)
// Output (SetHeader/Status chain before the body is written)
SetHeader(key, value string) Ctx
Status(code int) Ctx
JSON(v any) error
Send(b []byte) error
SendString(s string) error
Redirect(status int, url string) error
Render(name string, bind any, layouts ...string) error // html template render
// Next runs the next handler in the middleware chain. Middleware call it to
// continue; route handlers are terminal and ignore it.
Next() error
}
Ctx carries the request/response state for a Handler. It is implemented over plain net/http and built per request; path params come from the standard library (r.PathValue, set by the router), so Ctx.Params needs no custom context wiring.
type ErrorHandler ¶
ErrorHandler handles a non-nil error returned from a Handler. It may write a custom response (e.g. a JSON error body). If the Handler already wrote the response, further writes are superfluous. Set via WithErrorHandler; the default writes 500 + err.Error().
type Handler ¶
Handler is the typical handler signature: it receives a Ctx and returns an error (nil on success). Route registrars (Get/Post/.../All) accept a Handler or, for direct stdlib interop, an http.Handler.
func AcceptLanguage ¶
AcceptLanguage returns middleware that detects the request locale from the Accept-Language header and stores it in the request context (readable via Ctx.Locale). def is the default/fallback; others are additional supported locales. Matching uses golang.org/x/text/language (BCP-47), so an "en-US" request matches a supported "en", and "zh-Hans" matches "zh".
Register it with Use, e.g. app.Use(httpsrv.AcceptLanguage("en", "zh", "ja")).
type I18n ¶
type I18n struct {
// contains filtered or unexported fields
}
I18n is a locale message store: locale -> key -> text. Construct with NewI18n, add messages with Add/Set/LoadJSON, and read with Translate. For use in templates, pass i.Funcs() to TemplatesFS/TemplatesDir; for use in handlers, attach to the App with WithI18n (then Ctx.Translate / Ctx.Locale).
Locale keys are matched case-insensitively. Messages are flat key -> text (no plural forms). No date/number/currency/timezone formatting is included.
func NewI18n ¶
NewI18n creates an i18n store; defaultLocale is the fallback for lookups whose locale is empty or has no entry (defaults to "en").
func (*I18n) Funcs ¶
Funcs returns the template function (T) bound to this store, for passing to TemplatesFS/TemplatesDir as extraFuncs when i18n is wanted in templates.
type Option ¶
type Option func(*app)
Option configures an App at construction.
func WithConfig ¶
WithConfig applies server settings from cfg. Only non-zero fields override the defaults. Example:
app := httpsrv.New(httpsrv.WithConfig(httpsrv.Config{
Addr: ":3000",
ReadTimeout: 30 * time.Second,
}))
func WithErrorHandler ¶
func WithErrorHandler(h ErrorHandler) Option
WithErrorHandler sets a custom Handler-error handler.
func WithI18n ¶
WithI18n attaches an opt-in i18n store so Handler code can call Ctx.Translate and Ctx.Locale. i18n is not loaded by default. For template use, also pass the store's Funcs() to TemplatesFS/TemplatesDir.
func WithViews ¶
WithViews attaches a template engine (a Views implementation, e.g. one built by TemplatesDir/TemplatesFS) so Handler code can call Ctx.Render. A custom engine implementing Views may be plugged in the same way. It is the sole entry point for a template engine: Config holds server settings only.
type Router ¶
type Router interface {
// Get/Post/.../All accept a Handler (func(Ctx) error, the typical form) or an
// http.Handler (for direct stdlib interop); a Handler receives a request
// context (Ctx).
Get(path string, handler any) Router
Head(path string, handler any) Router
Post(path string, handler any) Router
Put(path string, handler any) Router
Patch(path string, handler any) Router
Delete(path string, handler any) Router
Options(path string, handler any) Router
All(path string, handler any) Router
// Use registers middleware. With a leading string argument it scopes the
// middleware to that path prefix (segment-aware, all methods); without one
// it runs for every request.
Use(args ...any) Router
// Group returns a sub-router whose routes are prefixed with prefix.
// Groups nest: a group created from another group inherits its prefix.
Group(prefix string) Router
}
Router is the shared route-registration surface implemented by both the App and route Groups. Each method registers a handler for one HTTP method and returns the receiver, so calls chain.
type Views ¶
type Views interface {
// Load is called once to load/parse templates. The built-in engine
// parses at construction, so its Load is a no-op.
Load() error
// Render writes the named template (with optional layouts) to w.
Render(w io.Writer, name string, bind any, layout ...string) error
}
Views is the interface that wraps the Render function. A template engine implements it so Handler code can call Ctx.Render. The built-in engine satisfies it; plug in a custom engine via WithViews.
Default: nil
func TemplatesDir ¶
TemplatesDir builds a template engine from the filesystem directory at root and returns it as a Views.
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
group
command
Example: groups, path params, static files, and template rendering.
|
Example: groups, path params, static files, and template rendering. |
|
hello
command
Example: the smallest possible v2 app.
|
Example: the smallest possible v2 app. |
|
i18n
command
Example: loading i18n messages from local JSON files.
|
Example: loading i18n messages from local JSON files. |
|
internal
|
|
|
lru
Package lru implements an LRU cache.
|
Package lru implements an LRU cache. |
|
radix
Package radix implements a generic radix tree for HTTP route matching.
|
Package radix implements a generic radix tree for HTTP route matching. |
|
middleware
|
|
|
compress
Package compress provides response-compression middleware for httpsrv (New(config) -> Handler).
|
Package compress provides response-compression middleware for httpsrv (New(config) -> Handler). |
|
static
Package static provides a static-file handler for httpsrv.
|
Package static provides a static-file handler for httpsrv. |