Documentation
ΒΆ
Overview ΒΆ
Package webfram provides a production-ready, lightweight Go web framework built on net/http.
WebFram offers enterprise-grade features including automatic template caching with layouts, comprehensive data binding with validation, internationalization (i18n), Server-Sent Events (SSE), JSON Patch support, JSONP, OpenAPI 3.2.0 documentation generation, built-in Prometheus telemetry, and flexible middleware supportβall while maintaining minimal dependencies and maximum performance.
Key Features:
- Smart Templates: Automatic caching with layout inheritance and hot-reload in development
- Data Binding: Type-safe Form, JSON, and XML binding with 20+ validation rules
- i18n Support: First-class internationalization using golang.org/x/text
- Telemetry: Built-in Prometheus metrics with optional separate server
- OpenAPI 3.2.0: Automatic API documentation generation from code
- SSE Support: Production-ready Server-Sent Events for real-time updates
- JSON Patch: Full RFC 6902 support for partial resource updates
- JSONP: Secure cross-origin requests with automatic callback validation
- Flexible Middleware: Support for both custom and standard HTTP middleware
Example usage:
package main
import (
app "github.com/bondowe/webfram"
)
func main() {
// Configure the application
app.Configure(&app.Config{
Telemetry: &app.Telemetry{Enabled: true},
})
// Create mux and register routes
mux := app.NewServeMux()
mux.HandleFunc("GET /hello", func(w app.ResponseWriter, r *app.Request) {
w.JSON(r.Context(), map[string]string{"message": "Hello, World!"})
})
// Start server with graceful shutdown
app.ListenAndServe(":8080", mux, nil)
}
For complete documentation and examples, visit: https://github.com/bondowe/webfram
Index ΒΆ
- Variables
- func Configure(cfg *Config)
- func GetI18nPrinter(tag language.Tag) *message.Printer
- func I18nMiddleware(_ fs.FS) func(Handler) Handler
- func ListenAndServe(addr string, mux *ServeMux, cfg *ServerConfig)
- func NewAPIKeySecurityScheme(options *APIKeySecuritySchemeOptions) *apiKeySecurityScheme
- func NewAuthorizationCodeOAuthFlow(options *AuthorizationCodeOAuthFlowOptions) *authorizationCodeOAuthFlow
- func NewClientCredentialsOAuthFlow(options *ClientCredentialsOAuthFlowOptions) *clientCredentialsOAuthFlow
- func NewDeviceAuthorizationOAuthFlow(options *DeviceAuthorizationOAuthFlowOptions) *deviceAuthorizationOAuthFlow
- func NewHTTPBasicSecurityScheme(options *HTTPBasicSecuritySchemeOptions) *httpBasicSecurityScheme
- func NewHTTPBearerSecurityScheme(options *HTTPBearerSecuritySchemeOptions) *httpBearerSecurityScheme
- func NewHTTPDigestSecurityScheme(options *HTTPDigestSecuritySchemeOptions) *httpDigestSecurityScheme
- func NewImplicitOAuthFlow(options *ImplicitOAuthFlowOptions) *implicitOAuthFlow
- func NewMutualTLSSecurityScheme(options *MutualTLSSecuritySchemeOptions) *mutualTLSSecurityScheme
- func NewOAuth2SecurityScheme(options *OAuth2SecuritySchemeOptions) *oAuth2SecurityScheme
- func NewOpenIdConnectSecurityScheme(options *OpenIdConnectSecuritySchemeOptions) *openIdConnectSecurityScheme
- func SetLanguageCookie(w ResponseWriter, lang string, maxAge int)
- func SetOpenAPIPathInfo(path string, info *PathInfo)
- func Use[H AppMiddleware | StandardMiddleware](mw H)
- type APIKeySecuritySchemeOptions
- type AppMiddleware
- type Assets
- type AuthorizationCodeOAuthFlowOptions
- type ClientCredentialsOAuthFlowOptions
- type Components
- type Config
- type Contact
- type DeviceAuthorizationOAuthFlowOptions
- type Example
- type ExternalDocs
- type HTTPBasicSecuritySchemeOptions
- type HTTPBearerSecuritySchemeOptions
- type HTTPDigestSecuritySchemeOptions
- type Handler
- type HandlerConfig
- type HandlerFunc
- type Header
- type I18nMessages
- type ImplicitOAuthFlowOptions
- type Info
- type License
- type Link
- type Middleware
- type MutualTLSSecuritySchemeOptions
- type OAuth2SecuritySchemeOptions
- type OAuthFlow
- type OpenAPI
- type OpenAPIConfig
- type OpenIdConnectSecuritySchemeOptions
- type OperationConfig
- type Parameter
- type PathInfo
- type Request
- type RequestBody
- type Response
- type ResponseWriter
- func (w *ResponseWriter) Bytes(bs []byte, contentType string) error
- func (w *ResponseWriter) Error(statusCode int, message string)
- func (w *ResponseWriter) Flush()
- func (w *ResponseWriter) HTML(ctx context.Context, path string, data any) error
- func (w *ResponseWriter) HTMLString(s string, data any) error
- func (w *ResponseWriter) Header() http.Header
- func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (w *ResponseWriter) JSON(ctx context.Context, v any) error
- func (w *ResponseWriter) JSONSeq(_ context.Context, items any) error
- func (w *ResponseWriter) NoContent()
- func (w *ResponseWriter) Push(target string, opts *http.PushOptions) error
- func (w *ResponseWriter) ReadFrom(src io.Reader) (int64, error)
- func (w *ResponseWriter) Redirect(req *Request, urlStr string, code int)
- func (w *ResponseWriter) ServeFile(req *Request, path string, options *ServeFileOptions)
- func (w *ResponseWriter) ServeFileFS(req *Request, fsys fs.FS, path string, options *ServeFileOptions)
- func (w *ResponseWriter) StatusCode() (int, bool)
- func (w *ResponseWriter) Text(ctx context.Context, path string, data any) error
- func (w *ResponseWriter) TextString(s string, data any) error
- func (w *ResponseWriter) Unwrap() http.ResponseWriter
- func (w *ResponseWriter) Write(b []byte) (int, error)
- func (w *ResponseWriter) WriteHeader(statusCode int)
- func (w *ResponseWriter) XML(v any) error
- func (w *ResponseWriter) XMLArray(items any, rootName string) error
- func (w *ResponseWriter) YAML(v any) error
- type SSEDisconnectFunc
- type SSEErrorFunc
- type SSEHandler
- type SSEPayload
- type SSEPayloadFunc
- type SecurityScheme
- type ServeFileOptions
- type ServeMux
- func (m *ServeMux) Handle(pattern string, handler Handler, mdwrs ...interface{}) *HandlerConfig
- func (m *ServeMux) HandleFunc(pattern string, handler HandlerFunc, mdwrs ...interface{}) *HandlerConfig
- func (m *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (m *ServeMux) Use(mw interface{})
- func (m *ServeMux) UseSecurity(cfg security.Config)
- type Server
- type ServerConfig
- type ServerVariable
- type StandardMiddleware
- type Tag
- type Telemetry
- type Templates
- type TypeInfo
- type ValidationError
- type ValidationErrors
- func BindCookie[T any](r *Request) (T, *ValidationErrors, error)
- func BindForm[T any](r *Request) (T, *ValidationErrors, error)
- func BindHeader[T any](r *Request) (T, *ValidationErrors, error)
- func BindJSON[T any](r *Request, validate bool) (T, *ValidationErrors, error)
- func BindPath[T any](r *Request) (T, *ValidationErrors)
- func BindQuery[T any](r *Request) (T, *ValidationErrors, error)
- func BindXML[T any](r *Request, validate bool) (T, *ValidationErrors, error)
Constants ΒΆ
This section is empty.
Variables ΒΆ
var ( // ErrMethodNotAllowed is returned when an HTTP method is not allowed for a route. ErrMethodNotAllowed = errors.New("method not allowed") )
Functions ΒΆ
func Configure ΒΆ
func Configure(cfg *Config)
Configure initializes the webfram application with the provided configuration. It sets up templates, i18n messages, OpenAPI documentation, and JSONP callback handling. This function must be called only once before using the framework. Calling it multiple times will panic. Pass nil to use default configuration values.
func GetI18nPrinter ΒΆ
GetI18nPrinter creates a message printer for the specified language tag. The printer can be used to format messages according to the configured i18n catalogs. Returns a printer that will use the best available language match from configured catalogs.
func I18nMiddleware ΒΆ
I18nMiddleware creates middleware that adds internationalization support to handlers. It parses the Accept-Language header and language cookie to determine the user's preferred language, then injects an i18n printer into the request context for message translation.
func ListenAndServe ΒΆ
func ListenAndServe(addr string, mux *ServeMux, cfg *ServerConfig)
ListenAndServe starts an HTTP server on the specified address with the given multiplexer. It automatically sets up OpenAPI endpoint if configured, applies server configuration, and handles graceful shutdown on SIGINT or SIGTERM signals. If telemetry is configured with a separate address, starts an additional server for metrics. Blocks until the server is shut down. Panics if server startup or shutdown fails.
func NewAPIKeySecurityScheme ΒΆ added in v0.2.1
func NewAPIKeySecurityScheme(options *APIKeySecuritySchemeOptions) *apiKeySecurityScheme
func NewAuthorizationCodeOAuthFlow ΒΆ added in v0.2.1
func NewAuthorizationCodeOAuthFlow(options *AuthorizationCodeOAuthFlowOptions) *authorizationCodeOAuthFlow
func NewClientCredentialsOAuthFlow ΒΆ added in v0.2.1
func NewClientCredentialsOAuthFlow(options *ClientCredentialsOAuthFlowOptions) *clientCredentialsOAuthFlow
func NewDeviceAuthorizationOAuthFlow ΒΆ added in v0.2.1
func NewDeviceAuthorizationOAuthFlow(options *DeviceAuthorizationOAuthFlowOptions) *deviceAuthorizationOAuthFlow
func NewHTTPBasicSecurityScheme ΒΆ added in v0.2.1
func NewHTTPBasicSecurityScheme(options *HTTPBasicSecuritySchemeOptions) *httpBasicSecurityScheme
func NewHTTPBearerSecurityScheme ΒΆ added in v0.2.1
func NewHTTPBearerSecurityScheme(options *HTTPBearerSecuritySchemeOptions) *httpBearerSecurityScheme
func NewHTTPDigestSecurityScheme ΒΆ added in v0.2.1
func NewHTTPDigestSecurityScheme(options *HTTPDigestSecuritySchemeOptions) *httpDigestSecurityScheme
func NewImplicitOAuthFlow ΒΆ added in v0.2.1
func NewImplicitOAuthFlow(options *ImplicitOAuthFlowOptions) *implicitOAuthFlow
func NewMutualTLSSecurityScheme ΒΆ added in v0.2.1
func NewMutualTLSSecurityScheme(options *MutualTLSSecuritySchemeOptions) *mutualTLSSecurityScheme
func NewOAuth2SecurityScheme ΒΆ added in v0.2.1
func NewOAuth2SecurityScheme(options *OAuth2SecuritySchemeOptions) *oAuth2SecurityScheme
func NewOpenIdConnectSecurityScheme ΒΆ added in v0.2.1
func NewOpenIdConnectSecurityScheme(options *OpenIdConnectSecuritySchemeOptions) *openIdConnectSecurityScheme
func SetLanguageCookie ΒΆ
func SetLanguageCookie(w ResponseWriter, lang string, maxAge int)
SetLanguageCookie sets a language preference cookie for the user. The maxAge parameter controls cookie lifetime in seconds (0 = delete cookie, -1 = session cookie).
func SetOpenAPIPathInfo ΒΆ
SetOpenAPIPathInfo adds or updates path-level information in the OpenAPI documentation. This should be called before registering handlers to set common parameters and servers for a path. Only works if OpenAPI endpoint is enabled in configuration.
func Use ΒΆ
func Use[H AppMiddleware | StandardMiddleware](mw H)
Use registers a global middleware that will be applied to all handlers. Accepts either AppMiddleware (func(Handler) Handler) or StandardMiddleware (func(http.Handler) http.Handler). Middlewares are executed in the order they are registered.
Types ΒΆ
type APIKeySecuritySchemeOptions ΒΆ added in v0.2.1
type APIKeySecuritySchemeOptions struct {
// Name of the header, query, or cookie parameter to be used.
Name string
// Description provides a description of the API Key security scheme.
Description string
// In specifies the location of the API key.
In string
// Extensions are custom extensions for the API Key security scheme.
Extensions map[string]interface{}
//nolint:gocritic // this is a field comment, not a deprecation notice
// Deprecated indicates whether the API Key security scheme is deprecated.
Deprecated bool
}
type AppMiddleware ΒΆ
type AppMiddleware = Middleware[Handler]
AppMiddleware is a middleware for custom Handler types.
type Assets ΒΆ
type Assets struct {
// FS is the file system containing the static assets.
FS fs.FS
// Templates configures template settings for the framework.
Templates *Templates
// I18nMessages configures internationalization message settings.
I18nMessages *I18nMessages
}
Assets configures static assets and their locations.
type AuthorizationCodeOAuthFlowOptions ΒΆ added in v0.2.1
type AuthorizationCodeOAuthFlowOptions struct {
// AuthorizationURL is the URL to obtain authorization.
AuthorizationURL string
// TokenURL is the URL to obtain tokens.
TokenURL string
// Scopes is a map of scope names to descriptions.
Scopes map[string]string
// RefreshURL is the URL to obtain authorization.
RefreshURL string
// Extensions are custom extensions for the Authorization Code OAuth2 flow.
Extensions map[string]interface{}
}
type ClientCredentialsOAuthFlowOptions ΒΆ added in v0.2.1
type ClientCredentialsOAuthFlowOptions struct {
// TokenURL is the URL to obtain tokens.
TokenURL string
// Scopes is a map of scope names to descriptions.
Scopes map[string]string
// RefreshURL is the URL to obtain authorization.
RefreshURL string
// Extensions are custom extensions for the Client Credentials OAuth2 flow.
Extensions map[string]interface{}
}
type Components ΒΆ added in v0.2.1
type Components struct {
// SecuritySchemes is a map of security scheme names to definitions.
SecuritySchemes map[string]SecurityScheme
}
type Config ΒΆ
type Config struct {
// Telemetry configures telemetry settings for the framework.
Telemetry *Telemetry
// Security configures security settings for the framework.
Security *security.Config
// I18nMessages configures internationalization message settings.
I18nMessages *I18nMessages
// Assets configures static assets and their locations.
Assets *Assets
// OpenAPI configures OpenAPI documentation settings.
OpenAPI *OpenAPI
// JSONPCallbackParamName is the name of the query parameter for JSONP callbacks.
JSONPCallbackParamName string
}
Config represents the framework configuration.
type Contact ΒΆ added in v0.1.31
type Contact struct {
// Name is the name of the contact.
Name string
// URL is the URL of the contact.
URL string
// Email is the email address of the contact.
Email string
}
Contact represents an OpenAPI contact definition.
type DeviceAuthorizationOAuthFlowOptions ΒΆ added in v0.2.1
type DeviceAuthorizationOAuthFlowOptions struct {
// DeviceAuthorizationURL is the URL to obtain device codes.
DeviceAuthorizationURL string
// TokenURL is the URL to obtain tokens.
TokenURL string
// Scopes is a map of scope names to descriptions.
Scopes map[string]string
// RefreshURL is the URL to obtain authorization.
RefreshURL string
// Extensions are custom extensions for the Device Authorization OAuth2 flow.
Extensions map[string]interface{}
}
type Example ΒΆ
type Example struct {
DataValue any
DefaultValue any
SerializedValue any
Server *Server
Summary string
Description string
ExternalValue string
}
Example represents an OpenAPI example value.
type ExternalDocs ΒΆ added in v0.1.31
type ExternalDocs struct {
// Description provides a description of the external documentation.
Description string
// URL is the URL of the external documentation.
URL string
}
ExternalDocs represents OpenAPI external documentation.
type HTTPBasicSecuritySchemeOptions ΒΆ added in v0.2.1
type HTTPBasicSecuritySchemeOptions struct {
// Description provides a description of the HTTP Basic security scheme.
Description string
// Extensions are custom extensions for the HTTP Basic security scheme.
Extensions map[string]interface{}
//nolint:gocritic // this is a field comment, not a deprecation notice
// Deprecated indicates whether the HTTP Basic security scheme is deprecated.
Deprecated bool
}
type HTTPBearerSecuritySchemeOptions ΒΆ added in v0.2.1
type HTTPBearerSecuritySchemeOptions struct {
// Description provides a description of the HTTP Bearer security scheme.
Description string
// BearerFormat is an optional hint to the client to identify how the bearer token is formatted.
// e.g., "JWT"
BearerFormat string
// Extensions are custom extensions for the HTTP Bearer security scheme.
Extensions map[string]interface{}
//nolint:gocritic // this is a field comment, not a deprecation notice
// Deprecated indicates whether the HTTP Bearer security scheme is deprecated.
Deprecated bool
}
type HTTPDigestSecuritySchemeOptions ΒΆ added in v0.2.1
type HTTPDigestSecuritySchemeOptions struct {
// Description provides a description of the HTTP Digest security scheme.
Description string
// Extensions are custom extensions for the HTTP Digest security scheme.
Extensions map[string]interface{}
//nolint:gocritic // this is a field comment, not a deprecation notice
// Deprecated indicates whether the HTTP Digest security scheme is deprecated.
Deprecated bool
}
type Handler ΒΆ
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
Handler responds to HTTP requests.
type HandlerConfig ΒΆ
type HandlerConfig struct {
OperationConfig *OperationConfig
// contains filtered or unexported fields
}
HandlerConfig provides configuration for registered handlers, particularly for OpenAPI documentation.
func (*HandlerConfig) WithOperationConfig ΒΆ added in v0.2.2
func (c *HandlerConfig) WithOperationConfig(operationConfig *OperationConfig)
WithOperationConfig attaches OpenAPI configuration to a handler. This generates OpenAPI documentation for the endpoint with request/response schemas, parameters, etc. Only works if OpenAPI endpoint is enabled in configuration.
type HandlerFunc ΒΆ
type HandlerFunc func(ResponseWriter, *Request)
HandlerFunc is a function that serves HTTP requests.
func (HandlerFunc) ServeHTTP ΒΆ
func (hf HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)
ServeHTTP implements the Handler interface, allowing HandlerFunc to be used as a Handler.
type Header ΒΆ
type Header struct {
Example any
TypeHint any
Examples map[string]Example
Explode *bool
Content map[string]TypeInfo
Description string
Style string
Required bool
Deprecated bool
}
Header describes an OpenAPI response header.
type I18nMessages ΒΆ
type I18nMessages struct {
// Dir is the directory where i18n message files are located.
Dir string
// SupportedLanguages is a list of supported language tags.
SupportedLanguages []string
}
I18nMessages configures internationalization message settings.
type ImplicitOAuthFlowOptions ΒΆ added in v0.2.1
type ImplicitOAuthFlowOptions struct {
// AuthorizationURL is the URL to obtain authorization.
AuthorizationURL string
// Scopes is a map of scope names to descriptions.
Scopes map[string]string
// RefreshURL is the URL to obtain authorization.
RefreshURL string
// Extensions are custom extensions for the Implicit OAuth2 flow.
Extensions map[string]interface{}
}
type Info ΒΆ added in v0.1.31
type Info struct {
// Title of the API.
Title string
// Summary provides a brief summary of the API.
Summary string
// Description provides a detailed description of the API.
Description string
// TermsOfService is the URL to the terms of service for the API.
TermsOfService string
// Contact information for the API.
Contact *Contact
// License information for the API.
License *License
// Version of the API.
Version string
}
Info represents OpenAPI information.
type License ΒΆ added in v0.1.31
type License struct {
// Name of the license.
Name string
// Identifier is the SPDX identifier of the license.
Identifier string
// URL is the URL of the license.
URL string
}
License represents an OpenAPI license definition.
type Link ΒΆ
type Link struct {
OperationRef string
OperationID string
Parameters map[string]any
RequestBody any
Description string
}
Link represents an OpenAPI link.
type Middleware ΒΆ
type Middleware[H any] = func(H) H
Middleware is a generic middleware function that wraps handlers.
type MutualTLSSecuritySchemeOptions ΒΆ added in v0.2.1
type MutualTLSSecuritySchemeOptions struct {
// Description provides a description of the Mutual TLS security scheme.
Description string
// Extensions are custom extensions for the Mutual TLS security scheme.
Extensions map[string]interface{}
//nolint:gocritic // this is a field comment, not a deprecation notice
// Deprecated indicates whether the Mutual TLS security scheme is deprecated.
Deprecated bool
}
type OAuth2SecuritySchemeOptions ΒΆ added in v0.2.1
type OAuth2SecuritySchemeOptions struct {
// Flows is a map of OAuth2 flows.
Flows []OAuthFlow
// Description provides a description of the OAuth2 security scheme.
Description string
// Extensions are custom extensions for the OAuth2 security scheme.
Extensions map[string]interface{}
//nolint:gocritic // this is a field comment, not a deprecation notice
// Deprecated indicates whether the OAuth2 security scheme is deprecated.
Deprecated bool
}
type OAuthFlow ΒΆ added in v0.2.1
type OAuthFlow interface {
// contains filtered or unexported methods
}
type OpenAPI ΒΆ
type OpenAPI struct {
// Config is the OpenAPI configuration.
Config *OpenAPIConfig
// URLPath is the HTTP path for the OpenAPI JSON endpoint (e.g., "GET /openapi.json").
URLPath string
// Enabled indicates whether OpenAPI documentation is enabled.
Enabled bool
// contains filtered or unexported fields
}
OpenAPI configures OpenAPI documentation settings.
type OpenAPIConfig ΒΆ added in v0.1.31
type OpenAPIConfig struct {
Info *Info
// Servers is a list of OpenAPI server definitions.
Servers []Server
// Tags is a list of OpenAPI tags.
Tags []Tag
// Security is a list of security requirements for the OpenAPI document.
Security []map[string][]string
// ExternalDocs provides external documentation for the OpenAPI document.
ExternalDocs *ExternalDocs
// Components holds various schema components.
Components *Components
}
OpenAPIConfig represents the OpenAPI configuration.
type OpenIdConnectSecuritySchemeOptions ΒΆ added in v0.2.1
type OpenIdConnectSecuritySchemeOptions struct {
//nolint:revive,staticcheck // OpenId naming follows OpenAPI specification convention
// OpenIdConnectURL is the OpenID Connect URL to discover OAuth2 configuration values.
OpenIdConnectURL string
// Description provides a description of the OpenID Connect security scheme.
Description string
// Extensions are custom extensions for the OpenID Connect security scheme.
Extensions map[string]interface{}
//nolint:gocritic // this is a field comment, not a deprecation notice
// Deprecated indicates whether the OpenID Connect security scheme is deprecated.
Deprecated bool
}
type OperationConfig ΒΆ added in v0.2.2
type OperationConfig struct {
Method string
Summary string
Description string
OperationID string
Tags []string
Parameters []Parameter
Security []map[string][]string
RequestBody *RequestBody
Responses map[string]Response
Servers []Server
}
OperationConfig configures OpenAPI documentation for a route.
type Parameter ΒΆ
type Parameter struct {
Example any
Default any
Const any
TypeHint any
Explode *bool
Examples map[string]Example
Content map[string]any
Style string
Format string
Name string
Description string
In string
Pattern string
Enum []any
Minimum float64
MinItems int
MinLength int
MaxLength int
ExclusiveMaximum float64
ExclusiveMinimum float64
Maximum float64
MaxItems int
MultipleOf float64
AllowReserved bool
Nullable bool
UniqueItems bool
Deprecated bool
Required bool
}
Parameter describes an operation parameter in OpenAPI.
type PathInfo ΒΆ
type PathInfo struct {
Summary string
Description string
// AdditionalOperations map[string]*Operation
Servers []Server
Parameters []Parameter
}
PathInfo contains path-level OpenAPI documentation.
type RequestBody ΒΆ
type RequestBody struct {
Content map[string]TypeInfo
Example *Example
Examples map[string]Example
Description string
Required bool
}
RequestBody describes an OpenAPI request body.
type Response ΒΆ
type Response struct {
Headers map[string]Header
Content map[string]TypeInfo
Links map[string]Link
Summary string
Description string
}
Response describes an OpenAPI response.
type ResponseWriter ΒΆ
type ResponseWriter struct {
http.ResponseWriter
// contains filtered or unexported fields
}
ResponseWriter wraps http.ResponseWriter with additional functionality.
func (*ResponseWriter) Bytes ΒΆ
func (w *ResponseWriter) Bytes(bs []byte, contentType string) error
Bytes writes raw byte data to the response with the specified content type. If contentType is empty, automatically detects the content type using http.DetectContentType. Returns an error if writing fails.
func (*ResponseWriter) Error ΒΆ
func (w *ResponseWriter) Error(statusCode int, message string)
Error sends an error response with the specified HTTP status code and message. Uses http.Error to format the error message as plain text.
func (*ResponseWriter) Flush ΒΆ
func (w *ResponseWriter) Flush()
Flush sends any buffered data to the client. If the underlying writer does not support flushing, this is a no-op.
func (*ResponseWriter) HTML ΒΆ
HTML renders a cached HTML template with the provided data. The path is relative to the template directory and does not include the extension. Automatically adds i18n support if a message printer is in the context. Sets Content-Type header to "text/html". The ctx parameter is used for i18n support; pass request context or context.Background(). Returns an error if templates are not configured, template is not found, or execution fails.
func (*ResponseWriter) HTMLString ΒΆ
func (w *ResponseWriter) HTMLString(s string, data any) error
HTMLString parses an HTML template string and executes it with the provided data. Sets Content-Type header to "text/html". Returns an error if template parsing or execution fails.
func (*ResponseWriter) Header ΒΆ
func (w *ResponseWriter) Header() http.Header
Header returns the response header map for inspection and modification.
func (*ResponseWriter) Hijack ΒΆ
func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack takes over the connection from the HTTP server. Returns the connection, buffered reader/writer, and any error. After hijacking, the HTTP server will not do anything else with the connection.
func (*ResponseWriter) JSON ΒΆ
func (w *ResponseWriter) JSON(ctx context.Context, v any) error
JSON marshals the provided data as JSON and writes it to the response. If a JSONP callback is present in the context, wraps the response in the callback function. Sets Content-Type header to "application/json" or "application/javascript" for JSONP. The ctx parameter is used to check for JSONP callback; pass request context or context.Background(). Returns an error if marshaling or writing fails.
func (*ResponseWriter) JSONSeq ΒΆ added in v0.2.3
func (w *ResponseWriter) JSONSeq(_ context.Context, items any) error
JSONSeq streams a sequence of JSON objects as per RFC 7464. Each JSON object is prefixed with the ASCII Record Separator character. Sets Content-Type header to "application/json-seq". Returns an error if items is not a slice, marshaling fails, or writing fails.
func (*ResponseWriter) NoContent ΒΆ
func (w *ResponseWriter) NoContent()
NoContent sends a 204 No Content response with no body.
func (*ResponseWriter) Push ΒΆ
func (w *ResponseWriter) Push(target string, opts *http.PushOptions) error
Push initiates an HTTP/2 server push for the specified target. Returns an error if the underlying connection does not support HTTP/2 push.
func (*ResponseWriter) ReadFrom ΒΆ
func (w *ResponseWriter) ReadFrom(src io.Reader) (int64, error)
ReadFrom reads data from src until EOF or error and writes it to the response. Implements the io.ReaderFrom interface for efficient data transfer.
func (*ResponseWriter) Redirect ΒΆ
func (w *ResponseWriter) Redirect(req *Request, urlStr string, code int)
Redirect replies to the request with a redirect to urlStr. The code should be a 3xx status code (e.g., http.StatusFound, http.StatusMovedPermanently).
func (*ResponseWriter) ServeFile ΒΆ
func (w *ResponseWriter) ServeFile(req *Request, path string, options *ServeFileOptions)
ServeFile serves a file from the local filesystem at the given path. The options parameter allows setting Content-Disposition headers for inline or attachment serving. If options is nil, defaults to attachment serving with the original filename. Uses http.ServeFile to handle file serving. The req parameter is the original request.
func (*ResponseWriter) ServeFileFS ΒΆ added in v0.1.31
func (w *ResponseWriter) ServeFileFS(req *Request, fsys fs.FS, path string, options *ServeFileOptions)
ServeFileFS serves a file from the specified fs.FS at the given path. The options parameter allows setting Content-Disposition headers for inline or attachment serving. If options is nil, defaults to attachment serving with the original filename. Uses http.ServeFileFS to handle file serving. The req parameter is the original request.
func (*ResponseWriter) StatusCode ΒΆ
func (w *ResponseWriter) StatusCode() (int, bool)
StatusCode retrieves the HTTP response status code that was written. Returns the status code and true if it was set, or 0 and false if not set.
func (*ResponseWriter) Text ΒΆ
Text renders a cached text template with the provided data. The path is relative to the template directory and does not include the extension. Automatically adds i18n support if a message printer is in the context. Sets Content-Type header to "text/plain". The ctx parameter is used for i18n support; pass request context or context.Background(). Returns an error if templates are not configured, template is not found, or execution fails.
func (*ResponseWriter) TextString ΒΆ
func (w *ResponseWriter) TextString(s string, data any) error
TextString parses a plain text template string and executes it with the provided data. Sets Content-Type header to "text/plain". Returns an error if template parsing or execution fails.
func (*ResponseWriter) Unwrap ΒΆ
func (w *ResponseWriter) Unwrap() http.ResponseWriter
Unwrap returns the underlying http.ResponseWriter.
func (*ResponseWriter) Write ΒΆ
func (w *ResponseWriter) Write(b []byte) (int, error)
Write writes the data to the connection as part of an HTTP reply. Implements the io.Writer interface.
func (*ResponseWriter) WriteHeader ΒΆ
func (w *ResponseWriter) WriteHeader(statusCode int)
WriteHeader sends an HTTP response header with the provided status code.
func (*ResponseWriter) XML ΒΆ
func (w *ResponseWriter) XML(v any) error
XML marshals the provided data as XML and writes it to the response. Sets Content-Type header to "application/xml". Returns an error if marshaling or writing fails.
func (*ResponseWriter) XMLArray ΒΆ added in v0.2.4
func (w *ResponseWriter) XMLArray(items any, rootName string) error
XMLArray marshals a slice with a wrapping root element and writes it to the response. This is a convenience method for properly serializing arrays to valid XML. The rootName parameter specifies the name of the wrapping element. Each item in the slice will use its struct's XMLName or type name for its element. Sets Content-Type header to "application/xml". Returns an error if items is not a slice, marshaling fails, or writing fails.
Example:
type User struct {
XMLName xml.Name `xml:"user"`
Name string `xml:"name"`
}
users := []User{{Name: "Alice"}, {Name: "Bob"}}
w.XMLArray(users, "users")
// Produces: <users><user><name>Alice</name></user><user><name>Bob</name></user></users>
func (*ResponseWriter) YAML ΒΆ
func (w *ResponseWriter) YAML(v any) error
YAML marshals the provided data as YAML and writes it to the response. Sets Content-Type header to "text/x-yaml". Returns an error if marshaling or writing fails.
type SSEDisconnectFunc ΒΆ
type SSEDisconnectFunc func()
SSEDisconnectFunc is called when an SSE connection is closed.
type SSEHandler ΒΆ
type SSEHandler struct {
// contains filtered or unexported fields
}
SSEHandler is the handler returned by SSE function for server-sent events.
func SSE ΒΆ
func SSE( payloadFunc SSEPayloadFunc, disconnectFunc SSEDisconnectFunc, errorFunc SSEErrorFunc, interval time.Duration, headers map[string]string, ) *SSEHandler
SSE creates a Server-Sent Events handler that sends real-time updates to clients. The payloadFunc is called at the specified interval to generate SSE payloads. The disconnectFunc is called when the client disconnects (can be nil for no-op). The errorFunc is called when an error occurs during streaming (can be nil for no-op). The interval must be positive, and custom headers can be added to each response. Panics if payloadFunc is nil or interval is non-positive.
func (*SSEHandler) ServeHTTP ΒΆ
func (m *SSEHandler) ServeHTTP(w ResponseWriter, r *Request)
type SSEPayload ΒΆ
type SSEPayload struct {
// Data is the event data.
Data any `json:"data" validate:"required"`
// ID is the event ID.
ID string `json:"id,omitempty"`
// Event is the event type.
Event string `json:"event,omitempty"`
// Comments are optional comments for the event.
Comments []string `json:"comments,omitempty"`
// Retry is the reconnection time in case of connection loss.
Retry time.Duration `json:"retry,omitempty"`
}
SSEPayload represents a Server-Sent Events message payload.
type SSEPayloadFunc ΒΆ
type SSEPayloadFunc func() SSEPayload
SSEPayloadFunc is a function that generates SSE payloads.
type SecurityScheme ΒΆ added in v0.2.1
type SecurityScheme interface {
// contains filtered or unexported methods
}
type ServeFileOptions ΒΆ added in v0.1.29
type ServeFileOptions struct {
Inline bool // If true, serves the file inline; otherwise as an attachment
Filename string // Optional filename for Content-Disposition header
}
ServeFileOptions configures how files are served to clients.
type ServeMux ΒΆ
ServeMux is an HTTP request multiplexer with middleware support.
func NewServeMux ΒΆ
func NewServeMux() *ServeMux
NewServeMux creates a new HTTP request multiplexer with webfram enhancements. Automatically calls Configure(nil) if the application hasn't been configured yet. Returns a ServeMux that supports middleware, custom handlers, and OpenAPI documentation.
func (*ServeMux) Handle ΒΆ
func (m *ServeMux) Handle(pattern string, handler Handler, mdwrs ...interface{}) *HandlerConfig
Handle registers a handler for the given pattern. The pattern can include HTTP method prefix (e.g., "GET /users"). Optional per-handler middlewares can be provided and will be applied only to this handler. Returns a handlerConfig that can be used to attach OpenAPI documentation via WithAPIConfig.
func (*ServeMux) HandleFunc ΒΆ
func (m *ServeMux) HandleFunc(pattern string, handler HandlerFunc, mdwrs ...interface{}) *HandlerConfig
HandleFunc registers a handler function for the given pattern. Convenience method that wraps a HandlerFunc and calls Handle. Returns a handlerConfig that can be used to attach OpenAPI documentation via WithAPIConfig.
func (*ServeMux) ServeHTTP ΒΆ
func (m *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface. It wraps the request, applies middlewares, and handles JSONP callbacks if configured.
func (*ServeMux) Use ΒΆ
func (m *ServeMux) Use(mw interface{})
Use registers middleware to be applied to all handlers registered on this ServeMux. Accepts either AppMiddleware (func(Handler) Handler) or StandardMiddleware (func(http.Handler) http.Handler). Panics if an unsupported middleware type is provided.
func (*ServeMux) UseSecurity ΒΆ added in v0.3.1
UseSecurity sets the security configuration for the ServeMux. This configuration will be applied to all handlers registered on this ServeMux. This overrides any global security configuration set via `Configure(*Config)`.
type Server ΒΆ
type Server struct {
Variables map[string]ServerVariable
URL string
Name string
Description string
}
Server describes an OpenAPI server.
type ServerConfig ΒΆ
type ServerConfig struct {
ConnState func(net.Conn, http.ConnState)
TLSConfig *tls.Config
Protocols *http.Protocols
HTTP2 *http.HTTP2Config
ConnContext func(ctx context.Context, c net.Conn) context.Context
BaseContext func(net.Listener) context.Context
ErrorLog *slog.Logger
TLSNextProto map[string]func(*http.Server, *tls.Conn, http.Handler)
ReadHeaderTimeout time.Duration
MaxHeaderBytes int
IdleTimeout time.Duration
WriteTimeout time.Duration
ReadTimeout time.Duration
DisableGeneralOptionsHandler bool
}
ServerConfig configures HTTP server settings.
type ServerVariable ΒΆ
ServerVariable represents a variable in a server URL template.
type StandardMiddleware ΒΆ
type StandardMiddleware = Middleware[http.Handler]
StandardMiddleware is a middleware for standard http.Handler types.
type Tag ΒΆ added in v0.1.31
type Tag struct {
// Name is the name of the tag.
Name string
// Summary provides a brief summary of the tag.
Summary string
// Description provides a detailed description of the tag.
Description string
// ExternalDocs provides external documentation for the tag.
ExternalDocs *ExternalDocs
// Parent is the name of the parent tag, if any.
Parent string
// Kind represents the kind of the tag.
Kind string
}
Tag represents an OpenAPI tag definition.
type Telemetry ΒΆ
type Telemetry struct {
// UseDefaultRegistry indicates whether to use the default Prometheus registry.
UseDefaultRegistry bool
// Collectors are custom Prometheus collectors to register.
Collectors []prometheus.Collector
// URLPath is the HTTP path for the metrics endpoint (e.g., "GET /metrics").
URLPath string
// Addr is the optional address for a separate telemetry server (e.g., ":9090").
// If empty or equal to the main server address, telemetry runs on the main server.
Addr string
// Enabled indicates whether telemetry is enabled.
Enabled bool
// HandlerOpts are options for the Prometheus HTTP handler.
HandlerOpts promhttp.HandlerOpts
}
Telemetry configures telemetry settings for the framework.
type Templates ΒΆ
type Templates struct {
// Dir is the directory where template files are located.
Dir string
// LayoutBaseName is the base name of the layout template.
LayoutBaseName string
// HTMLTemplateExtension is the file extension for HTML templates.
HTMLTemplateExtension string
// TextTemplateExtension is the file extension for text templates.
TextTemplateExtension string
}
Templates configures template settings for the framework.
type TypeInfo ΒΆ
type TypeInfo struct {
// TypeHint provides a hint about the data type.
TypeHint any
// XMLRootName specifies the root element name for XML serialization.
// Only applicable when using XML content type.
XMLRootName string
Example any
Examples map[string]Example
}
TypeInfo provides type information for OpenAPI content types.
type ValidationError ΒΆ
type ValidationError struct {
XMLName xml.Name `json:"-" xml:"validationError" form:"-"`
Field string `json:"field" xml:"field" form:"field"`
Error string `json:"error" xml:"error" form:"error"`
}
ValidationError represents a single field validation error.
func PatchJSON ΒΆ
PatchJSON applies JSON Patch (RFC 6902) operations to the provided data. The request must use PATCH method and have Content-Type application/json-patch+json. If validate is true, validates the patched data according to struct tags. Returns validation errors (empty if valid or validation disabled) and a parsing/application error (nil if successful).
type ValidationErrors ΒΆ
type ValidationErrors struct {
XMLName xml.Name `json:"-" xml:"validationErrors" form:"-"`
Errors []ValidationError `json:"errors" xml:"errors" form:"errors"`
}
ValidationErrors represents a collection of validation errors.
func BindCookie ΒΆ
BindCookie parses HTTP cookies from the request and binds them to the provided type T. It validates the data according to struct tags (validate, errmsg) and returns validation errors if any. Struct fields should use the "form" tag to specify cookie names. Returns the bound data, validation errors (nil if valid), and a parsing error (nil if successful).
func BindForm ΒΆ
BindForm parses form data from the request and binds it to the provided type T. It validates the data according to struct tags (validate, errmsg) and returns validation errors if any. Returns the bound data, validation errors (nil if valid), and a parsing error (nil if successful).
func BindHeader ΒΆ
BindHeader parses HTTP headers from the request and binds them to the provided type T. It validates the data according to struct tags (validate, errmsg) and returns validation errors if any. Struct fields should use the "form" tag to specify header names (case-insensitive). Supports slices for multi-value headers. Returns the bound data, validation errors (nil if valid), and a parsing error (nil if successful).
func BindJSON ΒΆ
BindJSON parses JSON from the request body and binds it to the provided type T. If validate is true, validates the data according to struct tags (validate, errmsg). Returns the bound data, validation errors (nil if valid or validation disabled), and a parsing error (nil if successful).
func BindPath ΒΆ
BindPath parses URL path parameters from the request and binds them to the provided type T. Path parameters are extracted using r.PathValue() method (Go 1.22+). It validates the data according to struct tags (validate, errmsg) and returns validation errors if any. Struct fields should use the "form" tag to specify parameter names. Returns the bound data and validation errors (nil if valid).
func BindQuery ΒΆ
BindQuery parses query parameters from the request URL and binds them to the provided type T. It validates the data according to struct tags (validate, errmsg) and returns validation errors if any. Struct fields should use the "form" tag to specify parameter names. Supports slices for multi-value query parameters. Returns the bound data, validation errors (nil if valid), and a parsing error (nil if successful).
func BindXML ΒΆ
BindXML parses XML from the request body and binds it to the provided type T. If validate is true, validates the data according to struct tags (validate, errmsg). Returns the bound data, validation errors (nil if valid or validation disabled), and a parsing error (nil if successful).
Directories
ΒΆ
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
webfram-i18n
command
Package main provides webfram-i18n, a CLI tool for extracting translatable strings from Go code and templates.
|
Package main provides webfram-i18n, a CLI tool for extracting translatable strings from Go code and templates. |
|
internal
|
|
|
bind
Package bind provides data binding functionality for forms, JSON, and XML.
|
Package bind provides data binding functionality for forms, JSON, and XML. |
|
i18n
Package i18n provides internationalization support for the framework.
|
Package i18n provides internationalization support for the framework. |
|
telemetry
Package telemetry provides Prometheus-based metrics collection and HTTP handler support for the framework.
|
Package telemetry provides Prometheus-based metrics collection and HTTP handler support for the framework. |
|
template
Package template provides template rendering functionality.
|
Package template provides template rendering functionality. |
|
openapi
module
|
|
|
security
module
|