gemquick

package module
v0.5.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 21, 2025 License: MIT Imports: 57 Imported by: 0

README

Gemquick

alt gemquick

Gemquick is a modern, full-featured web application framework for Go that provides everything you need to build scalable web applications quickly and securely.

Features

  • 🚀 Chi Router - Fast and lightweight HTTP router
  • 🗄️ Multi-Database Support - PostgreSQL, MySQL, MariaDB, SQLite
  • 🔐 Security First - CSRF protection, rate limiting, input validation, XSS prevention, 2FA
  • 📧 Email System - Multiple provider support with templates
  • 💾 Caching - Redis and Badger cache implementations
  • 🔄 Background Jobs - Job queue with cron scheduler
  • 🌐 WebSocket Support - Real-time communication with hub pattern
  • 📁 File Storage - S3 and MinIO filesystem integrations
  • 📱 SMS Integration - Multiple SMS provider support
  • 🎨 Template Engine - Jet template engine for dynamic views
  • 📊 Logging & Metrics - Structured logging with health monitoring
  • 🔭 OpenTelemetry - Distributed tracing and observability
  • 🔑 Session Management - Secure session handling with multiple stores
  • 🛠️ CLI Tools - Project scaffolding and code generation
  • 🤖 AI-Native Development - MCP server for AI assistants

AI-Native Development (MCP)

Gemquick is the first AI-native Go framework. Use natural language with AI assistants to build your application.

Setup

Add to your Claude Code / Cursor MCP config:

{
  "mcpServers": {
    "gemquick": {
      "command": "gq",
      "args": ["mcp"]
    }
  }
}
Available Tools
Tool Description
gemquick_create_project Create a new GemQuick project
gemquick_create_model Create a new database model
gemquick_create_handler Create a new HTTP handler
gemquick_create_migration Create a new database migration
gemquick_create_middleware Create a new middleware
gemquick_create_mail Create email template
gemquick_run_migrations Run pending migrations
gemquick_rollback Rollback migrations
gemquick_setup_auth Setup auth with 2FA support
gemquick_create_session_table Create session table
gemquick_setup_docker Generate Docker config
gemquick_module_info Get module setup instructions
Usage

Just ask your AI assistant:

  • "Create a User model with name and email"
  • "Add a migration to create a posts table"
  • "Create a handler for managing products"
  • "Run the database migrations"
  • "Setup authentication for my app"
  • "How do I add WebSocket support?"
  • "Generate Docker configuration"

Installation

Clone the repository and build the CLI tool:

git clone https://github.com/jimmitjoo/gemquick
cd gemquick
make build

This will create the gq executable in dist/gq. You can move this file to your PATH for global access.

Quick Start

Create a New Project
gq new my_project
cd my_project
make start
Project Structure
my_project/
├── .env                 # Environment configuration
├── Makefile            # Build and development commands
├── handlers/           # HTTP handlers
├── migrations/         # Database migrations
├── views/              # Template files
├── email/              # Email templates
├── data/               # Models and database logic
├── public/             # Static assets
├── middleware/         # Custom middleware
└── logs/               # Application logs

Development

Available Make Commands
make key           # Generate new encryption key
make auth          # Create authentication system with user model
make mail          # Create new email template
make model         # Create new model in data directory
make migration     # Create new database migration
make handler       # Create new HTTP handler
make session       # Create session tables in database
make api-controller    # Create new API controller
make controller    # Create new resource controller
make middleware    # Create new middleware
make docker        # Generate Docker configuration
make deploy        # Generate deployment configuration
Testing

Gemquick includes a beautiful test runner with colored output:

# Run all tests with colors
make test

# Run tests for specific package
./run-tests -p ./cache/...

# Generate coverage report
make cover

# Run tests without Docker dependencies
./run-tests -s
Database Migrations
# Run migrations up
gq migrate up

# Roll back migrations
gq migrate down

# Create new migration
make migration name=create_users_table

Opt-in Modules

Gemquick uses a modular architecture. Import only what you need:

import (
    "github.com/jimmitjoo/gemquick"
    "github.com/jimmitjoo/gemquick/sms"
    "github.com/jimmitjoo/gemquick/email"
    "github.com/jimmitjoo/gemquick/websocket"
    "github.com/jimmitjoo/gemquick/otel"
)

func main() {
    app := gemquick.Gemquick{}

    // Initialize with only the modules you need
    app.New(rootPath,
        sms.NewModule(),                    // SMS support
        email.NewModule(),                  // Email support
        websocket.NewModule(),              // WebSocket support
        otel.NewModule(                     // OpenTelemetry tracing
            otel.WithServiceName("my-app"),
            otel.WithOTLPExporter("localhost:4317", true),
        ),
    )
}
Using Modules
// Send SMS
if sms := app.GetModule("sms"); sms != nil {
    sms.(*sms.Module).Send("+1234567890", "Hello!", false)
}

