Documentation
¶
Index ¶
- Variables
- func GetHTTPStatus(err error) int
- func IsCode(err error, code ErrorCode) bool
- func ValidateEncryptionKey(key []byte) error
- type BackgroundService
- type DataService
- type Database
- type Encryption
- type ErrorCode
- type FileSystemRegistry
- type Gemquick
- func (g *Gemquick) AddMonitoringRoutes(mux *chi.Mux)
- func (g *Gemquick) BuildDSN() string
- func (g Gemquick) CreateDirIfNotExists(path string) error
- func (g Gemquick) CreateFileIfNotExists(path string) error
- func (g *Gemquick) DownloadFile(w http.ResponseWriter, r *http.Request, pathToFile, filename string) error
- func (g *Gemquick) Error404(w http.ResponseWriter, r *http.Request)
- func (g *Gemquick) Error500(w http.ResponseWriter, r *http.Request)
- func (g *Gemquick) ErrorForbidden(w http.ResponseWriter, r *http.Request)
- func (g *Gemquick) ErrorStatus(w http.ResponseWriter, status int)
- func (g *Gemquick) ErrorUnauthorized(w http.ResponseWriter, r *http.Request)
- func (g *Gemquick) GetModule(name string) Module
- func (g *Gemquick) HasModule(name string) bool
- func (g *Gemquick) Init(p initPaths) error
- func (g *Gemquick) ListenAndServe()
- func (g *Gemquick) LoadTime(start time.Time)
- func (g *Gemquick) MigrateDownAll(dsn string) error
- func (g *Gemquick) MigrateForce(dsn string) error
- func (g *Gemquick) MigrateUp(dsn string) error
- func (g *Gemquick) New(rootPath string, modules ...Module) error
- func (g *Gemquick) NoSurf(next http.Handler) http.Handler
- func (g *Gemquick) OpenDB(dbType, dsn string) (*sql.DB, error)
- func (g Gemquick) RandomString(length int) string
- func (g *Gemquick) ReadJson(w http.ResponseWriter, r *http.Request, data interface{}) error
- func (g *Gemquick) SessionLoad(next http.Handler) http.Handler
- func (g *Gemquick) Shutdown(ctx context.Context) error
- func (g *Gemquick) Steps(steps int, dsn string) error
- func (g *Gemquick) Validator(data url.Values) *Validation
- func (g *Gemquick) WriteJson(w http.ResponseWriter, status int, data interface{}, headers ...http.Header) error
- func (g *Gemquick) WriteXML(w http.ResponseWriter, status int, data interface{}, headers ...http.Header) error
- type GemquickError
- type HTTPService
- type LoggingService
- type Module
- type ModuleRegistry
- func (r *ModuleRegistry) Count() int
- func (r *ModuleRegistry) Get(name string) Module
- func (r *ModuleRegistry) Has(name string) bool
- func (r *ModuleRegistry) InitializeAll(g *Gemquick) error
- func (r *ModuleRegistry) Names() []string
- func (r *ModuleRegistry) Register(m Module) error
- func (r *ModuleRegistry) ShutdownAll(ctx context.Context) error
- type Server
- type Validation
- func (v *Validation) AddError(key, message string)
- func (v *Validation) Check(ok bool, key, message string)
- func (v *Validation) Equals(eq bool, field, verified string)
- func (v *Validation) EscapeHTML(value string) string
- func (v *Validation) Has(field string, r *http.Request) bool
- func (v *Validation) IsAlphanumeric(field, value string)
- func (v *Validation) IsDateISO(field, value string)
- func (v *Validation) IsEmail(field, value string)
- func (v *Validation) IsFloat(field, value string)
- func (v *Validation) IsInt(field, value string)
- func (v *Validation) IsString(field, value string)
- func (v *Validation) IsURL(field, value string)
- func (v *Validation) MaxLength(field, value string, maxLength int)
- func (v *Validation) MinLength(field, value string, minLength int)
- func (v *Validation) NoSpaces(field, value string)
- func (v *Validation) Required(r *http.Request, fields ...string)
- func (v *Validation) SanitizeHTML(value string) string
- func (v *Validation) SanitizeRichText(value string) string
- func (v *Validation) Valid() bool
- type ValidationError
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNotFoundError is returned when a resource is not found ErrNotFoundError = NewError("", "resource not found", ErrNotFound) ErrUnauthorizedError = NewError("", "unauthorized", ErrUnauthorized) // ErrForbiddenError is returned when access is denied ErrForbiddenError = NewError("", "access denied", ErrForbidden) // ErrInternalError is returned for internal server errors ErrInternalError = NewError("", "internal server error", ErrInternal) // ErrValidationError is returned for validation failures ErrValidationError = NewError("", "validation failed", ErrValidation) )
Common pre-defined errors for convenience
Functions ¶
func GetHTTPStatus ¶
GetHTTPStatus returns the appropriate HTTP status for an error
func ValidateEncryptionKey ¶
ValidateEncryptionKey checks that the key meets AES requirements. AES requires keys of exactly 16, 24, or 32 bytes for AES-128, AES-192, or AES-256.
Types ¶
type BackgroundService ¶
type BackgroundService struct {
Jobs *jobs.JobManager
Scheduler *cron.Cron
Mail email.Mail
SMS sms.SMSProvider
// contains filtered or unexported fields
}
BackgroundService handles background jobs, scheduling, mail, and SMS
func (*BackgroundService) GetCronEntry ¶
func (b *BackgroundService) GetCronEntry(name string) (cron.EntryID, bool)
GetCronEntry returns the entry ID for a named cron job.
func (*BackgroundService) ListCronJobs ¶
func (b *BackgroundService) ListCronJobs() []string
ListCronJobs returns all named cron job names.
func (*BackgroundService) ScheduleCron ¶
func (b *BackgroundService) ScheduleCron(name, expr string, fn func()) (cron.EntryID, error)
ScheduleCron adds a named cron job that can be unscheduled later. Returns the entry ID and any error from adding the job.
func (*BackgroundService) UnscheduleCron ¶
func (b *BackgroundService) UnscheduleCron(name string) bool
UnscheduleCron removes a named cron job. Returns true if the job was found and removed.
type DataService ¶
type DataService struct {
DB Database
Cache cache.Cache
Files *FileSystemRegistry
// contains filtered or unexported fields
}
DataService handles database, caching, and file storage
type Encryption ¶
type Encryption struct {
Key []byte
}
func NewEncryption ¶
func NewEncryption(key []byte) (*Encryption, error)
NewEncryption creates a validated encryption instance. Returns an error if the key doesn't meet AES requirements.
type ErrorCode ¶
type ErrorCode int
ErrorCode represents categories of errors for classification and handling
const ( // ErrInternal represents internal server errors ErrInternal ErrorCode = iota // ErrValidation represents input validation failures ErrValidation // ErrNotFound represents resource not found errors ErrNotFound ErrUnauthorized // ErrForbidden represents access denied errors ErrForbidden // ErrDatabase represents database operation failures ErrDatabase // ErrExternal represents external service failures ErrExternal // ErrConfiguration represents configuration errors ErrConfiguration // ErrTimeout represents operation timeout errors ErrTimeout )
func (ErrorCode) HTTPStatus ¶
HTTPStatus returns the appropriate HTTP status code for an ErrorCode
type FileSystemRegistry ¶
type FileSystemRegistry struct {
// contains filtered or unexported fields
}
FileSystemRegistry provides thread-safe access to registered file systems. It uses the filesystems.FS interface for type safety instead of map[string]interface{}.
func NewFileSystemRegistry ¶
func NewFileSystemRegistry() *FileSystemRegistry
NewFileSystemRegistry creates a new file system registry
func (*FileSystemRegistry) Get ¶
func (r *FileSystemRegistry) Get(name string) (filesystems.FS, bool)
Get retrieves a file system by name
func (*FileSystemRegistry) Has ¶
func (r *FileSystemRegistry) Has(name string) bool
Has checks if a file system is registered
func (*FileSystemRegistry) Names ¶
func (r *FileSystemRegistry) Names() []string
Names returns all registered file system names
func (*FileSystemRegistry) Register ¶
func (r *FileSystemRegistry) Register(name string, fs filesystems.FS)
Register adds a file system to the registry
type Gemquick ¶
type Gemquick struct {
// Core configuration
AppName string
Debug bool
Version string
RootPath string
EncryptionKey string
Server Server
Config *config.Config
// Services (composed)
Logging *LoggingService
HTTP *HTTPService
Data *DataService
Background *BackgroundService
// Modules (opt-in components)
Modules *ModuleRegistry
}
Gemquick is the main framework struct that orchestrates all components. It uses composition to organize functionality into focused services: - Logging: structured logging, metrics, and health monitoring - HTTP: routing, sessions, and template rendering - Data: database, caching, and file storage - Background: job processing, scheduling, mail, and SMS - Modules: optional components (SMS, Email, WebSocket, OTel, etc.)
func (*Gemquick) AddMonitoringRoutes ¶
AddMonitoringRoutes adds health and metrics endpoints. Call this in your routes() function AFTER adding your middleware.
func (*Gemquick) BuildDSN ¶
BuildDSN returns the database connection string. Deprecated: Use g.Config.Database.DSN(g.RootPath) instead.
func (Gemquick) CreateDirIfNotExists ¶
func (Gemquick) CreateFileIfNotExists ¶
func (*Gemquick) DownloadFile ¶
func (*Gemquick) ErrorForbidden ¶
func (g *Gemquick) ErrorForbidden(w http.ResponseWriter, r *http.Request)
func (*Gemquick) ErrorStatus ¶
func (g *Gemquick) ErrorStatus(w http.ResponseWriter, status int)
func (*Gemquick) ErrorUnauthorized ¶
func (g *Gemquick) ErrorUnauthorized(w http.ResponseWriter, r *http.Request)
func (*Gemquick) GetModule ¶ added in v0.5.2
GetModule returns a module by name, or nil if not registered. Use type assertion to get the concrete module type.
Example:
if m := app.GetModule("sms"); m != nil {
smsModule := m.(*sms.Module)
smsModule.Send("+1234567890", "Hello!", false)
}
func (*Gemquick) ListenAndServe ¶
func (g *Gemquick) ListenAndServe()
ListenAndServe starts the web server with graceful shutdown support. It handles SIGINT and SIGTERM signals to gracefully stop the server, waiting for in-flight requests to complete before shutting down.
func (*Gemquick) MigrateDownAll ¶
func (*Gemquick) MigrateForce ¶
func (*Gemquick) New ¶
New initializes the Gemquick framework with optional modules. Modules are opt-in components for features like SMS, Email, WebSocket, etc. Example:
app := gemquick.Gemquick{}
app.New(rootPath,
sms.NewModule(),
email.NewModule(),
)
func (Gemquick) RandomString ¶
func (*Gemquick) Shutdown ¶
Shutdown gracefully shuts down the application and all its components. It stops modules in reverse order, then stops background services, and closes connections.
type GemquickError ¶
type GemquickError struct {
// Op is the operation that failed (e.g., "database.query", "auth.validate")
Op string
// Err is the underlying error
Err error
// Code categorizes the error for handling
Code ErrorCode
// Context provides additional error context as key-value pairs
Context map[string]interface{}
}
GemquickError is the standard error type for the framework. It provides structured error information including operation context, error classification, and optional additional context.
func NewError ¶
func NewError(op string, message string, code ErrorCode) *GemquickError
NewError creates a new GemquickError with a message
func WrapError ¶
func WrapError(op string, err error, code ErrorCode) *GemquickError
WrapError wraps an error with operation context and classification. Use this when catching errors from lower-level operations.
func (*GemquickError) Error ¶
func (e *GemquickError) Error() string
Error implements the error interface
func (*GemquickError) Unwrap ¶
func (e *GemquickError) Unwrap() error
Unwrap returns the underlying error for errors.Is and errors.As
func (*GemquickError) WithContext ¶
func (e *GemquickError) WithContext(key string, value interface{}) *GemquickError
WithContext adds context to the error and returns it for chaining
type HTTPService ¶
type HTTPService struct {
Router *chi.Mux
Session *scs.SessionManager
Render *render.Render
JetViews *jet.Set
}
HTTPService handles HTTP routing, sessions, and rendering
type LoggingService ¶
type LoggingService struct {
Error *log.Logger
Info *log.Logger
Logger *logging.Logger
Metrics *logging.MetricRegistry
Health *logging.HealthMonitor
App *logging.ApplicationMetrics
OTel *otel.Provider // OpenTelemetry provider for distributed tracing
}
LoggingService handles all logging, metrics, and health monitoring
type Module ¶
type Module interface {
// Name returns a unique identifier for this module (e.g., "sms", "email", "websocket")
Name() string
// Initialize sets up the module with access to the framework.
// Called during app.New() after core services are ready.
Initialize(g *Gemquick) error
// Shutdown gracefully stops the module.
// Called during graceful shutdown with a context for timeout control.
Shutdown(ctx context.Context) error
}
Module defines the interface for optional framework components. Modules are initialized after core services and can depend on them. Use this for opt-in features like SMS, Email, WebSockets, OpenTelemetry, etc.
type ModuleRegistry ¶
type ModuleRegistry struct {
// contains filtered or unexported fields
}
ModuleRegistry manages module registration and lifecycle. It ensures modules are initialized in registration order and shut down in reverse order.
func NewModuleRegistry ¶
func NewModuleRegistry() *ModuleRegistry
NewModuleRegistry creates an empty module registry.
func (*ModuleRegistry) Count ¶
func (r *ModuleRegistry) Count() int
Count returns the number of registered modules.
func (*ModuleRegistry) Get ¶
func (r *ModuleRegistry) Get(name string) Module
Get returns a module by name, or nil if not found.
func (*ModuleRegistry) Has ¶
func (r *ModuleRegistry) Has(name string) bool
Has checks if a module is registered.
func (*ModuleRegistry) InitializeAll ¶
func (r *ModuleRegistry) InitializeAll(g *Gemquick) error
InitializeAll calls Initialize on all registered modules in order. Stops on first error and returns it.
func (*ModuleRegistry) Names ¶
func (r *ModuleRegistry) Names() []string
Names returns all registered module names in registration order.
func (*ModuleRegistry) Register ¶
func (r *ModuleRegistry) Register(m Module) error
Register adds a module to the registry. Modules are initialized in the order they are registered. Returns an error if a module with the same name already exists.
func (*ModuleRegistry) ShutdownAll ¶
func (r *ModuleRegistry) ShutdownAll(ctx context.Context) error
ShutdownAll calls Shutdown on all registered modules in reverse order. Collects all errors and returns them combined.
type Validation ¶
func (*Validation) AddError ¶
func (v *Validation) AddError(key, message string)
func (*Validation) Check ¶
func (v *Validation) Check(ok bool, key, message string)
func (*Validation) Equals ¶
func (v *Validation) Equals(eq bool, field, verified string)
func (*Validation) EscapeHTML ¶
func (v *Validation) EscapeHTML(value string) string
EscapeHTML completely escapes all HTML special characters. Use this when you want to display user input as literal text, preserving characters like < > & as visible text rather than HTML entities.
func (*Validation) IsAlphanumeric ¶
func (v *Validation) IsAlphanumeric(field, value string)
IsAlphanumeric validates that a field contains only letters and numbers
func (*Validation) IsDateISO ¶
func (v *Validation) IsDateISO(field, value string)
func (*Validation) IsEmail ¶
func (v *Validation) IsEmail(field, value string)
func (*Validation) IsFloat ¶
func (v *Validation) IsFloat(field, value string)
func (*Validation) IsInt ¶
func (v *Validation) IsInt(field, value string)
func (*Validation) IsString ¶
func (v *Validation) IsString(field, value string)
func (*Validation) IsURL ¶
func (v *Validation) IsURL(field, value string)
IsURL validates that a field contains a valid URL
func (*Validation) MaxLength ¶
func (v *Validation) MaxLength(field, value string, maxLength int)
MaxLength validates that a field doesn't exceed a maximum length
func (*Validation) MinLength ¶
func (v *Validation) MinLength(field, value string, minLength int)
MinLength validates that a field meets a minimum length requirement
func (*Validation) NoSpaces ¶
func (v *Validation) NoSpaces(field, value string)
func (*Validation) SanitizeHTML ¶
func (v *Validation) SanitizeHTML(value string) string
SanitizeHTML removes ALL HTML tags from input using bluemonday's strict policy. Use this for input that should be displayed as plain text.
func (*Validation) SanitizeRichText ¶
func (v *Validation) SanitizeRichText(value string) string
SanitizeRichText allows safe HTML formatting (bold, italic, links, etc.) while removing dangerous elements like scripts, iframes, and event handlers. Use this for user-generated content like blog posts, comments, or rich text editors.
func (*Validation) Valid ¶
func (v *Validation) Valid() bool
type ValidationError ¶
type ValidationError struct {
GemquickError
Fields map[string]string
}
ValidationError represents a validation error with field-specific messages
func NewValidationError ¶
func NewValidationError(fields map[string]string) *ValidationError
NewValidationError creates a new validation error with field messages
func (*ValidationError) AddField ¶
func (e *ValidationError) AddField(field, message string) *ValidationError
AddField adds a field error and returns the error for chaining
func (*ValidationError) HasErrors ¶
func (e *ValidationError) HasErrors() bool
HasErrors returns true if there are any validation errors
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
cli
command
|
|
|
Package config provides structured configuration with validation for Gemquick applications.
|
Package config provides structured configuration with validation for Gemquick applications. |
|
Package core provides minimal utilities for CLI tools and code generation.
|
Package core provides minimal utilities for CLI tools and code generation. |
|
email
module
|
|
|
otel
module
|
|
|
sms
module
|
|
