Documentation
¶
Overview ¶
Package http provides the HTTP kernel, context, request, and response abstractions.
Index ¶
- func ReleaseContext(c *Context)
- func SetTrustedProxies(cidrs ...string) error
- type Context
- func (c *Context) Abort(status int, message string) error
- func (c *Context) Bind(dest any) error
- func (c *Context) Cookie(name string) (string, error)
- func (c *Context) Ctx() context.Context
- func (c *Context) Data(status int, contentType string, b []byte) error
- func (c *Context) DefaultQuery(name, def string) string
- func (c *Context) Detach()
- func (c *Context) File(path string) error
- func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
- func (c *Context) FormValue(name string) string
- func (c *Context) Get(key string) (any, bool)
- func (c *Context) HTML(status int, html string) error
- func (c *Context) Header(name string) string
- func (c *Context) IP() string
- func (c *Context) IsAJAX() bool
- func (c *Context) IsJSON() bool
- func (c *Context) JSON(status int, v any) error
- func (c *Context) Method() string
- func (c *Context) MustGet(key string) any
- func (c *Context) NoContent() error
- func (c *Context) Param(name string) string
- func (c *Context) ParamInt(name string) (int, error)
- func (c *Context) ParseUpload(field string, cfg ...UploadConfig) (*UploadedFile, error)
- func (c *Context) ParseUploads(field string, cfg ...UploadConfig) ([]*UploadedFile, error)
- func (c *Context) Path() string
- func (c *Context) PushParam(key, value string)
- func (c *Context) Query(name string) string
- func (c *Context) QueryBool(name string) bool
- func (c *Context) QueryD(name, def string) string
- func (c *Context) QueryInt(name string, def int) int
- func (c *Context) Redirect(status int, url string) error
- func (c *Context) Set(key string, value any)
- func (c *Context) SetCookie(cookie *http.Cookie)
- func (c *Context) String(status int, format string, args ...any) error
- func (c *Context) Validate(dest any) error
- func (c *Context) WithContext(ctx context.Context) *Context
- func (c *Context) XML(status int, v any) error
- type HTTPError
- type HandlerFunc
- type Kernel
- type Map
- type MiddlewareFunc
- type Request
- func (r *Request) BearerToken() string
- func (r *Request) Bind(dest any) error
- func (r *Request) BodyBytes() ([]byte, error)
- func (r *Request) IP() string
- func (r *Request) IsSecure() bool
- func (r *Request) Param(name string) string
- func (r *Request) Params() map[string]string
- func (r *Request) WantsJSON() bool
- type Response
- func (r *Response) Committed() bool
- func (r *Response) Flush()
- func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (r *Response) Size() int64
- func (r *Response) Status() int
- func (r *Response) Unwrap() http.ResponseWriter
- func (r *Response) Wrap(w http.ResponseWriter)
- func (r *Response) Write(b []byte) (int, error)
- func (r *Response) WriteHeader(code int)
- type ServerConfig
- type UploadConfig
- type UploadedFile
- type ValidationError
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ReleaseContext ¶
func ReleaseContext(c *Context)
ReleaseContext returns a pooled Context to the pool. It is a no-op for Contexts that did not come from the pool (e.g. WithContext copies) or that were Detach()ed because something may still reference them.
func SetTrustedProxies ¶
SetTrustedProxies configures which upstream proxy addresses are allowed to set X-Forwarded-For / X-Real-IP. Accepts individual IPs ("10.0.0.1") or CIDR ranges ("10.0.0.0/8"). Pass the single value "*" to trust all proxies — only safe when the app is never directly reachable by clients.
Call once at startup. With no trusted proxies configured, forwarding headers are ignored and Request.IP() returns the direct peer address.
Types ¶
type Context ¶
type Context struct {
Request *Request
Response *Response
// contains filtered or unexported fields
}
Context holds the request, response writer, URL params, and a per-request store. It is the single argument to every handler and middleware.
A Context is only valid for the duration of the request that produced it. The router recycles Contexts through a sync.Pool, so handlers MUST NOT retain a *Context (or its Request/Response) past the point where they return. Use WithContext if you need a derived Context to carry into a goroutine that outlives the request — it returns an independent copy that is never pooled.
func AcquireContext ¶
func AcquireContext(w http.ResponseWriter, r *http.Request) *Context
AcquireContext returns a pooled Context bound to w and r. The caller must return it with ReleaseContext once the request completes. Intended for the router; application code receives its Context as a handler argument.
func NewContext ¶
NewContext creates a standalone (non-pooled) Context from a raw http.Request and ResponseWriter. Used by tests and callers that construct a Context directly; the router uses AcquireContext for the pooled hot path.
func (*Context) Abort ¶
Abort returns an HTTPError with the given status and message. Returning it from a handler or middleware stops the chain and renders the error.
func (*Context) Cookie ¶
Cookie returns the value of the named request cookie, or an error if absent.
func (*Context) DefaultQuery ¶
DefaultQuery returns a URL query parameter, or def if absent/empty.
func (*Context) Detach ¶
func (c *Context) Detach()
Detach permanently excludes this Context (and everything sharing its Request/Response/store, i.e. WithContext copies) from pool recycling. Call it when a reference may outlive the request — e.g. the Timeout middleware detaches when it abandons a still-running handler goroutine, so the goroutine can never race a recycled Context belonging to a later request. The objects are then reclaimed by the GC instead of the pool.
func (*Context) FormFile ¶
func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
FormFile returns the first file uploaded under the given field name.
func (*Context) IP ¶
IP returns the client's real IP address, respecting X-Forwarded-For only from trusted proxies (see SetTrustedProxies).
func (*Context) ParseUpload ¶
func (c *Context) ParseUpload(field string, cfg ...UploadConfig) (*UploadedFile, error)
ParseUpload parses a single file upload from the request field `name`.
func (*Context) ParseUploads ¶
func (c *Context) ParseUploads(field string, cfg ...UploadConfig) ([]*UploadedFile, error)
ParseUploads parses all files uploaded under a multi-value field name.
func (*Context) PushParam ¶
PushParam appends a URL path parameter. Called by the router as it matches; it writes into the Request's reused backing array (zero allocation on the hot path). Not intended for application code.
func (*Context) QueryBool ¶
QueryBool returns a URL query parameter parsed as a bool (false if absent/unparseable).
func (*Context) QueryInt ¶
QueryInt returns a URL query parameter parsed as an int, or def if absent/unparseable.
func (*Context) Validate ¶
Validate binds the request body into dest and then validates it against `validate` struct tags. On validation failure it returns a *ValidationError, which the router's error handler renders as a 422 with the field-level error map. Validate does NOT write to the response itself — returning the error is what triggers the single, correctly-formed response.
var req struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required,min=8"`
}
if err := c.Validate(&req); err != nil {
return err // automatic 422 with {"errors":{"email":["..."]}}
}
func (*Context) WithContext ¶
WithContext returns a shallow copy of the Context with a new context.Context. The copy shares the underlying store and lock with the original but is never returned to the pool, so it is safe to carry beyond the request lifecycle.
type HTTPError ¶
HTTPError represents an HTTP error with a status code and message.
func NewHTTPError ¶
NewHTTPError creates an HTTPError.
type HandlerFunc ¶
HandlerFunc is an OniWorks HTTP handler. Handlers return an error to signal failure; the error is dispatched to the registered error handler automatically.
type Kernel ¶
type Kernel struct {
// contains filtered or unexported fields
}
Kernel is the HTTP server kernel. It wraps the standard library's http.Server and adds graceful shutdown, TLS support, and signal handling.
func NewKernel ¶
func NewKernel(cfg ServerConfig, handler http.Handler) *Kernel
NewKernel creates a Kernel with the given config and handler.
func (*Kernel) Addr ¶
Addr returns the listening address (useful for tests that pick a random port).
func (*Kernel) ListenAndServeBackground ¶
ListenAndServeBackground starts the server in a goroutine and returns the bound address. Useful for integration tests.
func (*Kernel) Serve ¶
Serve starts the HTTP server and blocks until a shutdown signal is received. It handles SIGINT and SIGTERM for graceful shutdown.
type MiddlewareFunc ¶
type MiddlewareFunc func(HandlerFunc) HandlerFunc
MiddlewareFunc wraps a HandlerFunc, returning a new HandlerFunc.
type Request ¶
Request wraps *http.Request with additional helpers.
func (*Request) BearerToken ¶
BearerToken extracts the Bearer token from the Authorization header.
func (*Request) Bind ¶
Bind decodes the request body based on the Content-Type header. Supports application/json, application/xml, application/x-www-form-urlencoded, multipart/form-data.
func (*Request) BodyBytes ¶
BodyBytes reads and returns the request body as raw bytes. The body is restored afterward so a later Bind (or re-read) still sees the full payload.
func (*Request) IP ¶
IP returns the client IP address.
X-Forwarded-For / X-Real-IP are only honored when the direct peer (RemoteAddr) is a configured trusted proxy — see SetTrustedProxies. By default no proxies are trusted, so these client-controllable headers are ignored and the direct peer address is returned. This prevents a client from spoofing its IP to bypass IP-based rate limiting or forge audit logs.
func (*Request) IsSecure ¶
IsSecure reports whether the request was made over HTTPS.
The X-Forwarded-Proto header is only believed when the direct peer is a configured trusted proxy (see SetTrustedProxies); otherwise a client could spoof the scheme, influencing secure-cookie or HTTPS-redirect decisions.
func (*Request) Param ¶
Param returns a path parameter value (e.g. for route "/users/:id", Param("id")).
type Response ¶
type Response struct {
http.ResponseWriter
// contains filtered or unexported fields
}
Response wraps http.ResponseWriter with status tracking and body size counting.
func (*Response) Flush ¶
func (r *Response) Flush()
Flush implements http.Flusher if the underlying writer supports it.
func (*Response) Hijack ¶
Hijack implements http.Hijacker if the underlying writer supports it (needed for WebSocket upgrades).
func (*Response) Status ¶
Status returns the HTTP status code sent (or 200 if WriteHeader was never called).
func (*Response) Unwrap ¶
func (r *Response) Unwrap() http.ResponseWriter
Unwrap returns the underlying http.ResponseWriter for type-assertion chains.
func (*Response) Wrap ¶
func (r *Response) Wrap(w http.ResponseWriter)
Wrap replaces the underlying http.ResponseWriter. Used by middleware like Compress that need to intercept writes. The status/size counters are reset.
func (*Response) WriteHeader ¶
WriteHeader captures the status code and delegates to the underlying writer. Calling this more than once is a no-op (the header is sent only once).
type ServerConfig ¶
type ServerConfig struct {
Host string
Port int
TLSCertFile string
TLSKeyFile string
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
ShutdownTimeout time.Duration
}
ServerConfig holds configuration for the HTTP server.
func DefaultServerConfig ¶
func DefaultServerConfig() ServerConfig
DefaultServerConfig returns production-ready defaults.
type UploadConfig ¶
type UploadConfig struct {
MaxSize int64 // bytes; default 10 MB
AllowedTypes []string // e.g. ["image/jpeg","image/png"]; nil = all allowed
}
UploadConfig controls max file size and allowed MIME types.
func DefaultUploadConfig ¶
func DefaultUploadConfig() UploadConfig
DefaultUploadConfig returns sensible upload defaults.
type UploadedFile ¶
type UploadedFile struct {
Header *multipart.FileHeader
Original string // original filename from client
Size int64 // bytes
MIMEType string
}
UploadedFile wraps a *multipart.FileHeader with helpers for inspection and saving.
func (*UploadedFile) Ext ¶
func (uf *UploadedFile) Ext() string
Ext returns the lowercase file extension including the dot (e.g. ".jpg").
func (*UploadedFile) IsImage ¶
func (uf *UploadedFile) IsImage() bool
IsImage reports whether the MIME type indicates an image.
type ValidationError ¶
type ValidationError struct {
Fields validation.Errors
}
ValidationError carries field-level validation failures. The router's error handler renders it as a 422 Unprocessable Entity with the errors map.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string