// Send Email
if email := app.GetModule("email"); email != nil {
    email.(*email.Module).Send(email.Message{
        To:      "[email protected]",
        Subject: "Welcome!",
    })
}

// WebSocket broadcast
if ws := app.GetModule("websocket"); ws != nil {
    ws.(*websocket.Module).Broadcast([]byte("Hello everyone!"))
}

// Mount WebSocket handler
if ws := app.GetModule("websocket"); ws != nil {
    app.HTTP.Router.Get("/ws", ws.(*websocket.Module).Handler())
}
Module Configuration

Modules read from environment variables by default, or use functional options:

// SMS with Twilio
sms.NewModule(sms.WithTwilio(accountSid, apiKey, apiSecret, fromNumber))

// Email with SMTP
email.NewModule(
    email.WithSMTP("smtp.example.com", 587, "user", "pass", "tls"),
    email.WithFrom("[email protected]", "My App"),
)

// WebSocket with auth
websocket.NewModule(
    websocket.WithAllowedOrigins([]string{"https://example.com"}),
    websocket.WithAuthenticateConnection(myAuthFunc),
)

Core Components

Web Server Configuration
app := gemquick.Gemquick{}
app.New(rootPath)
app.AppName = "MyApp"
app.Debug = true
Database Connection

Supports multiple databases through environment configuration:

  • PostgreSQL
  • MySQL/MariaDB
  • SQLite
Caching

Choose between Redis or Badger cache:

// Redis cache
app.Cache = app.CreateRedisCache()

// Badger cache
app.Cache = app.CreateBadgerCache()
Background Jobs
// Register a job processor
app.JobManager.RegisterProcessor("send-email", emailProcessor)

// Queue a job
app.JobManager.QueueJob("send-email", data)
WebSocket Support
// Initialize WebSocket hub
hub := websocket.NewHub()
go hub.Run()
Security Features
  • CSRF protection middleware
  • Rate limiting and throttling
  • Input validation and sanitization
  • SQL injection prevention
  • XSS protection
  • Session fixation protection
  • Secure password hashing
  • Two-Factor Authentication (TOTP)
OpenTelemetry (Distributed Tracing)

Enable distributed tracing for production observability:

OTEL_ENABLED=true
OTEL_SERVICE_NAME=my-app
OTEL_ENDPOINT=localhost:4317
OTEL_INSECURE=true

Features:

  • Automatic HTTP request tracing
  • Database query tracing
  • Log correlation with trace IDs
  • Support for OTLP, Zipkin exporters

Custom Spans:

import "github.com/jimmitjoo/gemquick/otel"

func (h *Handler) ProcessOrder(w http.ResponseWriter, r *http.Request) {
    ctx, span := otel.Start(r.Context(), "process_order")
    defer span.End()

    otel.SetAttributes(ctx, otel.String("order.id", orderID))

    if err != nil {
        otel.RecordError(ctx, err)
    }
}

Database Tracing:

tracedDB := otel.WrapDB(db, "postgres", "mydb")
rows, _ := tracedDB.Query(ctx, "SELECT * FROM users")

Local Development with Jaeger:

docker run -d --name jaeger \
  -p 16686:16686 -p 4317:4317 \
  jaegertracing/all-in-one:latest
# View traces at http://localhost:16686

Configuration

Configuration is managed through .env file:

# Application
APP_NAME=MyApp
DEBUG=true
PORT=4000

# Database
DATABASE_TYPE=postgres
DATABASE_DSN=your_connection_string

# Cache
CACHE=redis
REDIS_HOST=localhost:6379

# Session
SESSION_TYPE=redis
SESSION_LIFETIME=24

# Mail
MAIL_PROVIDER=smtp
SMTP_HOST=localhost
SMTP_PORT=1025

# OpenTelemetry (optional)
OTEL_ENABLED=false
OTEL_SERVICE_NAME=my-app
OTEL_ENDPOINT=localhost:4317

API Development

Gemquick includes API utilities for building RESTful services:

  • Version management
  • Standardized JSON responses
  • API middleware
  • Error handling
// API versioning
api.Version("v1", func(r chi.Router) {
    r.Get("/users", handlers.GetUsers)
})

// JSON responses
api.JSON(w, http.StatusOK, data)

Testing Philosophy

  • Comprehensive test coverage (aim for >80% on critical paths)
  • Table-driven tests for better coverage
  • Security-focused testing
  • Docker-optional test execution
  • Colorful test output for better readability

Contributing

Bug reports and pull requests are welcome on GitHub at the Gemquick repository. This project is intended to be a safe, welcoming space for collaboration. Contributors are expected to adhere to the Contributor Covenant.

License

The Gemquick framework is available as open source under the terms of the MIT License.

