Loading documentation...
Loading documentation...
Loading documentation...
Complete API documentation for the helix package.
Import Path: github.com/kolosys/helix
Package helix provides a zero-dependency, context-aware, high-performance HTTP web framework for Go with stdlib compatibility.
MIMETextPlain, MIMETextHTML, MIMETextCSS, MIMETextCSV, MIMETextJavaScript, MIMETextXML, MIMETextPlainCharsetUTF8, MIMETextHTMLCharsetUTF8, MIMETextCSSCharsetUTF8, MIMETextCSVCharsetUTF8, MIMETextJavaScriptCharsetUTF8, MIMETextXMLCharsetUTF8, MIMEApplicationJSON, MIMEApplicationXML, MIMEApplicationJavaScript, MIMEApplicationXHTMLXML, MIMEApplicationJSONCharsetUTF8, MIMEApplicationXMLCharsetUTF8, MIMEApplicationJavaScriptCharsetUTF8, MIMEApplicationProblemJSON, MIMEApplicationForm, MIMEApplicationProtobuf, MIMEApplicationMsgPack, MIMEApplicationOctetStream, MIMEApplicationPDF, MIMEApplicationZip, MIMEApplicationGzip, MIMEMultipartForm, MIMEImagePNG, MIMEImageSVG, MIMEImageJPEG, MIMEImageGIF, MIMEImageWebP, MIMEImageICO, MIMEImageAVIF, MIMEAudioMPEG, MIMEAudioWAV, MIMEAudioOGG, MIMEVideoMP4, MIMEVideoWebM, MIMEVideoOGG
MIME type constants for HTTP Content-Type headers. Base types (without charset) are used for content-type detection/matching. CharsetUTF8 variants are used for setting response headers.
const MIMETextPlain = "text/plain" // Text types - base (for matching)
const MIMETextHTML = "text/html"
const MIMETextCSS = "text/css"
const MIMETextCSV = "text/csv"
const MIMETextJavaScript = "text/javascript"
const MIMETextXML = "text/xml"
const MIMETextPlainCharsetUTF8 = "text/plain; charset=utf-8" // Text types - with charset (for responses)
const MIMETextHTMLCharsetUTF8 = "text/html; charset=utf-8"
const MIMETextCSSCharsetUTF8 = "text/css; charset=utf-8"
const MIMETextCSVCharsetUTF8 = "text/csv; charset=utf-8"
const MIMETextJavaScriptCharsetUTF8 = "text/javascript; charset=utf-8"
const MIMETextXMLCharsetUTF8 = "text/xml; charset=utf-8"
const MIMEApplicationJSON = "application/json" // Application types - base (for matching)
const MIMEApplicationXML = "application/xml"
const MIMEApplicationJavaScript = "application/javascript"
const MIMEApplicationXHTMLXML = "application/xhtml+xml"
const MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8" // Application types - with charset (for responses)
const MIMEApplicationXMLCharsetUTF8 = "application/xml; charset=utf-8"
const MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8"
const MIMEApplicationProblemJSON = "application/problem+json" // Application types - no charset needed
const MIMEApplicationForm = "application/x-www-form-urlencoded"
const MIMEApplicationProtobuf = "application/x-protobuf"
const MIMEApplicationMsgPack = "application/msgpack"
const MIMEApplicationOctetStream = "application/octet-stream"
const MIMEApplicationPDF = "application/pdf"
const MIMEApplicationZip = "application/zip"
const MIMEApplicationGzip = "application/gzip"
const MIMEMultipartForm = "multipart/form-data"
const MIMEImagePNG = "image/png" // Image types
const MIMEImageSVG = "image/svg+xml"
const MIMEImageJPEG = "image/jpeg"
const MIMEImageGIF = "image/gif"
const MIMEImageWebP = "image/webp"
const MIMEImageICO = "image/x-icon"
const MIMEImageAVIF = "image/avif"
const MIMEAudioMPEG = "audio/mpeg" // Audio types
const MIMEAudioWAV = "audio/wav"
const MIMEAudioOGG = "audio/ogg"
const MIMEVideoMP4 = "video/mp4" // Video types
const MIMEVideoWebM = "video/webm"
const MIMEVideoOGG = "video/ogg"Version
const Version = "0.1.0" // Version of Hexix
ErrBindingFailed, ErrUnsupportedType, ErrInvalidJSON, ErrRequiredField, ErrBodyAlreadyRead, ErrInvalidFieldValue
Binding errors
var ErrBindingFailed = errors.New("helix: binding failed")
var ErrUnsupportedType = errors.New("helix: unsupported type for binding")
var ErrInvalidJSON = errors.New("helix: invalid JSON body")
var ErrRequiredField = errors.New("helix: required field missing")
var ErrBodyAlreadyRead = errors.New("helix: request body already read")
var ErrInvalidFieldValue = errors.New("helix: invalid field value")ErrBadRequest, ErrUnauthorized, ErrForbidden, ErrNotFound, ErrMethodNotAllowed, ErrConflict, ErrGone, ErrUnprocessableEntity, ErrTooManyRequests, ErrInternal, ErrNotImplemented, ErrBadGateway, ErrServiceUnavailable, ErrGatewayTimeout
Sentinel errors for common HTTP error responses.
var ErrBadRequest = NewProblem(http.StatusBadRequest, "bad_request", "Bad Request") // ErrBadRequest represents a 400 Bad Request error.
var ErrUnauthorized = NewProblem(http.StatusUnauthorized, "unauthorized", "Unauthorized") // ErrUnauthorized represents a 401 Unauthorized error.
var ErrForbidden = NewProblem(http.StatusForbidden, "forbidden", "Forbidden") // ErrForbidden represents a 403 Forbidden error.
var ErrNotFound = NewProblem(http.StatusNotFound, "not_found", "Not Found") // ErrNotFound represents a 404 Not Found error.
var ErrMethodNotAllowed = NewProblem(http.StatusMethodNotAllowed, "method_not_allowed", "Method Not Allowed") // ErrMethodNotAllowed represents a 405 Method Not Allowed error.
var ErrConflict = NewProblem(http.StatusConflict, "conflict", "Conflict") // ErrConflict represents a 409 Conflict error.
var ErrGone = NewProblem(http.StatusGone, "gone", "Gone") // ErrGone represents a 410 Gone error.
var ErrUnprocessableEntity = NewProblem(http.StatusUnprocessableEntity, "unprocessable_entity", "Unprocessable Entity") // ErrUnprocessableEntity represents a 422 Unprocessable Entity error.
var ErrTooManyRequests = NewProblem(http.StatusTooManyRequests, "too_many_requests", "Too Many Requests") // ErrTooManyRequests represents a 429 Too Many Requests error.
var ErrInternal = NewProblem(http.StatusInternalServerError, "internal_error", "Internal Server Error") // ErrInternal represents a 500 Internal Server Error.
var ErrNotImplemented = NewProblem(http.StatusNotImplemented, "not_implemented", "Not Implemented") // ErrNotImplemented represents a 501 Not Implemented error.
var ErrBadGateway = NewProblem(http.StatusBadGateway, "bad_gateway", "Bad Gateway") // ErrBadGateway represents a 502 Bad Gateway error.
var ErrServiceUnavailable = NewProblem(http.StatusServiceUnavailable, "service_unavailable", "Service Unavailable") // ErrServiceUnavailable represents a 503 Service Unavailable error.
var ErrGatewayTimeout = NewProblem(http.StatusGatewayTimeout, "gateway_timeout", "Gateway Timeout") // ErrGatewayTimeout represents a 504 Gateway Timeout error.
Ctx provides a unified context for HTTP handlers with fluent accessors for request data and response methods.
// Create a new Ctx
ctx := Ctx{
Request: &/* value */{},
Response: /* value */,
}type Ctx struct {
Request *http.Request
Response http.ResponseWriter
}| Field | Type | Description |
|---|---|---|
| Request | *http.Request | |
| Response | http.ResponseWriter |
NewCtx creates a new Ctx from an http.Request and http.ResponseWriter.
func NewCtx(w http.ResponseWriter, r *http.Request) *CtxParameters:
w (http.ResponseWriter)r (*http.Request)Returns:
Accepted writes a 202 Accepted JSON response.
func Accepted(w http.ResponseWriter, v any) errorParameters:
w (http.ResponseWriter)v (any)Returns:
AddHeader adds a response header value and returns the Ctx for chaining.
func (*Ctx) AddHeader(key, value string) *CtxParameters:
key (string)value (string)Returns:
Attachment sets the Content-Disposition header to attachment.
func (*Ctx) Attachment(filename string) *CtxParameters:
filename (string)Returns:
BadRequest writes a 400 Bad Request error response.
func BadRequest(w http.ResponseWriter, message string) errorParameters:
w (http.ResponseWriter)message (string)Returns:
Bind binds the request body to the given struct using JSON decoding.
func Bind(r *http.Request) (T, error)Parameters:
r (*http.Request)Returns:
BindJSON is an alias for Bind.
func (*Ctx) BindJSON(v any) errorParameters:
v (any)Returns:
BindPaginationCtx extracts pagination from the Ctx with defaults.
func (*Ctx) BindPagination(defaultLimit, maxLimit int) PaginationParameters:
defaultLimit (int)maxLimit (int)Returns:
Blob writes binary data with the given content type.
func Blob(w http.ResponseWriter, status int, contentType string, data []byte) errorParameters:
w (http.ResponseWriter)status (int)contentType (string)data ([]byte)Returns:
Context returns the request's context.Context.
func (*Ctx) Context() context.ContextParameters: None
Returns:
Created writes a 201 Created JSON response.
func (*Ctx) Created(v any) errorParameters:
v (any)Returns:
CreatedMessage writes a 201 Created response with a message and ID.
func (*Ctx) CreatedMessage(message string, id any) errorParameters:
message (string)id (any)Returns:
DeletedMessage writes a 200 OK response indicating deletion.
func (*Ctx) DeletedMessage(message string) errorParameters:
message (string)Returns:
File serves a file.
func File(w http.ResponseWriter, r *http.Request, path string)Parameters:
w (http.ResponseWriter)r (*http.Request)path (string)Returns: None
Forbidden writes a 403 Forbidden error response.
func (*Ctx) Forbidden(message string) errorParameters:
message (string)Returns:
Get retrieves a value from the request-scoped store.
func Get() (T, bool)Parameters: None
Returns:
GetInt retrieves an int value from the request-scoped store.
func (*Ctx) GetInt(key string) intParameters:
key (string)Returns:
GetString retrieves a string value from the request-scoped store.
func (*Ctx) GetString(key string) stringParameters:
key (string)Returns:
HTML writes an HTML response with the given status code.
func (*Ctx) HTML(status int, html string) errorParameters:
status (int)html (string)Returns:
Header returns the value of a request header.
func (*Ctx) Header(name string) stringParameters:
name (string)Returns:
Inline sets the Content-Disposition header to inline.
func Inline(w http.ResponseWriter, filename string)Parameters:
w (http.ResponseWriter)filename (string)Returns: None
InternalServerError writes a 500 Internal Server Error response.
func InternalServerError(w http.ResponseWriter, message string) errorParameters:
w (http.ResponseWriter)message (string)Returns:
JSON writes a JSON response with the given status code.
func JSON(w http.ResponseWriter, status int, v any) errorParameters:
w (http.ResponseWriter)status (int)v (any)Returns:
MustGet retrieves a value from the request-scoped store or panics if not found.
func (*Ctx) MustGet(key string) anyParameters:
key (string)Returns:
NoContent writes a 204 No Content response.
func NoContent(w http.ResponseWriter) errorParameters:
w (http.ResponseWriter)Returns:
NotFound writes a 404 Not Found error response.
func (*Ctx) NotFound(message string) errorParameters:
message (string)Returns:
OK writes a 200 OK JSON response.
func OK(w http.ResponseWriter, v any) errorParameters:
w (http.ResponseWriter)v (any)Returns:
OKMessage writes a 200 OK response with a message.
func (*Ctx) OKMessage(message string) errorParameters:
message (string)Returns:
Paginated writes a paginated JSON response.
func (*Ctx) Paginated(items any, total, page, limit int) errorParameters:
items (any)total (int)page (int)limit (int)Returns:
Param returns the value of a path parameter.
func (*Ctx) Param(name string) stringParameters:
name (string)Returns:
ParamInt returns the value of a path parameter as an int.
func (*Ctx) ParamInt(name string) (int, error)Parameters:
name (string)Returns:
ParamInt64 returns the value of a path parameter as an int64.
func ParamInt64(r *http.Request, name string) (int64, error)Parameters:
r (*http.Request)name (string)Returns:
ParamUUID returns the value of a path parameter validated as a UUID.
func (*Ctx) ParamUUID(name string) (string, error)Parameters:
name (string)Returns:
Problem writes an RFC 7807 Problem response.
func (*Ctx) Problem(p Problem) errorParameters:
p (Problem)Returns:
Query returns the first value of a query parameter.
func (*Ctx) Query(name string) stringParameters:
name (string)Returns:
QueryBool returns the first value of a query parameter as a bool.
func (*Ctx) QueryBool(name string) boolParameters:
name (string)Returns:
QueryDefault returns the first value of a query parameter or a default value.
func (*Ctx) QueryDefault(name, defaultVal string) stringParameters:
name (string)defaultVal (string)Returns:
QueryFloat64 returns the first value of a query parameter as a float64.
func (*Ctx) QueryFloat64(name string, defaultVal float64) float64Parameters:
name (string)defaultVal (float64)Returns:
QueryInt returns the first value of a query parameter as an int.
func (*Ctx) QueryInt(name string, defaultVal int) intParameters:
name (string)defaultVal (int)Returns:
QueryInt64 returns the first value of a query parameter as an int64.
func QueryInt64(r *http.Request, name string, defaultVal int64) int64Parameters:
r (*http.Request)name (string)defaultVal (int64)Returns:
QuerySlice returns all values of a query parameter as a string slice.
func QuerySlice(r *http.Request, name string) []stringParameters:
r (*http.Request)name (string)Returns:
Redirect redirects the request to the given URL.
func (*Ctx) Redirect(url string, code int)Parameters:
url (string)code (int)Returns: None
Reset resets the Ctx for reuse from a pool.
func (*Ctx) Reset(w http.ResponseWriter, r *http.Request)Parameters:
w (http.ResponseWriter)r (*http.Request)Returns: None
SendJSON writes a JSON response with the pending status code (or 200 if not set).
func (*Ctx) SendJSON(v any) errorParameters:
v (any)Returns:
Set stores a value in the request-scoped store.
func (*Ctx) Set(key string, value any)Parameters:
key (string)value (any)Returns: None
SetCookie sets a cookie on the response and returns the Ctx for chaining.
func (*Ctx) SetCookie(cookie *http.Cookie) *CtxParameters:
cookie (*http.Cookie)Returns:
SetHeader sets a response header and returns the Ctx for chaining.
func (*Ctx) SetHeader(key, value string) *CtxParameters:
key (string)value (string)Returns:
Status sets the pending status code for the response and returns the Ctx for chaining. The status is applied when a response body is written.
func (*Ctx) Status(code int) *CtxParameters:
code (int)Returns:
Text writes a plain text response with the given status code.
func (*Ctx) Text(status int, text string) errorParameters:
status (int)text (string)Returns:
Unauthorized writes a 401 Unauthorized error response.
func Unauthorized(w http.ResponseWriter, message string) errorParameters:
w (http.ResponseWriter)message (string)Returns:
----------------------------------------------------------------------------- CtxHandler and HandleCtx ----------------------------------------------------------------------------- CtxHandler is a handler function that uses the unified Ctx type.
// Example usage of CtxHandler
var value CtxHandler
// Initialize with appropriate valuetype CtxHandler func(c *Ctx) errorEmptyHandler is a handler that takes no request and returns no response.
// Example usage of EmptyHandler
var value EmptyHandler
// Initialize with appropriate valuetype EmptyHandler func(ctx context.Context) errorErrorHandler is a function that handles errors from handlers. It receives the response writer, request, and error, and is responsible for writing an appropriate error response.
// Example usage of ErrorHandler
var value ErrorHandler
// Initialize with appropriate valuetype ErrorHandler func(w http.ResponseWriter, r *http.Request, err error)----------------------------------------------------------------------------- Validation Errors ----------------------------------------------------------------------------- FieldError represents a validation error for a specific field.
// Create a new FieldError
fielderror := FieldError{
Field: "example",
Message: "example",
}type FieldError struct {
Field string `json:"field"`
Message string `json:"message"`
}| Field | Type | Description |
|---|---|---|
| Field | string | |
| Message | string |
Group represents a group of routes with a common prefix and middleware.
// Create a new Group
group := Group{
}type Group struct {
}Any registers a handler for all HTTP methods.
func (*Server) Any(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
DELETE registers a handler for DELETE requests.
func (*Server) DELETE(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
GET registers a handler for GET requests.
func (*Server) GET(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
Group creates a nested group with the given prefix. The prefix is appended to the parent group's prefix. Accepts Middleware (helix.Middleware is an alias for middleware.Middleware) or func(http.Handler) http.Handler.
func (*Group) Group(prefix string, mw ...any) *GroupParameters:
prefix (string)mw (...any)Returns:
HEAD registers a handler for HEAD requests.
func (*Server) HEAD(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
Handle registers a handler for the given method and pattern.
func (*Server) Handle(method, pattern string, handler http.HandlerFunc)Parameters:
method (string)pattern (string)handler (http.HandlerFunc)Returns: None
Mount mounts a module at the given prefix within a group.
func (*Group) Mount(prefix string, m Module, mw ...any)Parameters:
prefix (string)m (Module)mw (...any)Returns: None
MountFunc mounts a function as a module at the given prefix within a group.
func (*Group) MountFunc(prefix string, fn func(r RouteRegistrar), mw ...any)Parameters:
prefix (string)fn (func(r RouteRegistrar))mw (...any)Returns: None
OPTIONS registers a handler for OPTIONS requests.
func (*Group) OPTIONS(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
PATCH registers a handler for PATCH requests.
func (*Group) PATCH(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
POST registers a handler for POST requests.
func (*Server) POST(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
PUT registers a handler for PUT requests.
func (*Group) PUT(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
Resource creates a new ResourceBuilder for the given pattern within this group. The pattern is relative to the group's prefix. Optional middleware can be applied to all routes in the resource. Accepts helix.Middleware, middleware.Middleware, or func(http.Handler) http.Handler.
func (*Group) Resource(pattern string, mw ...any) *ResourceBuilderParameters:
pattern (string)mw (...any)Returns:
Static serves static files from the given file system root.
func (*Group) Static(pattern, root string)Parameters:
pattern (string)root (string)Returns: None
Use adds middleware to the group. Middleware is applied to all routes registered on this group. Accepts Middleware (helix.Middleware is an alias for middleware.Middleware) or func(http.Handler) http.Handler.
func (*Group) Use(mw ...any)Parameters:
mw (...any)Returns: None
Handler is a generic handler function that accepts a typed request and returns a typed response. The request type is automatically bound from path parameters, query parameters, headers, and JSON body. The response is automatically encoded as JSON.
// Example usage of Handler
var value Handler
// Initialize with appropriate valuetype Handler func(ctx context.Context, req Req) (Res, error)HealthBuilder provides a fluent interface for building health check endpoints.
// Create a new HealthBuilder
healthbuilder := HealthBuilder{
}type HealthBuilder struct {
}Health creates a new HealthBuilder.
func Health() *HealthBuilderParameters: None
Returns:
Check adds a health check for a named component.
func (*HealthBuilder) Check(name string, check HealthCheck) *HealthBuilderParameters:
name (string)check (HealthCheck)Returns:
CheckFunc adds a simple health check that returns an error.
func (*HealthBuilder) CheckFunc(name string, check func(ctx context.Context) error) *HealthBuilderParameters:
name (string)check (func(ctx context.Context) error)Returns:
Handler returns an http.HandlerFunc for the health check endpoint.
func (*HealthBuilder) Handler() http.HandlerFuncParameters: None
Returns:
Timeout sets the timeout for health checks.
func (*HealthBuilder) Timeout(d time.Duration) *HealthBuilderParameters:
d (time.Duration)Returns:
Version sets the application version shown in health responses.
func (*HealthBuilder) Version(v string) *HealthBuilderParameters:
v (string)Returns:
HealthCheck is a function that checks the health of a component.
// Example usage of HealthCheck
var value HealthCheck
// Initialize with appropriate valuetype HealthCheck func(ctx context.Context) HealthCheckResultHealthCheckResult contains the result of a health check.
// Create a new HealthCheckResult
healthcheckresult := HealthCheckResult{
Status: HealthStatus{},
Message: "example",
Latency: /* value */,
Details: map[],
}type HealthCheckResult struct {
Status HealthStatus `json:"status"`
Message string `json:"message,omitempty"`
Latency time.Duration `json:"latency_ms,omitempty"`
Details map[string]any `json:"details,omitempty"`
}| Field | Type | Description |
|---|---|---|
| Status | HealthStatus | |
| Message | string | |
| Latency | time.Duration | |
| Details | map[string]any |
HealthResponse is the response returned by the health endpoint.
// Create a new HealthResponse
healthresponse := HealthResponse{
Status: HealthStatus{},
Timestamp: /* value */,
Version: "example",
Components: map[],
}type HealthResponse struct {
Status HealthStatus `json:"status"`
Timestamp time.Time `json:"timestamp"`
Version string `json:"version,omitempty"`
Components map[string]HealthCheckResult `json:"components,omitempty"`
}| Field | Type | Description |
|---|---|---|
| Status | HealthStatus | |
| Timestamp | time.Time | |
| Version | string | |
| Components | map[string]HealthCheckResult |
HealthStatus represents the health status of a component.
// Example usage of HealthStatus
var value HealthStatus
// Initialize with appropriate valuetype HealthStatus stringIDRequest is a common request type for single-entity operations.
// Create a new IDRequest
idrequest := IDRequest{
ID: 42,
}type IDRequest struct {
ID int `path:"id"`
}| Field | Type | Description |
|---|---|---|
| ID | int |
ListRequest is a common request type for list operations.
// Create a new ListRequest
listrequest := ListRequest{
Page: 42,
Limit: 42,
Sort: "example",
Order: "example",
Search: "example",
}type ListRequest struct {
Page int `query:"page"`
Limit int `query:"limit"`
Sort string `query:"sort"`
Order string `query:"order"`
Search string `query:"search"`
}| Field | Type | Description |
|---|---|---|
| Page | int | |
| Limit | int | |
| Sort | string | |
| Order | string | |
| Search | string |
ListResponse wraps a list of entities with pagination metadata.
// Create a new ListResponse
listresponse := ListResponse{
Items: [],
Total: 42,
Page: 42,
Limit: 42,
}type ListResponse struct {
Items []Entity `json:"items"`
Total int `json:"total"`
Page int `json:"page,omitempty"`
Limit int `json:"limit,omitempty"`
}| Field | Type | Description |
|---|---|---|
| Items | []Entity | |
| Total | int | |
| Page | int | |
| Limit | int |
Middleware is a function that wraps an http.Handler to provide additional functionality. This is an alias to middleware.Middleware for convenience.
// Example usage of Middleware
var value Middleware
// Initialize with appropriate valuetype Middleware middleware.MiddlewareProvideMiddleware returns middleware that injects services into the request context. Services added this way are request-scoped.
func ProvideMiddleware(factory func(r *http.Request) T) MiddlewareParameters:
factory (func(r *http.Request) T)Returns:
} func (m *UserModule) Register(r RouteRegistrar) { r.GET("/", m.list) r.POST("/", m.create) r.GET("/{id}", m.get) } // Mount the module s.Mount("/users", &UserModule{store: store})
// Example implementation of Module
type MyModule struct {
// Add your fields here
}
func (m MyModule) Register(param1 RouteRegistrar) {
// Implement your logic here
return
}
type Module interface {
Register(r RouteRegistrar)
}| Method | Description |
|---|
ModuleFunc is a function that implements Module.
// Example usage of ModuleFunc
var value ModuleFunc
// Initialize with appropriate valuetype ModuleFunc func(r RouteRegistrar)Register implements Module.
func Register(service T)Parameters:
service (T)Returns: None
NoRequestHandler is a handler that takes no request body, only context.
// Example usage of NoRequestHandler
var value NoRequestHandler
// Initialize with appropriate valuetype NoRequestHandler func(ctx context.Context) (Res, error)NoResponseHandler is a handler that returns no response body.
// Example usage of NoResponseHandler
var value NoResponseHandler
// Initialize with appropriate valuetype NoResponseHandler func(ctx context.Context, req Req) errorOption configures a Server.
// Example usage of Option
var value Option
// Initialize with appropriate valuetype Option func(*Server)HideBanner hides the banner and sets the banner to an empty string.
func HideBanner() OptionParameters: None
Returns:
WithAddr sets the address the server listens on. Default is ":8080".
func WithAddr(addr string) OptionParameters:
addr (string)Returns:
WithBasePath sets a base path prefix for all routes. All registered routes will be prefixed with this path. For example, with base path "/api/v1", a route "/users" becomes "/api/v1/users". The base path should start with "/" but should not end with "/" (it will be normalized).
func WithBasePath(path string) OptionParameters:
path (string)Returns:
WithCustomBanner sets a custom banner for the server.
func WithCustomBanner(banner string) OptionParameters:
banner (string)Returns:
WithErrorHandler sets a custom error handler for the server. The error handler will be called whenever an error occurs in a handler. If not set, the default error handling (RFC 7807 Problem Details) is used.
func WithErrorHandler(handler ErrorHandler) OptionParameters:
handler (ErrorHandler)Returns:
WithGracePeriod sets the maximum duration to wait for active connections to finish during graceful shutdown.
func WithGracePeriod(d time.Duration) OptionParameters:
d (time.Duration)Returns:
WithIdleTimeout sets the maximum amount of time to wait for the next request when keep-alives are enabled.
func WithIdleTimeout(d time.Duration) OptionParameters:
d (time.Duration)Returns:
WithMaxHeaderBytes sets the maximum size of request headers.
func WithMaxHeaderBytes(n int) OptionParameters:
n (int)Returns:
WithReadTimeout sets the maximum duration for reading the entire request.
func WithReadTimeout(d time.Duration) OptionParameters:
d (time.Duration)Returns:
WithTLS configures the server to use TLS with the provided certificate and key files.
func WithTLS(certFile, keyFile string) OptionParameters:
certFile (string)keyFile (string)Returns:
WithTLSConfig sets a custom TLS configuration for the server.
func WithTLSConfig(config *tls.Config) OptionParameters:
config (*tls.Config)Returns:
WithWriteTimeout sets the maximum duration before timing out writes of the response.
func WithWriteTimeout(d time.Duration) OptionParameters:
d (time.Duration)Returns:
PaginatedResponse wraps a list response with pagination metadata.
// Create a new PaginatedResponse
paginatedresponse := PaginatedResponse{
Items: [],
Total: 42,
Page: 42,
Limit: 42,
TotalPages: 42,
HasMore: true,
NextCursor: "example",
}type PaginatedResponse struct {
Items []T `json:"items"`
Total int `json:"total"`
Page int `json:"page"`
Limit int `json:"limit"`
TotalPages int `json:"total_pages"`
HasMore bool `json:"has_more"`
NextCursor string `json:"next_cursor,omitempty"`
}| Field | Type | Description |
|---|---|---|
| Items | []T | |
| Total | int | |
| Page | int | |
| Limit | int | |
| TotalPages | int | |
| HasMore | bool | |
| NextCursor | string |
NewCursorResponse creates a new cursor-based paginated response.
func NewCursorResponse(items []T, total int, nextCursor string) *ast.IndexExprParameters:
items ([]T)total (int)nextCursor (string)Returns:
NewPaginatedResponse creates a new paginated response.
func NewPaginatedResponse(items []T, total, page, limit int) *ast.IndexExprParameters:
items ([]T)total (int)page (int)limit (int)Returns:
Pagination contains common pagination parameters. Use with struct embedding for automatic binding. Example: type ListUsersRequest struct { helix.Pagination Status string query:"status" }
// Create a new Pagination
pagination := Pagination{
Page: 42,
Limit: 42,
Sort: "example",
Order: "example",
Cursor: "example",
}type Pagination struct {
Page int `query:"page"`
Limit int `query:"limit"`
Sort string `query:"sort"`
Order string `query:"order"`
Cursor string `query:"cursor"`
}| Field | Type | Description |
|---|---|---|
| Page | int | |
| Limit | int | |
| Sort | string | |
| Order | string | |
| Cursor | string |
BindPagination extracts pagination from the request with defaults.
func (*Ctx) BindPagination(defaultLimit, maxLimit int) PaginationParameters:
defaultLimit (int)maxLimit (int)Returns:
GetLimit returns the limit with a default and maximum.
func (Pagination) GetLimit(defaultLimit, maxLimit int) intParameters:
defaultLimit (int)maxLimit (int)Returns:
GetOffset calculates the offset for SQL queries.
func (Pagination) GetOffset(limit int) intParameters:
limit (int)Returns:
GetOrder returns the order (asc/desc) with a default of desc.
func (Pagination) GetOrder() stringParameters: None
Returns:
GetPage returns the page number with a default of 1.
func (Pagination) GetPage() intParameters: None
Returns:
GetSort returns the sort field with a default.
func (Pagination) GetSort(defaultSort string, allowed []string) stringParameters:
defaultSort (string)allowed ([]string)Returns:
IsAscending returns true if the order is ascending.
func (Pagination) IsAscending() boolParameters: None
Returns:
Problem represents an RFC 7807 Problem Details for HTTP APIs. See: https://tools.ietf.org/html/rfc7807
// Create a new Problem
problem := Problem{
Type: "example",
Title: "example",
Status: 42,
Detail: "example",
Instance: "example",
Err: error{},
}type Problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
Instance string `json:"instance,omitempty"`
Err error `json:"-"`
}| Field | Type | Description |
|---|---|---|
| Type | string | Type is a URI reference that identifies the problem type. |
| Title | string | Title is a short, human-readable summary of the problem type. |
| Status | int | Status is the HTTP status code for this problem. |
| Detail | string | Detail is a human-readable explanation specific to this occurrence of the problem. |
| Instance | string | Instance is a URI reference that identifies the specific occurrence of the problem. |
| Err | error | Err is the error that caused the problem. |
BadGatewayf creates a 502 Bad Gateway Problem with a formatted detail message.
func BadGatewayf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
BadRequestf creates a 400 Bad Request Problem with a formatted detail message.
func BadRequestf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
Conflictf creates a 409 Conflict Problem with a formatted detail message.
func Conflictf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
Forbiddenf creates a 403 Forbidden Problem with a formatted detail message.
func Forbiddenf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
GatewayTimeoutf creates a 504 Gateway Timeout Problem with a formatted detail message.
func GatewayTimeoutf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
Gonef creates a 410 Gone Problem with a formatted detail message.
func Gonef(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
Internalf creates a 500 Internal Server Error Problem with a formatted detail message.
func Internalf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
MethodNotAllowedf creates a 405 Method Not Allowed Problem with a formatted detail message.
func MethodNotAllowedf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
NewProblem creates a new Problem with the given status, type, and title.
func NewProblem(status int, problemType, title string) ProblemParameters:
status (int)problemType (string)title (string)Returns:
NotFoundf creates a 404 Not Found Problem with a formatted detail message.
func NotFoundf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
NotImplementedf creates a 501 Not Implemented Problem with a formatted detail message.
func NotImplementedf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
ProblemFromStatus creates a Problem from an HTTP status code.
func ProblemFromStatus(status int) ProblemParameters:
status (int)Returns:
ServiceUnavailablef creates a 503 Service Unavailable Problem with a formatted detail message.
func ServiceUnavailablef(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
TooManyRequestsf creates a 429 Too Many Requests Problem with a formatted detail message.
func TooManyRequestsf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
Unauthorizedf creates a 401 Unauthorized Problem with a formatted detail message.
func Unauthorizedf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
UnprocessableEntityf creates a 422 Unprocessable Entity Problem with a formatted detail message.
func UnprocessableEntityf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
Error implements the error interface.
func (*ValidationErrors) Error() stringParameters: None
Returns:
func (Problem) WithDetail(detail string) ProblemParameters:
detail (string)Returns:
WithDetailf returns a copy of the Problem with the given detail message.
func (Problem) WithDetailf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
WithStack returns a copy of the Problem with the given stack trace.
func (Problem) WithErr(err error) ProblemParameters:
err (error)Returns:
WithInstance returns a copy of the Problem with the given instance URI.
func (Problem) WithInstance(instance string) ProblemParameters:
instance (string)Returns:
WithType returns a copy of the Problem with the given type URI.
func (Problem) WithType(problemType string) ProblemParameters:
problemType (string)Returns:
ResourceBuilder provides a fluent interface for defining REST resource routes.
// Create a new ResourceBuilder
resourcebuilder := ResourceBuilder{
}type ResourceBuilder struct {
}CRUD registers all standard CRUD handlers in one call. Handlers: list, create, get, update, delete
func (*ResourceBuilder) CRUD(list, create, get, update, delete http.HandlerFunc) *ResourceBuilderParameters:
list (http.HandlerFunc)create (http.HandlerFunc)get (http.HandlerFunc)update (http.HandlerFunc)delete (http.HandlerFunc)Returns:
Create registers a POST handler for creating resources (e.g., POST /users).
func (**ast.IndexExpr) Create(h *ast.IndexListExpr) **ast.IndexExprParameters:
h (*ast.IndexListExpr)Returns:
Custom registers a handler with a custom method and path suffix. The suffix is appended to the base pattern. Example: Custom("POST", "/{id}/archive", archiveHandler) for POST /users/{id}/archive
func (**ast.IndexExpr) Custom(method, suffix string, handler http.HandlerFunc) **ast.IndexExprParameters:
method (string)suffix (string)handler (http.HandlerFunc)Returns:
Delete registers a DELETE handler for deleting a resource (e.g., DELETE /users/{id}).
func (**ast.IndexExpr) Delete(h *ast.IndexExpr) **ast.IndexExprParameters:
h (*ast.IndexExpr)Returns:
Destroy is an alias for Delete.
func (*ResourceBuilder) Destroy(handler http.HandlerFunc) *ResourceBuilderParameters:
handler (http.HandlerFunc)Returns:
Get registers a GET handler for a single resource (e.g., GET /users/{id}).
func Get() (T, bool)Parameters: None
Returns:
Index is an alias for List.
func (*ResourceBuilder) Index(handler http.HandlerFunc) *ResourceBuilderParameters:
handler (http.HandlerFunc)Returns:
List registers a GET handler for the collection (e.g., GET /users).
func (**ast.IndexExpr) List(h *ast.IndexListExpr) **ast.IndexExprParameters:
h (*ast.IndexListExpr)Returns:
Patch registers a PATCH handler for partial updates (e.g., PATCH /users/{id}).
func (**ast.IndexExpr) Patch(h *ast.IndexListExpr) **ast.IndexExprParameters:
h (*ast.IndexListExpr)Returns:
ReadOnly registers only read handlers (list and get).
func (*ResourceBuilder) ReadOnly(list, get http.HandlerFunc) *ResourceBuilderParameters:
list (http.HandlerFunc)get (http.HandlerFunc)Returns:
Show is an alias for Get.
func (*ResourceBuilder) Show(handler http.HandlerFunc) *ResourceBuilderParameters:
handler (http.HandlerFunc)Returns:
Store is an alias for Create.
func (*ResourceBuilder) Store(handler http.HandlerFunc) *ResourceBuilderParameters:
handler (http.HandlerFunc)Returns:
Update registers a PUT handler for updating a resource (e.g., PUT /users/{id}).
func (**ast.IndexExpr) Update(h *ast.IndexListExpr) **ast.IndexExprParameters:
h (*ast.IndexListExpr)Returns:
RouteInfo contains information about a registered route.
// Create a new RouteInfo
routeinfo := RouteInfo{
Method: "example",
Pattern: "example",
}type RouteInfo struct {
Method string
Pattern string
}| Field | Type | Description |
|---|---|---|
| Method | string | |
| Pattern | string |
RouteRegistrar is an interface for registering routes. Both Server and Group implement this interface.
// Example implementation of RouteRegistrar
type MyRouteRegistrar struct {
// Add your fields here
}
func (m MyRouteRegistrar) GET(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) POST(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) PUT(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) PATCH(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) DELETE(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) OPTIONS(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) HEAD(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) Handle(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) Group(param1 string, param2 ...any) *Group {
// Implement your logic here
return
}
func (m MyRouteRegistrar) Resource(param1 string, param2 ...any) *ResourceBuilder {
// Implement your logic here
return
}
type RouteRegistrar interface {
GET(pattern string, handler http.HandlerFunc)
POST(pattern string, handler http.HandlerFunc)
PUT(pattern string, handler http.HandlerFunc)
PATCH(pattern string, handler http.HandlerFunc)
DELETE(pattern string, handler http.HandlerFunc)
OPTIONS(pattern string, handler http.HandlerFunc)
HEAD(pattern string, handler http.HandlerFunc)
Handle(method, pattern string, handler http.HandlerFunc)
Group(prefix string, mw ...any) *Group
Resource(pattern string, mw ...any) *ResourceBuilder
}| Method | Description |
|---|
Router handles HTTP request routing.
// Create a new Router
router := Router{
}type Router struct {
}Handle registers a new route with the given method and pattern.
func Handle(h *ast.IndexListExpr) http.HandlerFuncParameters:
h (*ast.IndexListExpr)Returns:
Routes returns all registered routes.
func (*Server) Routes() []RouteInfoParameters: None
Returns:
ServeHTTP implements http.Handler.
func (*Server) ServeHTTP(w http.ResponseWriter, r *http.Request)Parameters:
w (http.ResponseWriter)r (*http.Request)Returns: None
Server is the main HTTP server for the Helix framework.
// Create a new Server
server := Server{
}type Server struct {
}Default creates a new Server with sensible defaults for development. It includes RequestID, Logger (dev format), and Recover middleware.
func Default(opts ...Option) *ServerParameters:
opts (...Option)Returns:
New creates a new Server with the provided options.
func New(opts ...Option) *ServerParameters:
opts (...Option)Returns:
Addr returns the address the server is configured to listen on.
func (*Server) Addr() stringParameters: None
Returns:
Any registers a handler for all HTTP methods.
func (*Server) Any(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
Build pre-compiles the middleware chain for optimal performance. This is called automatically before the server starts, but can be called manually after all routes and middleware are registered.
func (*Server) Build()Parameters: None
Returns: None
CONNECT registers a handler for CONNECT requests.
func (*Server) CONNECT(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
DELETE registers a handler for DELETE requests.
func (*Server) DELETE(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
GET registers a handler for GET requests.
func (*Server) GET(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
Group creates a new route group with the given prefix. The prefix is prepended to all routes registered on the group. Accepts Middleware (helix.Middleware is an alias for middleware.Middleware) or func(http.Handler) http.Handler.
func (*Group) Group(prefix string, mw ...any) *GroupParameters:
prefix (string)mw (...any)Returns:
HEAD registers a handler for HEAD requests.
func (*Server) HEAD(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
Handle registers a handler for the given method and pattern.
func (*Server) Handle(method, pattern string, handler http.HandlerFunc)Parameters:
method (string)pattern (string)handler (http.HandlerFunc)Returns: None
Mount mounts a module at the given prefix. The module's routes are prefixed with the given path.
func (*Group) Mount(prefix string, m Module, mw ...any)Parameters:
prefix (string)m (Module)mw (...any)Returns: None
MountFunc mounts a function as a module at the given prefix.
func (*Group) MountFunc(prefix string, fn func(r RouteRegistrar), mw ...any)Parameters:
prefix (string)fn (func(r RouteRegistrar))mw (...any)Returns: None
OPTIONS registers a handler for OPTIONS requests.
func (*Group) OPTIONS(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
OnStart registers a function to be called when the server starts. Multiple functions can be registered and will be called in order.
func (*Server) OnStart(fn func(s *Server))Parameters:
fn (func(s *Server))Returns: None
OnStop registers a function to be called when the server stops. Multiple functions can be registered and will be called in order. The context passed to the function has the grace period as its deadline.
func (*Server) OnStop(fn func(ctx context.Context, s *Server))Parameters:
fn (func(ctx context.Context, s *Server))Returns: None
PATCH registers a handler for PATCH requests.
func (*Server) PATCH(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
POST registers a handler for POST requests.
func (*Group) POST(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
PUT registers a handler for PUT requests.
func (*Group) PUT(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
PrintRoutes prints all registered routes to the given writer. Routes are sorted by pattern, then by method.
func (*Server) PrintRoutes(w io.Writer)Parameters:
w (io.Writer)Returns: None
Resource creates a new ResourceBuilder for the given pattern. The pattern should be the base path for the resource (e.g., "/users"). Optional middleware can be applied to all routes in the resource. Accepts Middleware (helix.Middleware is an alias for middleware.Middleware) or func(http.Handler) http.Handler.
func (*Server) Resource(pattern string, mw ...any) *ResourceBuilderParameters:
pattern (string)mw (...any)Returns:
Routes returns all registered routes.
func (*Server) Routes() []RouteInfoParameters: None
Returns:
Run starts the server and blocks until the context is canceled or a shutdown signal is received. It performs graceful shutdown, waiting for active connections to finish within the grace period.
func (*Server) Run(ctx context.Context) errorParameters:
ctx (context.Context)Returns:
ServeHTTP implements the http.Handler interface.
func (*Router) ServeHTTP(w http.ResponseWriter, req *http.Request)Parameters:
w (http.ResponseWriter)req (*http.Request)Returns: None
Shutdown gracefully shuts down the server without interrupting active connections. It waits for the grace period for active connections to finish.
func (*Server) Shutdown(ctx context.Context) errorParameters:
ctx (context.Context)Returns:
Start starts the server and blocks until shutdown. If an address is provided, it will be used instead of the WithAddr option. If the address is not provided and the WithAddr option is not set, it will use ":8080". This is a convenience method that calls Run with a background context.
func (*Server) Start(addr ...string) errorParameters:
addr (...string)Returns:
Static serves static files from the given file system root.
func (*Server) Static(pattern, root string)Parameters:
pattern (string)root (string)Returns: None
TRACE registers a handler for TRACE requests.
func (*Server) TRACE(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
Use adds middleware to the server's middleware chain. Middleware is executed in the order it is added. Accepts Middleware (helix.Middleware is an alias for middleware.Middleware) or func(http.Handler) http.Handler.
func (*Group) Use(mw ...any)Parameters:
mw (...any)Returns: None
TypedResourceBuilder provides a fluent interface for defining typed REST resource routes.
// Create a new TypedResourceBuilder
typedresourcebuilder := TypedResourceBuilder{
}type TypedResourceBuilder struct {
}TypedResource creates a typed resource builder for the given entity type. This provides a fluent API for registering typed handlers for CRUD operations. Example: helix.TypedResourceUser. List(listUsers). Create(createUser). Get(getUser). Update(updateUser). Delete(deleteUser)
func TypedResource(s *Server, pattern string, mw ...any) **ast.IndexExprParameters:
s (*Server)pattern (string)mw (...any)Returns:
TypedResourceForGroup creates a typed resource builder within a group.
func TypedResourceForGroup(g *Group, pattern string, mw ...any) **ast.IndexExprParameters:
g (*Group)pattern (string)mw (...any)Returns:
Create registers a typed POST handler for creating resources. Handler signature: func(ctx, CreateReq) (Entity, error)
func (**ast.IndexExpr) Create(h *ast.IndexListExpr) **ast.IndexExprParameters:
h (*ast.IndexListExpr)Returns:
Custom registers a handler with a custom method and path suffix.
func (**ast.IndexExpr) Custom(method, suffix string, handler http.HandlerFunc) **ast.IndexExprParameters:
method (string)suffix (string)handler (http.HandlerFunc)Returns:
Delete registers a typed DELETE handler for deleting a resource. Handler signature: func(ctx, IDRequest) error
func (**ast.IndexExpr) Delete(h *ast.IndexExpr) **ast.IndexExprParameters:
h (*ast.IndexExpr)Returns:
Get registers a typed GET handler for a single resource. Handler signature: func(ctx, IDRequest) (Entity, error)
func Get() (T, bool)Parameters: None
Returns:
List registers a typed GET handler for the collection. Handler signature: func(ctx, ListReq) (ListResponse[Entity], error)
func (**ast.IndexExpr) List(h *ast.IndexListExpr) **ast.IndexExprParameters:
h (*ast.IndexListExpr)Returns:
Patch registers a typed PATCH handler for partial updates.
func (**ast.IndexExpr) Patch(h *ast.IndexListExpr) **ast.IndexExprParameters:
h (*ast.IndexListExpr)Returns:
Update registers a typed PUT handler for updating a resource. The request type should include the ID from path and the update data.
func (**ast.IndexExpr) Update(h *ast.IndexListExpr) **ast.IndexExprParameters:
h (*ast.IndexListExpr)Returns:
Validatable is an interface for types that can validate themselves.
// Example implementation of Validatable
type MyValidatable struct {
// Add your fields here
}
func (m MyValidatable) Validate() error {
// Implement your logic here
return
}
type Validatable interface {
Validate() error
}| Method | Description |
|---|
ValidationErrors collects multiple validation errors for RFC 7807 response. Implements the error interface and can be returned from Validate() methods.
// Create a new ValidationErrors
validationerrors := ValidationErrors{
}type ValidationErrors struct {
}NewValidationErrors creates a new empty ValidationErrors collector.
func NewValidationErrors() *ValidationErrorsParameters: None
Returns:
Add adds a validation error for a specific field.
func (*ValidationErrors) Add(field, message string)Parameters:
field (string)message (string)Returns: None
Addf adds a validation error for a specific field with a formatted message.
func (*ValidationErrors) Addf(field, format string, args ...any)Parameters:
field (string)format (string)args (...any)Returns: None
Err returns nil if there are no errors, otherwise returns the ValidationErrors. This is useful for the common pattern: return v.Err()
func (*ValidationErrors) Err() errorParameters: None
Returns:
Error implements the error interface.
func (*ValidationErrors) Error() stringParameters: None
Returns:
Errors returns the list of field errors.
func (*ValidationErrors) Errors() []FieldErrorParameters: None
Returns:
HasErrors returns true if there are any validation errors.
func (*ValidationErrors) HasErrors() boolParameters: None
Returns:
Len returns the number of validation errors.
func (*ValidationErrors) Len() intParameters: None
Returns:
ToProblem converts ValidationErrors to a ValidationProblem for RFC 7807 response.
func (*ValidationErrors) ToProblem() ValidationProblemParameters: None
Returns:
ValidationProblem is an RFC 7807 Problem with validation errors extension.
// Create a new ValidationProblem
validationproblem := ValidationProblem{
Errors: [],
}type ValidationProblem struct {
Problem
Errors []FieldError `json:"errors,omitempty"`
}| Field | Type | Description |
|---|---|---|
| *Problem | Problem | |
| Errors | []FieldError |
Accepted writes a 202 Accepted JSON response.
func Accepted(w http.ResponseWriter, v any) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
v | any |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of Accepted
result := Accepted(/* parameters */)Attachment sets the Content-Disposition header to attachment with the given filename.
func (*Ctx) Attachment(filename string) *CtxParameters:
| Parameter | Type | Description |
|---|---|---|
filename | string |
Returns:
| Type | Description |
|---|---|
*Ctx |
Example:
// Example usage of Attachment
result := Attachment(/* parameters */)BadRequest writes a 400 Bad Request error response.
func (*Ctx) BadRequest(message string) errorParameters:
| Parameter | Type | Description |
|---|---|---|
message | string |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of BadRequest
result := BadRequest(/* parameters */)Bind binds path parameters, query parameters, headers, and JSON body to a struct. The binding sources are determined by struct tags: - path:"name" - binds from URL path parameters - query:"name" - binds from URL query parameters - header:"name" - binds from HTTP headers - json:"name" - binds from JSON body - form:"name" - binds from form data
func Bind(r *http.Request) (T, error)Parameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request |
Returns:
| Type | Description |
|---|---|
T | |
error |
Example:
// Example usage of Bind
result := Bind(/* parameters */)BindAndValidate binds and validates a request. If the bound type implements Validatable, Validate() is called after binding.
func BindAndValidate(r *http.Request) (T, error)Parameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request |
Returns:
| Type | Description |
|---|---|
T | |
error |
Example:
// Example usage of BindAndValidate
result := BindAndValidate(/* parameters */)BindHeader binds HTTP headers to a struct. Uses the header struct tag to determine field names.
func BindHeader(r *http.Request) (T, error)Parameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request |
Returns:
| Type | Description |
|---|---|
T | |
error |
Example:
// Example usage of BindHeader
result := BindHeader(/* parameters */)BindJSON binds the JSON request body to a struct.
func (*Ctx) BindJSON(v any) errorParameters:
| Parameter | Type | Description |
|---|---|---|
v | any |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of BindJSON
result := BindJSON(/* parameters */)BindPath binds URL path parameters to a struct. Uses the path struct tag to determine field names.
func BindPath(r *http.Request) (T, error)Parameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request |
Returns:
| Type | Description |
|---|---|
T | |
error |
Example:
// Example usage of BindPath
result := BindPath(/* parameters */)BindQuery binds URL query parameters to a struct. Uses the query struct tag to determine field names.
func BindQuery(r *http.Request) (T, error)Parameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request |
Returns:
| Type | Description |
|---|---|
T | |
error |
Example:
// Example usage of BindQuery
result := BindQuery(/* parameters */)Blob writes binary data with the given content type.
func Blob(w http.ResponseWriter, status int, contentType string, data []byte) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
status | int | |
contentType | string | |
data | []byte |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of Blob
result := Blob(/* parameters */)Created writes a 201 Created JSON response.
func (*Ctx) Created(v any) errorParameters:
| Parameter | Type | Description |
|---|---|---|
v | any |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of Created
result := Created(/* parameters */)Error writes an error response with the given status code and message.
func Error(w http.ResponseWriter, status int, message string) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
status | int | |
message | string |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of Error
result := Error(/* parameters */)File serves a file with the given content type.
func File(w http.ResponseWriter, r *http.Request, path string)Parameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
r | *http.Request | |
path | string |
Returns: None
Example:
// Example usage of File
result := File(/* parameters */)Forbidden writes a 403 Forbidden error response.
func (*Ctx) Forbidden(message string) errorParameters:
| Parameter | Type | Description |
|---|---|---|
message | string |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of Forbidden
result := Forbidden(/* parameters */)FromContext retrieves a service from the context or falls back to global registry.
func FromContext(ctx context.Context) (T, bool)Parameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context |
Returns:
| Type | Description |
|---|---|
T | |
bool |
Example:
// Example usage of FromContext
result := FromContext(/* parameters */)Get retrieves a service from the global registry. Returns the zero value and false if not found.
func Get() (T, bool)Parameters: None
Returns:
| Type | Description |
|---|---|
T | |
bool |
Example:
// Example usage of Get
result := Get(/* parameters */)HTML writes an HTML response with the given status code.
func HTML(w http.ResponseWriter, status int, html string) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
status | int | |
html | string |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of HTML
result := HTML(/* parameters */)Handle wraps a generic Handler into an http.HandlerFunc. It automatically: - Binds the request to the Req type - Calls the handler with the context and request - Encodes the response as JSON - Handles errors using RFC 7807 Problem Details
func Handle(h *ast.IndexListExpr) http.HandlerFuncParameters:
| Parameter | Type | Description |
|---|---|---|
h | *ast.IndexListExpr |
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of Handle
result := Handle(/* parameters */)HandleAccepted wraps a generic Handler into an http.HandlerFunc that returns 202 Accepted. Useful for async operations where processing happens in the background.
func HandleAccepted(h *ast.IndexListExpr) http.HandlerFuncParameters:
| Parameter | Type | Description |
|---|---|---|
h | *ast.IndexListExpr |
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of HandleAccepted
result := HandleAccepted(/* parameters */)HandleCreated wraps a generic Handler into an http.HandlerFunc that returns 201 Created. This is a convenience wrapper for HandleWithStatus(http.StatusCreated, h).
func HandleCreated(h *ast.IndexListExpr) http.HandlerFuncParameters:
| Parameter | Type | Description |
|---|---|---|
h | *ast.IndexListExpr |
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of HandleCreated
result := HandleCreated(/* parameters */)HandleCtx wraps a CtxHandler into an http.HandlerFunc. Errors returned from the handler are automatically converted to RFC 7807 responses.
func HandleCtx(h CtxHandler) http.HandlerFuncParameters:
| Parameter | Type | Description |
|---|---|---|
h | CtxHandler |
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of HandleCtx
result := HandleCtx(/* parameters */)HandleEmpty wraps an EmptyHandler into an http.HandlerFunc. Returns 204 No Content on success.
func HandleEmpty(h EmptyHandler) http.HandlerFuncParameters:
| Parameter | Type | Description |
|---|---|---|
h | EmptyHandler |
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of HandleEmpty
result := HandleEmpty(/* parameters */)HandleErrorDefault provides the default error handling logic. This can be called from custom error handlers to fall back to default behavior.
func HandleErrorDefault(w http.ResponseWriter, r *http.Request, err error)Parameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
r | *http.Request | |
err | error |
Returns: None
Example:
// Example usage of HandleErrorDefault
result := HandleErrorDefault(/* parameters */)HandleNoRequest wraps a NoRequestHandler into an http.HandlerFunc. Useful for endpoints that don't need request binding (e.g., GET /users).
func HandleNoRequest(h *ast.IndexExpr) http.HandlerFuncParameters:
| Parameter | Type | Description |
|---|---|---|
h | *ast.IndexExpr |
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of HandleNoRequest
result := HandleNoRequest(/* parameters */)HandleNoResponse wraps a NoResponseHandler into an http.HandlerFunc. Returns 204 No Content on success.
func HandleNoResponse(h *ast.IndexExpr) http.HandlerFuncParameters:
| Parameter | Type | Description |
|---|---|---|
h | *ast.IndexExpr |
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of HandleNoResponse
result := HandleNoResponse(/* parameters */)HandleWithStatus wraps a generic Handler into an http.HandlerFunc with a custom success status code.
func HandleWithStatus(status int, h *ast.IndexListExpr) http.HandlerFuncParameters:
| Parameter | Type | Description |
|---|---|---|
status | int | |
h | *ast.IndexListExpr |
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of HandleWithStatus
result := HandleWithStatus(/* parameters */)Inline sets the Content-Disposition header to inline with the given filename.
func Inline(w http.ResponseWriter, filename string)Parameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
filename | string |
Returns: None
Example:
// Example usage of Inline
result := Inline(/* parameters */)InternalServerError writes a 500 Internal Server Error response.
func InternalServerError(w http.ResponseWriter, message string) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
message | string |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of InternalServerError
result := InternalServerError(/* parameters */)JSON writes a JSON response with the given status code. Uses pooled buffer for zero-allocation in the hot path.
func (*Ctx) JSON(status int, v any) errorParameters:
| Parameter | Type | Description |
|---|---|---|
status | int | |
v | any |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of JSON
result := JSON(/* parameters */)JSONPretty writes a pretty-printed JSON response with the given status code.
func JSONPretty(w http.ResponseWriter, status int, v any, indent string) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
status | int | |
v | any | |
indent | string |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of JSONPretty
result := JSONPretty(/* parameters */)LivenessHandler returns a simple liveness probe handler. Returns 200 OK if the server is running.
func LivenessHandler() http.HandlerFuncParameters: None
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of LivenessHandler
result := LivenessHandler(/* parameters */)MustFromContext retrieves a service from context or panics.
func MustFromContext(ctx context.Context) TParameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context |
Returns:
| Type | Description |
|---|---|
T |
Example:
// Example usage of MustFromContext
result := MustFromContext(/* parameters */)MustGet retrieves a service from the global registry or panics.
func MustGet() TParameters: None
Returns:
| Type | Description |
|---|---|
T |
Example:
// Example usage of MustGet
result := MustGet(/* parameters */)NoContent writes a 204 No Content response.
func (*Ctx) NoContent() errorParameters: None
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of NoContent
result := NoContent(/* parameters */)NotFound writes a 404 Not Found error response.
func NotFound(w http.ResponseWriter, message string) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
message | string |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of NotFound
result := NotFound(/* parameters */)OK writes a 200 OK JSON response.
func OK(w http.ResponseWriter, v any) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
v | any |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of OK
result := OK(/* parameters */)Param returns the value of a path parameter. Returns an empty string if the parameter does not exist.
func (*Ctx) Param(name string) stringParameters:
| Parameter | Type | Description |
|---|---|---|
name | string |
Returns:
| Type | Description |
|---|---|
string |
Example:
// Example usage of Param
result := Param(/* parameters */)ParamInt returns the value of a path parameter as an int. Returns an error if the parameter does not exist or cannot be parsed.
func (*Ctx) ParamInt(name string) (int, error)Parameters:
| Parameter | Type | Description |
|---|---|---|
name | string |
Returns:
| Type | Description |
|---|---|
int | |
error |
Example:
// Example usage of ParamInt
result := ParamInt(/* parameters */)ParamInt64 returns the value of a path parameter as an int64. Returns an error if the parameter does not exist or cannot be parsed.
func (*Ctx) ParamInt64(name string) (int64, error)Parameters:
| Parameter | Type | Description |
|---|---|---|
name | string |
Returns:
| Type | Description |
|---|---|
int64 | |
error |
Example:
// Example usage of ParamInt64
result := ParamInt64(/* parameters */)ParamUUID returns the value of a path parameter validated as a UUID. Returns an error if the parameter does not exist or is not a valid UUID format.
func ParamUUID(r *http.Request, name string) (string, error)Parameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request | |
name | string |
Returns:
| Type | Description |
|---|---|
string | |
error |
Example:
// Example usage of ParamUUID
result := ParamUUID(/* parameters */)Query returns the first value of a query parameter. Returns an empty string if the parameter does not exist.
func Query(r *http.Request, name string) stringParameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request | |
name | string |
Returns:
| Type | Description |
|---|---|
string |
Example:
// Example usage of Query
result := Query(/* parameters */)QueryBool returns the first value of a query parameter as a bool. Returns false if the parameter does not exist or cannot be parsed. Accepts "1", "t", "T", "true", "TRUE", "True" as true. Accepts "0", "f", "F", "false", "FALSE", "False" as false.
func QueryBool(r *http.Request, name string) boolParameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request | |
name | string |
Returns:
| Type | Description |
|---|---|
bool |
Example:
// Example usage of QueryBool
result := QueryBool(/* parameters */)QueryDefault returns the first value of a query parameter or a default value.
func (*Ctx) QueryDefault(name, defaultVal string) stringParameters:
| Parameter | Type | Description |
|---|---|---|
name | string | |
defaultVal | string |
Returns:
| Type | Description |
|---|---|
string |
Example:
// Example usage of QueryDefault
result := QueryDefault(/* parameters */)QueryFloat64 returns the first value of a query parameter as a float64. Returns the default value if the parameter does not exist or cannot be parsed.
func QueryFloat64(r *http.Request, name string, defaultVal float64) float64Parameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request | |
name | string | |
defaultVal | float64 |
Returns:
| Type | Description |
|---|---|
float64 |
Example:
// Example usage of QueryFloat64
result := QueryFloat64(/* parameters */)QueryInt returns the first value of a query parameter as an int. Returns the default value if the parameter does not exist or cannot be parsed.
func QueryInt(r *http.Request, name string, defaultVal int) intParameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request | |
name | string | |
defaultVal | int |
Returns:
| Type | Description |
|---|---|
int |
Example:
// Example usage of QueryInt
result := QueryInt(/* parameters */)QueryInt64 returns the first value of a query parameter as an int64. Returns the default value if the parameter does not exist or cannot be parsed.
func (*Ctx) QueryInt64(name string, defaultVal int64) int64Parameters:
| Parameter | Type | Description |
|---|---|---|
name | string | |
defaultVal | int64 |
Returns:
| Type | Description |
|---|---|
int64 |
Example:
// Example usage of QueryInt64
result := QueryInt64(/* parameters */)QuerySlice returns all values of a query parameter as a string slice. Returns nil if the parameter does not exist.
func QuerySlice(r *http.Request, name string) []stringParameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request | |
name | string |
Returns:
| Type | Description |
|---|---|
[]string |
Example:
// Example usage of QuerySlice
result := QuerySlice(/* parameters */)ReadinessHandler returns a simple readiness probe handler. Uses the provided checks to determine readiness.
func ReadinessHandler(checks ...func(ctx context.Context) error) http.HandlerFuncParameters:
| Parameter | Type | Description |
|---|---|---|
checks | ...func(ctx context.Context) error |
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of ReadinessHandler
result := ReadinessHandler(/* parameters */)Redirect redirects the request to the given URL.
func Redirect(w http.ResponseWriter, r *http.Request, url string, code int)Parameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
r | *http.Request | |
url | string | |
code | int |
Returns: None
Example:
// Example usage of Redirect
result := Redirect(/* parameters */)Register registers a service in the global registry by its type.
func (ModuleFunc) Register(r RouteRegistrar)Parameters:
| Parameter | Type | Description |
|---|---|---|
r | RouteRegistrar |
Returns: None
Example:
// Example usage of Register
result := Register(/* parameters */)Stream streams the content from the reader to the response.
func Stream(w http.ResponseWriter, contentType string, reader io.Reader) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
contentType | string | |
reader | io.Reader |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of Stream
result := Stream(/* parameters */)Text writes a plain text response with the given status code.
func Text(w http.ResponseWriter, status int, text string) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
status | int | |
text | string |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of Text
result := Text(/* parameters */)Unauthorized writes a 401 Unauthorized error response.
func Unauthorized(w http.ResponseWriter, message string) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
message | string |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of Unauthorized
result := Unauthorized(/* parameters */)WithService returns a new context with the service added. This is useful for request-scoped services like database transactions.
func WithService(ctx context.Context, service T) context.ContextParameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
service | T |
Returns:
| Type | Description |
|---|---|
context.Context |
Example:
// Example usage of WithService
result := WithService(/* parameters */)WriteProblem writes a Problem response to the http.ResponseWriter.
func WriteProblem(w http.ResponseWriter, p Problem) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
p | Problem |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of WriteProblem
result := WriteProblem(/* parameters */)WriteValidationProblem writes a ValidationProblem response to the http.ResponseWriter.
func WriteValidationProblem(w http.ResponseWriter, v *ValidationErrors) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
v | *ValidationErrors |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of WriteValidationProblem
result := WriteValidationProblem(/* parameters */)Complete API documentation for the helix package.
Import Path: github.com/kolosys/helix
Package helix provides a zero-dependency, context-aware, high-performance HTTP web framework for Go with stdlib compatibility.
MIMETextPlain, MIMETextHTML, MIMETextCSS, MIMETextCSV, MIMETextJavaScript, MIMETextXML, MIMETextPlainCharsetUTF8, MIMETextHTMLCharsetUTF8, MIMETextCSSCharsetUTF8, MIMETextCSVCharsetUTF8, MIMETextJavaScriptCharsetUTF8, MIMETextXMLCharsetUTF8, MIMEApplicationJSON, MIMEApplicationXML, MIMEApplicationJavaScript, MIMEApplicationXHTMLXML, MIMEApplicationJSONCharsetUTF8, MIMEApplicationXMLCharsetUTF8, MIMEApplicationJavaScriptCharsetUTF8, MIMEApplicationProblemJSON, MIMEApplicationForm, MIMEApplicationProtobuf, MIMEApplicationMsgPack, MIMEApplicationOctetStream, MIMEApplicationPDF, MIMEApplicationZip, MIMEApplicationGzip, MIMEMultipartForm, MIMEImagePNG, MIMEImageSVG, MIMEImageJPEG, MIMEImageGIF, MIMEImageWebP, MIMEImageICO, MIMEImageAVIF, MIMEAudioMPEG, MIMEAudioWAV, MIMEAudioOGG, MIMEVideoMP4, MIMEVideoWebM, MIMEVideoOGG
MIME type constants for HTTP Content-Type headers. Base types (without charset) are used for content-type detection/matching. CharsetUTF8 variants are used for setting response headers.
const MIMETextPlain = "text/plain" // Text types - base (for matching)
const MIMETextHTML = "text/html"
const MIMETextCSS = "text/css"
const MIMETextCSV = "text/csv"
const MIMETextJavaScript = "text/javascript"
const MIMETextXML = "text/xml"
const MIMETextPlainCharsetUTF8 = "text/plain; charset=utf-8" // Text types - with charset (for responses)
const MIMETextHTMLCharsetUTF8 = "text/html; charset=utf-8"
const MIMETextCSSCharsetUTF8 = "text/css; charset=utf-8"
const MIMETextCSVCharsetUTF8 = "text/csv; charset=utf-8"
const MIMETextJavaScriptCharsetUTF8 = "text/javascript; charset=utf-8"
const MIMETextXMLCharsetUTF8 = "text/xml; charset=utf-8"
const MIMEApplicationJSON = "application/json" // Application types - base (for matching)
const MIMEApplicationXML = "application/xml"
const MIMEApplicationJavaScript = "application/javascript"
const MIMEApplicationXHTMLXML = "application/xhtml+xml"
const MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8" // Application types - with charset (for responses)
const MIMEApplicationXMLCharsetUTF8 = "application/xml; charset=utf-8"
const MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8"
const MIMEApplicationProblemJSON = "application/problem+json" // Application types - no charset needed
const MIMEApplicationForm = "application/x-www-form-urlencoded"
const MIMEApplicationProtobuf = "application/x-protobuf"
const MIMEApplicationMsgPack = "application/msgpack"
const MIMEApplicationOctetStream = "application/octet-stream"
const MIMEApplicationPDF = "application/pdf"
const MIMEApplicationZip = "application/zip"
const MIMEApplicationGzip = "application/gzip"
const MIMEMultipartForm = "multipart/form-data"
const MIMEImagePNG = "image/png" // Image types
const MIMEImageSVG = "image/svg+xml"
const MIMEImageJPEG = "image/jpeg"
const MIMEImageGIF = "image/gif"
const MIMEImageWebP = "image/webp"
const MIMEImageICO = "image/x-icon"
const MIMEImageAVIF = "image/avif"
const MIMEAudioMPEG = "audio/mpeg" // Audio types
const MIMEAudioWAV = "audio/wav"
const MIMEAudioOGG = "audio/ogg"
const MIMEVideoMP4 = "video/mp4" // Video types
const MIMEVideoWebM = "video/webm"
const MIMEVideoOGG = "video/ogg"Version
const Version = "0.1.0" // Version of Hexix
ErrBindingFailed, ErrUnsupportedType, ErrInvalidJSON, ErrRequiredField, ErrBodyAlreadyRead, ErrInvalidFieldValue
Binding errors
var ErrBindingFailed = errors.New("helix: binding failed")
var ErrUnsupportedType = errors.New("helix: unsupported type for binding")
var ErrInvalidJSON = errors.New("helix: invalid JSON body")
var ErrRequiredField = errors.New("helix: required field missing")
var ErrBodyAlreadyRead = errors.New("helix: request body already read")
var ErrInvalidFieldValue = errors.New("helix: invalid field value")ErrBadRequest, ErrUnauthorized, ErrForbidden, ErrNotFound, ErrMethodNotAllowed, ErrConflict, ErrGone, ErrUnprocessableEntity, ErrTooManyRequests, ErrInternal, ErrNotImplemented, ErrBadGateway, ErrServiceUnavailable, ErrGatewayTimeout
Sentinel errors for common HTTP error responses.
var ErrBadRequest = NewProblem(http.StatusBadRequest, "bad_request", "Bad Request") // ErrBadRequest represents a 400 Bad Request error.
var ErrUnauthorized = NewProblem(http.StatusUnauthorized, "unauthorized", "Unauthorized") // ErrUnauthorized represents a 401 Unauthorized error.
var ErrForbidden = NewProblem(http.StatusForbidden, "forbidden", "Forbidden") // ErrForbidden represents a 403 Forbidden error.
var ErrNotFound = NewProblem(http.StatusNotFound, "not_found", "Not Found") // ErrNotFound represents a 404 Not Found error.
var ErrMethodNotAllowed = NewProblem(http.StatusMethodNotAllowed, "method_not_allowed", "Method Not Allowed") // ErrMethodNotAllowed represents a 405 Method Not Allowed error.
var ErrConflict = NewProblem(http.StatusConflict, "conflict", "Conflict") // ErrConflict represents a 409 Conflict error.
var ErrGone = NewProblem(http.StatusGone, "gone", "Gone") // ErrGone represents a 410 Gone error.
var ErrUnprocessableEntity = NewProblem(http.StatusUnprocessableEntity, "unprocessable_entity", "Unprocessable Entity") // ErrUnprocessableEntity represents a 422 Unprocessable Entity error.
var ErrTooManyRequests = NewProblem(http.StatusTooManyRequests, "too_many_requests", "Too Many Requests") // ErrTooManyRequests represents a 429 Too Many Requests error.
var ErrInternal = NewProblem(http.StatusInternalServerError, "internal_error", "Internal Server Error") // ErrInternal represents a 500 Internal Server Error.
var ErrNotImplemented = NewProblem(http.StatusNotImplemented, "not_implemented", "Not Implemented") // ErrNotImplemented represents a 501 Not Implemented error.
var ErrBadGateway = NewProblem(http.StatusBadGateway, "bad_gateway", "Bad Gateway") // ErrBadGateway represents a 502 Bad Gateway error.
var ErrServiceUnavailable = NewProblem(http.StatusServiceUnavailable, "service_unavailable", "Service Unavailable") // ErrServiceUnavailable represents a 503 Service Unavailable error.
var ErrGatewayTimeout = NewProblem(http.StatusGatewayTimeout, "gateway_timeout", "Gateway Timeout") // ErrGatewayTimeout represents a 504 Gateway Timeout error.
Ctx provides a unified context for HTTP handlers with fluent accessors for request data and response methods.
// Create a new Ctx
ctx := Ctx{
Request: &/* value */{},
Response: /* value */,
}type Ctx struct {
Request *http.Request
Response http.ResponseWriter
}| Field | Type | Description |
|---|---|---|
| Request | *http.Request | |
| Response | http.ResponseWriter |
NewCtx creates a new Ctx from an http.Request and http.ResponseWriter.
func NewCtx(w http.ResponseWriter, r *http.Request) *CtxParameters:
w (http.ResponseWriter)r (*http.Request)Returns:
Accepted writes a 202 Accepted JSON response.
func Accepted(w http.ResponseWriter, v any) errorParameters:
w (http.ResponseWriter)v (any)Returns:
AddHeader adds a response header value and returns the Ctx for chaining.
func (*Ctx) AddHeader(key, value string) *CtxParameters:
key (string)value (string)Returns:
Attachment sets the Content-Disposition header to attachment.
func (*Ctx) Attachment(filename string) *CtxParameters:
filename (string)Returns:
BadRequest writes a 400 Bad Request error response.
func BadRequest(w http.ResponseWriter, message string) errorParameters:
w (http.ResponseWriter)message (string)Returns:
Bind binds the request body to the given struct using JSON decoding.
func Bind(r *http.Request) (T, error)Parameters:
r (*http.Request)Returns:
BindJSON is an alias for Bind.
func (*Ctx) BindJSON(v any) errorParameters:
v (any)Returns:
BindPaginationCtx extracts pagination from the Ctx with defaults.
func (*Ctx) BindPagination(defaultLimit, maxLimit int) PaginationParameters:
defaultLimit (int)maxLimit (int)Returns:
Blob writes binary data with the given content type.
func Blob(w http.ResponseWriter, status int, contentType string, data []byte) errorParameters:
w (http.ResponseWriter)status (int)contentType (string)data ([]byte)Returns:
Context returns the request's context.Context.
func (*Ctx) Context() context.ContextParameters: None
Returns:
Created writes a 201 Created JSON response.
func (*Ctx) Created(v any) errorParameters:
v (any)Returns:
CreatedMessage writes a 201 Created response with a message and ID.
func (*Ctx) CreatedMessage(message string, id any) errorParameters:
message (string)id (any)Returns:
DeletedMessage writes a 200 OK response indicating deletion.
func (*Ctx) DeletedMessage(message string) errorParameters:
message (string)Returns:
File serves a file.
func File(w http.ResponseWriter, r *http.Request, path string)Parameters:
w (http.ResponseWriter)r (*http.Request)path (string)Returns: None
Forbidden writes a 403 Forbidden error response.
func (*Ctx) Forbidden(message string) errorParameters:
message (string)Returns:
Get retrieves a value from the request-scoped store.
func Get() (T, bool)Parameters: None
Returns:
GetInt retrieves an int value from the request-scoped store.
func (*Ctx) GetInt(key string) intParameters:
key (string)Returns:
GetString retrieves a string value from the request-scoped store.
func (*Ctx) GetString(key string) stringParameters:
key (string)Returns:
HTML writes an HTML response with the given status code.
func (*Ctx) HTML(status int, html string) errorParameters:
status (int)html (string)Returns:
Header returns the value of a request header.
func (*Ctx) Header(name string) stringParameters:
name (string)Returns:
Inline sets the Content-Disposition header to inline.
func Inline(w http.ResponseWriter, filename string)Parameters:
w (http.ResponseWriter)filename (string)Returns: None
InternalServerError writes a 500 Internal Server Error response.
func InternalServerError(w http.ResponseWriter, message string) errorParameters:
w (http.ResponseWriter)message (string)Returns:
JSON writes a JSON response with the given status code.
func JSON(w http.ResponseWriter, status int, v any) errorParameters:
w (http.ResponseWriter)status (int)v (any)Returns:
MustGet retrieves a value from the request-scoped store or panics if not found.
func (*Ctx) MustGet(key string) anyParameters:
key (string)Returns:
NoContent writes a 204 No Content response.
func NoContent(w http.ResponseWriter) errorParameters:
w (http.ResponseWriter)Returns:
NotFound writes a 404 Not Found error response.
func (*Ctx) NotFound(message string) errorParameters:
message (string)Returns:
OK writes a 200 OK JSON response.
func OK(w http.ResponseWriter, v any) errorParameters:
w (http.ResponseWriter)v (any)Returns:
OKMessage writes a 200 OK response with a message.
func (*Ctx) OKMessage(message string) errorParameters:
message (string)Returns:
Paginated writes a paginated JSON response.
func (*Ctx) Paginated(items any, total, page, limit int) errorParameters:
items (any)total (int)page (int)limit (int)Returns:
Param returns the value of a path parameter.
func (*Ctx) Param(name string) stringParameters:
name (string)Returns:
ParamInt returns the value of a path parameter as an int.
func (*Ctx) ParamInt(name string) (int, error)Parameters:
name (string)Returns:
ParamInt64 returns the value of a path parameter as an int64.
func ParamInt64(r *http.Request, name string) (int64, error)Parameters:
r (*http.Request)name (string)Returns:
ParamUUID returns the value of a path parameter validated as a UUID.
func (*Ctx) ParamUUID(name string) (string, error)Parameters:
name (string)Returns:
Problem writes an RFC 7807 Problem response.
func (*Ctx) Problem(p Problem) errorParameters:
p (Problem)Returns:
Query returns the first value of a query parameter.
func (*Ctx) Query(name string) stringParameters:
name (string)Returns:
QueryBool returns the first value of a query parameter as a bool.
func (*Ctx) QueryBool(name string) boolParameters:
name (string)Returns:
QueryDefault returns the first value of a query parameter or a default value.
func (*Ctx) QueryDefault(name, defaultVal string) stringParameters:
name (string)defaultVal (string)Returns:
QueryFloat64 returns the first value of a query parameter as a float64.
func (*Ctx) QueryFloat64(name string, defaultVal float64) float64Parameters:
name (string)defaultVal (float64)Returns:
QueryInt returns the first value of a query parameter as an int.
func (*Ctx) QueryInt(name string, defaultVal int) intParameters:
name (string)defaultVal (int)Returns:
QueryInt64 returns the first value of a query parameter as an int64.
func QueryInt64(r *http.Request, name string, defaultVal int64) int64Parameters:
r (*http.Request)name (string)defaultVal (int64)Returns:
QuerySlice returns all values of a query parameter as a string slice.
func QuerySlice(r *http.Request, name string) []stringParameters:
r (*http.Request)name (string)Returns:
Redirect redirects the request to the given URL.
func (*Ctx) Redirect(url string, code int)Parameters:
url (string)code (int)Returns: None
Reset resets the Ctx for reuse from a pool.
func (*Ctx) Reset(w http.ResponseWriter, r *http.Request)Parameters:
w (http.ResponseWriter)r (*http.Request)Returns: None
SendJSON writes a JSON response with the pending status code (or 200 if not set).
func (*Ctx) SendJSON(v any) errorParameters:
v (any)Returns:
Set stores a value in the request-scoped store.
func (*Ctx) Set(key string, value any)Parameters:
key (string)value (any)Returns: None
SetCookie sets a cookie on the response and returns the Ctx for chaining.
func (*Ctx) SetCookie(cookie *http.Cookie) *CtxParameters:
cookie (*http.Cookie)Returns:
SetHeader sets a response header and returns the Ctx for chaining.
func (*Ctx) SetHeader(key, value string) *CtxParameters:
key (string)value (string)Returns:
Status sets the pending status code for the response and returns the Ctx for chaining. The status is applied when a response body is written.
func (*Ctx) Status(code int) *CtxParameters:
code (int)Returns:
Text writes a plain text response with the given status code.
func (*Ctx) Text(status int, text string) errorParameters:
status (int)text (string)Returns:
Unauthorized writes a 401 Unauthorized error response.
func Unauthorized(w http.ResponseWriter, message string) errorParameters:
w (http.ResponseWriter)message (string)Returns:
----------------------------------------------------------------------------- CtxHandler and HandleCtx ----------------------------------------------------------------------------- CtxHandler is a handler function that uses the unified Ctx type.
// Example usage of CtxHandler
var value CtxHandler
// Initialize with appropriate valuetype CtxHandler func(c *Ctx) errorEmptyHandler is a handler that takes no request and returns no response.
// Example usage of EmptyHandler
var value EmptyHandler
// Initialize with appropriate valuetype EmptyHandler func(ctx context.Context) errorErrorHandler is a function that handles errors from handlers. It receives the response writer, request, and error, and is responsible for writing an appropriate error response.
// Example usage of ErrorHandler
var value ErrorHandler
// Initialize with appropriate valuetype ErrorHandler func(w http.ResponseWriter, r *http.Request, err error)----------------------------------------------------------------------------- Validation Errors ----------------------------------------------------------------------------- FieldError represents a validation error for a specific field.
// Create a new FieldError
fielderror := FieldError{
Field: "example",
Message: "example",
}type FieldError struct {
Field string `json:"field"`
Message string `json:"message"`
}| Field | Type | Description |
|---|---|---|
| Field | string | |
| Message | string |
Group represents a group of routes with a common prefix and middleware.
// Create a new Group
group := Group{
}type Group struct {
}Any registers a handler for all HTTP methods.
func (*Server) Any(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
DELETE registers a handler for DELETE requests.
func (*Server) DELETE(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
GET registers a handler for GET requests.
func (*Server) GET(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
Group creates a nested group with the given prefix. The prefix is appended to the parent group's prefix. Accepts Middleware (helix.Middleware is an alias for middleware.Middleware) or func(http.Handler) http.Handler.
func (*Group) Group(prefix string, mw ...any) *GroupParameters:
prefix (string)mw (...any)Returns:
HEAD registers a handler for HEAD requests.
func (*Server) HEAD(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
Handle registers a handler for the given method and pattern.
func (*Server) Handle(method, pattern string, handler http.HandlerFunc)Parameters:
method (string)pattern (string)handler (http.HandlerFunc)Returns: None
Mount mounts a module at the given prefix within a group.
func (*Group) Mount(prefix string, m Module, mw ...any)Parameters:
prefix (string)m (Module)mw (...any)Returns: None
MountFunc mounts a function as a module at the given prefix within a group.
func (*Group) MountFunc(prefix string, fn func(r RouteRegistrar), mw ...any)Parameters:
prefix (string)fn (func(r RouteRegistrar))mw (...any)Returns: None
OPTIONS registers a handler for OPTIONS requests.
func (*Group) OPTIONS(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
PATCH registers a handler for PATCH requests.
func (*Group) PATCH(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
POST registers a handler for POST requests.
func (*Server) POST(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
PUT registers a handler for PUT requests.
func (*Group) PUT(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
Resource creates a new ResourceBuilder for the given pattern within this group. The pattern is relative to the group's prefix. Optional middleware can be applied to all routes in the resource. Accepts helix.Middleware, middleware.Middleware, or func(http.Handler) http.Handler.
func (*Group) Resource(pattern string, mw ...any) *ResourceBuilderParameters:
pattern (string)mw (...any)Returns:
Static serves static files from the given file system root.
func (*Group) Static(pattern, root string)Parameters:
pattern (string)root (string)Returns: None
Use adds middleware to the group. Middleware is applied to all routes registered on this group. Accepts Middleware (helix.Middleware is an alias for middleware.Middleware) or func(http.Handler) http.Handler.
func (*Group) Use(mw ...any)Parameters:
mw (...any)Returns: None
Handler is a generic handler function that accepts a typed request and returns a typed response. The request type is automatically bound from path parameters, query parameters, headers, and JSON body. The response is automatically encoded as JSON.
// Example usage of Handler
var value Handler
// Initialize with appropriate valuetype Handler func(ctx context.Context, req Req) (Res, error)HealthBuilder provides a fluent interface for building health check endpoints.
// Create a new HealthBuilder
healthbuilder := HealthBuilder{
}type HealthBuilder struct {
}Health creates a new HealthBuilder.
func Health() *HealthBuilderParameters: None
Returns:
Check adds a health check for a named component.
func (*HealthBuilder) Check(name string, check HealthCheck) *HealthBuilderParameters:
name (string)check (HealthCheck)Returns:
CheckFunc adds a simple health check that returns an error.
func (*HealthBuilder) CheckFunc(name string, check func(ctx context.Context) error) *HealthBuilderParameters:
name (string)check (func(ctx context.Context) error)Returns:
Handler returns an http.HandlerFunc for the health check endpoint.
func (*HealthBuilder) Handler() http.HandlerFuncParameters: None
Returns:
Timeout sets the timeout for health checks.
func (*HealthBuilder) Timeout(d time.Duration) *HealthBuilderParameters:
d (time.Duration)Returns:
Version sets the application version shown in health responses.
func (*HealthBuilder) Version(v string) *HealthBuilderParameters:
v (string)Returns:
HealthCheck is a function that checks the health of a component.
// Example usage of HealthCheck
var value HealthCheck
// Initialize with appropriate valuetype HealthCheck func(ctx context.Context) HealthCheckResultHealthCheckResult contains the result of a health check.
// Create a new HealthCheckResult
healthcheckresult := HealthCheckResult{
Status: HealthStatus{},
Message: "example",
Latency: /* value */,
Details: map[],
}type HealthCheckResult struct {
Status HealthStatus `json:"status"`
Message string `json:"message,omitempty"`
Latency time.Duration `json:"latency_ms,omitempty"`
Details map[string]any `json:"details,omitempty"`
}| Field | Type | Description |
|---|---|---|
| Status | HealthStatus | |
| Message | string | |
| Latency | time.Duration | |
| Details | map[string]any |
HealthResponse is the response returned by the health endpoint.
// Create a new HealthResponse
healthresponse := HealthResponse{
Status: HealthStatus{},
Timestamp: /* value */,
Version: "example",
Components: map[],
}type HealthResponse struct {
Status HealthStatus `json:"status"`
Timestamp time.Time `json:"timestamp"`
Version string `json:"version,omitempty"`
Components map[string]HealthCheckResult `json:"components,omitempty"`
}| Field | Type | Description |
|---|---|---|
| Status | HealthStatus | |
| Timestamp | time.Time | |
| Version | string | |
| Components | map[string]HealthCheckResult |
HealthStatus represents the health status of a component.
// Example usage of HealthStatus
var value HealthStatus
// Initialize with appropriate valuetype HealthStatus stringIDRequest is a common request type for single-entity operations.
// Create a new IDRequest
idrequest := IDRequest{
ID: 42,
}type IDRequest struct {
ID int `path:"id"`
}| Field | Type | Description |
|---|---|---|
| ID | int |
ListRequest is a common request type for list operations.
// Create a new ListRequest
listrequest := ListRequest{
Page: 42,
Limit: 42,
Sort: "example",
Order: "example",
Search: "example",
}type ListRequest struct {
Page int `query:"page"`
Limit int `query:"limit"`
Sort string `query:"sort"`
Order string `query:"order"`
Search string `query:"search"`
}| Field | Type | Description |
|---|---|---|
| Page | int | |
| Limit | int | |
| Sort | string | |
| Order | string | |
| Search | string |
ListResponse wraps a list of entities with pagination metadata.
// Create a new ListResponse
listresponse := ListResponse{
Items: [],
Total: 42,
Page: 42,
Limit: 42,
}type ListResponse struct {
Items []Entity `json:"items"`
Total int `json:"total"`
Page int `json:"page,omitempty"`
Limit int `json:"limit,omitempty"`
}| Field | Type | Description |
|---|---|---|
| Items | []Entity | |
| Total | int | |
| Page | int | |
| Limit | int |
Middleware is a function that wraps an http.Handler to provide additional functionality. This is an alias to middleware.Middleware for convenience.
// Example usage of Middleware
var value Middleware
// Initialize with appropriate valuetype Middleware middleware.MiddlewareProvideMiddleware returns middleware that injects services into the request context. Services added this way are request-scoped.
func ProvideMiddleware(factory func(r *http.Request) T) MiddlewareParameters:
factory (func(r *http.Request) T)Returns:
} func (m *UserModule) Register(r RouteRegistrar) { r.GET("/", m.list) r.POST("/", m.create) r.GET("/{id}", m.get) } // Mount the module s.Mount("/users", &UserModule{store: store})
// Example implementation of Module
type MyModule struct {
// Add your fields here
}
func (m MyModule) Register(param1 RouteRegistrar) {
// Implement your logic here
return
}
type Module interface {
Register(r RouteRegistrar)
}| Method | Description |
|---|
ModuleFunc is a function that implements Module.
// Example usage of ModuleFunc
var value ModuleFunc
// Initialize with appropriate valuetype ModuleFunc func(r RouteRegistrar)Register implements Module.
func Register(service T)Parameters:
service (T)Returns: None
NoRequestHandler is a handler that takes no request body, only context.
// Example usage of NoRequestHandler
var value NoRequestHandler
// Initialize with appropriate valuetype NoRequestHandler func(ctx context.Context) (Res, error)NoResponseHandler is a handler that returns no response body.
// Example usage of NoResponseHandler
var value NoResponseHandler
// Initialize with appropriate valuetype NoResponseHandler func(ctx context.Context, req Req) errorOption configures a Server.
// Example usage of Option
var value Option
// Initialize with appropriate valuetype Option func(*Server)HideBanner hides the banner and sets the banner to an empty string.
func HideBanner() OptionParameters: None
Returns:
WithAddr sets the address the server listens on. Default is ":8080".
func WithAddr(addr string) OptionParameters:
addr (string)Returns:
WithBasePath sets a base path prefix for all routes. All registered routes will be prefixed with this path. For example, with base path "/api/v1", a route "/users" becomes "/api/v1/users". The base path should start with "/" but should not end with "/" (it will be normalized).
func WithBasePath(path string) OptionParameters:
path (string)Returns:
WithCustomBanner sets a custom banner for the server.
func WithCustomBanner(banner string) OptionParameters:
banner (string)Returns:
WithErrorHandler sets a custom error handler for the server. The error handler will be called whenever an error occurs in a handler. If not set, the default error handling (RFC 7807 Problem Details) is used.
func WithErrorHandler(handler ErrorHandler) OptionParameters:
handler (ErrorHandler)Returns:
WithGracePeriod sets the maximum duration to wait for active connections to finish during graceful shutdown.
func WithGracePeriod(d time.Duration) OptionParameters:
d (time.Duration)Returns:
WithIdleTimeout sets the maximum amount of time to wait for the next request when keep-alives are enabled.
func WithIdleTimeout(d time.Duration) OptionParameters:
d (time.Duration)Returns:
WithMaxHeaderBytes sets the maximum size of request headers.
func WithMaxHeaderBytes(n int) OptionParameters:
n (int)Returns:
WithReadTimeout sets the maximum duration for reading the entire request.
func WithReadTimeout(d time.Duration) OptionParameters:
d (time.Duration)Returns:
WithTLS configures the server to use TLS with the provided certificate and key files.
func WithTLS(certFile, keyFile string) OptionParameters:
certFile (string)keyFile (string)Returns:
WithTLSConfig sets a custom TLS configuration for the server.
func WithTLSConfig(config *tls.Config) OptionParameters:
config (*tls.Config)Returns:
WithWriteTimeout sets the maximum duration before timing out writes of the response.
func WithWriteTimeout(d time.Duration) OptionParameters:
d (time.Duration)Returns:
PaginatedResponse wraps a list response with pagination metadata.
// Create a new PaginatedResponse
paginatedresponse := PaginatedResponse{
Items: [],
Total: 42,
Page: 42,
Limit: 42,
TotalPages: 42,
HasMore: true,
NextCursor: "example",
}type PaginatedResponse struct {
Items []T `json:"items"`
Total int `json:"total"`
Page int `json:"page"`
Limit int `json:"limit"`
TotalPages int `json:"total_pages"`
HasMore bool `json:"has_more"`
NextCursor string `json:"next_cursor,omitempty"`
}| Field | Type | Description |
|---|---|---|
| Items | []T | |
| Total | int | |
| Page | int | |
| Limit | int | |
| TotalPages | int | |
| HasMore | bool | |
| NextCursor | string |
NewCursorResponse creates a new cursor-based paginated response.
func NewCursorResponse(items []T, total int, nextCursor string) *ast.IndexExprParameters:
items ([]T)total (int)nextCursor (string)Returns:
NewPaginatedResponse creates a new paginated response.
func NewPaginatedResponse(items []T, total, page, limit int) *ast.IndexExprParameters:
items ([]T)total (int)page (int)limit (int)Returns:
Pagination contains common pagination parameters. Use with struct embedding for automatic binding. Example: type ListUsersRequest struct { helix.Pagination Status string query:"status" }
// Create a new Pagination
pagination := Pagination{
Page: 42,
Limit: 42,
Sort: "example",
Order: "example",
Cursor: "example",
}type Pagination struct {
Page int `query:"page"`
Limit int `query:"limit"`
Sort string `query:"sort"`
Order string `query:"order"`
Cursor string `query:"cursor"`
}| Field | Type | Description |
|---|---|---|
| Page | int | |
| Limit | int | |
| Sort | string | |
| Order | string | |
| Cursor | string |
BindPagination extracts pagination from the request with defaults.
func (*Ctx) BindPagination(defaultLimit, maxLimit int) PaginationParameters:
defaultLimit (int)maxLimit (int)Returns:
GetLimit returns the limit with a default and maximum.
func (Pagination) GetLimit(defaultLimit, maxLimit int) intParameters:
defaultLimit (int)maxLimit (int)Returns:
GetOffset calculates the offset for SQL queries.
func (Pagination) GetOffset(limit int) intParameters:
limit (int)Returns:
GetOrder returns the order (asc/desc) with a default of desc.
func (Pagination) GetOrder() stringParameters: None
Returns:
GetPage returns the page number with a default of 1.
func (Pagination) GetPage() intParameters: None
Returns:
GetSort returns the sort field with a default.
func (Pagination) GetSort(defaultSort string, allowed []string) stringParameters:
defaultSort (string)allowed ([]string)Returns:
IsAscending returns true if the order is ascending.
func (Pagination) IsAscending() boolParameters: None
Returns:
Problem represents an RFC 7807 Problem Details for HTTP APIs. See: https://tools.ietf.org/html/rfc7807
// Create a new Problem
problem := Problem{
Type: "example",
Title: "example",
Status: 42,
Detail: "example",
Instance: "example",
Err: error{},
}type Problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
Instance string `json:"instance,omitempty"`
Err error `json:"-"`
}| Field | Type | Description |
|---|---|---|
| Type | string | Type is a URI reference that identifies the problem type. |
| Title | string | Title is a short, human-readable summary of the problem type. |
| Status | int | Status is the HTTP status code for this problem. |
| Detail | string | Detail is a human-readable explanation specific to this occurrence of the problem. |
| Instance | string | Instance is a URI reference that identifies the specific occurrence of the problem. |
| Err | error | Err is the error that caused the problem. |
BadGatewayf creates a 502 Bad Gateway Problem with a formatted detail message.
func BadGatewayf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
BadRequestf creates a 400 Bad Request Problem with a formatted detail message.
func BadRequestf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
Conflictf creates a 409 Conflict Problem with a formatted detail message.
func Conflictf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
Forbiddenf creates a 403 Forbidden Problem with a formatted detail message.
func Forbiddenf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
GatewayTimeoutf creates a 504 Gateway Timeout Problem with a formatted detail message.
func GatewayTimeoutf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
Gonef creates a 410 Gone Problem with a formatted detail message.
func Gonef(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
Internalf creates a 500 Internal Server Error Problem with a formatted detail message.
func Internalf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
MethodNotAllowedf creates a 405 Method Not Allowed Problem with a formatted detail message.
func MethodNotAllowedf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
NewProblem creates a new Problem with the given status, type, and title.
func NewProblem(status int, problemType, title string) ProblemParameters:
status (int)problemType (string)title (string)Returns:
NotFoundf creates a 404 Not Found Problem with a formatted detail message.
func NotFoundf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
NotImplementedf creates a 501 Not Implemented Problem with a formatted detail message.
func NotImplementedf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
ProblemFromStatus creates a Problem from an HTTP status code.
func ProblemFromStatus(status int) ProblemParameters:
status (int)Returns:
ServiceUnavailablef creates a 503 Service Unavailable Problem with a formatted detail message.
func ServiceUnavailablef(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
TooManyRequestsf creates a 429 Too Many Requests Problem with a formatted detail message.
func TooManyRequestsf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
Unauthorizedf creates a 401 Unauthorized Problem with a formatted detail message.
func Unauthorizedf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
UnprocessableEntityf creates a 422 Unprocessable Entity Problem with a formatted detail message.
func UnprocessableEntityf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
Error implements the error interface.
func (*ValidationErrors) Error() stringParameters: None
Returns:
func (Problem) WithDetail(detail string) ProblemParameters:
detail (string)Returns:
WithDetailf returns a copy of the Problem with the given detail message.
func (Problem) WithDetailf(format string, args ...any) ProblemParameters:
format (string)args (...any)Returns:
WithStack returns a copy of the Problem with the given stack trace.
func (Problem) WithErr(err error) ProblemParameters:
err (error)Returns:
WithInstance returns a copy of the Problem with the given instance URI.
func (Problem) WithInstance(instance string) ProblemParameters:
instance (string)Returns:
WithType returns a copy of the Problem with the given type URI.
func (Problem) WithType(problemType string) ProblemParameters:
problemType (string)Returns:
ResourceBuilder provides a fluent interface for defining REST resource routes.
// Create a new ResourceBuilder
resourcebuilder := ResourceBuilder{
}type ResourceBuilder struct {
}CRUD registers all standard CRUD handlers in one call. Handlers: list, create, get, update, delete
func (*ResourceBuilder) CRUD(list, create, get, update, delete http.HandlerFunc) *ResourceBuilderParameters:
list (http.HandlerFunc)create (http.HandlerFunc)get (http.HandlerFunc)update (http.HandlerFunc)delete (http.HandlerFunc)Returns:
Create registers a POST handler for creating resources (e.g., POST /users).
func (**ast.IndexExpr) Create(h *ast.IndexListExpr) **ast.IndexExprParameters:
h (*ast.IndexListExpr)Returns:
Custom registers a handler with a custom method and path suffix. The suffix is appended to the base pattern. Example: Custom("POST", "/{id}/archive", archiveHandler) for POST /users/{id}/archive
func (**ast.IndexExpr) Custom(method, suffix string, handler http.HandlerFunc) **ast.IndexExprParameters:
method (string)suffix (string)handler (http.HandlerFunc)Returns:
Delete registers a DELETE handler for deleting a resource (e.g., DELETE /users/{id}).
func (**ast.IndexExpr) Delete(h *ast.IndexExpr) **ast.IndexExprParameters:
h (*ast.IndexExpr)Returns:
Destroy is an alias for Delete.
func (*ResourceBuilder) Destroy(handler http.HandlerFunc) *ResourceBuilderParameters:
handler (http.HandlerFunc)Returns:
Get registers a GET handler for a single resource (e.g., GET /users/{id}).
func Get() (T, bool)Parameters: None
Returns:
Index is an alias for List.
func (*ResourceBuilder) Index(handler http.HandlerFunc) *ResourceBuilderParameters:
handler (http.HandlerFunc)Returns:
List registers a GET handler for the collection (e.g., GET /users).
func (**ast.IndexExpr) List(h *ast.IndexListExpr) **ast.IndexExprParameters:
h (*ast.IndexListExpr)Returns:
Patch registers a PATCH handler for partial updates (e.g., PATCH /users/{id}).
func (**ast.IndexExpr) Patch(h *ast.IndexListExpr) **ast.IndexExprParameters:
h (*ast.IndexListExpr)Returns:
ReadOnly registers only read handlers (list and get).
func (*ResourceBuilder) ReadOnly(list, get http.HandlerFunc) *ResourceBuilderParameters:
list (http.HandlerFunc)get (http.HandlerFunc)Returns:
Show is an alias for Get.
func (*ResourceBuilder) Show(handler http.HandlerFunc) *ResourceBuilderParameters:
handler (http.HandlerFunc)Returns:
Store is an alias for Create.
func (*ResourceBuilder) Store(handler http.HandlerFunc) *ResourceBuilderParameters:
handler (http.HandlerFunc)Returns:
Update registers a PUT handler for updating a resource (e.g., PUT /users/{id}).
func (**ast.IndexExpr) Update(h *ast.IndexListExpr) **ast.IndexExprParameters:
h (*ast.IndexListExpr)Returns:
RouteInfo contains information about a registered route.
// Create a new RouteInfo
routeinfo := RouteInfo{
Method: "example",
Pattern: "example",
}type RouteInfo struct {
Method string
Pattern string
}| Field | Type | Description |
|---|---|---|
| Method | string | |
| Pattern | string |
RouteRegistrar is an interface for registering routes. Both Server and Group implement this interface.
// Example implementation of RouteRegistrar
type MyRouteRegistrar struct {
// Add your fields here
}
func (m MyRouteRegistrar) GET(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) POST(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) PUT(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) PATCH(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) DELETE(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) OPTIONS(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) HEAD(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) Handle(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) Group(param1 string, param2 ...any) *Group {
// Implement your logic here
return
}
func (m MyRouteRegistrar) Resource(param1 string, param2 ...any) *ResourceBuilder {
// Implement your logic here
return
}
type RouteRegistrar interface {
GET(pattern string, handler http.HandlerFunc)
POST(pattern string, handler http.HandlerFunc)
PUT(pattern string, handler http.HandlerFunc)
PATCH(pattern string, handler http.HandlerFunc)
DELETE(pattern string, handler http.HandlerFunc)
OPTIONS(pattern string, handler http.HandlerFunc)
HEAD(pattern string, handler http.HandlerFunc)
Handle(method, pattern string, handler http.HandlerFunc)
Group(prefix string, mw ...any) *Group
Resource(pattern string, mw ...any) *ResourceBuilder
}| Method | Description |
|---|
Router handles HTTP request routing.
// Create a new Router
router := Router{
}type Router struct {
}Handle registers a new route with the given method and pattern.
func Handle(h *ast.IndexListExpr) http.HandlerFuncParameters:
h (*ast.IndexListExpr)Returns:
Routes returns all registered routes.
func (*Server) Routes() []RouteInfoParameters: None
Returns:
ServeHTTP implements http.Handler.
func (*Server) ServeHTTP(w http.ResponseWriter, r *http.Request)Parameters:
w (http.ResponseWriter)r (*http.Request)Returns: None
Server is the main HTTP server for the Helix framework.
// Create a new Server
server := Server{
}type Server struct {
}Default creates a new Server with sensible defaults for development. It includes RequestID, Logger (dev format), and Recover middleware.
func Default(opts ...Option) *ServerParameters:
opts (...Option)Returns:
New creates a new Server with the provided options.
func New(opts ...Option) *ServerParameters:
opts (...Option)Returns:
Addr returns the address the server is configured to listen on.
func (*Server) Addr() stringParameters: None
Returns:
Any registers a handler for all HTTP methods.
func (*Server) Any(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
Build pre-compiles the middleware chain for optimal performance. This is called automatically before the server starts, but can be called manually after all routes and middleware are registered.
func (*Server) Build()Parameters: None
Returns: None
CONNECT registers a handler for CONNECT requests.
func (*Server) CONNECT(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
DELETE registers a handler for DELETE requests.
func (*Server) DELETE(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
GET registers a handler for GET requests.
func (*Server) GET(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
Group creates a new route group with the given prefix. The prefix is prepended to all routes registered on the group. Accepts Middleware (helix.Middleware is an alias for middleware.Middleware) or func(http.Handler) http.Handler.
func (*Group) Group(prefix string, mw ...any) *GroupParameters:
prefix (string)mw (...any)Returns:
HEAD registers a handler for HEAD requests.
func (*Server) HEAD(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
Handle registers a handler for the given method and pattern.
func (*Server) Handle(method, pattern string, handler http.HandlerFunc)Parameters:
method (string)pattern (string)handler (http.HandlerFunc)Returns: None
Mount mounts a module at the given prefix. The module's routes are prefixed with the given path.
func (*Group) Mount(prefix string, m Module, mw ...any)Parameters:
prefix (string)m (Module)mw (...any)Returns: None
MountFunc mounts a function as a module at the given prefix.
func (*Group) MountFunc(prefix string, fn func(r RouteRegistrar), mw ...any)Parameters:
prefix (string)fn (func(r RouteRegistrar))mw (...any)Returns: None
OPTIONS registers a handler for OPTIONS requests.
func (*Group) OPTIONS(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
OnStart registers a function to be called when the server starts. Multiple functions can be registered and will be called in order.
func (*Server) OnStart(fn func(s *Server))Parameters:
fn (func(s *Server))Returns: None
OnStop registers a function to be called when the server stops. Multiple functions can be registered and will be called in order. The context passed to the function has the grace period as its deadline.
func (*Server) OnStop(fn func(ctx context.Context, s *Server))Parameters:
fn (func(ctx context.Context, s *Server))Returns: None
PATCH registers a handler for PATCH requests.
func (*Server) PATCH(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
POST registers a handler for POST requests.
func (*Group) POST(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
PUT registers a handler for PUT requests.
func (*Group) PUT(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
PrintRoutes prints all registered routes to the given writer. Routes are sorted by pattern, then by method.
func (*Server) PrintRoutes(w io.Writer)Parameters:
w (io.Writer)Returns: None
Resource creates a new ResourceBuilder for the given pattern. The pattern should be the base path for the resource (e.g., "/users"). Optional middleware can be applied to all routes in the resource. Accepts Middleware (helix.Middleware is an alias for middleware.Middleware) or func(http.Handler) http.Handler.
func (*Server) Resource(pattern string, mw ...any) *ResourceBuilderParameters:
pattern (string)mw (...any)Returns:
Routes returns all registered routes.
func (*Server) Routes() []RouteInfoParameters: None
Returns:
Run starts the server and blocks until the context is canceled or a shutdown signal is received. It performs graceful shutdown, waiting for active connections to finish within the grace period.
func (*Server) Run(ctx context.Context) errorParameters:
ctx (context.Context)Returns:
ServeHTTP implements the http.Handler interface.
func (*Router) ServeHTTP(w http.ResponseWriter, req *http.Request)Parameters:
w (http.ResponseWriter)req (*http.Request)Returns: None
Shutdown gracefully shuts down the server without interrupting active connections. It waits for the grace period for active connections to finish.
func (*Server) Shutdown(ctx context.Context) errorParameters:
ctx (context.Context)Returns:
Start starts the server and blocks until shutdown. If an address is provided, it will be used instead of the WithAddr option. If the address is not provided and the WithAddr option is not set, it will use ":8080". This is a convenience method that calls Run with a background context.
func (*Server) Start(addr ...string) errorParameters:
addr (...string)Returns:
Static serves static files from the given file system root.
func (*Server) Static(pattern, root string)Parameters:
pattern (string)root (string)Returns: None
TRACE registers a handler for TRACE requests.
func (*Server) TRACE(pattern string, handler http.HandlerFunc)Parameters:
pattern (string)handler (http.HandlerFunc)Returns: None
Use adds middleware to the server's middleware chain. Middleware is executed in the order it is added. Accepts Middleware (helix.Middleware is an alias for middleware.Middleware) or func(http.Handler) http.Handler.
func (*Group) Use(mw ...any)Parameters:
mw (...any)Returns: None
TypedResourceBuilder provides a fluent interface for defining typed REST resource routes.
// Create a new TypedResourceBuilder
typedresourcebuilder := TypedResourceBuilder{
}type TypedResourceBuilder struct {
}TypedResource creates a typed resource builder for the given entity type. This provides a fluent API for registering typed handlers for CRUD operations. Example: helix.TypedResourceUser. List(listUsers). Create(createUser). Get(getUser). Update(updateUser). Delete(deleteUser)
func TypedResource(s *Server, pattern string, mw ...any) **ast.IndexExprParameters:
s (*Server)pattern (string)mw (...any)Returns:
TypedResourceForGroup creates a typed resource builder within a group.
func TypedResourceForGroup(g *Group, pattern string, mw ...any) **ast.IndexExprParameters:
g (*Group)pattern (string)mw (...any)Returns:
Create registers a typed POST handler for creating resources. Handler signature: func(ctx, CreateReq) (Entity, error)
func (**ast.IndexExpr) Create(h *ast.IndexListExpr) **ast.IndexExprParameters:
h (*ast.IndexListExpr)Returns:
Custom registers a handler with a custom method and path suffix.
func (**ast.IndexExpr) Custom(method, suffix string, handler http.HandlerFunc) **ast.IndexExprParameters:
method (string)suffix (string)handler (http.HandlerFunc)Returns:
Delete registers a typed DELETE handler for deleting a resource. Handler signature: func(ctx, IDRequest) error
func (**ast.IndexExpr) Delete(h *ast.IndexExpr) **ast.IndexExprParameters:
h (*ast.IndexExpr)Returns:
Get registers a typed GET handler for a single resource. Handler signature: func(ctx, IDRequest) (Entity, error)
func Get() (T, bool)Parameters: None
Returns:
List registers a typed GET handler for the collection. Handler signature: func(ctx, ListReq) (ListResponse[Entity], error)
func (**ast.IndexExpr) List(h *ast.IndexListExpr) **ast.IndexExprParameters:
h (*ast.IndexListExpr)Returns:
Patch registers a typed PATCH handler for partial updates.
func (**ast.IndexExpr) Patch(h *ast.IndexListExpr) **ast.IndexExprParameters:
h (*ast.IndexListExpr)Returns:
Update registers a typed PUT handler for updating a resource. The request type should include the ID from path and the update data.
func (**ast.IndexExpr) Update(h *ast.IndexListExpr) **ast.IndexExprParameters:
h (*ast.IndexListExpr)Returns:
Validatable is an interface for types that can validate themselves.
// Example implementation of Validatable
type MyValidatable struct {
// Add your fields here
}
func (m MyValidatable) Validate() error {
// Implement your logic here
return
}
type Validatable interface {
Validate() error
}| Method | Description |
|---|
ValidationErrors collects multiple validation errors for RFC 7807 response. Implements the error interface and can be returned from Validate() methods.
// Create a new ValidationErrors
validationerrors := ValidationErrors{
}type ValidationErrors struct {
}NewValidationErrors creates a new empty ValidationErrors collector.
func NewValidationErrors() *ValidationErrorsParameters: None
Returns:
Add adds a validation error for a specific field.
func (*ValidationErrors) Add(field, message string)Parameters:
field (string)message (string)Returns: None
Addf adds a validation error for a specific field with a formatted message.
func (*ValidationErrors) Addf(field, format string, args ...any)Parameters:
field (string)format (string)args (...any)Returns: None
Err returns nil if there are no errors, otherwise returns the ValidationErrors. This is useful for the common pattern: return v.Err()
func (*ValidationErrors) Err() errorParameters: None
Returns:
Error implements the error interface.
func (*ValidationErrors) Error() stringParameters: None
Returns:
Errors returns the list of field errors.
func (*ValidationErrors) Errors() []FieldErrorParameters: None
Returns:
HasErrors returns true if there are any validation errors.
func (*ValidationErrors) HasErrors() boolParameters: None
Returns:
Len returns the number of validation errors.
func (*ValidationErrors) Len() intParameters: None
Returns:
ToProblem converts ValidationErrors to a ValidationProblem for RFC 7807 response.
func (*ValidationErrors) ToProblem() ValidationProblemParameters: None
Returns:
ValidationProblem is an RFC 7807 Problem with validation errors extension.
// Create a new ValidationProblem
validationproblem := ValidationProblem{
Errors: [],
}type ValidationProblem struct {
Problem
Errors []FieldError `json:"errors,omitempty"`
}| Field | Type | Description |
|---|---|---|
| *Problem | Problem | |
| Errors | []FieldError |
Accepted writes a 202 Accepted JSON response.
func Accepted(w http.ResponseWriter, v any) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
v | any |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of Accepted
result := Accepted(/* parameters */)Attachment sets the Content-Disposition header to attachment with the given filename.
func (*Ctx) Attachment(filename string) *CtxParameters:
| Parameter | Type | Description |
|---|---|---|
filename | string |
Returns:
| Type | Description |
|---|---|
*Ctx |
Example:
// Example usage of Attachment
result := Attachment(/* parameters */)BadRequest writes a 400 Bad Request error response.
func (*Ctx) BadRequest(message string) errorParameters:
| Parameter | Type | Description |
|---|---|---|
message | string |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of BadRequest
result := BadRequest(/* parameters */)Bind binds path parameters, query parameters, headers, and JSON body to a struct. The binding sources are determined by struct tags: - path:"name" - binds from URL path parameters - query:"name" - binds from URL query parameters - header:"name" - binds from HTTP headers - json:"name" - binds from JSON body - form:"name" - binds from form data
func Bind(r *http.Request) (T, error)Parameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request |
Returns:
| Type | Description |
|---|---|
T | |
error |
Example:
// Example usage of Bind
result := Bind(/* parameters */)BindAndValidate binds and validates a request. If the bound type implements Validatable, Validate() is called after binding.
func BindAndValidate(r *http.Request) (T, error)Parameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request |
Returns:
| Type | Description |
|---|---|
T | |
error |
Example:
// Example usage of BindAndValidate
result := BindAndValidate(/* parameters */)BindHeader binds HTTP headers to a struct. Uses the header struct tag to determine field names.
func BindHeader(r *http.Request) (T, error)Parameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request |
Returns:
| Type | Description |
|---|---|
T | |
error |
Example:
// Example usage of BindHeader
result := BindHeader(/* parameters */)BindJSON binds the JSON request body to a struct.
func (*Ctx) BindJSON(v any) errorParameters:
| Parameter | Type | Description |
|---|---|---|
v | any |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of BindJSON
result := BindJSON(/* parameters */)BindPath binds URL path parameters to a struct. Uses the path struct tag to determine field names.
func BindPath(r *http.Request) (T, error)Parameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request |
Returns:
| Type | Description |
|---|---|
T | |
error |
Example:
// Example usage of BindPath
result := BindPath(/* parameters */)BindQuery binds URL query parameters to a struct. Uses the query struct tag to determine field names.
func BindQuery(r *http.Request) (T, error)Parameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request |
Returns:
| Type | Description |
|---|---|
T | |
error |
Example:
// Example usage of BindQuery
result := BindQuery(/* parameters */)Blob writes binary data with the given content type.
func Blob(w http.ResponseWriter, status int, contentType string, data []byte) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
status | int | |
contentType | string | |
data | []byte |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of Blob
result := Blob(/* parameters */)Created writes a 201 Created JSON response.
func (*Ctx) Created(v any) errorParameters:
| Parameter | Type | Description |
|---|---|---|
v | any |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of Created
result := Created(/* parameters */)Error writes an error response with the given status code and message.
func Error(w http.ResponseWriter, status int, message string) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
status | int | |
message | string |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of Error
result := Error(/* parameters */)File serves a file with the given content type.
func File(w http.ResponseWriter, r *http.Request, path string)Parameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
r | *http.Request | |
path | string |
Returns: None
Example:
// Example usage of File
result := File(/* parameters */)Forbidden writes a 403 Forbidden error response.
func (*Ctx) Forbidden(message string) errorParameters:
| Parameter | Type | Description |
|---|---|---|
message | string |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of Forbidden
result := Forbidden(/* parameters */)FromContext retrieves a service from the context or falls back to global registry.
func FromContext(ctx context.Context) (T, bool)Parameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context |
Returns:
| Type | Description |
|---|---|
T | |
bool |
Example:
// Example usage of FromContext
result := FromContext(/* parameters */)Get retrieves a service from the global registry. Returns the zero value and false if not found.
func Get() (T, bool)Parameters: None
Returns:
| Type | Description |
|---|---|
T | |
bool |
Example:
// Example usage of Get
result := Get(/* parameters */)HTML writes an HTML response with the given status code.
func HTML(w http.ResponseWriter, status int, html string) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
status | int | |
html | string |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of HTML
result := HTML(/* parameters */)Handle wraps a generic Handler into an http.HandlerFunc. It automatically: - Binds the request to the Req type - Calls the handler with the context and request - Encodes the response as JSON - Handles errors using RFC 7807 Problem Details
func Handle(h *ast.IndexListExpr) http.HandlerFuncParameters:
| Parameter | Type | Description |
|---|---|---|
h | *ast.IndexListExpr |
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of Handle
result := Handle(/* parameters */)HandleAccepted wraps a generic Handler into an http.HandlerFunc that returns 202 Accepted. Useful for async operations where processing happens in the background.
func HandleAccepted(h *ast.IndexListExpr) http.HandlerFuncParameters:
| Parameter | Type | Description |
|---|---|---|
h | *ast.IndexListExpr |
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of HandleAccepted
result := HandleAccepted(/* parameters */)HandleCreated wraps a generic Handler into an http.HandlerFunc that returns 201 Created. This is a convenience wrapper for HandleWithStatus(http.StatusCreated, h).
func HandleCreated(h *ast.IndexListExpr) http.HandlerFuncParameters:
| Parameter | Type | Description |
|---|---|---|
h | *ast.IndexListExpr |
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of HandleCreated
result := HandleCreated(/* parameters */)HandleCtx wraps a CtxHandler into an http.HandlerFunc. Errors returned from the handler are automatically converted to RFC 7807 responses.
func HandleCtx(h CtxHandler) http.HandlerFuncParameters:
| Parameter | Type | Description |
|---|---|---|
h | CtxHandler |
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of HandleCtx
result := HandleCtx(/* parameters */)HandleEmpty wraps an EmptyHandler into an http.HandlerFunc. Returns 204 No Content on success.
func HandleEmpty(h EmptyHandler) http.HandlerFuncParameters:
| Parameter | Type | Description |
|---|---|---|
h | EmptyHandler |
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of HandleEmpty
result := HandleEmpty(/* parameters */)HandleErrorDefault provides the default error handling logic. This can be called from custom error handlers to fall back to default behavior.
func HandleErrorDefault(w http.ResponseWriter, r *http.Request, err error)Parameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
r | *http.Request | |
err | error |
Returns: None
Example:
// Example usage of HandleErrorDefault
result := HandleErrorDefault(/* parameters */)HandleNoRequest wraps a NoRequestHandler into an http.HandlerFunc. Useful for endpoints that don't need request binding (e.g., GET /users).
func HandleNoRequest(h *ast.IndexExpr) http.HandlerFuncParameters:
| Parameter | Type | Description |
|---|---|---|
h | *ast.IndexExpr |
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of HandleNoRequest
result := HandleNoRequest(/* parameters */)HandleNoResponse wraps a NoResponseHandler into an http.HandlerFunc. Returns 204 No Content on success.
func HandleNoResponse(h *ast.IndexExpr) http.HandlerFuncParameters:
| Parameter | Type | Description |
|---|---|---|
h | *ast.IndexExpr |
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of HandleNoResponse
result := HandleNoResponse(/* parameters */)HandleWithStatus wraps a generic Handler into an http.HandlerFunc with a custom success status code.
func HandleWithStatus(status int, h *ast.IndexListExpr) http.HandlerFuncParameters:
| Parameter | Type | Description |
|---|---|---|
status | int | |
h | *ast.IndexListExpr |
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of HandleWithStatus
result := HandleWithStatus(/* parameters */)Inline sets the Content-Disposition header to inline with the given filename.
func Inline(w http.ResponseWriter, filename string)Parameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
filename | string |
Returns: None
Example:
// Example usage of Inline
result := Inline(/* parameters */)InternalServerError writes a 500 Internal Server Error response.
func InternalServerError(w http.ResponseWriter, message string) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
message | string |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of InternalServerError
result := InternalServerError(/* parameters */)JSON writes a JSON response with the given status code. Uses pooled buffer for zero-allocation in the hot path.
func (*Ctx) JSON(status int, v any) errorParameters:
| Parameter | Type | Description |
|---|---|---|
status | int | |
v | any |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of JSON
result := JSON(/* parameters */)JSONPretty writes a pretty-printed JSON response with the given status code.
func JSONPretty(w http.ResponseWriter, status int, v any, indent string) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
status | int | |
v | any | |
indent | string |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of JSONPretty
result := JSONPretty(/* parameters */)LivenessHandler returns a simple liveness probe handler. Returns 200 OK if the server is running.
func LivenessHandler() http.HandlerFuncParameters: None
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of LivenessHandler
result := LivenessHandler(/* parameters */)MustFromContext retrieves a service from context or panics.
func MustFromContext(ctx context.Context) TParameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context |
Returns:
| Type | Description |
|---|---|
T |
Example:
// Example usage of MustFromContext
result := MustFromContext(/* parameters */)MustGet retrieves a service from the global registry or panics.
func MustGet() TParameters: None
Returns:
| Type | Description |
|---|---|
T |
Example:
// Example usage of MustGet
result := MustGet(/* parameters */)NoContent writes a 204 No Content response.
func (*Ctx) NoContent() errorParameters: None
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of NoContent
result := NoContent(/* parameters */)NotFound writes a 404 Not Found error response.
func NotFound(w http.ResponseWriter, message string) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
message | string |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of NotFound
result := NotFound(/* parameters */)OK writes a 200 OK JSON response.
func OK(w http.ResponseWriter, v any) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
v | any |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of OK
result := OK(/* parameters */)Param returns the value of a path parameter. Returns an empty string if the parameter does not exist.
func (*Ctx) Param(name string) stringParameters:
| Parameter | Type | Description |
|---|---|---|
name | string |
Returns:
| Type | Description |
|---|---|
string |
Example:
// Example usage of Param
result := Param(/* parameters */)ParamInt returns the value of a path parameter as an int. Returns an error if the parameter does not exist or cannot be parsed.
func (*Ctx) ParamInt(name string) (int, error)Parameters:
| Parameter | Type | Description |
|---|---|---|
name | string |
Returns:
| Type | Description |
|---|---|
int | |
error |
Example:
// Example usage of ParamInt
result := ParamInt(/* parameters */)ParamInt64 returns the value of a path parameter as an int64. Returns an error if the parameter does not exist or cannot be parsed.
func (*Ctx) ParamInt64(name string) (int64, error)Parameters:
| Parameter | Type | Description |
|---|---|---|
name | string |
Returns:
| Type | Description |
|---|---|
int64 | |
error |
Example:
// Example usage of ParamInt64
result := ParamInt64(/* parameters */)ParamUUID returns the value of a path parameter validated as a UUID. Returns an error if the parameter does not exist or is not a valid UUID format.
func ParamUUID(r *http.Request, name string) (string, error)Parameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request | |
name | string |
Returns:
| Type | Description |
|---|---|
string | |
error |
Example:
// Example usage of ParamUUID
result := ParamUUID(/* parameters */)Query returns the first value of a query parameter. Returns an empty string if the parameter does not exist.
func Query(r *http.Request, name string) stringParameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request | |
name | string |
Returns:
| Type | Description |
|---|---|
string |
Example:
// Example usage of Query
result := Query(/* parameters */)QueryBool returns the first value of a query parameter as a bool. Returns false if the parameter does not exist or cannot be parsed. Accepts "1", "t", "T", "true", "TRUE", "True" as true. Accepts "0", "f", "F", "false", "FALSE", "False" as false.
func QueryBool(r *http.Request, name string) boolParameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request | |
name | string |
Returns:
| Type | Description |
|---|---|
bool |
Example:
// Example usage of QueryBool
result := QueryBool(/* parameters */)QueryDefault returns the first value of a query parameter or a default value.
func (*Ctx) QueryDefault(name, defaultVal string) stringParameters:
| Parameter | Type | Description |
|---|---|---|
name | string | |
defaultVal | string |
Returns:
| Type | Description |
|---|---|
string |
Example:
// Example usage of QueryDefault
result := QueryDefault(/* parameters */)QueryFloat64 returns the first value of a query parameter as a float64. Returns the default value if the parameter does not exist or cannot be parsed.
func QueryFloat64(r *http.Request, name string, defaultVal float64) float64Parameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request | |
name | string | |
defaultVal | float64 |
Returns:
| Type | Description |
|---|---|
float64 |
Example:
// Example usage of QueryFloat64
result := QueryFloat64(/* parameters */)QueryInt returns the first value of a query parameter as an int. Returns the default value if the parameter does not exist or cannot be parsed.
func QueryInt(r *http.Request, name string, defaultVal int) intParameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request | |
name | string | |
defaultVal | int |
Returns:
| Type | Description |
|---|---|
int |
Example:
// Example usage of QueryInt
result := QueryInt(/* parameters */)QueryInt64 returns the first value of a query parameter as an int64. Returns the default value if the parameter does not exist or cannot be parsed.
func (*Ctx) QueryInt64(name string, defaultVal int64) int64Parameters:
| Parameter | Type | Description |
|---|---|---|
name | string | |
defaultVal | int64 |
Returns:
| Type | Description |
|---|---|
int64 |
Example:
// Example usage of QueryInt64
result := QueryInt64(/* parameters */)QuerySlice returns all values of a query parameter as a string slice. Returns nil if the parameter does not exist.
func QuerySlice(r *http.Request, name string) []stringParameters:
| Parameter | Type | Description |
|---|---|---|
r | *http.Request | |
name | string |
Returns:
| Type | Description |
|---|---|
[]string |
Example:
// Example usage of QuerySlice
result := QuerySlice(/* parameters */)ReadinessHandler returns a simple readiness probe handler. Uses the provided checks to determine readiness.
func ReadinessHandler(checks ...func(ctx context.Context) error) http.HandlerFuncParameters:
| Parameter | Type | Description |
|---|---|---|
checks | ...func(ctx context.Context) error |
Returns:
| Type | Description |
|---|---|
http.HandlerFunc |
Example:
// Example usage of ReadinessHandler
result := ReadinessHandler(/* parameters */)Redirect redirects the request to the given URL.
func Redirect(w http.ResponseWriter, r *http.Request, url string, code int)Parameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
r | *http.Request | |
url | string | |
code | int |
Returns: None
Example:
// Example usage of Redirect
result := Redirect(/* parameters */)Register registers a service in the global registry by its type.
func (ModuleFunc) Register(r RouteRegistrar)Parameters:
| Parameter | Type | Description |
|---|---|---|
r | RouteRegistrar |
Returns: None
Example:
// Example usage of Register
result := Register(/* parameters */)Stream streams the content from the reader to the response.
func Stream(w http.ResponseWriter, contentType string, reader io.Reader) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
contentType | string | |
reader | io.Reader |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of Stream
result := Stream(/* parameters */)Text writes a plain text response with the given status code.
func Text(w http.ResponseWriter, status int, text string) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
status | int | |
text | string |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of Text
result := Text(/* parameters */)Unauthorized writes a 401 Unauthorized error response.
func Unauthorized(w http.ResponseWriter, message string) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
message | string |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of Unauthorized
result := Unauthorized(/* parameters */)WithService returns a new context with the service added. This is useful for request-scoped services like database transactions.
func WithService(ctx context.Context, service T) context.ContextParameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
service | T |
Returns:
| Type | Description |
|---|---|
context.Context |
Example:
// Example usage of WithService
result := WithService(/* parameters */)WriteProblem writes a Problem response to the http.ResponseWriter.
func WriteProblem(w http.ResponseWriter, p Problem) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
p | Problem |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of WriteProblem
result := WriteProblem(/* parameters */)WriteValidationProblem writes a ValidationProblem response to the http.ResponseWriter.
func WriteValidationProblem(w http.ResponseWriter, v *ValidationErrors) errorParameters:
| Parameter | Type | Description |
|---|---|---|
w | http.ResponseWriter | |
v | *ValidationErrors |
Returns:
| Type | Description |
|---|---|
error |
Example:
// Example usage of WriteValidationProblem
result := WriteValidationProblem(/* parameters */)const MIMETextPlain = "text/plain" // Text types - base (for matching)
const MIMETextHTML = "text/html"
const MIMETextCSS = "text/css"
const MIMETextCSV = "text/csv"
const MIMETextJavaScript = "text/javascript"
const MIMETextXML = "text/xml"
const MIMETextPlainCharsetUTF8 = "text/plain; charset=utf-8" // Text types - with charset (for responses)
const MIMETextHTMLCharsetUTF8 = "text/html; charset=utf-8"
const MIMETextCSSCharsetUTF8 = "text/css; charset=utf-8"
const MIMETextCSVCharsetUTF8 = "text/csv; charset=utf-8"
const MIMETextJavaScriptCharsetUTF8 = "text/javascript; charset=utf-8"
const MIMETextXMLCharsetUTF8 = "text/xml; charset=utf-8"
const MIMEApplicationJSON = "application/json" // Application types - base (for matching)
const MIMEApplicationXML = "application/xml"
const MIMEApplicationJavaScript = "application/javascript"
const MIMEApplicationXHTMLXML = "application/xhtml+xml"
const MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8" // Application types - with charset (for responses)
const MIMEApplicationXMLCharsetUTF8 = "application/xml; charset=utf-8"
const MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8"
const MIMEApplicationProblemJSON = "application/problem+json" // Application types - no charset needed
const MIMEApplicationForm = "application/x-www-form-urlencoded"
const MIMEApplicationProtobuf = "application/x-protobuf"
const MIMEApplicationMsgPack = "application/msgpack"
const MIMEApplicationOctetStream = "application/octet-stream"
const MIMEApplicationPDF = "application/pdf"
const MIMEApplicationZip = "application/zip"
const MIMEApplicationGzip = "application/gzip"
const MIMEMultipartForm = "multipart/form-data"
const MIMEImagePNG = "image/png" // Image types
const MIMEImageSVG = "image/svg+xml"
const MIMEImageJPEG = "image/jpeg"
const MIMEImageGIF = "image/gif"
const MIMEImageWebP = "image/webp"
const MIMEImageICO = "image/x-icon"
const MIMEImageAVIF = "image/avif"
const MIMEAudioMPEG = "audio/mpeg" // Audio types
const MIMEAudioWAV = "audio/wav"
const MIMEAudioOGG = "audio/ogg"
const MIMEVideoMP4 = "video/mp4" // Video types
const MIMEVideoWebM = "video/webm"
const MIMEVideoOGG = "video/ogg"const Version = "0.1.0" // Version of Hexix
var ErrBindingFailed = errors.New("helix: binding failed")
var ErrUnsupportedType = errors.New("helix: unsupported type for binding")
var ErrInvalidJSON = errors.New("helix: invalid JSON body")
var ErrRequiredField = errors.New("helix: required field missing")
var ErrBodyAlreadyRead = errors.New("helix: request body already read")
var ErrInvalidFieldValue = errors.New("helix: invalid field value")var ErrBadRequest = NewProblem(http.StatusBadRequest, "bad_request", "Bad Request") // ErrBadRequest represents a 400 Bad Request error.
var ErrUnauthorized = NewProblem(http.StatusUnauthorized, "unauthorized", "Unauthorized") // ErrUnauthorized represents a 401 Unauthorized error.
var ErrForbidden = NewProblem(http.StatusForbidden, "forbidden", "Forbidden") // ErrForbidden represents a 403 Forbidden error.
var ErrNotFound = NewProblem(http.StatusNotFound, "not_found", "Not Found") // ErrNotFound represents a 404 Not Found error.
var ErrMethodNotAllowed = NewProblem(http.StatusMethodNotAllowed, "method_not_allowed", "Method Not Allowed") // ErrMethodNotAllowed represents a 405 Method Not Allowed error.
var ErrConflict = NewProblem(http.StatusConflict, "conflict", "Conflict") // ErrConflict represents a 409 Conflict error.
var ErrGone = NewProblem(http.StatusGone, "gone", "Gone") // ErrGone represents a 410 Gone error.
var ErrUnprocessableEntity = NewProblem(http.StatusUnprocessableEntity, "unprocessable_entity", "Unprocessable Entity") // ErrUnprocessableEntity represents a 422 Unprocessable Entity error.
var ErrTooManyRequests = NewProblem(http.StatusTooManyRequests, "too_many_requests", "Too Many Requests") // ErrTooManyRequests represents a 429 Too Many Requests error.
var ErrInternal = NewProblem(http.StatusInternalServerError, "internal_error", "Internal Server Error") // ErrInternal represents a 500 Internal Server Error.
var ErrNotImplemented = NewProblem(http.StatusNotImplemented, "not_implemented", "Not Implemented") // ErrNotImplemented represents a 501 Not Implemented error.
var ErrBadGateway = NewProblem(http.StatusBadGateway, "bad_gateway", "Bad Gateway") // ErrBadGateway represents a 502 Bad Gateway error.
var ErrServiceUnavailable = NewProblem(http.StatusServiceUnavailable, "service_unavailable", "Service Unavailable") // ErrServiceUnavailable represents a 503 Service Unavailable error.
var ErrGatewayTimeout = NewProblem(http.StatusGatewayTimeout, "gateway_timeout", "Gateway Timeout") // ErrGatewayTimeout represents a 504 Gateway Timeout error.
// Create a new Ctx
ctx := Ctx{
Request: &/* value */{},
Response: /* value */,
}type Ctx struct {
Request *http.Request
Response http.ResponseWriter
}func NewCtx(w http.ResponseWriter, r *http.Request) *Ctxfunc Accepted(w http.ResponseWriter, v any) errorfunc (*Ctx) AddHeader(key, value string) *Ctxfunc (*Ctx) Attachment(filename string) *Ctxfunc BadRequest(w http.ResponseWriter, message string) errorfunc Bind(r *http.Request) (T, error)func (*Ctx) BindJSON(v any) errorfunc (*Ctx) BindPagination(defaultLimit, maxLimit int) Paginationfunc Blob(w http.ResponseWriter, status int, contentType string, data []byte) errorfunc (*Ctx) Context() context.Contextfunc (*Ctx) Created(v any) errorfunc (*Ctx) CreatedMessage(message string, id any) errorfunc (*Ctx) DeletedMessage(message string) errorfunc File(w http.ResponseWriter, r *http.Request, path string)func (*Ctx) Forbidden(message string) errorfunc Get() (T, bool)func (*Ctx) GetInt(key string) intfunc (*Ctx) GetString(key string) stringfunc (*Ctx) HTML(status int, html string) errorfunc (*Ctx) Header(name string) stringfunc Inline(w http.ResponseWriter, filename string)func InternalServerError(w http.ResponseWriter, message string) errorfunc JSON(w http.ResponseWriter, status int, v any) errorfunc (*Ctx) MustGet(key string) anyfunc NoContent(w http.ResponseWriter) errorfunc (*Ctx) NotFound(message string) errorfunc OK(w http.ResponseWriter, v any) errorfunc (*Ctx) OKMessage(message string) errorfunc (*Ctx) Paginated(items any, total, page, limit int) errorfunc (*Ctx) Param(name string) stringfunc (*Ctx) ParamInt(name string) (int, error)func ParamInt64(r *http.Request, name string) (int64, error)func (*Ctx) ParamUUID(name string) (string, error)func (*Ctx) Problem(p Problem) errorfunc (*Ctx) Query(name string) stringfunc (*Ctx) QueryBool(name string) boolfunc (*Ctx) QueryDefault(name, defaultVal string) stringfunc (*Ctx) QueryFloat64(name string, defaultVal float64) float64func (*Ctx) QueryInt(name string, defaultVal int) intfunc QueryInt64(r *http.Request, name string, defaultVal int64) int64func QuerySlice(r *http.Request, name string) []stringfunc (*Ctx) Redirect(url string, code int)func (*Ctx) Reset(w http.ResponseWriter, r *http.Request)func (*Ctx) SendJSON(v any) errorfunc (*Ctx) Set(key string, value any)func (*Ctx) SetCookie(cookie *http.Cookie) *Ctxfunc (*Ctx) SetHeader(key, value string) *Ctxfunc (*Ctx) Status(code int) *Ctxfunc (*Ctx) Text(status int, text string) errorfunc Unauthorized(w http.ResponseWriter, message string) error// Example usage of CtxHandler
var value CtxHandler
// Initialize with appropriate valuetype CtxHandler func(c *Ctx) error// Example usage of EmptyHandler
var value EmptyHandler
// Initialize with appropriate valuetype EmptyHandler func(ctx context.Context) error// Example usage of ErrorHandler
var value ErrorHandler
// Initialize with appropriate valuetype ErrorHandler func(w http.ResponseWriter, r *http.Request, err error)// Create a new FieldError
fielderror := FieldError{
Field: "example",
Message: "example",
}type FieldError struct {
Field string `json:"field"`
Message string `json:"message"`
}// Create a new Group
group := Group{
}type Group struct {
}func (*Server) Any(pattern string, handler http.HandlerFunc)func (*Server) DELETE(pattern string, handler http.HandlerFunc)func (*Server) GET(pattern string, handler http.HandlerFunc)func (*Group) Group(prefix string, mw ...any) *Groupfunc (*Server) HEAD(pattern string, handler http.HandlerFunc)func (*Server) Handle(method, pattern string, handler http.HandlerFunc)func (*Group) Mount(prefix string, m Module, mw ...any)func (*Group) MountFunc(prefix string, fn func(r RouteRegistrar), mw ...any)func (*Group) OPTIONS(pattern string, handler http.HandlerFunc)func (*Group) PATCH(pattern string, handler http.HandlerFunc)func (*Server) POST(pattern string, handler http.HandlerFunc)func (*Group) PUT(pattern string, handler http.HandlerFunc)func (*Group) Resource(pattern string, mw ...any) *ResourceBuilderfunc (*Group) Static(pattern, root string)func (*Group) Use(mw ...any)// Example usage of Handler
var value Handler
// Initialize with appropriate valuetype Handler func(ctx context.Context, req Req) (Res, error)// Create a new HealthBuilder
healthbuilder := HealthBuilder{
}type HealthBuilder struct {
}func Health() *HealthBuilderfunc (*HealthBuilder) Check(name string, check HealthCheck) *HealthBuilderfunc (*HealthBuilder) CheckFunc(name string, check func(ctx context.Context) error) *HealthBuilderfunc (*HealthBuilder) Handler() http.HandlerFuncfunc (*HealthBuilder) Timeout(d time.Duration) *HealthBuilderfunc (*HealthBuilder) Version(v string) *HealthBuilder// Example usage of HealthCheck
var value HealthCheck
// Initialize with appropriate valuetype HealthCheck func(ctx context.Context) HealthCheckResult// Create a new HealthCheckResult
healthcheckresult := HealthCheckResult{
Status: HealthStatus{},
Message: "example",
Latency: /* value */,
Details: map[],
}type HealthCheckResult struct {
Status HealthStatus `json:"status"`
Message string `json:"message,omitempty"`
Latency time.Duration `json:"latency_ms,omitempty"`
Details map[string]any `json:"details,omitempty"`
}// Create a new HealthResponse
healthresponse := HealthResponse{
Status: HealthStatus{},
Timestamp: /* value */,
Version: "example",
Components: map[],
}type HealthResponse struct {
Status HealthStatus `json:"status"`
Timestamp time.Time `json:"timestamp"`
Version string `json:"version,omitempty"`
Components map[string]HealthCheckResult `json:"components,omitempty"`
}// Example usage of HealthStatus
var value HealthStatus
// Initialize with appropriate valuetype HealthStatus string// Create a new IDRequest
idrequest := IDRequest{
ID: 42,
}type IDRequest struct {
ID int `path:"id"`
}// Create a new ListRequest
listrequest := ListRequest{
Page: 42,
Limit: 42,
Sort: "example",
Order: "example",
Search: "example",
}type ListRequest struct {
Page int `query:"page"`
Limit int `query:"limit"`
Sort string `query:"sort"`
Order string `query:"order"`
Search string `query:"search"`
}// Create a new ListResponse
listresponse := ListResponse{
Items: [],
Total: 42,
Page: 42,
Limit: 42,
}type ListResponse struct {
Items []Entity `json:"items"`
Total int `json:"total"`
Page int `json:"page,omitempty"`
Limit int `json:"limit,omitempty"`
}// Example usage of Middleware
var value Middleware
// Initialize with appropriate valuetype Middleware middleware.Middlewarefunc ProvideMiddleware(factory func(r *http.Request) T) Middleware// Example implementation of Module
type MyModule struct {
// Add your fields here
}
func (m MyModule) Register(param1 RouteRegistrar) {
// Implement your logic here
return
}
type Module interface {
Register(r RouteRegistrar)
}// Example usage of ModuleFunc
var value ModuleFunc
// Initialize with appropriate valuetype ModuleFunc func(r RouteRegistrar)func Register(service T)// Example usage of NoRequestHandler
var value NoRequestHandler
// Initialize with appropriate valuetype NoRequestHandler func(ctx context.Context) (Res, error)// Example usage of NoResponseHandler
var value NoResponseHandler
// Initialize with appropriate valuetype NoResponseHandler func(ctx context.Context, req Req) error// Example usage of Option
var value Option
// Initialize with appropriate valuetype Option func(*Server)func HideBanner() Optionfunc WithAddr(addr string) Optionfunc WithBasePath(path string) Optionfunc WithCustomBanner(banner string) Optionfunc WithErrorHandler(handler ErrorHandler) Optionfunc WithGracePeriod(d time.Duration) Optionfunc WithIdleTimeout(d time.Duration) Optionfunc WithMaxHeaderBytes(n int) Optionfunc WithReadTimeout(d time.Duration) Optionfunc WithTLS(certFile, keyFile string) Optionfunc WithTLSConfig(config *tls.Config) Optionfunc WithWriteTimeout(d time.Duration) Option// Create a new PaginatedResponse
paginatedresponse := PaginatedResponse{
Items: [],
Total: 42,
Page: 42,
Limit: 42,
TotalPages: 42,
HasMore: true,
NextCursor: "example",
}type PaginatedResponse struct {
Items []T `json:"items"`
Total int `json:"total"`
Page int `json:"page"`
Limit int `json:"limit"`
TotalPages int `json:"total_pages"`
HasMore bool `json:"has_more"`
NextCursor string `json:"next_cursor,omitempty"`
}func NewCursorResponse(items []T, total int, nextCursor string) *ast.IndexExprfunc NewPaginatedResponse(items []T, total, page, limit int) *ast.IndexExpr// Create a new Pagination
pagination := Pagination{
Page: 42,
Limit: 42,
Sort: "example",
Order: "example",
Cursor: "example",
}type Pagination struct {
Page int `query:"page"`
Limit int `query:"limit"`
Sort string `query:"sort"`
Order string `query:"order"`
Cursor string `query:"cursor"`
}func (*Ctx) BindPagination(defaultLimit, maxLimit int) Paginationfunc (Pagination) GetLimit(defaultLimit, maxLimit int) intfunc (Pagination) GetOffset(limit int) intfunc (Pagination) GetOrder() stringfunc (Pagination) GetPage() intfunc (Pagination) GetSort(defaultSort string, allowed []string) stringfunc (Pagination) IsAscending() bool// Create a new Problem
problem := Problem{
Type: "example",
Title: "example",
Status: 42,
Detail: "example",
Instance: "example",
Err: error{},
}type Problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
Instance string `json:"instance,omitempty"`
Err error `json:"-"`
}func BadGatewayf(format string, args ...any) Problemfunc BadRequestf(format string, args ...any) Problemfunc Conflictf(format string, args ...any) Problemfunc Forbiddenf(format string, args ...any) Problemfunc GatewayTimeoutf(format string, args ...any) Problemfunc Gonef(format string, args ...any) Problemfunc Internalf(format string, args ...any) Problemfunc MethodNotAllowedf(format string, args ...any) Problemfunc NewProblem(status int, problemType, title string) Problemfunc NotFoundf(format string, args ...any) Problemfunc NotImplementedf(format string, args ...any) Problemfunc ProblemFromStatus(status int) Problemfunc ServiceUnavailablef(format string, args ...any) Problemfunc TooManyRequestsf(format string, args ...any) Problemfunc Unauthorizedf(format string, args ...any) Problemfunc UnprocessableEntityf(format string, args ...any) Problemfunc (*ValidationErrors) Error() stringfunc (Problem) WithDetail(detail string) Problemfunc (Problem) WithDetailf(format string, args ...any) Problemfunc (Problem) WithErr(err error) Problemfunc (Problem) WithInstance(instance string) Problemfunc (Problem) WithType(problemType string) Problem// Create a new ResourceBuilder
resourcebuilder := ResourceBuilder{
}type ResourceBuilder struct {
}func (*ResourceBuilder) CRUD(list, create, get, update, delete http.HandlerFunc) *ResourceBuilderfunc (**ast.IndexExpr) Create(h *ast.IndexListExpr) **ast.IndexExprfunc (**ast.IndexExpr) Custom(method, suffix string, handler http.HandlerFunc) **ast.IndexExprfunc (**ast.IndexExpr) Delete(h *ast.IndexExpr) **ast.IndexExprfunc (*ResourceBuilder) Destroy(handler http.HandlerFunc) *ResourceBuilderfunc Get() (T, bool)func (*ResourceBuilder) Index(handler http.HandlerFunc) *ResourceBuilderfunc (**ast.IndexExpr) List(h *ast.IndexListExpr) **ast.IndexExprfunc (**ast.IndexExpr) Patch(h *ast.IndexListExpr) **ast.IndexExprfunc (*ResourceBuilder) ReadOnly(list, get http.HandlerFunc) *ResourceBuilderfunc (*ResourceBuilder) Show(handler http.HandlerFunc) *ResourceBuilderfunc (*ResourceBuilder) Store(handler http.HandlerFunc) *ResourceBuilderfunc (**ast.IndexExpr) Update(h *ast.IndexListExpr) **ast.IndexExpr// Create a new RouteInfo
routeinfo := RouteInfo{
Method: "example",
Pattern: "example",
}type RouteInfo struct {
Method string
Pattern string
}// Example implementation of RouteRegistrar
type MyRouteRegistrar struct {
// Add your fields here
}
func (m MyRouteRegistrar) GET(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) POST(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) PUT(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) PATCH(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) DELETE(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) OPTIONS(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) HEAD(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) Handle(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) Group(param1 string, param2 ...any) *Group {
// Implement your logic here
return
}
func (m MyRouteRegistrar) Resource(param1 string, param2 ...any) *ResourceBuilder {
// Implement your logic here
return
}
type RouteRegistrar interface {
GET(pattern string, handler http.HandlerFunc)
POST(pattern string, handler http.HandlerFunc)
PUT(pattern string, handler http.HandlerFunc)
PATCH(pattern string, handler http.HandlerFunc)
DELETE(pattern string, handler http.HandlerFunc)
OPTIONS(pattern string, handler http.HandlerFunc)
HEAD(pattern string, handler http.HandlerFunc)
Handle(method, pattern string, handler http.HandlerFunc)
Group(prefix string, mw ...any) *Group
Resource(pattern string, mw ...any) *ResourceBuilder
}// Create a new Router
router := Router{
}type Router struct {
}func Handle(h *ast.IndexListExpr) http.HandlerFuncfunc (*Server) Routes() []RouteInfofunc (*Server) ServeHTTP(w http.ResponseWriter, r *http.Request)// Create a new Server
server := Server{
}type Server struct {
}func Default(opts ...Option) *Serverfunc New(opts ...Option) *Serverfunc (*Server) Addr() stringfunc (*Server) Any(pattern string, handler http.HandlerFunc)func (*Server) Build()func (*Server) CONNECT(pattern string, handler http.HandlerFunc)func (*Server) DELETE(pattern string, handler http.HandlerFunc)func (*Server) GET(pattern string, handler http.HandlerFunc)func (*Group) Group(prefix string, mw ...any) *Groupfunc (*Server) HEAD(pattern string, handler http.HandlerFunc)func (*Server) Handle(method, pattern string, handler http.HandlerFunc)func (*Group) Mount(prefix string, m Module, mw ...any)func (*Group) MountFunc(prefix string, fn func(r RouteRegistrar), mw ...any)func (*Group) OPTIONS(pattern string, handler http.HandlerFunc)func (*Server) OnStart(fn func(s *Server))func (*Server) OnStop(fn func(ctx context.Context, s *Server))func (*Server) PATCH(pattern string, handler http.HandlerFunc)func (*Group) POST(pattern string, handler http.HandlerFunc)func (*Group) PUT(pattern string, handler http.HandlerFunc)func (*Server) PrintRoutes(w io.Writer)func (*Server) Resource(pattern string, mw ...any) *ResourceBuilderfunc (*Server) Routes() []RouteInfofunc (*Server) Run(ctx context.Context) errorfunc (*Router) ServeHTTP(w http.ResponseWriter, req *http.Request)func (*Server) Shutdown(ctx context.Context) errorfunc (*Server) Start(addr ...string) errorfunc (*Server) Static(pattern, root string)func (*Server) TRACE(pattern string, handler http.HandlerFunc)func (*Group) Use(mw ...any)// Create a new TypedResourceBuilder
typedresourcebuilder := TypedResourceBuilder{
}type TypedResourceBuilder struct {
}func TypedResource(s *Server, pattern string, mw ...any) **ast.IndexExprfunc TypedResourceForGroup(g *Group, pattern string, mw ...any) **ast.IndexExprfunc (**ast.IndexExpr) Create(h *ast.IndexListExpr) **ast.IndexExprfunc (**ast.IndexExpr) Custom(method, suffix string, handler http.HandlerFunc) **ast.IndexExprfunc (**ast.IndexExpr) Delete(h *ast.IndexExpr) **ast.IndexExprfunc Get() (T, bool)func (**ast.IndexExpr) List(h *ast.IndexListExpr) **ast.IndexExprfunc (**ast.IndexExpr) Patch(h *ast.IndexListExpr) **ast.IndexExprfunc (**ast.IndexExpr) Update(h *ast.IndexListExpr) **ast.IndexExpr// Example implementation of Validatable
type MyValidatable struct {
// Add your fields here
}
func (m MyValidatable) Validate() error {
// Implement your logic here
return
}
type Validatable interface {
Validate() error
}// Create a new ValidationErrors
validationerrors := ValidationErrors{
}type ValidationErrors struct {
}func NewValidationErrors() *ValidationErrorsfunc (*ValidationErrors) Add(field, message string)func (*ValidationErrors) Addf(field, format string, args ...any)func (*ValidationErrors) Err() errorfunc (*ValidationErrors) Error() stringfunc (*ValidationErrors) Errors() []FieldErrorfunc (*ValidationErrors) HasErrors() boolfunc (*ValidationErrors) Len() intfunc (*ValidationErrors) ToProblem() ValidationProblem// Create a new ValidationProblem
validationproblem := ValidationProblem{
Errors: [],
}type ValidationProblem struct {
Problem
Errors []FieldError `json:"errors,omitempty"`
}func Accepted(w http.ResponseWriter, v any) error// Example usage of Accepted
result := Accepted(/* parameters */)func (*Ctx) Attachment(filename string) *Ctx// Example usage of Attachment
result := Attachment(/* parameters */)func (*Ctx) BadRequest(message string) error// Example usage of BadRequest
result := BadRequest(/* parameters */)func Bind(r *http.Request) (T, error)// Example usage of Bind
result := Bind(/* parameters */)func BindAndValidate(r *http.Request) (T, error)// Example usage of BindAndValidate
result := BindAndValidate(/* parameters */)func BindHeader(r *http.Request) (T, error)// Example usage of BindHeader
result := BindHeader(/* parameters */)func (*Ctx) BindJSON(v any) error// Example usage of BindJSON
result := BindJSON(/* parameters */)func BindPath(r *http.Request) (T, error)// Example usage of BindPath
result := BindPath(/* parameters */)func BindQuery(r *http.Request) (T, error)// Example usage of BindQuery
result := BindQuery(/* parameters */)func Blob(w http.ResponseWriter, status int, contentType string, data []byte) error// Example usage of Blob
result := Blob(/* parameters */)func (*Ctx) Created(v any) error// Example usage of Created
result := Created(/* parameters */)func Error(w http.ResponseWriter, status int, message string) error// Example usage of Error
result := Error(/* parameters */)func File(w http.ResponseWriter, r *http.Request, path string)// Example usage of File
result := File(/* parameters */)func (*Ctx) Forbidden(message string) error// Example usage of Forbidden
result := Forbidden(/* parameters */)func FromContext(ctx context.Context) (T, bool)// Example usage of FromContext
result := FromContext(/* parameters */)func Get() (T, bool)// Example usage of Get
result := Get(/* parameters */)func HTML(w http.ResponseWriter, status int, html string) error// Example usage of HTML
result := HTML(/* parameters */)func Handle(h *ast.IndexListExpr) http.HandlerFunc// Example usage of Handle
result := Handle(/* parameters */)func HandleAccepted(h *ast.IndexListExpr) http.HandlerFunc// Example usage of HandleAccepted
result := HandleAccepted(/* parameters */)func HandleCreated(h *ast.IndexListExpr) http.HandlerFunc// Example usage of HandleCreated
result := HandleCreated(/* parameters */)func HandleCtx(h CtxHandler) http.HandlerFunc// Example usage of HandleCtx
result := HandleCtx(/* parameters */)func HandleEmpty(h EmptyHandler) http.HandlerFunc// Example usage of HandleEmpty
result := HandleEmpty(/* parameters */)func HandleErrorDefault(w http.ResponseWriter, r *http.Request, err error)// Example usage of HandleErrorDefault
result := HandleErrorDefault(/* parameters */)func HandleNoRequest(h *ast.IndexExpr) http.HandlerFunc// Example usage of HandleNoRequest
result := HandleNoRequest(/* parameters */)func HandleNoResponse(h *ast.IndexExpr) http.HandlerFunc// Example usage of HandleNoResponse
result := HandleNoResponse(/* parameters */)func HandleWithStatus(status int, h *ast.IndexListExpr) http.HandlerFunc// Example usage of HandleWithStatus
result := HandleWithStatus(/* parameters */)func Inline(w http.ResponseWriter, filename string)// Example usage of Inline
result := Inline(/* parameters */)func InternalServerError(w http.ResponseWriter, message string) error// Example usage of InternalServerError
result := InternalServerError(/* parameters */)func (*Ctx) JSON(status int, v any) error// Example usage of JSON
result := JSON(/* parameters */)func JSONPretty(w http.ResponseWriter, status int, v any, indent string) error// Example usage of JSONPretty
result := JSONPretty(/* parameters */)func LivenessHandler() http.HandlerFunc// Example usage of LivenessHandler
result := LivenessHandler(/* parameters */)func MustFromContext(ctx context.Context) T// Example usage of MustFromContext
result := MustFromContext(/* parameters */)func MustGet() T// Example usage of MustGet
result := MustGet(/* parameters */)func (*Ctx) NoContent() error// Example usage of NoContent
result := NoContent(/* parameters */)func NotFound(w http.ResponseWriter, message string) error// Example usage of NotFound
result := NotFound(/* parameters */)func OK(w http.ResponseWriter, v any) error// Example usage of OK
result := OK(/* parameters */)func (*Ctx) Param(name string) string// Example usage of Param
result := Param(/* parameters */)func (*Ctx) ParamInt(name string) (int, error)// Example usage of ParamInt
result := ParamInt(/* parameters */)func (*Ctx) ParamInt64(name string) (int64, error)// Example usage of ParamInt64
result := ParamInt64(/* parameters */)func ParamUUID(r *http.Request, name string) (string, error)// Example usage of ParamUUID
result := ParamUUID(/* parameters */)func Query(r *http.Request, name string) string// Example usage of Query
result := Query(/* parameters */)func QueryBool(r *http.Request, name string) bool// Example usage of QueryBool
result := QueryBool(/* parameters */)func (*Ctx) QueryDefault(name, defaultVal string) string// Example usage of QueryDefault
result := QueryDefault(/* parameters */)func QueryFloat64(r *http.Request, name string, defaultVal float64) float64// Example usage of QueryFloat64
result := QueryFloat64(/* parameters */)func QueryInt(r *http.Request, name string, defaultVal int) int// Example usage of QueryInt
result := QueryInt(/* parameters */)func (*Ctx) QueryInt64(name string, defaultVal int64) int64// Example usage of QueryInt64
result := QueryInt64(/* parameters */)func QuerySlice(r *http.Request, name string) []string// Example usage of QuerySlice
result := QuerySlice(/* parameters */)func ReadinessHandler(checks ...func(ctx context.Context) error) http.HandlerFunc// Example usage of ReadinessHandler
result := ReadinessHandler(/* parameters */)func Redirect(w http.ResponseWriter, r *http.Request, url string, code int)// Example usage of Redirect
result := Redirect(/* parameters */)func (ModuleFunc) Register(r RouteRegistrar)// Example usage of Register
result := Register(/* parameters */)func Stream(w http.ResponseWriter, contentType string, reader io.Reader) error// Example usage of Stream
result := Stream(/* parameters */)func Text(w http.ResponseWriter, status int, text string) error// Example usage of Text
result := Text(/* parameters */)func Unauthorized(w http.ResponseWriter, message string) error// Example usage of Unauthorized
result := Unauthorized(/* parameters */)func WithService(ctx context.Context, service T) context.Context// Example usage of WithService
result := WithService(/* parameters */)func WriteProblem(w http.ResponseWriter, p Problem) error// Example usage of WriteProblem
result := WriteProblem(/* parameters */)func WriteValidationProblem(w http.ResponseWriter, v *ValidationErrors) error// Example usage of WriteValidationProblem
result := WriteValidationProblem(/* parameters */)const MIMETextPlain = "text/plain" // Text types - base (for matching)
const MIMETextHTML = "text/html"
const MIMETextCSS = "text/css"
const MIMETextCSV = "text/csv"
const MIMETextJavaScript = "text/javascript"
const MIMETextXML = "text/xml"
const MIMETextPlainCharsetUTF8 = "text/plain; charset=utf-8" // Text types - with charset (for responses)
const MIMETextHTMLCharsetUTF8 = "text/html; charset=utf-8"
const MIMETextCSSCharsetUTF8 = "text/css; charset=utf-8"
const MIMETextCSVCharsetUTF8 = "text/csv; charset=utf-8"
const MIMETextJavaScriptCharsetUTF8 = "text/javascript; charset=utf-8"
const MIMETextXMLCharsetUTF8 = "text/xml; charset=utf-8"
const MIMEApplicationJSON = "application/json" // Application types - base (for matching)
const MIMEApplicationXML = "application/xml"
const MIMEApplicationJavaScript = "application/javascript"
const MIMEApplicationXHTMLXML = "application/xhtml+xml"
const MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8" // Application types - with charset (for responses)
const MIMEApplicationXMLCharsetUTF8 = "application/xml; charset=utf-8"
const MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8"
const MIMEApplicationProblemJSON = "application/problem+json" // Application types - no charset needed
const MIMEApplicationForm = "application/x-www-form-urlencoded"
const MIMEApplicationProtobuf = "application/x-protobuf"
const MIMEApplicationMsgPack = "application/msgpack"
const MIMEApplicationOctetStream = "application/octet-stream"
const MIMEApplicationPDF = "application/pdf"
const MIMEApplicationZip = "application/zip"
const MIMEApplicationGzip = "application/gzip"
const MIMEMultipartForm = "multipart/form-data"
const MIMEImagePNG = "image/png" // Image types
const MIMEImageSVG = "image/svg+xml"
const MIMEImageJPEG = "image/jpeg"
const MIMEImageGIF = "image/gif"
const MIMEImageWebP = "image/webp"
const MIMEImageICO = "image/x-icon"
const MIMEImageAVIF = "image/avif"
const MIMEAudioMPEG = "audio/mpeg" // Audio types
const MIMEAudioWAV = "audio/wav"
const MIMEAudioOGG = "audio/ogg"
const MIMEVideoMP4 = "video/mp4" // Video types
const MIMEVideoWebM = "video/webm"
const MIMEVideoOGG = "video/ogg"const Version = "0.1.0" // Version of Hexix
var ErrBindingFailed = errors.New("helix: binding failed")
var ErrUnsupportedType = errors.New("helix: unsupported type for binding")
var ErrInvalidJSON = errors.New("helix: invalid JSON body")
var ErrRequiredField = errors.New("helix: required field missing")
var ErrBodyAlreadyRead = errors.New("helix: request body already read")
var ErrInvalidFieldValue = errors.New("helix: invalid field value")var ErrBadRequest = NewProblem(http.StatusBadRequest, "bad_request", "Bad Request") // ErrBadRequest represents a 400 Bad Request error.
var ErrUnauthorized = NewProblem(http.StatusUnauthorized, "unauthorized", "Unauthorized") // ErrUnauthorized represents a 401 Unauthorized error.
var ErrForbidden = NewProblem(http.StatusForbidden, "forbidden", "Forbidden") // ErrForbidden represents a 403 Forbidden error.
var ErrNotFound = NewProblem(http.StatusNotFound, "not_found", "Not Found") // ErrNotFound represents a 404 Not Found error.
var ErrMethodNotAllowed = NewProblem(http.StatusMethodNotAllowed, "method_not_allowed", "Method Not Allowed") // ErrMethodNotAllowed represents a 405 Method Not Allowed error.
var ErrConflict = NewProblem(http.StatusConflict, "conflict", "Conflict") // ErrConflict represents a 409 Conflict error.
var ErrGone = NewProblem(http.StatusGone, "gone", "Gone") // ErrGone represents a 410 Gone error.
var ErrUnprocessableEntity = NewProblem(http.StatusUnprocessableEntity, "unprocessable_entity", "Unprocessable Entity") // ErrUnprocessableEntity represents a 422 Unprocessable Entity error.
var ErrTooManyRequests = NewProblem(http.StatusTooManyRequests, "too_many_requests", "Too Many Requests") // ErrTooManyRequests represents a 429 Too Many Requests error.
var ErrInternal = NewProblem(http.StatusInternalServerError, "internal_error", "Internal Server Error") // ErrInternal represents a 500 Internal Server Error.
var ErrNotImplemented = NewProblem(http.StatusNotImplemented, "not_implemented", "Not Implemented") // ErrNotImplemented represents a 501 Not Implemented error.
var ErrBadGateway = NewProblem(http.StatusBadGateway, "bad_gateway", "Bad Gateway") // ErrBadGateway represents a 502 Bad Gateway error.
var ErrServiceUnavailable = NewProblem(http.StatusServiceUnavailable, "service_unavailable", "Service Unavailable") // ErrServiceUnavailable represents a 503 Service Unavailable error.
var ErrGatewayTimeout = NewProblem(http.StatusGatewayTimeout, "gateway_timeout", "Gateway Timeout") // ErrGatewayTimeout represents a 504 Gateway Timeout error.
// Create a new Ctx
ctx := Ctx{
Request: &/* value */{},
Response: /* value */,
}type Ctx struct {
Request *http.Request
Response http.ResponseWriter
}func NewCtx(w http.ResponseWriter, r *http.Request) *Ctxfunc Accepted(w http.ResponseWriter, v any) errorfunc (*Ctx) AddHeader(key, value string) *Ctxfunc (*Ctx) Attachment(filename string) *Ctxfunc BadRequest(w http.ResponseWriter, message string) errorfunc Bind(r *http.Request) (T, error)func (*Ctx) BindJSON(v any) errorfunc (*Ctx) BindPagination(defaultLimit, maxLimit int) Paginationfunc Blob(w http.ResponseWriter, status int, contentType string, data []byte) errorfunc (*Ctx) Context() context.Contextfunc (*Ctx) Created(v any) errorfunc (*Ctx) CreatedMessage(message string, id any) errorfunc (*Ctx) DeletedMessage(message string) errorfunc File(w http.ResponseWriter, r *http.Request, path string)func (*Ctx) Forbidden(message string) errorfunc Get() (T, bool)func (*Ctx) GetInt(key string) intfunc (*Ctx) GetString(key string) stringfunc (*Ctx) HTML(status int, html string) errorfunc (*Ctx) Header(name string) stringfunc Inline(w http.ResponseWriter, filename string)func InternalServerError(w http.ResponseWriter, message string) errorfunc JSON(w http.ResponseWriter, status int, v any) errorfunc (*Ctx) MustGet(key string) anyfunc NoContent(w http.ResponseWriter) errorfunc (*Ctx) NotFound(message string) errorfunc OK(w http.ResponseWriter, v any) errorfunc (*Ctx) OKMessage(message string) errorfunc (*Ctx) Paginated(items any, total, page, limit int) errorfunc (*Ctx) Param(name string) stringfunc (*Ctx) ParamInt(name string) (int, error)func ParamInt64(r *http.Request, name string) (int64, error)func (*Ctx) ParamUUID(name string) (string, error)func (*Ctx) Problem(p Problem) errorfunc (*Ctx) Query(name string) stringfunc (*Ctx) QueryBool(name string) boolfunc (*Ctx) QueryDefault(name, defaultVal string) stringfunc (*Ctx) QueryFloat64(name string, defaultVal float64) float64func (*Ctx) QueryInt(name string, defaultVal int) intfunc QueryInt64(r *http.Request, name string, defaultVal int64) int64func QuerySlice(r *http.Request, name string) []stringfunc (*Ctx) Redirect(url string, code int)func (*Ctx) Reset(w http.ResponseWriter, r *http.Request)func (*Ctx) SendJSON(v any) errorfunc (*Ctx) Set(key string, value any)func (*Ctx) SetCookie(cookie *http.Cookie) *Ctxfunc (*Ctx) SetHeader(key, value string) *Ctxfunc (*Ctx) Status(code int) *Ctxfunc (*Ctx) Text(status int, text string) errorfunc Unauthorized(w http.ResponseWriter, message string) error// Example usage of CtxHandler
var value CtxHandler
// Initialize with appropriate valuetype CtxHandler func(c *Ctx) error// Example usage of EmptyHandler
var value EmptyHandler
// Initialize with appropriate valuetype EmptyHandler func(ctx context.Context) error// Example usage of ErrorHandler
var value ErrorHandler
// Initialize with appropriate valuetype ErrorHandler func(w http.ResponseWriter, r *http.Request, err error)// Create a new FieldError
fielderror := FieldError{
Field: "example",
Message: "example",
}type FieldError struct {
Field string `json:"field"`
Message string `json:"message"`
}// Create a new Group
group := Group{
}type Group struct {
}func (*Server) Any(pattern string, handler http.HandlerFunc)func (*Server) DELETE(pattern string, handler http.HandlerFunc)func (*Server) GET(pattern string, handler http.HandlerFunc)func (*Group) Group(prefix string, mw ...any) *Groupfunc (*Server) HEAD(pattern string, handler http.HandlerFunc)func (*Server) Handle(method, pattern string, handler http.HandlerFunc)func (*Group) Mount(prefix string, m Module, mw ...any)func (*Group) MountFunc(prefix string, fn func(r RouteRegistrar), mw ...any)func (*Group) OPTIONS(pattern string, handler http.HandlerFunc)func (*Group) PATCH(pattern string, handler http.HandlerFunc)func (*Server) POST(pattern string, handler http.HandlerFunc)func (*Group) PUT(pattern string, handler http.HandlerFunc)func (*Group) Resource(pattern string, mw ...any) *ResourceBuilderfunc (*Group) Static(pattern, root string)func (*Group) Use(mw ...any)// Example usage of Handler
var value Handler
// Initialize with appropriate valuetype Handler func(ctx context.Context, req Req) (Res, error)// Create a new HealthBuilder
healthbuilder := HealthBuilder{
}type HealthBuilder struct {
}func Health() *HealthBuilderfunc (*HealthBuilder) Check(name string, check HealthCheck) *HealthBuilderfunc (*HealthBuilder) CheckFunc(name string, check func(ctx context.Context) error) *HealthBuilderfunc (*HealthBuilder) Handler() http.HandlerFuncfunc (*HealthBuilder) Timeout(d time.Duration) *HealthBuilderfunc (*HealthBuilder) Version(v string) *HealthBuilder// Example usage of HealthCheck
var value HealthCheck
// Initialize with appropriate valuetype HealthCheck func(ctx context.Context) HealthCheckResult// Create a new HealthCheckResult
healthcheckresult := HealthCheckResult{
Status: HealthStatus{},
Message: "example",
Latency: /* value */,
Details: map[],
}type HealthCheckResult struct {
Status HealthStatus `json:"status"`
Message string `json:"message,omitempty"`
Latency time.Duration `json:"latency_ms,omitempty"`
Details map[string]any `json:"details,omitempty"`
}// Create a new HealthResponse
healthresponse := HealthResponse{
Status: HealthStatus{},
Timestamp: /* value */,
Version: "example",
Components: map[],
}type HealthResponse struct {
Status HealthStatus `json:"status"`
Timestamp time.Time `json:"timestamp"`
Version string `json:"version,omitempty"`
Components map[string]HealthCheckResult `json:"components,omitempty"`
}// Example usage of HealthStatus
var value HealthStatus
// Initialize with appropriate valuetype HealthStatus string// Create a new IDRequest
idrequest := IDRequest{
ID: 42,
}type IDRequest struct {
ID int `path:"id"`
}// Create a new ListRequest
listrequest := ListRequest{
Page: 42,
Limit: 42,
Sort: "example",
Order: "example",
Search: "example",
}type ListRequest struct {
Page int `query:"page"`
Limit int `query:"limit"`
Sort string `query:"sort"`
Order string `query:"order"`
Search string `query:"search"`
}// Create a new ListResponse
listresponse := ListResponse{
Items: [],
Total: 42,
Page: 42,
Limit: 42,
}type ListResponse struct {
Items []Entity `json:"items"`
Total int `json:"total"`
Page int `json:"page,omitempty"`
Limit int `json:"limit,omitempty"`
}// Example usage of Middleware
var value Middleware
// Initialize with appropriate valuetype Middleware middleware.Middlewarefunc ProvideMiddleware(factory func(r *http.Request) T) Middleware// Example implementation of Module
type MyModule struct {
// Add your fields here
}
func (m MyModule) Register(param1 RouteRegistrar) {
// Implement your logic here
return
}
type Module interface {
Register(r RouteRegistrar)
}// Example usage of ModuleFunc
var value ModuleFunc
// Initialize with appropriate valuetype ModuleFunc func(r RouteRegistrar)func Register(service T)// Example usage of NoRequestHandler
var value NoRequestHandler
// Initialize with appropriate valuetype NoRequestHandler func(ctx context.Context) (Res, error)// Example usage of NoResponseHandler
var value NoResponseHandler
// Initialize with appropriate valuetype NoResponseHandler func(ctx context.Context, req Req) error// Example usage of Option
var value Option
// Initialize with appropriate valuetype Option func(*Server)func HideBanner() Optionfunc WithAddr(addr string) Optionfunc WithBasePath(path string) Optionfunc WithCustomBanner(banner string) Optionfunc WithErrorHandler(handler ErrorHandler) Optionfunc WithGracePeriod(d time.Duration) Optionfunc WithIdleTimeout(d time.Duration) Optionfunc WithMaxHeaderBytes(n int) Optionfunc WithReadTimeout(d time.Duration) Optionfunc WithTLS(certFile, keyFile string) Optionfunc WithTLSConfig(config *tls.Config) Optionfunc WithWriteTimeout(d time.Duration) Option// Create a new PaginatedResponse
paginatedresponse := PaginatedResponse{
Items: [],
Total: 42,
Page: 42,
Limit: 42,
TotalPages: 42,
HasMore: true,
NextCursor: "example",
}type PaginatedResponse struct {
Items []T `json:"items"`
Total int `json:"total"`
Page int `json:"page"`
Limit int `json:"limit"`
TotalPages int `json:"total_pages"`
HasMore bool `json:"has_more"`
NextCursor string `json:"next_cursor,omitempty"`
}func NewCursorResponse(items []T, total int, nextCursor string) *ast.IndexExprfunc NewPaginatedResponse(items []T, total, page, limit int) *ast.IndexExpr// Create a new Pagination
pagination := Pagination{
Page: 42,
Limit: 42,
Sort: "example",
Order: "example",
Cursor: "example",
}type Pagination struct {
Page int `query:"page"`
Limit int `query:"limit"`
Sort string `query:"sort"`
Order string `query:"order"`
Cursor string `query:"cursor"`
}func (*Ctx) BindPagination(defaultLimit, maxLimit int) Paginationfunc (Pagination) GetLimit(defaultLimit, maxLimit int) intfunc (Pagination) GetOffset(limit int) intfunc (Pagination) GetOrder() stringfunc (Pagination) GetPage() intfunc (Pagination) GetSort(defaultSort string, allowed []string) stringfunc (Pagination) IsAscending() bool// Create a new Problem
problem := Problem{
Type: "example",
Title: "example",
Status: 42,
Detail: "example",
Instance: "example",
Err: error{},
}type Problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
Instance string `json:"instance,omitempty"`
Err error `json:"-"`
}func BadGatewayf(format string, args ...any) Problemfunc BadRequestf(format string, args ...any) Problemfunc Conflictf(format string, args ...any) Problemfunc Forbiddenf(format string, args ...any) Problemfunc GatewayTimeoutf(format string, args ...any) Problemfunc Gonef(format string, args ...any) Problemfunc Internalf(format string, args ...any) Problemfunc MethodNotAllowedf(format string, args ...any) Problemfunc NewProblem(status int, problemType, title string) Problemfunc NotFoundf(format string, args ...any) Problemfunc NotImplementedf(format string, args ...any) Problemfunc ProblemFromStatus(status int) Problemfunc ServiceUnavailablef(format string, args ...any) Problemfunc TooManyRequestsf(format string, args ...any) Problemfunc Unauthorizedf(format string, args ...any) Problemfunc UnprocessableEntityf(format string, args ...any) Problemfunc (*ValidationErrors) Error() stringfunc (Problem) WithDetail(detail string) Problemfunc (Problem) WithDetailf(format string, args ...any) Problemfunc (Problem) WithErr(err error) Problemfunc (Problem) WithInstance(instance string) Problemfunc (Problem) WithType(problemType string) Problem// Create a new ResourceBuilder
resourcebuilder := ResourceBuilder{
}type ResourceBuilder struct {
}func (*ResourceBuilder) CRUD(list, create, get, update, delete http.HandlerFunc) *ResourceBuilderfunc (**ast.IndexExpr) Create(h *ast.IndexListExpr) **ast.IndexExprfunc (**ast.IndexExpr) Custom(method, suffix string, handler http.HandlerFunc) **ast.IndexExprfunc (**ast.IndexExpr) Delete(h *ast.IndexExpr) **ast.IndexExprfunc (*ResourceBuilder) Destroy(handler http.HandlerFunc) *ResourceBuilderfunc Get() (T, bool)func (*ResourceBuilder) Index(handler http.HandlerFunc) *ResourceBuilderfunc (**ast.IndexExpr) List(h *ast.IndexListExpr) **ast.IndexExprfunc (**ast.IndexExpr) Patch(h *ast.IndexListExpr) **ast.IndexExprfunc (*ResourceBuilder) ReadOnly(list, get http.HandlerFunc) *ResourceBuilderfunc (*ResourceBuilder) Show(handler http.HandlerFunc) *ResourceBuilderfunc (*ResourceBuilder) Store(handler http.HandlerFunc) *ResourceBuilderfunc (**ast.IndexExpr) Update(h *ast.IndexListExpr) **ast.IndexExpr// Create a new RouteInfo
routeinfo := RouteInfo{
Method: "example",
Pattern: "example",
}type RouteInfo struct {
Method string
Pattern string
}// Example implementation of RouteRegistrar
type MyRouteRegistrar struct {
// Add your fields here
}
func (m MyRouteRegistrar) GET(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) POST(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) PUT(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) PATCH(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) DELETE(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) OPTIONS(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) HEAD(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) Handle(param1 string, param2 http.HandlerFunc) {
// Implement your logic here
return
}
func (m MyRouteRegistrar) Group(param1 string, param2 ...any) *Group {
// Implement your logic here
return
}
func (m MyRouteRegistrar) Resource(param1 string, param2 ...any) *ResourceBuilder {
// Implement your logic here
return
}
type RouteRegistrar interface {
GET(pattern string, handler http.HandlerFunc)
POST(pattern string, handler http.HandlerFunc)
PUT(pattern string, handler http.HandlerFunc)
PATCH(pattern string, handler http.HandlerFunc)
DELETE(pattern string, handler http.HandlerFunc)
OPTIONS(pattern string, handler http.HandlerFunc)
HEAD(pattern string, handler http.HandlerFunc)
Handle(method, pattern string, handler http.HandlerFunc)
Group(prefix string, mw ...any) *Group
Resource(pattern string, mw ...any) *ResourceBuilder
}// Create a new Router
router := Router{
}type Router struct {
}func Handle(h *ast.IndexListExpr) http.HandlerFuncfunc (*Server) Routes() []RouteInfofunc (*Server) ServeHTTP(w http.ResponseWriter, r *http.Request)// Create a new Server
server := Server{
}type Server struct {
}func Default(opts ...Option) *Serverfunc New(opts ...Option) *Serverfunc (*Server) Addr() stringfunc (*Server) Any(pattern string, handler http.HandlerFunc)func (*Server) Build()func (*Server) CONNECT(pattern string, handler http.HandlerFunc)func (*Server) DELETE(pattern string, handler http.HandlerFunc)func (*Server) GET(pattern string, handler http.HandlerFunc)func (*Group) Group(prefix string, mw ...any) *Groupfunc (*Server) HEAD(pattern string, handler http.HandlerFunc)func (*Server) Handle(method, pattern string, handler http.HandlerFunc)func (*Group) Mount(prefix string, m Module, mw ...any)func (*Group) MountFunc(prefix string, fn func(r RouteRegistrar), mw ...any)func (*Group) OPTIONS(pattern string, handler http.HandlerFunc)func (*Server) OnStart(fn func(s *Server))func (*Server) OnStop(fn func(ctx context.Context, s *Server))func (*Server) PATCH(pattern string, handler http.HandlerFunc)func (*Group) POST(pattern string, handler http.HandlerFunc)func (*Group) PUT(pattern string, handler http.HandlerFunc)func (*Server) PrintRoutes(w io.Writer)func (*Server) Resource(pattern string, mw ...any) *ResourceBuilderfunc (*Server) Routes() []RouteInfofunc (*Server) Run(ctx context.Context) errorfunc (*Router) ServeHTTP(w http.ResponseWriter, req *http.Request)func (*Server) Shutdown(ctx context.Context) errorfunc (*Server) Start(addr ...string) errorfunc (*Server) Static(pattern, root string)func (*Server) TRACE(pattern string, handler http.HandlerFunc)func (*Group) Use(mw ...any)// Create a new TypedResourceBuilder
typedresourcebuilder := TypedResourceBuilder{
}type TypedResourceBuilder struct {
}func TypedResource(s *Server, pattern string, mw ...any) **ast.IndexExprfunc TypedResourceForGroup(g *Group, pattern string, mw ...any) **ast.IndexExprfunc (**ast.IndexExpr) Create(h *ast.IndexListExpr) **ast.IndexExprfunc (**ast.IndexExpr) Custom(method, suffix string, handler http.HandlerFunc) **ast.IndexExprfunc (**ast.IndexExpr) Delete(h *ast.IndexExpr) **ast.IndexExprfunc Get() (T, bool)func (**ast.IndexExpr) List(h *ast.IndexListExpr) **ast.IndexExprfunc (**ast.IndexExpr) Patch(h *ast.IndexListExpr) **ast.IndexExprfunc (**ast.IndexExpr) Update(h *ast.IndexListExpr) **ast.IndexExpr// Example implementation of Validatable
type MyValidatable struct {
// Add your fields here
}
func (m MyValidatable) Validate() error {
// Implement your logic here
return
}
type Validatable interface {
Validate() error
}// Create a new ValidationErrors
validationerrors := ValidationErrors{
}type ValidationErrors struct {
}func NewValidationErrors() *ValidationErrorsfunc (*ValidationErrors) Add(field, message string)func (*ValidationErrors) Addf(field, format string, args ...any)func (*ValidationErrors) Err() errorfunc (*ValidationErrors) Error() stringfunc (*ValidationErrors) Errors() []FieldErrorfunc (*ValidationErrors) HasErrors() boolfunc (*ValidationErrors) Len() intfunc (*ValidationErrors) ToProblem() ValidationProblem// Create a new ValidationProblem
validationproblem := ValidationProblem{
Errors: [],
}type ValidationProblem struct {
Problem
Errors []FieldError `json:"errors,omitempty"`
}func Accepted(w http.ResponseWriter, v any) error// Example usage of Accepted
result := Accepted(/* parameters */)func (*Ctx) Attachment(filename string) *Ctx// Example usage of Attachment
result := Attachment(/* parameters */)func (*Ctx) BadRequest(message string) error// Example usage of BadRequest
result := BadRequest(/* parameters */)func Bind(r *http.Request) (T, error)// Example usage of Bind
result := Bind(/* parameters */)func BindAndValidate(r *http.Request) (T, error)// Example usage of BindAndValidate
result := BindAndValidate(/* parameters */)func BindHeader(r *http.Request) (T, error)// Example usage of BindHeader
result := BindHeader(/* parameters */)func (*Ctx) BindJSON(v any) error// Example usage of BindJSON
result := BindJSON(/* parameters */)func BindPath(r *http.Request) (T, error)// Example usage of BindPath
result := BindPath(/* parameters */)func BindQuery(r *http.Request) (T, error)// Example usage of BindQuery
result := BindQuery(/* parameters */)func Blob(w http.ResponseWriter, status int, contentType string, data []byte) error// Example usage of Blob
result := Blob(/* parameters */)func (*Ctx) Created(v any) error// Example usage of Created
result := Created(/* parameters */)func Error(w http.ResponseWriter, status int, message string) error// Example usage of Error
result := Error(/* parameters */)func File(w http.ResponseWriter, r *http.Request, path string)// Example usage of File
result := File(/* parameters */)func (*Ctx) Forbidden(message string) error// Example usage of Forbidden
result := Forbidden(/* parameters */)func FromContext(ctx context.Context) (T, bool)// Example usage of FromContext
result := FromContext(/* parameters */)func Get() (T, bool)// Example usage of Get
result := Get(/* parameters */)func HTML(w http.ResponseWriter, status int, html string) error// Example usage of HTML
result := HTML(/* parameters */)func Handle(h *ast.IndexListExpr) http.HandlerFunc// Example usage of Handle
result := Handle(/* parameters */)func HandleAccepted(h *ast.IndexListExpr) http.HandlerFunc// Example usage of HandleAccepted
result := HandleAccepted(/* parameters */)func HandleCreated(h *ast.IndexListExpr) http.HandlerFunc// Example usage of HandleCreated
result := HandleCreated(/* parameters */)func HandleCtx(h CtxHandler) http.HandlerFunc// Example usage of HandleCtx
result := HandleCtx(/* parameters */)func HandleEmpty(h EmptyHandler) http.HandlerFunc// Example usage of HandleEmpty
result := HandleEmpty(/* parameters */)func HandleErrorDefault(w http.ResponseWriter, r *http.Request, err error)// Example usage of HandleErrorDefault
result := HandleErrorDefault(/* parameters */)func HandleNoRequest(h *ast.IndexExpr) http.HandlerFunc// Example usage of HandleNoRequest
result := HandleNoRequest(/* parameters */)func HandleNoResponse(h *ast.IndexExpr) http.HandlerFunc// Example usage of HandleNoResponse
result := HandleNoResponse(/* parameters */)func HandleWithStatus(status int, h *ast.IndexListExpr) http.HandlerFunc// Example usage of HandleWithStatus
result := HandleWithStatus(/* parameters */)func Inline(w http.ResponseWriter, filename string)// Example usage of Inline
result := Inline(/* parameters */)func InternalServerError(w http.ResponseWriter, message string) error// Example usage of InternalServerError
result := InternalServerError(/* parameters */)func (*Ctx) JSON(status int, v any) error// Example usage of JSON
result := JSON(/* parameters */)func JSONPretty(w http.ResponseWriter, status int, v any, indent string) error// Example usage of JSONPretty
result := JSONPretty(/* parameters */)func LivenessHandler() http.HandlerFunc// Example usage of LivenessHandler
result := LivenessHandler(/* parameters */)func MustFromContext(ctx context.Context) T// Example usage of MustFromContext
result := MustFromContext(/* parameters */)func MustGet() T// Example usage of MustGet
result := MustGet(/* parameters */)func (*Ctx) NoContent() error// Example usage of NoContent
result := NoContent(/* parameters */)func NotFound(w http.ResponseWriter, message string) error// Example usage of NotFound
result := NotFound(/* parameters */)func OK(w http.ResponseWriter, v any) error// Example usage of OK
result := OK(/* parameters */)func (*Ctx) Param(name string) string// Example usage of Param
result := Param(/* parameters */)func (*Ctx) ParamInt(name string) (int, error)// Example usage of ParamInt
result := ParamInt(/* parameters */)func (*Ctx) ParamInt64(name string) (int64, error)// Example usage of ParamInt64
result := ParamInt64(/* parameters */)func ParamUUID(r *http.Request, name string) (string, error)// Example usage of ParamUUID
result := ParamUUID(/* parameters */)func Query(r *http.Request, name string) string// Example usage of Query
result := Query(/* parameters */)func QueryBool(r *http.Request, name string) bool// Example usage of QueryBool
result := QueryBool(/* parameters */)func (*Ctx) QueryDefault(name, defaultVal string) string// Example usage of QueryDefault
result := QueryDefault(/* parameters */)func QueryFloat64(r *http.Request, name string, defaultVal float64) float64// Example usage of QueryFloat64
result := QueryFloat64(/* parameters */)func QueryInt(r *http.Request, name string, defaultVal int) int// Example usage of QueryInt
result := QueryInt(/* parameters */)func (*Ctx) QueryInt64(name string, defaultVal int64) int64// Example usage of QueryInt64
result := QueryInt64(/* parameters */)func QuerySlice(r *http.Request, name string) []string// Example usage of QuerySlice
result := QuerySlice(/* parameters */)func ReadinessHandler(checks ...func(ctx context.Context) error) http.HandlerFunc// Example usage of ReadinessHandler
result := ReadinessHandler(/* parameters */)func Redirect(w http.ResponseWriter, r *http.Request, url string, code int)// Example usage of Redirect
result := Redirect(/* parameters */)func (ModuleFunc) Register(r RouteRegistrar)// Example usage of Register
result := Register(/* parameters */)func Stream(w http.ResponseWriter, contentType string, reader io.Reader) error// Example usage of Stream
result := Stream(/* parameters */)func Text(w http.ResponseWriter, status int, text string) error// Example usage of Text
result := Text(/* parameters */)func Unauthorized(w http.ResponseWriter, message string) error// Example usage of Unauthorized
result := Unauthorized(/* parameters */)func WithService(ctx context.Context, service T) context.Context// Example usage of WithService
result := WithService(/* parameters */)func WriteProblem(w http.ResponseWriter, p Problem) error// Example usage of WriteProblem
result := WriteProblem(/* parameters */)func WriteValidationProblem(w http.ResponseWriter, v *ValidationErrors) error// Example usage of WriteValidationProblem
result := WriteValidationProblem(/* parameters */)