Documentation
¶
Overview ¶
Package shinobi is a lightweight HTTP micro-framework built on top of the Go standard library.
Index ¶
- Constants
- Variables
- func JSONMaxBytes(n int64) func(*jsonBinder)
- func JSONNumber() func(*jsonBinder)
- func JSONStrict() func(*jsonBinder)
- type App
- func (a *App) Connect(pattern string, h HandlerFunc)
- func (a *App) Delete(pattern string, h HandlerFunc)
- func (a *App) Get(pattern string, h HandlerFunc)
- func (a *App) Group(prefix string, fn func(Router))
- func (a *App) Handle(pattern string, h Handler)
- func (a *App) HandleFunc(pattern string, h HandlerFunc)
- func (a *App) Head(pattern string, h HandlerFunc)
- func (a *App) IsDebug() bool
- func (a *App) Listen(addr string) error
- func (a *App) ListenGraceful(addr string, timeout time.Duration) error
- func (a *App) ListenTLS(addr, certFile, keyFile string) error
- func (a *App) ListenTLSGraceful(addr, certFile, keyFile string, timeout time.Duration) error
- func (a *App) Method(method, pattern string, h Handler)
- func (a *App) MethodFunc(method, pattern string, h HandlerFunc)
- func (a *App) Mount(prefix string, h Handler)
- func (a *App) Name() string
- func (a *App) NotFound(h HandlerFunc)
- func (a *App) Options(pattern string, h HandlerFunc)
- func (a *App) Patch(pattern string, h HandlerFunc)
- func (a *App) Post(pattern string, h HandlerFunc)
- func (a *App) Put(pattern string, h HandlerFunc)
- func (a *App) Route(pattern string, fn func(Route))
- func (a *App) Router() Router
- func (a *App) Routes() []RouteInfo
- func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (a *App) Server(addr string) *http.Server
- func (a *App) SetDebug(v bool)
- func (a *App) SetLogger(l *slog.Logger)
- func (a *App) SetName(name string)
- func (a *App) Trace(pattern string, h HandlerFunc)
- func (a *App) Use(middlewares ...Middleware)
- func (a *App) With(middlewares ...Middleware) Router
- type Binder
- type BinderRegistry
- type Config
- type Ctx
- type ErrorHandler
- type FileUpload
- type Handler
- type HandlerFunc
- type Middleware
- type Option
- func WithBinder(b Binder) Option
- func WithDebug(v bool) Option
- func WithErrorHandler(h ErrorHandler) Option
- func WithLogger(l *slog.Logger) Option
- func WithMux(mux *http.ServeMux) Option
- func WithNotFound(h HandlerFunc) Option
- func WithPrefix(prefix string) Option
- func WithRenderer(r render.Renderer) Option
- func WithValidator(v Validator) Option
- type Response
- func (r *Response) SetResponseWriter(fn func(http.ResponseWriter) http.ResponseWriter)
- func (r *Response) Status() int
- func (r *Response) Unwrap() http.ResponseWriter
- func (r *Response) Write(b []byte) (int, error)
- func (r *Response) WriteHeader(code int)
- func (r *Response) WriteString(s string) (int, error)
- func (r *Response) Written() bool
- type Route
- type RouteInfo
- type Router
- type StatusError
- type Validatable
- type Validator
Constants ¶
const ( KB int64 = 1 << 10 // 1 024 bytes MB int64 = 1 << 20 // 1 048 576 bytes GB int64 = 1 << 30 // 1 073 741 824 bytes )
Size constants for use with MaxSize, BodyLimit, and JSONMaxBytes. Example: shinobi.NewImageUpload(f, h, 5*shinobi.MB)
Variables ¶
var DefaultBinder = BinderRegistry{ "application/json": JSONBinder(), "application/xml": XMLBinder(), "application/x-www-form-urlencoded": FormBinder(), }
DefaultBinder is the default BinderRegistry used when no custom Binder is configured. It supports application/json, application/xml, and application/x-www-form-urlencoded out of the box.
var ( // ErrInvalidRedirectStatusCode is returned when an invalid HTTP status code is provided for redirection. ErrInvalidRedirectStatusCode = errors.New("invalid redirect status code") )
HTTP Errors
var ( // ErrTemplateRendererNotSet is returned when HTML is called without a configured template renderer. ErrTemplateRendererNotSet = errors.New("template renderer not configured") )
Renderer errors
var ( // ErrUnsupportedContentType is returned when no Binder is registered for the request Content-Type. ErrUnsupportedContentType = errors.New("unsupported content type") )
Binder errors
var ( // ErrValidatorNotSet is returned when Validate is called without a configured Validator. ErrValidatorNotSet = errors.New("validator not configured") )
Validate errors
Functions ¶
func JSONMaxBytes ¶ added in v0.3.0
func JSONMaxBytes(n int64) func(*jsonBinder)
JSONMaxBytes configures JSONBinder to limit the request body size to n bytes.
func JSONNumber ¶ added in v0.3.0
func JSONNumber() func(*jsonBinder)
JSONNumber configures JSONBinder to decode numbers as json.Number instead of float64.
func JSONStrict ¶ added in v0.3.0
func JSONStrict() func(*jsonBinder)
JSONStrict configures JSONBinder to reject unknown fields.
Types ¶
type App ¶
type App struct {
// contains filtered or unexported fields
}
App is the top-level shinobi application. It wraps a Router and manages the HTTP server lifecycle.
func New ¶
New creates a new App with the given options. All options configure the underlying Router.
func (*App) Connect ¶
func (a *App) Connect(pattern string, h HandlerFunc)
Connect registers a CONNECT route.
func (*App) Delete ¶
func (a *App) Delete(pattern string, h HandlerFunc)
Delete registers a DELETE route.
func (*App) HandleFunc ¶
func (a *App) HandleFunc(pattern string, h HandlerFunc)
HandleFunc registers a new route with a handler function for the given pattern.
func (*App) IsDebug ¶ added in v0.11.0
IsDebug reports whether the application is running in debug mode.
func (*App) ListenGraceful ¶
ListenGraceful starts an HTTP server and shuts it down gracefully on SIGINT or SIGTERM.
func (*App) ListenTLSGraceful ¶
ListenTLSGraceful starts an HTTPS server and shuts it down gracefully on SIGINT or SIGTERM.
func (*App) MethodFunc ¶
func (a *App) MethodFunc(method, pattern string, h HandlerFunc)
MethodFunc registers a new route with a specific HTTP method and handler function.
func (*App) NotFound ¶
func (a *App) NotFound(h HandlerFunc)
NotFound registers a custom handler for 404 responses.
func (*App) Options ¶
func (a *App) Options(pattern string, h HandlerFunc)
Options registers an OPTIONS route.
func (*App) Patch ¶
func (a *App) Patch(pattern string, h HandlerFunc)
Patch registers a PATCH route.
func (*App) ServeHTTP ¶
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler, delegating to the underlying router.
func (*App) Server ¶
Server returns an http.Server pre-configured with production-safe defaults: ReadHeaderTimeout 5s, ReadTimeout 10s, WriteTimeout 30s, IdleTimeout 120s. Any field can be overridden after calling this method.
func (*App) SetDebug ¶ added in v0.11.0
SetDebug enables or disables debug mode. In debug mode, routes are logged at startup and error responses include the original error message.
func (*App) SetLogger ¶ added in v0.11.0
SetLogger sets the logger used by the application and injected into each request context. Ignored if l is nil. Defaults to slog.Default().
func (*App) SetName ¶ added in v0.7.0
SetName sets the application name used in log messages. Ignored if name is empty. Defaults to "shinobi".
func (*App) Trace ¶
func (a *App) Trace(pattern string, h HandlerFunc)
Trace registers a TRACE route.
func (*App) Use ¶
func (a *App) Use(middlewares ...Middleware)
Use appends one or more middlewares to the global middleware stack.
func (*App) With ¶
func (a *App) With(middlewares ...Middleware) Router
With returns a new Router scoped with the provided middlewares.
type Binder ¶ added in v0.3.0
Binder decodes an HTTP request body into a value.
func FormBinder ¶ added in v0.5.0
func FormBinder() Binder
FormBinder returns a Binder that decodes form fields into a struct using `form:""` field tags. Supported types: string, int, int64, float64, bool, time.Time. Use `format:""` to specify a custom time layout. Pointer fields are treated as optional — nil when the field is absent.
func JSONBinder ¶ added in v0.3.0
func JSONBinder(opts ...func(*jsonBinder)) Binder
JSONBinder returns a Binder that decodes JSON request bodies.
func QueryBinder ¶ added in v0.5.0
func QueryBinder() Binder
QueryBinder returns a Binder that decodes URL query parameters into a struct using `query:""` field tags. Supported types: string, int, int64, float64, bool, time.Time. Use `format:""` to specify a custom time layout. Pointer fields are treated as optional — nil when the parameter is absent.
type BinderRegistry ¶ added in v0.3.0
BinderRegistry maps MIME type prefixes to their corresponding Binder. It implements Binder itself, selecting the appropriate decoder based on Content-Type.
type Config ¶ added in v0.11.0
type Config struct {
// contains filtered or unexported fields
}
Config holds the configuration for an App and its Router. Use functional Options to customize it; most callers rely on DefaultConfig.
func DefaultConfig ¶ added in v0.11.0
func DefaultConfig() *Config
DefaultConfig returns a Config with production-safe defaults.
type Ctx ¶
type Ctx interface {
// Request returns the underlying HTTP request.
Request() *http.Request
// Response returns the wrapped HTTP response writer.
Response() *Response
// Context returns the request's stdlib context.
Context() context.Context
// WithContext returns a shallow copy of Ctx with the request context replaced.
WithContext(ctx context.Context) Ctx
// Set stores a value in the request context chain.
Set(key, value any)
// Get retrieves a value from the request context chain.
Get(key any) (any, bool)
// Logger returns the logger associated with this request context.
Logger() *slog.Logger
// Debug reports whether the application is running in debug mode.
Debug() bool
// IsLoopback reports whether addr is a loopback address.
IsLoopback(addr string) bool
// IsSecure reports whether the request was made over HTTPS.
IsSecure() bool
// IsXHR reports whether the request was made via XMLHttpRequest.
IsXHR() bool
// IsWebSocket reports whether the request is a WebSocket upgrade.
IsWebSocket() bool
// IsMethod reports whether the request method matches m (case-insensitive).
IsMethod(s string) bool
// Method returns the HTTP method of the request (e.g. "GET", "POST").
Method() string
// Path returns the URL path of the request (e.g. "/users/42").
Path() string
// Host returns the host from the request (e.g. "example.com").
Host() string
// Scheme returns "https" if the request is secure, "http" otherwise.
Scheme() string
// Query returns the first value for the named query parameter.
Query(key string) string
// QueryValues returns all query parameters as url.Values.
QueryValues() url.Values
// FormValue returns the first value for the named form field.
FormValue(key string) string
// ParseForm populates Request.Form and Request.PostForm.
ParseForm() error
// Param returns the path parameter value for the given key.
Param(key string) string
// ContentType returns the Content-Type header of the request.
ContentType() string
// UserAgent returns the User-Agent header of the request.
UserAgent() string
// Referer returns the Referer header of the request.
Referer() string
// FormFile returns the uploaded file for the named form key.
FormFile(key string) (multipart.File, *multipart.FileHeader, error)
// Bind decodes the request body into v based on the Content-Type header.
Bind(v any) error
// BindQuery decodes URL query parameters into v using struct field tags.
// Fields are mapped via the `query:""` tag. Supported types: string, int,
// int64, float64, bool, time.Time. Use `format:""` to specify a custom time
// layout; otherwise RFC3339, DateTime and DateOnly are tried in order.
// Pointer fields are optional — nil when the parameter is absent.
// Fields without a tag or with tag `query:"-"` are ignored.
//
// Example:
//
// type SearchParams struct {
// Query string `query:"q"`
// Page int `query:"page"`
// Since time.Time `query:"since"`
// }
// var p SearchParams
// if err := c.BindQuery(&p); err != nil {
// return err
// }
BindQuery(v any) error
// BindForm decodes form fields from the request body into v using `form:""` struct tags.
// Supported types: string, int, int64, float64, bool, time.Time. Use `format:""`
// to specify a custom time layout; otherwise RFC3339, DateTime and DateOnly are tried in order.
// Pointer fields are optional — nil when the field is absent.
// Fields without a tag or with tag `form:"-"` are ignored.
BindForm(v any) error
// Validate validates v using the configured Validator.
Validate(v any) error
// SetCookie adds a Set-Cookie header to the response.
SetCookie(cookie *http.Cookie)
// DeleteCookie expires a cookie by name and path.
DeleteCookie(name, path string)
// SetHeader sets a response header, replacing any existing value.
SetHeader(key, value string)
// AddHeader adds a response header value without replacing existing ones.
AddHeader(key, value string)
// Redirect sends an HTTP redirect. Returns an error if code is not 3xx.
Redirect(url string, code int) error
// NoContent sends a 204 No Content response.
NoContent() error
// Render writes data to the response using the given renderer.
Render(code int, r render.Renderer, data any, opts ...func(*render.Options)) error
// String sends a plain text response, formatted if args are provided.
String(code int, s string, args ...any) error
// JSON sends a JSON-encoded response.
JSON(code int, data any, opts ...func(*render.Options)) error
// XML sends an XML-encoded response.
XML(code int, data any, opts ...func(*render.Options)) error
// HTML renders a named template with the pre-loaded template renderer.
HTML(code int, name string, data any, opts ...func(*render.Options)) error
// CSV renders a 2D string slice as a CSV response.
CSV(code int, data [][]string, opts ...func(*render.Options)) error
// Blob sends raw binary data with the given content type via the render package.
Blob(code int, data []byte, opts ...func(*render.Options)) error
// File serves a file from the given path using http.ServeContent.
File(path string) error
// Attachment serves a file as a downloadable attachment with Content-Disposition.
Attachment(path string) error
// Inline serves a file inline in the browser with Content-Disposition.
Inline(path string) error
}
Ctx represents the context of an HTTP request/response cycle. It wraps http.Request and http.ResponseWriter and provides a unified API for handlers and middleware.
type ErrorHandler ¶
ErrorHandler handles errors returned by a Handler.
type FileUpload ¶ added in v0.12.1
type FileUpload struct {
File multipart.File
Header *multipart.FileHeader
MaxSize int64 // maximum allowed size in bytes; 0 disables the check
AllowedTypes []string // accepted MIME type prefixes; nil disables the check
AllowedExtensions []string // accepted extensions e.g. ".jpg"; nil disables the check
DetectFunc func([]byte) string // custom MIME detector; nil falls back to http.DetectContentType
}
FileUpload holds a multipart file and its metadata, and implements Validatable. Pass it to Ctx.Validate to enforce size, MIME type, and extension constraints.
Size is measured by reading the actual file body — not from Header.Size which is declared by the client and cannot be trusted. The file is seeked back to the start after measurement.
MIME type is detected from the first 512 bytes of the file content. By default http.DetectContentType is used (W3C MIME sniffing), which covers common formats but not all — SVG for instance is detected as text/xml. Provide a custom DetectFunc to use a more complete detection library.
AllowedExtensions is checked against the filename declared by the client. It is spoofable on its own — always combine with AllowedTypes for reliable validation.
func NewDocumentUpload ¶ added in v0.12.1
func NewDocumentUpload(file multipart.File, header *multipart.FileHeader, maxSize int64) *FileUpload
NewDocumentUpload creates a FileUpload preset for PDF documents. maxSize is the maximum allowed file size in bytes.
func NewFileUploadValidator ¶ added in v0.12.1
func NewFileUploadValidator(file multipart.File, header *multipart.FileHeader) *FileUpload
NewFileUploadValidator creates a bare FileUpload from the result of Ctx.FormFile. No constraints are set — configure MaxSize, AllowedTypes, AllowedExtensions, and DetectFunc directly on the returned value, or use a preset constructor.
func NewImageUpload ¶ added in v0.12.1
func NewImageUpload(file multipart.File, header *multipart.FileHeader, maxSize int64) *FileUpload
NewImageUpload creates a FileUpload preset for common web image formats (JPEG, PNG, GIF, WebP). maxSize is the maximum allowed file size in bytes.
func (*FileUpload) AddExtension ¶ added in v0.12.1
func (fu *FileUpload) AddExtension(exts ...string) *FileUpload
AddExtension appends one or more file extensions to the allowed extensions list. Extensions should include the leading dot (e.g. ".svg"). Returns the FileUpload to allow method chaining.
func (*FileUpload) AddType ¶ added in v0.12.1
func (fu *FileUpload) AddType(t ...string) *FileUpload
AddType appends one or more MIME type prefixes to the allowed types list. Returns the FileUpload to allow method chaining.
func (*FileUpload) Validate ¶ added in v0.12.1
func (fu *FileUpload) Validate() error
Validate checks the file against the configured constraints in order: actual size, MIME type, and file extension. It implements Validatable and is called automatically by Ctx.Validate.
type Handler ¶
Handler is the core interface for handling an HTTP request within a shinobi context.
func AdaptHTTP ¶
AdaptHTTP wraps a stdlib http.Handler as a shinobi Handler. Use it to mount external handlers (file servers, third-party routers) via Mount.
func FileServer ¶
FileServer returns a Handler that serves static files from the given directory. Designed to be used with Mount.
Example:
r.Mount("/assets", shinobi.FileServer("./public"))
func FileServerFS ¶
FileServerFS returns a Handler that serves static files from the given fs.FS. Useful with Go's embed package.
Example:
//go:embed public
var public embed.FS
r.Mount("/assets", shinobi.FileServerFS(public))
type HandlerFunc ¶
HandlerFunc is a function adapter that implements Handler.
func (HandlerFunc) Handle ¶
func (f HandlerFunc) Handle(c Ctx) error
Handle calls f(c) and returns its error.
type Middleware ¶
Middleware wraps a Handler to extend or intercept request processing.
type Option ¶
type Option func(*Config)
Option defines a function type for configuring the Config.
func WithBinder ¶ added in v0.3.0
WithBinder sets a custom Binder used to decode request bodies in Ctx.Bind.
func WithDebug ¶ added in v0.11.0
WithDebug enables or disables debug mode injected into each Ctx. In debug mode, error responses include the original error message.
func WithErrorHandler ¶
func WithErrorHandler(h ErrorHandler) Option
WithErrorHandler sets a custom handler for errors returned by route handlers.
func WithLogger ¶ added in v0.11.0
WithLogger sets the logger injected into each Ctx. Ignored if l is nil. Defaults to slog.Default().
func WithNotFound ¶
func WithNotFound(h HandlerFunc) Option
WithNotFound sets a custom handler for 404 Not Found errors during initialization.
func WithPrefix ¶
WithPrefix sets an initial global prefix for all routes.
func WithRenderer ¶ added in v0.3.0
WithRenderer sets the template renderer injected into each Ctx.
func WithValidator ¶ added in v0.4.0
WithValidator sets the validator injected into each Ctx.
type Response ¶
type Response struct {
http.ResponseWriter
// contains filtered or unexported fields
}
Response wraps http.ResponseWriter to capture the HTTP status code and guard against writing headers more than once.
func NewResponse ¶
func NewResponse(w http.ResponseWriter) *Response
NewResponse returns a Response with a default 200 OK status.
func (*Response) SetResponseWriter ¶ added in v0.5.0
func (r *Response) SetResponseWriter(fn func(http.ResponseWriter) http.ResponseWriter)
SetResponseWriter replaces the underlying ResponseWriter using a wrapping function. The function receives the current writer, ensuring the chain is never broken.
func (*Response) Unwrap ¶
func (r *Response) Unwrap() http.ResponseWriter
Unwrap returns the underlying http.ResponseWriter.
func (*Response) Write ¶
Write sends the response body, writing a 200 OK header first if not yet sent.
func (*Response) WriteHeader ¶
WriteHeader sends the HTTP status code once, ignoring subsequent calls.
func (*Response) WriteString ¶
WriteString writes a string to the response body.
type Route ¶
type Route interface {
Connect(h HandlerFunc)
Delete(h HandlerFunc)
Get(h HandlerFunc)
Head(h HandlerFunc)
Options(h HandlerFunc)
Patch(h HandlerFunc)
Post(h HandlerFunc)
Put(h HandlerFunc)
Trace(h HandlerFunc)
}
Route defines multi-method registration on a single pattern.
type RouteInfo ¶
type RouteInfo struct {
Method string // HTTP method (e.g. "GET", "POST")
Pattern string // Full resolved path (e.g. "/api/v1/users/{id}")
}
RouteInfo holds the HTTP method and fully resolved pattern of a registered route. It is returned by Router.Routes() for introspection and debugging purposes.
type Router ¶
type Router interface {
http.Handler
// Handle registers a new route with a handler for the given pattern.
Handle(pattern string, h Handler)
// HandleFunc registers a new route with a handler function.
HandleFunc(pattern string, h HandlerFunc)
// Method registers a new route with a specific HTTP method and handler.
Method(method, pattern string, h Handler)
// MethodFunc registers a new route with a specific HTTP method and handler function.
MethodFunc(method, pattern string, h HandlerFunc)
// HTTP Verb shortcuts.
Connect(pattern string, h HandlerFunc)
Delete(pattern string, h HandlerFunc)
Get(pattern string, h HandlerFunc)
Head(pattern string, h HandlerFunc)
Options(pattern string, h HandlerFunc)
Patch(pattern string, h HandlerFunc)
Post(pattern string, h HandlerFunc)
Put(pattern string, h HandlerFunc)
Trace(pattern string, h HandlerFunc)
// Group creates a new sub-router with a prefix.
// All routes registered within the provided function will inherit this prefix.
Group(prefix string, fn func(Router))
// Mount attaches a shinobi Handler at the given prefix.
// The mounted handler receives requests with the prefix stripped from the path.
// Use AdaptHTTP to mount stdlib http.Handler implementations.
Mount(prefix string, h Handler)
// Use appends one or more middlewares to the router's global middleware stack.
Use(...Middleware)
Route(pattern string, fn func(Route))
// Routes returns all registered routes.
Routes() []RouteInfo
// With returns a new Router instance that includes the provided middlewares
// in addition to the existing ones. Perfect for method chaining.
With(middlewares ...Middleware) Router
// NotFound registers a custom handler for 404 Not Found errors.
NotFound(h HandlerFunc)
}
Router defines the interface for a layered HTTP router.
type StatusError ¶ added in v0.5.0
StatusError represents an HTTP error with a status code and message.
func HTTPError ¶ added in v0.5.0
func HTTPError(code int, message ...any) *StatusError
HTTPError creates a new StatusError with the given HTTP status code and optional message.
func (*StatusError) Error ¶ added in v0.5.0
func (e *StatusError) Error() string
func (*StatusError) Unwrap ¶ added in v0.5.0
func (e *StatusError) Unwrap() error
Unwrap returns the internal cause, enabling errors.Is and errors.As traversal.
func (*StatusError) WithInternal ¶ added in v0.5.0
func (e *StatusError) WithInternal(err error) *StatusError
WithInternal wraps an internal error for logging without exposing it to the client.
type Validatable ¶ added in v0.12.1
type Validatable interface {
Validate() error
}
Validatable may be implemented by any value that knows how to validate itself. If a value passed to Ctx.Validate implements this interface, its Validate method is called directly, bypassing the globally configured Validator. This is useful for types that carry their own validation logic (e.g. FileUpload) without depending on the application-level validator.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
_example
|
|
|
basic
command
|
|
|
bind
command
|
|
|
errors
command
|
|
|
middleware
command
|
|
|
profiling
command
Profiling example — exposes pprof endpoints behind BasicAuth.
|
Profiling example — exposes pprof endpoints behind BasicAuth. |
|
renderer
command
|
|
|
routing
command
|
|
|
security
command
Security example — demonstrates BasicAuth, SecureHeaders, CORS and BodyLimit.
|
Security example — demonstrates BasicAuth, SecureHeaders, CORS and BodyLimit. |
|
static
command
|
|
|
upload
command
|
|
|
validate
command
|
|
|
Package middleware provides built-in HTTP middlewares for the Shinobi framework.
|
Package middleware provides built-in HTTP middlewares for the Shinobi framework. |
|
Package websocket provides an interface for integrating any WebSocket library with Shinobi.
|
Package websocket provides an interface for integrating any WebSocket library with Shinobi. |