Documentation

For detailed documentation and examples, see:

Support

For issues, questions, or suggestions, please open an issue on the GitHub repository.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFoundError is returned when a resource is not found
	ErrNotFoundError = NewError("", "resource not found", ErrNotFound)
	// ErrUnauthorizedError is returned when authentication fails
	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

func GetHTTPStatus(err error) int

GetHTTPStatus returns the appropriate HTTP status for an error

func IsCode

func IsCode(err error, code ErrorCode) bool

IsCode checks if an error is a GemquickError with a specific code

func ValidateEncryptionKey

func ValidateEncryptionKey(key []byte) error

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

func NewDataService

func NewDataService() *DataService

NewDataService creates a new data service

type Database

type Database struct {
	DataType    string
	Pool        *sql.DB
	TablePrefix string
}

Database represents a database connection with metadata

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.

func (Encryption) Decrypt

func (e Encryption) Decrypt(cryptoText string) (string, error)

func (Encryption) Encrypt

func (e Encryption) Encrypt(data string) (string, error)

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 represents authentication/authorization failures
	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 GetCode

func GetCode(err error) ErrorCode

GetCode returns the ErrorCode from an error, or ErrInternal if not a GemquickError

func (ErrorCode) HTTPStatus

func (c ErrorCode) HTTPStatus() int

HTTPStatus returns the appropriate HTTP status code for an ErrorCode

func (ErrorCode) String

func (c ErrorCode) String() string

String returns the string representation of 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

func (g *Gemquick) AddMonitoringRoutes(mux *chi.Mux)

AddMonitoringRoutes adds health and metrics endpoints. Call this in your routes() function AFTER adding your middleware.

func (*Gemquick) BuildDSN

func (g *Gemquick) BuildDSN() string

BuildDSN returns the database connection string. Deprecated: Use g.Config.Database.DSN(g.RootPath) instead.

func (Gemquick) CreateDirIfNotExists

func (g Gemquick) CreateDirIfNotExists(path string) error

func (Gemquick) CreateFileIfNotExists

func (g Gemquick) CreateFileIfNotExists(path string) error

func (*Gemquick) DownloadFile

func (g *Gemquick) DownloadFile(w http.ResponseWriter, r *http.Request, pathToFile, filename string) error

func (*Gemquick) Error404

func (g *Gemquick) Error404(w http.ResponseWriter, r *http.Request)

func (*Gemquick) Error500

func (g *Gemquick) Error500(w http.ResponseWriter, r *http.Request)

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

func (g *Gemquick) GetModule(name string) Module

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) HasModule added in v0.5.2

func (g *Gemquick) HasModule(name string) bool

HasModule checks if a module is registered.

func (*Gemquick) Init

func (g *Gemquick) Init(p initPaths) error

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) LoadTime

func (g *Gemquick) LoadTime(start time.Time)

func (*Gemquick) MigrateDownAll

func (g *Gemquick) MigrateDownAll(dsn string) error

func (*Gemquick) MigrateForce

func (g *Gemquick) MigrateForce(dsn string) error

func (*Gemquick) MigrateUp

func (g *Gemquick) MigrateUp(dsn string) error

func (*Gemquick) New

func (g *Gemquick) New(rootPath string, modules ...Module) error

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) NoSurf

func (g *Gemquick) NoSurf(next http.Handler) http.Handler

func (*Gemquick) OpenDB

func (g *Gemquick) OpenDB(dbType, dsn string) (*sql.DB, error)

func (Gemquick) RandomString

func (g Gemquick) RandomString(length int) string

func (*Gemquick) ReadJson

func (g *Gemquick) ReadJson(w http.ResponseWriter, r *http.Request, data interface{}) error

func (*Gemquick) SessionLoad

func (g *Gemquick) SessionLoad(next http.Handler) http.Handler

func (*Gemquick) Shutdown

func (g *Gemquick) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the application and all its components. It stops modules in reverse order, then stops background services, and closes connections.

func (*Gemquick) Steps

func (g *Gemquick) Steps(steps int, dsn string) error

func (*Gemquick) Validator

func (g *Gemquick) Validator(data url.Values) *Validation

func (*Gemquick) WriteJson

func (g *Gemquick) WriteJson(w http.ResponseWriter, status int, data interface{}, headers ...http.Header) error

func (*Gemquick) WriteXML

func (g *Gemquick) WriteXML(w http.ResponseWriter, status int, data interface{}, headers ...http.Header) error

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 Server

type Server struct {
	ServerName string
	Port       string
	Secure     bool
	URL        string
}

type Validation

type Validation struct {
	Data   url.Values
	Errors map[string]string
}

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) Has

func (v *Validation) Has(field string, r *http.Request) bool

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) Required

func (v *Validation) Required(r *http.Request, fields ...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

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL