Documentation
¶
Overview ¶
Package gpp provides an HTTP application framework with routing, request contexts, strict binding and validation, RFC 7807 errors, generated protocol helpers, and server lifecycle management.
Applications own domain rules, authorization policy, persistence schemas, dependency construction, and deployment. Optional packages provide adapters whose production readiness is documented in docs/readiness.md.
Index ¶
- Constants
- func BindResource[T any](group *RouterGroup, relativePath string, repo *dbcore.Repository[T])
- func BindSearchGraphQL(engine *Engine, fieldName string, registry *search.Registry) error
- func BindSearchResource(group *RouterGroup, relativePath string, resource *search.Resource)
- func BindUserResource[T any](target any, relativePath string, tableName ...string)
- func GetAs[T any](c *Context, key string) (T, bool)
- func GetOrDefault[T any](c *Context, key string, defaultValue T) T
- func IsInternalFailure(err error) bool
- func MustGetAs[T any](c *Context, key string) T
- func TotalPages(total, limit int) (int, error)
- type AppConfig
- type CLIOptions
- type Context
- func (c *Context) Abort()
- func (c *Context) AbortWithStatusJSON(statusCode int, payload any) error
- func (c *Context) Accepted(data any) error
- func (c *Context) Async(fn func(c *Context) error)
- func (c *Context) AsyncTask(name string, fn func(c *Context) error) string
- func (c *Context) BadRequest(message string) error
- func (c *Context) BindAndValidate(v any) error
- func (c *Context) BindJSON(v any) error
- func (c *Context) BindNormalizeAndValidate(v any, normalize NormalizeFunc) error
- func (c *Context) Body() ([]byte, error)
- func (c *Context) Conflict(message string) error
- func (c *Context) Created(data any) error
- func (c *Context) DB() *sql.DB
- func (c *Context) DBClient() *dbcore.Client
- func (c *Context) Data(statusCode int, contentType string, data []byte) error
- func (c *Context) Delete(key string)
- func (c *Context) Engine() *Engine
- func (c *Context) File(filepath string) error
- func (c *Context) Forbidden(message string) error
- func (c *Context) Get(key string) (any, bool)
- func (c *Context) GetAny(key string) any
- func (c *Context) GetBool(key string) bool
- func (c *Context) GetCursorAndLimit(defaultLimit ...int) (string, int)
- func (c *Context) GetFloat64(key string) float64
- func (c *Context) GetHeader(key string) string
- func (c *Context) GetInt(key string) int
- func (c *Context) GetInt64(key string) int64
- func (c *Context) GetPageAndLimit(defaultLimit ...int) (int, int)
- func (c *Context) GetString(key string) string
- func (c *Context) GetTaskStatus(taskID string) (*queue.TaskInfo, bool)
- func (c *Context) HTML(statusCode int, html string) error
- func (c *Context) InternalError(message string) error
- func (c *Context) IsAborted() bool
- func (c *Context) IsCancelled() bool
- func (c *Context) JSON(statusCode int, data any) error
- func (c *Context) MustGet(key string) any
- func (c *Context) Next() error
- func (c *Context) NoContent() error
- func (c *Context) NotFound(message string) error
- func (c *Context) OK(data any) error
- func (c *Context) Paginate(statusCode int, items any, page, limit, total int) error
- func (c *Context) PaginateCursor(statusCode int, items any, nextCursor string, hasMore bool, limit int) error
- func (c *Context) Parallel(tasks ...func(c *Context) error) error
- func (c *Context) Param(key string) string
- func (c *Context) ParamInt(key string, defaultValue ...int) int
- func (c *Context) ParamInt64(key string, defaultValue ...int64) int64
- func (c *Context) ParamInt64Strict(key string) (int64, error)
- func (c *Context) ParamIntStrict(key string) (int, error)
- func (c *Context) ParamPositiveInt64(key string) (int64, error)
- func (c *Context) ParamUUIDStrict(key string) (string, error)
- func (c *Context) PathValue(key string) string
- func (c *Context) Problem(problem ProblemDetails) error
- func (c *Context) Query(key string) string
- func (c *Context) QueryBool(key string, defaultValue ...bool) bool
- func (c *Context) QueryDefault(key, defaultValue string) string
- func (c *Context) QueryInt(key string, defaultValue ...int) int
- func (c *Context) QueryInt64Strict(key string) (int64, error)
- func (c *Context) QueryOptionalInt64Strict(key string) (*int64, error)
- func (c *Context) Redirect(code int, location string) error
- func (c *Context) RequestID() string
- func (c *Context) RequireUserID() (int64, error)
- func (c *Context) RequireUserSubject() (string, error)
- func (c *Context) Retry(maxAttempts int, fn func(c *Context) error) error
- func (c *Context) RunWithTimeout(duration time.Duration) error
- func (c *Context) SSE(eventChan <-chan any) error
- func (c *Context) Set(key string, value any)
- func (c *Context) SetHeader(key, value string)
- func (c *Context) Status(code int)
- func (c *Context) String(statusCode int, format string, values ...any) error
- func (c *Context) Unauthorized(message string) error
- func (c *Context) UserID() int64
- func (c *Context) UserSubject() string
- func (c *Context) Validate(v any) error
- func (c *Context) Value(key string) any
- type Engine
- func (engine *Engine) AuthManager() any
- func (engine *Engine) AutoGRPCMultiplex(grpcHandler http.Handler) HandlerFunc
- func (engine *Engine) AutoGraphQLHandler() HandlerFunc
- func (engine *Engine) AutoGraphQLPlayground(graphqlEndpoint string) HandlerFunc
- func (engine *Engine) AutoSwaggerUI() HandlerFunc
- func (engine *Engine) DB() *sql.DB
- func (engine *Engine) DBClient() *dbcore.Client
- func (engine *Engine) HandleCLI(opts CLIOptions) bool
- func (engine *Engine) Listen(addr string) error
- func (engine *Engine) ListenTLS(addr, certFile, keyFile string) error
- func (engine *Engine) RegisterGraphQLQuery(name string, field *graphql.Field) error
- func (engine *Engine) RegisterModel(ctx context.Context, models ...any) error
- func (engine *Engine) RegisterModule(prefix string, module Module)
- func (engine *Engine) RegisterModules(modules ...Module)
- func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (engine *Engine) SetAuthManager(mgr any)
- func (engine *Engine) SetDBClient(client *dbcore.Client)
- type FieldViolation
- type H
- type HTTPError
- type HandlerFunc
- type HandlersChain
- type InternalErrorOption
- type InternalFailure
- type JSONBindingConfig
- type Map
- type Module
- type NormalizeFunc
- type OpenAPIGenerator
- type Pagination
- type PaginationPolicy
- type Param
- type Params
- type ProblemDetails
- func ErrBadRequest(detail string) *ProblemDetails
- func ErrConflict(detail string) *ProblemDetails
- func ErrForbidden(detail string) *ProblemDetails
- func ErrInternal(detail string) *ProblemDetails
- func ErrNotFound(detail string) *ProblemDetails
- func ErrRequestTimeout(detail string) *ProblemDetails
- func ErrUnauthorized(detail string) *ProblemDetails
- func ErrValidation(violations []FieldViolation) *ProblemDetails
- type RouteMetadata
- type RouterGroup
- func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc)
- func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc)
- func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc)
- func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup
- func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc)
- func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc)
- func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc)
- func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc)
- func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc)
- func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc)
- func (group *RouterGroup) RegisterModule(relativePath string, module Module)
- func (group *RouterGroup) Static(relativePath, root string)
- func (group *RouterGroup) StaticEmbed(relativePath string, embedFS embed.FS, optionalSubDir ...string)
- func (group *RouterGroup) StaticFS(relativePath string, fsys fs.FS)
- func (group *RouterGroup) Use(middlewares ...HandlerFunc)
- func (group *RouterGroup) V1(relativePath ...string) *RouterGroup
- func (group *RouterGroup) V2(relativePath ...string) *RouterGroup
- func (group *RouterGroup) Version(v string, relativePath ...string) *RouterGroup
Constants ¶
const ( // DefaultMaxJSONBodyBytes is the default accepted JSON request size. DefaultMaxJSONBodyBytes int64 = 1 << 20 // MaximumJSONBodyBytes is the hard upper bound for configured JSON request sizes. MaximumJSONBodyBytes int64 = 64 << 20 )
const Version = "v1.11.9"
Version is the current release version of the goplusplus framework.
Variables ¶
This section is empty.
Functions ¶
func BindResource ¶
func BindResource[T any](group *RouterGroup, relativePath string, repo *dbcore.Repository[T])
BindResource automatically mounts a complete set of RESTful CRUD routes (GET /, GET /:id, POST /, PUT /:id, DELETE /:id) for entity T using dbcore.Repository[T].
func BindSearchGraphQL ¶
BindSearchGraphQL registers a typed search query field backed by registry.
func BindSearchResource ¶
func BindSearchResource(group *RouterGroup, relativePath string, resource *search.Resource)
BindSearchResource registers a JSON search endpoint on group.
func BindUserResource ¶ added in v1.11.9
BindUserResource automatically mounts complete, user-scoped RESTful CRUD routes (GET /, GET /:id, POST /, PUT /:id, DELETE /:id) for entity T. All operations are strictly filtered and authorized by the logged-in User's ID.
func GetOrDefault ¶
GetOrDefault retrieves a context value typed as T, or returns defaultValue if not set or wrong type.
func IsInternalFailure ¶
IsInternalFailure reports whether err represents a server-side failure.
func TotalPages ¶
TotalPages calculates the page count for a non-negative total and positive limit.
Types ¶
type AppConfig ¶ added in v1.11.9
type AppConfig struct {
Env string
Port int
DBDriver string
DBPath string
RWDSN string
RODSN string
AuthSecret string
AutoMigrate bool
}
AppConfig defines options for high-level zero-boilerplate app initialization.
type CLIOptions ¶
type CLIOptions struct {
Client *dbcore.Client
Migrations []dbcore.Migration
SeedPlans []seed.Plan
Args []string // Optional override args for testing (defaults to os.Args if empty)
}
CLIOptions defines configuration for application binary CLI flags.
type Context ¶
type Context struct {
Writer http.ResponseWriter
Request *http.Request
Params Params
// contains filtered or unexported fields
}
Context represents the request-scoped context containing Request, ResponseWriter, and parameter metadata.
func (*Context) Abort ¶
func (c *Context) Abort()
Abort stops the execution of remaining handlers in the current request chain.
func (*Context) AbortWithStatusJSON ¶
AbortWithStatusJSON aborts execution and writes a JSON error payload immediately.
func (*Context) Accepted ¶
Accepted writes an HTTP 202 Accepted JSON response for asynchronous operations.
func (*Context) Async ¶
Async dispatches a non-blocking background task in a detached goroutine with panic safety.
func (*Context) AsyncTask ¶
AsyncTask dispatches a background task with automatic retries on failure and persistent status tracking, returning a task ID.
func (*Context) BadRequest ¶
BadRequest writes an HTTP 400 Bad Request error response.
func (*Context) BindAndValidate ¶
BindAndValidate decodes the JSON request body and validates struct fields in a single atomic step.
func (*Context) BindNormalizeAndValidate ¶
func (c *Context) BindNormalizeAndValidate(v any, normalize NormalizeFunc) error
BindNormalizeAndValidate executes the explicit request processing pipeline.
func (*Context) DB ¶ added in v1.11.9
DB returns the primary *sql.DB connection associated with the engine.
func (*Context) DBClient ¶ added in v1.11.9
DBClient returns the active dbcore.Client associated with the engine.
func (*Context) Engine ¶ added in v1.11.9
Engine returns the engine back-reference for this request.
func (*Context) GetAny ¶
GetAny retrieves a stored value by key as a single return value (nil if not found).
func (*Context) GetBool ¶
GetBool retrieves a stored value converted to bool. Returns false if not found or unconvertible.
func (*Context) GetCursorAndLimit ¶
GetCursorAndLimit parses query parameters 'cursor' and 'limit' with safe fallback defaults.
func (*Context) GetFloat64 ¶
GetFloat64 retrieves a stored value converted to float64. Returns 0.0 if not found or unconvertible.
func (*Context) GetInt ¶
GetInt retrieves a stored value converted to int. Returns 0 if not found or unconvertible.
func (*Context) GetInt64 ¶
GetInt64 retrieves a stored value converted to int64. Returns 0 if not found or unconvertible.
func (*Context) GetPageAndLimit ¶
GetPageAndLimit parses query parameters 'page' and 'limit' with safe fallback defaults.
func (*Context) GetString ¶
GetString retrieves a stored string value from context storage, converting numeric/boolean values if necessary.
func (*Context) GetTaskStatus ¶
GetTaskStatus retrieves the status and retry details of a background task by ID.
func (*Context) InternalError ¶
InternalError writes an HTTP 500 Internal Server Error response.
func (*Context) IsAborted ¶
IsAborted returns true if the current context request chain has been aborted.
func (*Context) IsCancelled ¶
IsCancelled returns true if the client closed the browser connection or cancelled the request.
func (*Context) JSON ¶
JSON serializes the given data struct into JSON and writes it with the status code.
func (*Context) PaginateCursor ¶
func (c *Context) PaginateCursor(statusCode int, items any, nextCursor string, hasMore bool, limit int) error
PaginateCursor writes a standardized O(1) high-performance cursor-based paginated JSON response.
func (*Context) Parallel ¶
Parallel executes multiple task functions concurrently in parallel goroutines.
func (*Context) Param ¶
Param retrieves a path parameter by name (e.g. /users/:id -> c.Param("id")).
func (*Context) ParamInt ¶
ParamInt retrieves a path parameter converted directly to int with optional default fallback.
func (*Context) ParamInt64 ¶
ParamInt64 retrieves a path parameter converted directly to int64 with optional default fallback.
func (*Context) ParamInt64Strict ¶
ParamInt64Strict parses a required path parameter as an int64.
func (*Context) ParamIntStrict ¶
ParamIntStrict parses a required path parameter without fallback behavior.
func (*Context) ParamPositiveInt64 ¶
ParamPositiveInt64 parses a required positive int64 path parameter.
func (*Context) ParamUUIDStrict ¶
ParamUUIDStrict validates a required UUID path parameter.
func (*Context) PathValue ¶
PathValue is an alias for Param, providing Go 1.22+ r.PathValue() compatibility.
func (*Context) Problem ¶
func (c *Context) Problem(problem ProblemDetails) error
Problem writes an RFC 7807/9457 Problem Details response.
func (*Context) QueryBool ¶
QueryBool retrieves a query parameter converted to boolean with optional default fallback.
func (*Context) QueryDefault ¶
QueryDefault retrieves a URL query parameter by name, returning defaultValue if empty.
func (*Context) QueryInt ¶
QueryInt retrieves a query parameter converted to integer with optional default fallback.
func (*Context) QueryInt64Strict ¶
QueryInt64Strict parses a required query parameter as an int64.
func (*Context) QueryOptionalInt64Strict ¶
QueryOptionalInt64Strict parses an optional int64 query parameter.
func (*Context) RequireUserID ¶
RequireUserID returns the active authenticated user ID, or returns a 401 Unauthorized error if unauthenticated.
func (*Context) RequireUserSubject ¶
RequireUserSubject returns the canonical string identity or a 401 error.
func (*Context) Retry ¶
Retry executes a function with up to maxAttempts automatic retries on error.
func (*Context) RunWithTimeout ¶
RunWithTimeout executes the remaining handler chain against an isolated, buffered response. Only the request goroutine commits a response.
func (*Context) Unauthorized ¶
Unauthorized writes an HTTP 401 Unauthorized error response.
func (*Context) UserID ¶
UserID extracts the active authenticated user ID (int64) from request context storage ("user_id" or "sub").
func (*Context) UserSubject ¶
UserSubject returns the canonical authenticated string identity. Unlike UserID, it supports UUIDs and other bounded opaque identifiers.
type Engine ¶
type Engine struct {
RouterGroup
NotFoundHandler HandlerFunc
ErrorHandler func(c *Context, err error)
Server *http.Server
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
MaxHeaderBytes int
ShutdownTimeout time.Duration
JSONBinding JSONBindingConfig
// contains filtered or unexported fields
}
Engine is the central core of the go++ framework, serving as router, HTTP server wrapper, and handler.
func New ¶
func New() *Engine
New creates a fresh instance of the go++ engine with high-performance default configurations.
func NewApp ¶ added in v1.11.9
NewApp creates a zero-boilerplate application engine pre-configured with logging, recovery, security headers, CORS, and auto-DB connection.
func (*Engine) AuthManager ¶ added in v1.11.9
AuthManager returns the registered authentication manager handle.
func (*Engine) AutoGRPCMultiplex ¶
func (engine *Engine) AutoGRPCMultiplex(grpcHandler http.Handler) HandlerFunc
AutoGRPCMultiplex returns middleware that automatically detects gRPC requests over HTTP/2 and multiplexes them to a gRPC server.
func (*Engine) AutoGraphQLHandler ¶
func (engine *Engine) AutoGraphQLHandler() HandlerFunc
AutoGraphQLHandler executes schema-validated GraphQL queries over registered fields.
func (*Engine) AutoGraphQLPlayground ¶
func (engine *Engine) AutoGraphQLPlayground(graphqlEndpoint string) HandlerFunc
AutoGraphQLPlayground returns a HandlerFunc that serves the GraphQL Playground IDE automatically linked to /graphql.
func (*Engine) AutoSwaggerUI ¶
func (engine *Engine) AutoSwaggerUI() HandlerFunc
AutoSwaggerUI returns a HandlerFunc that serves Swagger UI using the auto-generated OpenAPI spec.
func (*Engine) DBClient ¶ added in v1.11.9
DBClient returns the initialized dbcore.Client associated with the engine.
func (*Engine) HandleCLI ¶
func (engine *Engine) HandleCLI(opts CLIOptions) bool
HandleCLI inspects binary CLI flags (e.g. ./myapp migrate, ./myapp seed, ./myapp migrate:fresh). If a CLI flag is detected, it executes the target database task and returns true.
func (*Engine) Listen ¶
Listen starts an HTTP server listening on the provided address with graceful shutdown support.
func (*Engine) ListenTLS ¶
ListenTLS starts an HTTPS server listening on the provided address using TLS certificates.
func (*Engine) RegisterGraphQLQuery ¶
RegisterGraphQLQuery adds a schema-validated field to the automatic GraphQL endpoint.
func (*Engine) RegisterModel ¶ added in v1.11.9
RegisterModel registers entity models and automatically creates their database tables.
func (*Engine) RegisterModule ¶
RegisterModule mounts a self-contained domain module under a specific URL path prefix.
func (*Engine) RegisterModules ¶
RegisterModules mounts multiple domain modules onto the root engine.
func (*Engine) ServeHTTP ¶
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP implements net/http.Handler using pooled request contexts.
func (*Engine) SetAuthManager ¶ added in v1.11.9
SetAuthManager attaches an authentication token manager or provider to the app engine.
func (*Engine) SetDBClient ¶ added in v1.11.9
SetDBClient attaches an explicit database client to the app engine.
type FieldViolation ¶
type FieldViolation struct {
Field string `json:"field"`
Rule string `json:"rule"`
Message string `json:"message"`
}
FieldViolation is a machine-readable request validation failure. Values are intentionally excluded to avoid exposing passwords, tokens, or personal data.
type HTTPError ¶
type HTTPError struct {
Code int `json:"code"`
Message string `json:"message"`
Details any `json:"details,omitempty"`
}
HTTPError represents a standardized structured framework error.
func NewHTTPError ¶
NewHTTPError constructs a new HTTPError with status code, message, and optional details.
type HandlerFunc ¶
HandlerFunc defines the function signature for framework handlers and middleware.
type HandlersChain ¶
type HandlersChain []HandlerFunc
HandlersChain is a slice of HandlerFunc executed in sequence.
type InternalErrorOption ¶
type InternalErrorOption func(*InternalFailure)
InternalErrorOption configures a causal internal failure.
func WithErrorCategory ¶
func WithErrorCategory(category string) InternalErrorOption
WithErrorCategory sets a stable internal error category.
func WithInternalStatus ¶
func WithInternalStatus(status int) InternalErrorOption
WithInternalStatus sets a 5xx response status for the internal failure.
func WithPublicDetail ¶
func WithPublicDetail(detail string) InternalErrorOption
WithPublicDetail opts into a caller-authored, non-sensitive 5xx detail.
func WithSafeAttributes ¶
func WithSafeAttributes(attributes map[string]any) InternalErrorOption
WithSafeAttributes copies explicitly non-sensitive structured log attributes.
type InternalFailure ¶
type InternalFailure struct {
Operation string
Category string
Cause error
Attributes map[string]any
PublicDetail string
Status int
}
InternalFailure is a causal server-side failure. Only PublicDetail and the stable category are eligible for client rendering; Cause and Attributes are logged internally.
func NewInternalError ¶
func NewInternalError(operation string, cause error, options ...InternalErrorOption) *InternalFailure
NewInternalError preserves cause identity while keeping the response safe.
func (*InternalFailure) Error ¶
func (e *InternalFailure) Error() string
Error returns a sanitized internal failure summary.
func (*InternalFailure) Unwrap ¶
func (e *InternalFailure) Unwrap() error
Unwrap returns the causal internal error.
type JSONBindingConfig ¶
type JSONBindingConfig struct {
MaxBodyBytes int64
AllowUnknownFields bool
AllowNonJSONContentType bool
}
JSONBindingConfig controls request JSON decoding. Zero values retain secure defaults.
type Module ¶
type Module interface {
Name() string
Register(group *RouterGroup)
}
Module defines the contract for self-contained domain modules in a modular monolith.
type NormalizeFunc ¶
NormalizeFunc applies application-owned normalization after binding and before validation. A nil callback is a documented no-op.
type OpenAPIGenerator ¶
type OpenAPIGenerator struct {
Title string
Version string
// contains filtered or unexported fields
}
OpenAPIGenerator automatically inspects routes and constructs live OpenAPI 3.0 specs.
func (*OpenAPIGenerator) GenerateJSON ¶
func (g *OpenAPIGenerator) GenerateJSON() string
GenerateJSON builds a JSON OpenAPI 3.0 specification string.
func (*OpenAPIGenerator) RegisterRoute ¶
func (g *OpenAPIGenerator) RegisterRoute(method, pathStr string)
RegisterRoute registers route metadata into the OpenAPI specification tree.
type Pagination ¶
type Pagination struct {
Page int `json:"page"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
Pagination is a normalized, overflow-checked offset pagination request.
type PaginationPolicy ¶
type PaginationPolicy struct {
DefaultPage int
DefaultLimit int
MaximumLimit int
MaximumPage int
PageParameter string
LimitParameter string
Strict bool
}
PaginationPolicy defines names, defaults, limits, and strictness for offset pagination.
func (PaginationPolicy) Parse ¶
func (policy PaginationPolicy) Parse(c *Context) (Pagination, error)
Parse reads and normalizes pagination parameters from c.
type ProblemDetails ¶
type ProblemDetails struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail"`
Instance string `json:"instance,omitempty"`
TraceID string `json:"trace_id,omitempty"`
Errors []FieldViolation `json:"errors,omitempty"`
}
ProblemDetails implements the RFC 7807 standard specification for HTTP API Problem Details.
func ErrBadRequest ¶
func ErrBadRequest(detail string) *ProblemDetails
ErrBadRequest creates an RFC 7807 400 Bad Request problem details error.
func ErrConflict ¶
func ErrConflict(detail string) *ProblemDetails
ErrConflict creates an RFC 7807 409 Conflict problem details error.
func ErrForbidden ¶
func ErrForbidden(detail string) *ProblemDetails
ErrForbidden creates an RFC 7807 403 Forbidden problem details error.
func ErrInternal ¶
func ErrInternal(detail string) *ProblemDetails
ErrInternal creates an RFC 7807 500 Internal Server Error problem details error.
func ErrNotFound ¶
func ErrNotFound(detail string) *ProblemDetails
ErrNotFound creates an RFC 7807 404 Not Found problem details error.
func ErrRequestTimeout ¶
func ErrRequestTimeout(detail string) *ProblemDetails
ErrRequestTimeout creates an RFC 7807 504 Gateway Timeout error.
func ErrUnauthorized ¶
func ErrUnauthorized(detail string) *ProblemDetails
ErrUnauthorized creates an RFC 7807 401 Unauthorized problem details error.
func ErrValidation ¶
func ErrValidation(violations []FieldViolation) *ProblemDetails
ErrValidation creates a structured RFC 7807 validation response.
func (*ProblemDetails) Error ¶
func (p *ProblemDetails) Error() string
Error implements standard Go error interface.
type RouteMetadata ¶
type RouteMetadata struct {
Method string
Path string
Summary string
Description string
Params []string
}
RouteMetadata holds parameter and summary metadata for an endpoint.
type RouterGroup ¶
type RouterGroup struct {
// contains filtered or unexported fields
}
RouterGroup organizes routes under a common path prefix and middleware set.
func (*RouterGroup) Any ¶
func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc)
Any registers a route for all common HTTP methods.
func (*RouterGroup) DELETE ¶
func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc)
DELETE registers a DELETE route.
func (*RouterGroup) GET ¶
func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc)
GET registers a GET route.
func (*RouterGroup) Group ¶
func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup
Group creates a new child route group with a path prefix and optional middleware.
func (*RouterGroup) HEAD ¶
func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc)
HEAD registers a HEAD route.
func (*RouterGroup) Handle ¶
func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc)
Handle registers a new request handler for a given HTTP method and path.
func (*RouterGroup) OPTIONS ¶
func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc)
OPTIONS registers an OPTIONS route.
func (*RouterGroup) PATCH ¶
func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc)
PATCH registers a PATCH route.
func (*RouterGroup) POST ¶
func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc)
POST registers a POST route.
func (*RouterGroup) PUT ¶
func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc)
PUT registers a PUT route.
func (*RouterGroup) RegisterModule ¶
func (group *RouterGroup) RegisterModule(relativePath string, module Module)
RegisterModule mounts a domain module under a relative sub-route group.
func (*RouterGroup) Static ¶
func (group *RouterGroup) Static(relativePath, root string)
Static serves static files from a root directory under a URL path prefix.
func (*RouterGroup) StaticEmbed ¶
func (group *RouterGroup) StaticEmbed(relativePath string, embedFS embed.FS, optionalSubDir ...string)
StaticEmbed mounts an embedded filesystem (embed.FS) with zero-boilerplate automatic subfolder resolution (dist, build, static, public) and SPA index.html fallback.
func (*RouterGroup) StaticFS ¶
func (group *RouterGroup) StaticFS(relativePath string, fsys fs.FS)
StaticFS serves embedded static files from an io/fs.FS filesystem (e.g. embed.FS) with SPA fallback routing to index.html.
func (*RouterGroup) Use ¶
func (group *RouterGroup) Use(middlewares ...HandlerFunc)
Use appends middleware to the current route group.
func (*RouterGroup) V1 ¶ added in v1.11.9
func (group *RouterGroup) V1(relativePath ...string) *RouterGroup
V1 creates a router group versioned under /api/v1.
func (*RouterGroup) V2 ¶ added in v1.11.9
func (group *RouterGroup) V2(relativePath ...string) *RouterGroup
V2 creates a router group versioned under /api/v2.
func (*RouterGroup) Version ¶ added in v1.11.9
func (group *RouterGroup) Version(v string, relativePath ...string) *RouterGroup
Version creates a versioned router group under /api/{version} or /{version}.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package audit emits structured security and business audit events through log/slog.
|
Package audit emits structured security and business audit events through log/slog. |
|
Package auth provides password policy, signed token verification, session helpers, verified request identity, role checks, and attribute policies.
|
Package auth provides password policy, signed token verification, session helpers, verified request identity, role checks, and attribute policies. |
|
Package bloom implements process-local probabilistic membership filters.
|
Package bloom implements process-local probabilistic membership filters. |
|
Package cache defines cache stores and bounded memory and Redis implementations.
|
Package cache defines cache stores and bounded memory and Redis implementations. |
|
cmd
|
|
|
doccheck
command
Command doccheck verifies package and exported API documentation coverage.
|
Command doccheck verifies package and exported API documentation coverage. |
|
gpp
command
|
|
|
Package config loads typed application configuration from explicit sources.
|
Package config loads typed application configuration from explicit sources. |
|
Package dbcore provides PostgreSQL and SQLite clients, transactions, migrations, typed queries, ORM conveniences, and stable database error classification.
|
Package dbcore provides PostgreSQL and SQLite clients, transactions, migrations, typed queries, ORM conveniences, and stable database error classification. |
|
seed
Package seed provides development and test data generation.
|
Package seed provides development and test data generation. |
|
Package di provides a small process-local dependency container.
|
Package di provides a small process-local dependency container. |
|
examples
|
|
|
authentication
Package authentication demonstrates application-owned registration, login, account persistence, and hash migration using framework-owned auth mechanics.
|
Package authentication demonstrates application-owned registration, login, account persistence, and hash migration using framework-owned auth mechanics. |
|
cloud_infrastructure
command
|
|
|
config_demo
command
|
|
|
enterprise_platform
command
|
|
|
enterprise_stack
command
|
|
|
grpc_gateway/gateway
command
|
|
|
grpc_gateway/proto
Package proto declares the transport-neutral user contract for the gRPC example.
|
Package proto declares the transport-neutral user contract for the gRPC example. |
|
grpc_gateway/services
Package services provides local and remote user-service example adapters.
|
Package services provides local and remote user-service example adapters. |
|
hyper_scale_app
command
|
|
|
interface_architecture
command
|
|
|
load_test
command
|
|
|
modular_monolith/cmd/monolith
command
|
|
|
modular_monolith/modules/order
Package order demonstrates a self-contained modular-monolith order domain.
|
Package order demonstrates a self-contained modular-monolith order domain. |
|
modular_monolith/modules/user
Package user demonstrates a self-contained modular-monolith user domain.
|
Package user demonstrates a self-contained modular-monolith user domain. |
|
parallel_concurrency
command
|
|
|
probabilistic_demo
command
|
|
|
production_ready_app
command
|
|
|
react_embedded
command
|
|
|
realtime_demo
command
|
|
|
secure_platform
command
|
|
|
task_tracker_demo
command
|
|
|
Package features provides process-local feature flag evaluation.
|
Package features provides process-local feature flag evaluation. |
|
Package gpptest provides typed helpers for exercising gpp applications through httptest without opening network sockets.
|
Package gpptest provides typed helpers for exercising gpp applications through httptest without opening network sockets. |
|
Package health provides bounded liveness and readiness HTTP handlers.
|
Package health provides bounded liveness and readiness HTTP handlers. |
|
Package i18n provides language negotiation, translation catalogs, plurals, locale-aware number and money formatting, and localized date/time rendering.
|
Package i18n provides language negotiation, translation catalogs, plurals, locale-aware number and money formatting, and localized date/time rendering. |
|
Package id generates UUID, UUIDv7, ULID, Snowflake, and prefixed identifiers.
|
Package id generates UUID, UUIDv7, ULID, Snowflake, and prefixed identifiers. |
|
Package middleware provides gpp HTTP middleware for security, observability, recovery, request IDs, timeouts, rate limiting, idempotency, and protocol endpoints.
|
Package middleware provides gpp HTTP middleware for security, observability, recovery, request IDs, timeouts, rate limiting, idempotency, and protocol endpoints. |
|
Package notify defines email and SMS provider contracts and bounded SendGrid and Twilio adapters.
|
Package notify defines email and SMS provider contracts and bounded SendGrid and Twilio adapters. |
|
Package pubsub provides development-only in-memory publish/subscribe plus Redis and RabbitMQ adapters.
|
Package pubsub provides development-only in-memory publish/subscribe plus Redis and RabbitMQ adapters. |
|
Package queue defines task publication, Kafka producer and consumer adapters, transactional outbox support, and process-local task tracking.
|
Package queue defines task publication, Kafka producer and consumer adapters, transactional outbox support, and process-local task tracking. |
|
Package realtime provides Server-Sent Events and WebSocket handlers with bounded connection and message behavior.
|
Package realtime provides Server-Sent Events and WebSocket handlers with bounded connection and message behavior. |
|
Package resilience provides circuit breaking, adaptive concurrency limiting, and retry helpers.
|
Package resilience provides circuit breaking, adaptive concurrency limiting, and retry helpers. |
|
Package saga provides experimental process-local step coordination with reverse compensation.
|
Package saga provides experimental process-local step coordination with reverse compensation. |
|
Package search defines schemas, normalized search requests, resource indexing, facets, and memory, PostgreSQL, and Elasticsearch backends.
|
Package search defines schemas, normalized search requests, resource indexing, facets, and memory, PostgreSQL, and Elasticsearch backends. |
|
Package storage defines object storage operations and local and S3-backed implementations.
|
Package storage defines object storage operations and local and S3-backed implementations. |
|
Package tenant extracts and installs tenant identity for request processing.
|
Package tenant extracts and installs tenant identity for request processing. |
|
Package tracing configures OpenTelemetry trace export and lifecycle helpers.
|
Package tracing configures OpenTelemetry trace export and lifecycle helpers. |
|
Package versioning negotiates API versions and emits deprecation and sunset metadata.
|
Package versioning negotiates API versions and emits deprecation and sunset metadata. |