hm

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 27, 2025 License: MIT Imports: 36 Imported by: 0

README

hm

Go Reference codecov

A collection of Go primitives and utilities for Hermes organization projects. Provides common interfaces and helper functions for entity management, validation, and HTTP handling.

Installation

go get github.com/hermesgen/hm

Quick Start

package main

import (
	"context"
	"embed"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/hermesgen/hm"
)

const (
	name    = "myapp"
	version = "v1.0.0"
)

//go:embed assets
var assetsFS embed.FS

func main() {
	ctx := context.Background()
	log := hm.NewLogger("info")
	cfg := hm.LoadCfg("myapp", hm.Flags)

	params := hm.XParams{Cfg: cfg, Log: log}

	// Infrastructure
	queryManager := hm.NewQueryManager(assetsFS, "sqlite", params)
	templateManager := hm.NewTemplateManager(assetsFS, params)
	migrator := hm.NewMigrator(assetsFS, "sqlite", params)
	fileServer := hm.NewFileServer(assetsFS, params)
	fm := hm.NewFlashManager(params)

	// Application
	app := hm.NewApp("myapp", params)
	app.MountFileServer("/", fileServer)

	// API Router
	apiRouter := hm.NewAPIRouter("api-router", params)
	app.MountAPI("/api/v1", apiRouter)

	// Web Router
	webRouter := hm.NewWebRouter("web-router", params)
	app.MountWeb("/", webRouter)

	// Add dependencies
	app.Add(migrator, queryManager, templateManager, fileServer, fm)

	err := app.Setup(ctx)
	if err != nil {
		log.Errorf("Cannot setup app: %v", err)
		return
	}

	stop := make(chan os.Signal, 1)
	signal.Notify(stop, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)

	go func() {
		err := app.Start(ctx)
		if err != nil {
			log.Errorf("Cannot start %s(%s): %v", name, version, err)
		}
	}()

	log.Infof("%s(%s) started successfully", name, version)

	<-stop

	log.Infof("Shutting down %s(%s)...", name, version)
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	err = app.Stop(shutdownCtx)
	if err != nil {
		log.Errorf("Error during shutdown: %v", err)
	} else {
		log.Infof("%s(%s) stopped gracefully", name, version)
	}
}

Development

Running Tests
# Run all tests
make test

# Run tests with coverage
make coverage

# Run tests with HTML coverage report
make coverage-html

# Check if coverage meets 80% threshold
make coverage-check
Quality Checks
# Run all quality checks (format, vet, test, coverage, lint)
make check

# Run CI pipeline (strict)
make ci

Documentation

Index

Constants

View Source
const (
	CSRFFieldName      = "aquamarine.csrf.token"
	TimeFormat         = "2006-01-02T15:04:05Z07:00"
	InternalAuthHeader = "X-Internal-GitAuth"
	SecBypassAuth      = "sec.bypass.auth"
)
View Source
const (
	NoSlug = ""
	Slug   = "?slug=%s"
)
View Source
const (
	MsgGetAllItems = "%s retrieved successfully"
	MsgGetItem     = "%s retrieved successfully"
	MsgCreateItem  = "%s created successfully"
	MsgUpdateItem  = "%s updated successfully"
	MsgDeleteItem  = "%s deleted successfully"

	ErrInvalidID            = "Invalid %s ID"
	ErrCannotGetResources   = "Could not get %s from database"
	ErrCannotGetResource    = "Could not get %s from database"
	ErrCannotCreateResource = "Could not create %s in database"
	ErrCannotUpdateResource = "Could not update %s in database"
	ErrCannotDeleteResource = "Could not delete %s from database"
)
View Source
const (
	ErrBadRequest           = "Bad request"
	ErrResourceNotFound     = "Resource not found"
	ErrTemplateNotFound     = "Template not found"
	ErrCannotRenderTemplate = "Cannot render template"
	ErrCannotWriteResponse  = "Cannot write response"
	ErrInvalidFormData      = "Invalid form data"
	ErrValidationFailed     = "Validation failed"
	ErrInvalidBody          = "Invalid request body"
	ErrInvalidParam         = "Invalid parameter"
)
View Source
const (
	FlashKey        FlashCtxKey = "aqmflash"
	FlashCookieName string      = "aqmflash"
)
View Source
const (
	EngSQLite     = "sqlite"
	EngPostgres   = "postgres"
	MigrationPath = "assets/migration/%s"
)
View Source
const (
	StatusSuccess = "success"
	StatusError   = "error"
)
View Source
const (
	ErrorCodeInternalError = "INTERNAL_ERROR"
	ErrorCodeBadRequest    = "BAD_REQUEST"
	ErrorCodeNotFound      = "NOT_FOUND"
)
View Source
const (
	EncryptionKeyCtxKey contextKey = "encryptionKey"
)

Variables

View Source
var (
	ErrEncryptionFailed = errors.New("encryption failed")
	ErrDecryptionFailed = errors.New("decryption failed")
)
View Source
var Flags = map[string]interface{}{
	Key.ServerWebHost:        "localhost",
	Key.ServerWebPort:        "8080",
	Key.ServerWebEnabled:     true,
	Key.ServerAPIHost:        "localhost",
	Key.ServerAPIPort:        "8081",
	Key.ServerAPIEnabled:     true,
	Key.ServerPreviewHost:    "localhost",
	Key.ServerPreviewPort:    "8082",
	Key.ServerPreviewEnabled: true,
	Key.ServerResPath:        "/res",

	Key.SecHashKey:  "0123456789abcdef0123456789abcdef",
	Key.SecBlockKey: "0123456789abcdef0123456789abcdef",
}
View Source
var HTTPMethod = HTTPMethods{
	GET:    "GET",
	POST:   "POST",
	PUT:    "PUT",
	PATCH:  "PATCH",
	DELETE: "DELETE",
	HEAD:   "HEAD",
}
View Source
var Key = Keys{
	AppEnv: "app.env",

	ServerWebHost:      "server.web.host",
	ServerWebPort:      "server.web.port",
	ServerWebEnabled:   "server.web.enabled",
	ServerAPIHost:      "server.api.host",
	ServerAPIPort:      "server.api.port",
	ServerAPIEnabled:   "server.api.enabled",
	ServerResPath:      "server.res.path",
	ServerIndexEnabled: "server.index.enabled",

	ServerPreviewHost:    "server.preview.host",
	ServerPreviewPort:    "server.preview.port",
	ServerPreviewEnabled: "server.preview.enabled",

	DBSQLiteDSN: "db.sqlite.dsn",

	SecCSRFKey:       "sec.csrf.key",
	SecCSRFRedirect:  "sec.csrf.redirect",
	SecEncryptionKey: "sec.encryption.key",
	SecHashKey:       "sec.hash.key",
	SecBlockKey:      "sec.block.key",
	SecBypassAuth:    "sec.bypass.auth",

	ButtonStyleGray:   "button.style.gray",
	ButtonStyleBlue:   "button.style.blue",
	ButtonStyleRed:    "button.style.red",
	ButtonStyleGreen:  "button.style.green",
	ButtonStyleYellow: "button.style.yellow",

	NotificationSuccessStyle: "notification.success.style",
	NotificationInfoStyle:    "notification.info.style",
	NotificationWarnStyle:    "notification.warn.style",
	NotificationErrorStyle:   "notification.error.style",
	NotificationDebugStyle:   "notification.debug.style",

	RenderWebErrors: "render.web.errors",
	RenderAPIErrors: "render.api.errors",
}
View Source
var NotificationType = notificationTypes{
	Success: "success",
	Info:    "info",
	Warn:    "warning",
	Error:   "danger",
	Debug:   "debug",
}
View Source
var ReqIDKey = contextKey("requestID")

ReqIDKey is the context key for the request ID.

View Source
var UserKey = contextKey("user")

UserKey is the context key for the authenticated user.

Functions

func Add

func Add(a, b int) int

Add adds a and b

func AddPluralRule

func AddPluralRule(plural, singular string)

func AddRelatedPath

func AddRelatedPath(i Identifiable, j Identifiable) string

AddRelatedPath returns the path for adding a related resource

func AddSingularRule

func AddSingularRule(singular, plural string)

func AddUncountableRule

func AddUncountableRule(word string)

func AuthMw

func AuthMw(app *App, sessionStore SessionStore, userService UserService) func(next http.Handler) http.Handler

AuthMw is a middleware that handles authentication for both internal and external requests.

func CORSMw

func CORSMw(next http.Handler) http.Handler

CORSMw is a middleware that handles Cross-Origin Resource Sharing (CORS) headers.

func CSRFMw

func CSRFMw(cfg *Config) func(next http.Handler) http.Handler

CSRFMw is a middleware that protects against CSRF attacks.

func Cap

func Cap(s string) string

Cap capitalizes the first letter of a string.

func CreatePath

func CreatePath(i Identifiable) string

CreatePath returns the path for creating a resource

func DebugFS

func DebugFS(efs embed.FS, root string) error

DebugFS prints the tree structure of the given embedded filesystem.

func DefaultType

func DefaultType(currentType string) string

func DeletePath

func DeletePath(i Identifiable, id uuid.UUID) string

DeletePath returns the path for deleting a resource

func EditPath

func EditPath(i Identifiable, id uuid.UUID) string

EditPath returns the path for editing a resource

func EncryptionKeyMw

func EncryptionKeyMw(app *App) func(next http.Handler) http.Handler

EncryptionKeyMw is a middleware that injects the encryption key into the request context.

func FieldMsg

func FieldMsg(form Form, field string, classes ...string) template.HTML

func GenID

func GenID(i Identifiable)

GenID generates a new UUID for a model if it doesn't have one.

func GenShortID

func GenShortID(i Identifiable)

GenShortID generates a new short ID for a model if it doesn't have one.

func InternalAuthMiddleware

func InternalAuthMiddleware(app *App) func(next http.Handler) http.Handler

InternalAuthMiddleware is a middleware that verifies the internal authentication token.

func IsHTMXRequest

func IsHTMXRequest(r *http.Request) bool

func IsPlural

func IsPlural(s string) bool

func IsSingular

func IsSingular(s string) bool

func ListPath

func ListPath(i Identifiable) string

ListPath returns the path for listing resources

func ListRelatedPath

func ListRelatedPath(i Identifiable, j Identifiable, id uuid.UUID) string

ListRelatedPath returns the path for listing related resources

func LogHeadersMw

func LogHeadersMw(next http.Handler) http.Handler

LogHeadersMw is a middleware that logs all request headers.

func MethodOverrideMw

func MethodOverrideMw(next http.Handler) http.Handler

MethodOverrideMw is a middleware that checks for a _method form field and overrides the request method.

func Min

func Min(a, b int) int

Min returns the minimum of a and b

func Mul

func Mul(a, b int) int

Mul multiplies a and b

func NewPath

func NewPath(i Identifiable) string

NewPath returns the path for creating a new resource

func Normalize

func Normalize(str string) string

Normalize utility function

func ParseUUID

func ParseUUID(s string) uuid.UUID

func PathID

func PathID(r *http.Request, key string) (uuid.UUID, error)

PathID extracts a UUID from the request's path values based on the provided key.

func Plural

func Plural(s string) string

func RemoveRelatedPath

func RemoveRelatedPath(i Identifiable, j Identifiable) string

RemoveRelatedPath returns the path for removing a related resource

func ReqID

func ReqID(r *http.Request) string

ReqID returns the request ID from the context, or an empty string if not set.

func RequestIDMw

func RequestIDMw(next http.Handler) http.Handler

RequestIDMw is a middleware that assigns a unique ID to each request and stores it in the context and as a header.

func Respond

func Respond(w http.ResponseWriter, status int, response Response)

func SetCreateValues

func SetCreateValues(m Model, userID ...uuid.UUID)

SetCreateValues sets the initial values for a new model.

func SetUpdateValues

func SetUpdateValues(m Model, userID ...uuid.UUID)

SetUpdateValues updates the timestamp for a model modification.

func ShowPath

func ShowPath(i Identifiable, id uuid.UUID) string

ShowPath returns the path for showing a resource

func Singular

func Singular(s string) string

func StringPtr

func StringPtr(s string) *string

func StringVal

func StringVal(s *string) string

func Sub

func Sub(a, b int) int

Sub subtracts b from a

func TimePtr

func TimePtr(t time.Time) *time.Time

func TimeVal

func TimeVal(t *time.Time) time.Time

func ToForm

func ToForm(r *http.Request, v interface{}, config ...FormConfig) error

ToForm is a convenience function that creates a FormMapper and maps form values from an HTTP request to a struct.

func ToPtrSlice

func ToPtrSlice[T any](s []T) []*T

ToPtrSlice converts a slice of values to a slice of pointers.

func Truncate

func Truncate(s string, length int) string

Truncate truncates a string to a specified length and appends an ellipsis if truncated.

func TxFromContext

func TxFromContext(ctx context.Context) (interface{}, bool)

TxFromContext retrieves the transaction from the context, if present.

func UUIDPtr

func UUIDPtr(id uuid.UUID) *string

func UUIDVal

func UUIDVal(s *string) uuid.UUID

func UpdatePath

func UpdatePath(i Identifiable) string

UpdatePath returns the path for updating a resource

func ValidateEmail

func ValidateEmail(email string) error

func WithTx

func WithTx(ctx context.Context, tx interface{}) context.Context

WithTx returns a new context with the transaction stored.

Types

type APIClient

type APIClient struct {
	Core
	// contains filtered or unexported fields
}

func NewAPIClient

func NewAPIClient(name string, getToken func() string, baseURL string, params XParams) *APIClient

func (*APIClient) Delete

func (c *APIClient) Delete(r *http.Request, path string) error

Delete sends a DELETE request to the specified path.

func (*APIClient) Get

func (c *APIClient) Get(r *http.Request, path string, target interface{}) error

Get sends a GET request to the specified path.

func (*APIClient) Post

func (c *APIClient) Post(r *http.Request, path string, body, target interface{}) error

Post sends a POST request to the specified path with the given body.

func (*APIClient) Put

func (c *APIClient) Put(r *http.Request, path string, body, target interface{}) error

Put sends a PUT request to the specified path with the given body.

type APIError

type APIError struct {
	Code    string `json:"code"`
	Details string `json:"details"`
}

type APIHandler

type APIHandler struct {
	*Handler
}

func NewAPIHandler

func NewAPIHandler(name string, params XParams) *APIHandler

func (*APIHandler) Created

func (h *APIHandler) Created(w http.ResponseWriter, message string, data interface{})

func (*APIHandler) Err

func (h *APIHandler) Err(w http.ResponseWriter, code int, message string, err error)

func (*APIHandler) ID

func (*APIHandler) OK

func (h *APIHandler) OK(w http.ResponseWriter, message string, data interface{})

func (*APIHandler) Param

func (h *APIHandler) Param(w http.ResponseWriter, r *http.Request, key string) (string, error)

type Action

type Action struct {
	Path   string
	Text   string
	Style  string
	IsForm bool
}

func DeleteAction

func DeleteAction(i Identifiable, id uuid.UUID, style string) Action

func EditAction

func EditAction(i Identifiable, id uuid.UUID, style string) Action

func ListAction

func ListAction(i Identifiable, style string) Action

func NewAction

func NewAction(url, text, style string) Action

type App

type App struct {
	Core
	Version        string
	Router         *Router
	APIRouter      *Router
	PreviewHandler http.Handler

	InternalToken string
	// contains filtered or unexported fields
}

func NewApp

func NewApp(name, version string, fs embed.FS, params XParams) *App

func (*App) Add

func (a *App) Add(dep Core)

func (*App) Dep

func (a *App) Dep(name string) (*Dep, bool)

func (*App) InternalAuthToken

func (a *App) InternalAuthToken() string

func (*App) MountAPI

func (a *App) MountAPI(path string, handler http.Handler)

func (*App) MountFileServer

func (a *App) MountFileServer(path string, fs *FileServer)

func (*App) MountWeb

func (app *App) MountWeb(path string, handler http.Handler)

func (*App) SetAPIRouter

func (app *App) SetAPIRouter(router *Router)

func (*App) SetWebRouter

func (app *App) SetWebRouter(router *Router)

func (*App) Setup

func (a *App) Setup(ctx context.Context) error

func (*App) Start

func (a *App) Start(ctx context.Context) error

func (*App) StartServer

func (a *App) StartServer(server *http.Server, addr string)

func (*App) Stop

func (a *App) Stop(ctx context.Context) error

Stop gracefully shuts down all dependencies in reverse order

type Auditable

type Auditable interface {
	// CreatedBy returns the UUID of the user who created the entity.
	GetCreatedBy() uuid.UUID
	// UpdatedBy returns the UUID of the user who last updated the entity.
	GetUpdatedBy() uuid.UUID
	// CreatedAt returns the creation time of the entity.
	GetCreatedAt() time.Time
	// UpdatedAt returns the last update time of the entity.
	GetUpdatedAt() time.Time
	// Setters for audit fields
	SetCreatedBy(uuid.UUID)
	SetUpdatedBy(uuid.UUID)
	SetCreatedAt(time.Time)
	SetUpdatedAt(time.Time)
}

Auditable interface represents an entity with audit information.

type AuthMethod

type AuthMethod string

AuthMethod represents the authentication method.

const (
	AuthToken AuthMethod = "token"
	AuthSSH   AuthMethod = "ssh"
)

type BaseCore

type BaseCore struct {
	// contains filtered or unexported fields
}

func NewCore

func NewCore(name string, params XParams) *BaseCore

NewCore creates a new BaseCore instance with XParams.

func (*BaseCore) Cfg

func (c *BaseCore) Cfg() *Config

Cfg returns the Config in BaseCore.

func (*BaseCore) Log

func (c *BaseCore) Log() Logger

func (*BaseCore) Name

func (c *BaseCore) Name() string

Name returns the name in BaseCore.

func (*BaseCore) SetCfg

func (c *BaseCore) SetCfg(cfg *Config)

SetCfg sets the Config in BaseCore.

func (*BaseCore) SetLog

func (c *BaseCore) SetLog(log Logger)

SetLog sets the Logger in BaseCore.

func (*BaseCore) SetName

func (c *BaseCore) SetName(name string)

SetName sets the name in BaseCore.

func (*BaseCore) SetOpts

func (c *BaseCore) SetOpts(opts ...Option)

SetOpts sets the options in BaseCore.

func (*BaseCore) Setup

func (c *BaseCore) Setup(ctx context.Context) error

Setup is the default implementation for the Setup method in BaseCore.

func (*BaseCore) Start

func (c *BaseCore) Start(ctx context.Context) error

Start is the default implementation for the Start method in BaseCore.

func (*BaseCore) Stop

func (c *BaseCore) Stop(ctx context.Context) error

Stop is the default implementation for the Stop method in BaseCore.

type BaseForm

type BaseForm struct {
	// contains filtered or unexported fields
}

BaseForm struct represents a form with action, method, csrf token, and a button.

func NewBaseForm

func NewBaseForm(r *http.Request) *BaseForm

func (*BaseForm) Action

func (f *BaseForm) Action() string

Accessors and setters for BaseForm to satisfy Form interface

func (*BaseForm) Button

func (f *BaseForm) Button() Button

func (*BaseForm) CSRF

func (f *BaseForm) CSRF() string

func (*BaseForm) GenCSRFToken

func (f *BaseForm) GenCSRFToken(r *http.Request)

GenCSRFToken generates a csrf token and sets it in the form.

func (*BaseForm) HasErrors

func (f *BaseForm) HasErrors() bool

func (*BaseForm) Method

func (f *BaseForm) Method() string

func (*BaseForm) SetAction

func (f *BaseForm) SetAction(action string)

func (*BaseForm) SetButton

func (f *BaseForm) SetButton(button Button)

func (*BaseForm) SetCSRF

func (f *BaseForm) SetCSRF(csrf string)

func (*BaseForm) SetMethod

func (f *BaseForm) SetMethod(method string)

func (*BaseForm) SetSubmitButtonStyle

func (f *BaseForm) SetSubmitButtonStyle(style string)

func (*BaseForm) SetSubmitButtonText

func (f *BaseForm) SetSubmitButtonText(text string)

func (*BaseForm) SetValidation

func (f *BaseForm) SetValidation(validation *Validation)

func (*BaseForm) Validation

func (f *BaseForm) Validation() *Validation

type BaseLogger

type BaseLogger struct {
	// contains filtered or unexported fields
}

func NewLogger

func NewLogger(logLevel string) *BaseLogger

func (*BaseLogger) Debug

func (l *BaseLogger) Debug(v ...any)

func (*BaseLogger) Debugf

func (l *BaseLogger) Debugf(format string, a ...any)

func (*BaseLogger) Error

func (l *BaseLogger) Error(v ...any)

func (*BaseLogger) Errorf

func (l *BaseLogger) Errorf(format string, a ...any)

func (*BaseLogger) Info

func (l *BaseLogger) Info(v ...any)

func (*BaseLogger) Infof

func (l *BaseLogger) Infof(format string, a ...any)

func (*BaseLogger) SetDebugOutput

func (l *BaseLogger) SetDebugOutput(debug *bytes.Buffer)

SetDebugOutput set the internal log. Used for package testing.

func (*BaseLogger) SetErrorOutput

func (l *BaseLogger) SetErrorOutput(error *bytes.Buffer)

SetErrorOutput set the internal log. Used for package testing.

func (*BaseLogger) SetInfoOutput

func (l *BaseLogger) SetInfoOutput(info *bytes.Buffer)

SetInfoOutput set the internal log. Used for package testing.

func (*BaseLogger) SetLogLevel

func (l *BaseLogger) SetLogLevel(level LogLevel)

type BaseRepo

type BaseRepo struct {
	*BaseCore
	// contains filtered or unexported fields
}

func NewRepo

func NewRepo(name string, qm *QueryManager, params XParams) *BaseRepo

func (BaseRepo) BeginTx

func (r BaseRepo) BeginTx(ctx context.Context) (updatedCtx context.Context, tx Tx, err error)

func (*BaseRepo) Query

func (r *BaseRepo) Query() *QueryManager

type Button

type Button struct {
	Text  string
	Style string
}

Button struct represents a button with text and style.

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config manages configuration settings loaded from environment variables and CLI flags.

func LoadCfg

func LoadCfg(namespace string, flagDefs map[string]interface{}) *Config

LoadCfg initializes a Config instance with the specified namespace and loads the corresponding environment variables and CLI flags.

func NewConfig

func NewConfig() *Config

func (*Config) APIAddr

func (cfg *Config) APIAddr() string

func (*Config) BoolVal

func (cfg *Config) BoolVal(key string, defVal bool, reload ...bool) (value bool)

BoolVal retrieves the value of a specific namespaced environment variable or CLI flag as a bool. If the key is not found or cannot be parsed as a bool, it returns the provided default value. If reload is true, it re-reads the values from the environment and CLI flags.

func (*Config) ByteSliceVal

func (cfg *Config) ByteSliceVal(key string, reload ...bool) []byte

ByteSliceVal retrieves the value of a specific namespaced environment variable or CLI flag as a byte slice. If the key is not found, it returns an empty byte slice. If reload is true, it re-reads the values from the environment and CLI flags.

func (*Config) Debug

func (cfg *Config) Debug()

Debug prints the configuration values in a readable format.

func (*Config) FloatVal

func (cfg *Config) FloatVal(key string, defVal float64, reload ...bool) (value float64)

FloatVal retrieves the value of a specific namespaced environment variable or CLI flag as a float. If the key is not found or cannot be parsed as a float, it returns the provided default value. If reload is true, it re-reads the values from the environment and CLI flags.

func (*Config) Get

func (cfg *Config) Get(reload ...bool) map[string]string

Get retrieves all environment variables that belong to the namespace. If reload is true, it re-reads the values from the environment.

func (*Config) GetStr

func (cfg *Config) GetStr(key string, reload ...bool) (string, error)

GetStr retrieves the value of a specific namespaced environment variable or CLI flag as a string. If the key is not found, it returns an empty string and an error.

func (*Config) IntVal

func (cfg *Config) IntVal(key string, defVal int64, reload ...bool) (value int64)

IntVal retrieves the value of a specific namespaced environment variable or CLI flag as an int. If the key is not found or cannot be parsed as an int, it returns the provided default value. If reload is true, it re-reads the values from the environment and CLI flags.

func (*Config) PreviewAddr

func (cfg *Config) PreviewAddr() string

func (*Config) Set

func (cfg *Config) Set(key string, value interface{})

Set sets a configuration value.

func (*Config) SetNamespace

func (cfg *Config) SetNamespace(namespace string)

SetNamespace sets the namespace for the configuration, converting it to uppercase.

func (*Config) SetValues

func (cfg *Config) SetValues(values map[string]string)

SetValues sets the configuration values directly.

func (*Config) StrVal

func (cfg *Config) StrVal(key string, reload ...bool) (value string, ok bool)

StrVal retrieves the value of a specific namespaced environment variable or CLI flag. If reload is true, it re-reads the values from the environment and CLI flags.

func (*Config) StrValOrDef

func (cfg *Config) StrValOrDef(key, defVal string, reload ...bool) (value string)

StrValOrDef retrieves the value of a specific namespaced environment variable or CLI flag. If the key is not found, it returns the provided default value. If reload is true, it re-reads the values from the environment and CLI flags.

func (*Config) WebAddr

func (cfg *Config) WebAddr() string

type Configuring

type Configuring interface {
	Cfg() *Config
	SetCfg(cfg *Config)
}

type Core

type Core interface {
	SetOpts(opts ...Option)
	Naming
	Logging
	Configuring
	Lifecycle
}

type Crypto

type Crypto struct {
	// contains filtered or unexported fields
}

func NewCrypto

func NewCrypto(key ...[]byte) *Crypto

func (*Crypto) CheckPassword

func (c *Crypto) CheckPassword(hash []byte, password string) error

func (*Crypto) DecryptEmail

func (c *Crypto) DecryptEmail(ciphertext []byte) (string, error)

func (*Crypto) EncryptEmail

func (c *Crypto) EncryptEmail(email string) ([]byte, error)

func (*Crypto) HashPassword

func (c *Crypto) HashPassword(password string) ([]byte, error)

func (*Crypto) SetKey

func (c *Crypto) SetKey(key []byte)

type Dep

type Dep struct {
	Core
	Status Status
}

type Feat

type Feat struct {
	Path       string // The base path for the action (i.e. `/feat/auth`)
	Action     string // Action name (command or query, i.e. `edit-user`)
	PathSuffix string // The path suffix for the feature (i.e.: `/auth`)
}

Feat struct represents a feature with base path, feature name, and action.

type FileServer

type FileServer struct {
	*Router
	// contains filtered or unexported fields
}

FileServer serves static files from an embedded filesystem.

func NewFileServer

func NewFileServer(fs embed.FS, params XParams) *FileServer

func (*FileServer) Setup

func (f *FileServer) Setup(ctx context.Context) error

Setup is the default implementation for the Setup method in FileServer.

func (*FileServer) SetupRoutes

func (f *FileServer) SetupRoutes() error

func (*FileServer) SetupRoutesIndex

func (f *FileServer) SetupRoutesIndex() error

SetupRoutesIndex sets up the routes to serve static files index listing.

func (*FileServer) SetupRoutesNoIndex

func (f *FileServer) SetupRoutesNoIndex() error

SetupRoutesNoIndex sets up the routes to serve static files without index listing.

type Flash

type Flash struct {
	Notifications []Notification
}

func NewFlash

func NewFlash() Flash

func (*Flash) Add

func (f *Flash) Add(typ, msg string)

func (*Flash) Clear

func (f *Flash) Clear()

func (*Flash) HasMessages

func (f *Flash) HasMessages() bool

type FlashCtxKey

type FlashCtxKey string

type FlashManager

type FlashManager struct {
	Core
	// contains filtered or unexported fields
}

func NewFlashManager

func NewFlashManager(params XParams) *FlashManager

func (*FlashManager) AddFlash

func (fm *FlashManager) AddFlash(r *http.Request, typ, msg string)

func (*FlashManager) ClearFlash

func (fm *FlashManager) ClearFlash(w http.ResponseWriter, r *http.Request)

func (*FlashManager) ClearFlashCookie

func (fm *FlashManager) ClearFlashCookie(w http.ResponseWriter)

func (*FlashManager) GetFlash

func (fm *FlashManager) GetFlash(r *http.Request) Flash

func (*FlashManager) GetFlashFromCookie

func (fm *FlashManager) GetFlashFromCookie(r *http.Request) Flash

func (*FlashManager) Middleware

func (fm *FlashManager) Middleware(next http.Handler) http.Handler

func (*FlashManager) Middlewares

func (fm *FlashManager) Middlewares() []Middleware

func (*FlashManager) SaveFlash

func (fm *FlashManager) SaveFlash(r *http.Request, flash Flash)

func (*FlashManager) SetFlashInCookie

func (fm *FlashManager) SetFlashInCookie(w http.ResponseWriter, flash Flash)

func (*FlashManager) Setup

func (fm *FlashManager) Setup(ctx context.Context) error

type Form

type Form interface {
	Action() string
	SetAction(action string)
	Method() string
	SetMethod(method string)
	CSRF() string
	SetCSRF(csrf string)
	Button() Button
	SetButton(button Button)
	SetSubmitButtonText(text string)
	SetSubmitButtonStyle(style string)
	GenCSRFToken(r *http.Request)
	SetValidation(validation *Validation)
	Validation() *Validation
	HasErrors() bool
}

Form interface defines accessors and setters for BaseForm properties and its methods. NOTE: We might want to review this interface later to see if all methods are necessary.

type FormConfig

type FormConfig struct {
	FieldTag    string // Form field tag name
	RequiredTag string // Required field tag name
}

FormConfig holds configuration for form mapping

func DefaultFormConfig

func DefaultFormConfig() FormConfig

DefaultFormConfig returns the default form configuration

type FormField

type FormField struct {
	Name     string
	Required bool
	Type     reflect.Type
	Convert  TypeConverter
}

FormField represents a form field mapping

type FormMapper

type FormMapper struct {
	// contains filtered or unexported fields
}

FormMapper maps form values to struct fields

func NewFormMapper

func NewFormMapper(v interface{}, config ...FormConfig) (*FormMapper, error)

NewFormMapper creates a new FormMapper for the given struct type

func (*FormMapper) MapForm

func (m *FormMapper) MapForm(r *http.Request, v interface{}) error

MapForm maps form values to the struct

type GitAuth

type GitAuth struct {
	Method AuthMethod
	Token  string
}

GitAuth holds authentication details for Git operations.

type GitClient

type GitClient interface {
	Clone(ctx context.Context, repoURL, localPath string, auth GitAuth, env []string) error
	Checkout(ctx context.Context, localRepoPath, branch string, create bool, env []string) error
	Add(ctx context.Context, localRepoPath, pathspec string, env []string) error
	Commit(ctx context.Context, localRepoPath string, commit GitCommit, env []string) (string, error)
	Push(ctx context.Context, localRepoPath string, auth GitAuth, remote, branch string, env []string) error
	Status(ctx context.Context, localRepoPath string, env []string) (string, error)
	GitLog(ctx context.Context, localRepoPath string, args []string, env []string) (string, error) // args is now a slice
}

GitClient defines the interface for Git operations.

type GitCommit

type GitCommit struct {
	UserName  string
	UserEmail string
	Message   string
}

GitCommit holds commit details.

type HTTPMethods

type HTTPMethods struct {
	GET    string
	POST   string
	PUT    string
	PATCH  string
	DELETE string
	HEAD   string
}

type Handler

type Handler struct {
	Core
}

func NewHandler

func NewHandler(name string, params XParams) *Handler

func (*Handler) Err

func (h *Handler) Err(w http.ResponseWriter, err error, msg string, code int)

Err writes an error response to the client. This method can be overridden by types that embed Handler.

func (*Handler) ID

ID returns the ID from the request query parameters. If the ID is missing or invalid, it writes an error response and returns an error.

func (*Handler) ParseUUIDFromQuery

func (h *Handler) ParseUUIDFromQuery(r *http.Request, paramName string) (uuid.UUID, error)

ParseUUIDFromQuery parses a UUID from the URL query parameters. Returns the parsed UUID and an error if the ID is missing or invalid.

func (*Handler) ParseUUIDsFromQuery

func (h *Handler) ParseUUIDsFromQuery(w http.ResponseWriter, r *http.Request, paramName string) ([]uuid.UUID, bool)

ParseUUIDsFromQuery parses multiple UUIDs from the URL query parameters. The UUIDs should be comma-separated in the query parameter. If any UUID is invalid, it writes an error response and returns false. Returns the parsed UUIDs and true if successful.

func (*Handler) Redir

func (h *Handler) Redir(w http.ResponseWriter, r *http.Request, path string)

Redir redirects to the specified path with http.StatusSeeOther

func (*Handler) Render

func (h *Handler) Render(w http.ResponseWriter, r *http.Request, template string, data any) error

Render writes a template to the response writer. This method can be overridden by types that embed Handler.

func (*Handler) ShowItem

func (h *Handler) ShowItem(w http.ResponseWriter, r *http.Request, getter func(uuid.UUID) (any, error), template string) bool

ShowItem is a helper method that shows an item by ID. It handles ID parsing, item retrieval, and rendering. If any step fails, it writes an error response and returns false.

type Identifiable

type Identifiable interface {
	// Type returns the type of the entity.
	Type() string
	// GetID returns the unique identifier of the entity.
	GetID() uuid.UUID
	// GenID generates and sets the unique identifier of the entity if it is not set yet.
	GenID()
	// SetID sets the unique identifier of the entity.
	SetID(id uuid.UUID, force ...bool)
	// GetShortID returns the short ID portion of the slug.
	GetShortID() string
	// GenShortID generates and sets the short ID if it is not set yet.
	GenShortID()
	// SetShortID sets the short ID of the entity.
	SetShortID(shortID string, force ...bool)
	// Slug returns the slug of the entity,
	Slug() string
}

Identifiable interface represents an entity with an ID and Slug.

type JSONSeed

type JSONSeed struct {
	Datetime string
	Name     string
	Content  string
}

type JSONSeeder

type JSONSeeder struct {
	Core
	// contains filtered or unexported fields
}

func NewJSONSeeder

func NewJSONSeeder(feat string, assetsFS embed.FS, engine string, params XParams) *JSONSeeder

func (*JSONSeeder) ApplyJSONSeed

func (s *JSONSeeder) ApplyJSONSeed(datetime, name, context, content string) error

func (*JSONSeeder) LoadJSONSeeds

func (s *JSONSeeder) LoadJSONSeeds() (map[string][]JSONSeed, error)

LoadJSONSeeds loads all JSON seed files by feature (e.g. "auth")

func (*JSONSeeder) SeedApplied

func (s *JSONSeeder) SeedApplied(datetime, name, context string) (bool, error)

func (*JSONSeeder) Setup

func (s *JSONSeeder) Setup(ctx context.Context) error

type Keys

type Keys struct {
	AppEnv string

	ServerWebHost      string
	ServerWebPort      string
	ServerWebEnabled   string
	ServerAPIHost      string
	ServerAPIPort      string
	ServerAPIEnabled   string
	ServerResPath      string
	ServerIndexEnabled string

	ServerPreviewHost    string
	ServerPreviewPort    string
	ServerPreviewEnabled string

	DBSQLiteDSN string

	SecCSRFKey       string
	SecCSRFRedirect  string
	SecEncryptionKey string
	SecHashKey       string
	SecBlockKey      string
	SecBypassAuth    string

	ButtonStyleGray   string
	ButtonStyleBlue   string
	ButtonStyleRed    string
	ButtonStyleGreen  string
	ButtonStyleYellow string

	NotificationSuccessStyle string
	NotificationInfoStyle    string
	NotificationWarnStyle    string
	NotificationErrorStyle   string
	NotificationDebugStyle   string

	RenderWebErrors string
	RenderAPIErrors string
}

type Lifecycle

type Lifecycle interface {
	Setup(ctx context.Context) error
	Start(ctx context.Context) error
	Stop(ctx context.Context) error
}

type LogLevel

type LogLevel int
const (
	DebugLevel LogLevel = iota
	InfoLevel
	ErrorLevel
)

func ToValidLevel

func ToValidLevel(level string) LogLevel

type Logger

type Logger interface {
	SetLogLevel(level LogLevel)
	Debug(v ...any)
	Debugf(format string, a ...any)
	Info(v ...any)
	Infof(format string, a ...any)
	Error(v ...any)
	Errorf(format string, a ...any)
}

type Logging

type Logging interface {
	Log() Logger
	SetLog(log Logger)
}
type Menu struct {
	Path      string
	Items     []MenuItem
	CSRFToken string
}

Menu represents the entire menu structure (optional, depending on your needs). NOTE: Path and CSRFToken are stored in order to be able to provide them to the MenuItem. but maybe a better approach could be implemented later. This is a WIP

func NewMenu

func NewMenu(paths ...string) *Menu

NewMenu creates a new Menu with the given parameters.

func (m *Menu) AddDeleteItem(i Identifiable, text ...string)

AddDeleteItem adds a new MenuItem for deleting a resource.

func (m *Menu) AddEditItem(i Identifiable, text ...string)

AddEditItem adds a new MenuItem for editing a resource.

func (m *Menu) AddGenericItem(action, url string, text ...string)

AddGenericItem adds a new generic MenuItem.

func (m *Menu) AddListItem(resource Identifiable, text ...string)

AddListItem adds a new MenuItem for listing resources.

func (m *Menu) AddNewItem(r Identifiable, text ...string)

AddNewItem adds a new MenuItem for creating a new resource.

func (m *Menu) AddResDeleteItem(i Identifiable, text ...string)

AddResDeleteItem adds a new MenuItem for deleting a resource in a RESTful way.

func (m *Menu) AddResEditItem(i Identifiable, text ...string)

AddResEditItem adds a new MenuItem for editing a resource in a RESTful way.

func (m *Menu) AddResGenericItem(action, id string, text ...string)

AddResGenericItem adds a new MenuItem for a generic RESTful action.

func (m *Menu) AddResListItem(resource Identifiable, text ...string)

AddResListItem adds a new MenuItem for listing resources in a RESTful way.

func (m *Menu) AddResNewItem(resourceType string, text ...string)

AddResNewItem adds a new MenuItem for creating a new resource in a RESTful way.

func (m *Menu) AddResShowItem(i Identifiable, text ...string)

AddResShowItem adds a new MenuItem for showing a resource in a RESTful way.

func (m *Menu) AddShowItem(i Identifiable, text ...string)

AddShowItem adds a new MenuItem for showing a resource.

type MenuItem struct {
	Feat        Feat              // The feature this menu item calls
	Text        string            // The text to display for the menu item
	Method      string            // "GET" or "POST"
	IsForm      bool              // Indicates if the action should be triggered via a form submission (POST)
	Style       MenuItemStyle     // The style of the menu item
	QueryParams map[string]string // Query parameters for the Path
	CSRFToken   string            // Only applicable for POST requests
}

MenuItem represents a single item in the menu. NOTE: Maybe some of these field can be removed later.

func (i *MenuItem) GenLinkButton() string

GenLinkButton generates an HTML link button.

func (i *MenuItem) GenPath() string

GenPath constructs the href path from the MenuItem data.

func (i *MenuItem) Path() string

Path generates the href path for a menu item based on the feature and menu item data.

type MenuItemStyle string

MenuItemStyle defines the styling for a menu item.

const (
	// BtnPrimaryStyle is the main action style (e.g., "Save", "Submit").
	BtnPrimaryStyle MenuItemStyle = "bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"

	// BtnSecondaryStyle is the neutral action style (e.g., "Back", "Cancel").
	BtnSecondaryStyle MenuItemStyle = "bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded"

	// BtnDangerStyle is the destructive action style (e.g., "Delete").
	BtnDangerStyle MenuItemStyle = "bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded"

	// BtnWarningStyle is the risky but not destructive action style (e.g., "Override", "Reset").
	BtnWarningStyle MenuItemStyle = "bg-yellow-500 hover:bg-yellow-700 text-white font-bold py-2 px-4 rounded"

	// BtnInfoStyle is the informative or contextual action style (optional, e.g., "More info").
	BtnInfoStyle MenuItemStyle = "bg-teal-500 hover:bg-teal-700 text-white font-bold py-2 px-4 rounded"

	// BtnGenericStyle is the generic action style.
	BtnGenericStyle MenuItemStyle = "bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded"
)

Define constants for button styles. WIP: These styles are expected to be configurable by editing some SCSS when the assets pipeline is in place. We also don't want to enforce TailwindCSS at this level, so these are temnporary until a better solution is found.

type Middleware

type Middleware func(http.Handler) http.Handler

type Migration

type Migration struct {
	Datetime string
	Name     string
	Up       string
	Down     string
}

type Migrator

type Migrator struct {
	Core
	// contains filtered or unexported fields
}

func NewMigrator

func NewMigrator(assetsFS embed.FS, engine string, params XParams) *Migrator

func (*Migrator) Migrate

func (m *Migrator) Migrate(pendingMigrations []Migration) error

func (*Migrator) SetDB

func (m *Migrator) SetDB(db *sql.DB)

func (*Migrator) SetPath

func (m *Migrator) SetPath(path string)

func (*Migrator) Setup

func (m *Migrator) Setup(ctx context.Context) error

func (*Migrator) SetupMigrations

func (m *Migrator) SetupMigrations() error

func (*Migrator) Start

func (m *Migrator) Start(ctx context.Context) error

type Model

type Model interface {
	Identifiable
	Auditable
	Stampable
	Seedable
}

Model interface composes Identifiable, Auditable, and Stampable interfaces.

type Naming

type Naming interface {
	Name() string
	SetName(name string)
}

type Notification

type Notification struct {
	Type string
	Msg  string
}

type Option

type Option func(Core)

Option defines a type for setting optional parameters in BaseCore.

func WithConfigValue

func WithConfigValue(key string, value interface{}) Option

WithConfigValue sets a specific key-value pair in the Config.

type Page

type Page struct {
	Name     string // Name of the page (e.g. title)
	Title    string // Title of the page (e.g. for <title> tag)
	IsNew    bool   // True if the page is for a new entity
	Form     Form
	Entity   any   // Single entity instance of any type
	Entities []any // Collection of entities of any type
	Data     any   // For any additional or wrapper data
	Flash    Flash
	Menu     *Menu
	Feat     Feat
	Select   map[string][]SelectOpt // For select/dropdown options and similar lists
}

Page struct represents a web page with data, fm messages, form, menu, and feature information.

func NewPage

func NewPage(r *http.Request, data interface{}) *Page

NewPage creates a new Page with the given data.

func (*Page) AddSelect

func (p *Page) AddSelect(key string, values []SelectOpt)

func (*Page) GenCSRFToken

func (p *Page) GenCSRFToken(r *http.Request)

GenCSRFToken generates a csrf token and sets it in the form.

func (*Page) GetSelects

func (p *Page) GetSelects(key string) []SelectOpt

func (*Page) NewMenu

func (p *Page) NewMenu(paths ...string) *Menu

NewMenu returns a new menu associated with this page, configured with the given path

func (*Page) Path

func (p *Page) Path(feat Feat, item MenuItem) string

Path generates the href path for a menu item based on the feature and menu item data.

func (*Page) SetData

func (p *Page) SetData(data interface{})

SetData sets the Data property for the page.

func (*Page) SetFeat

func (p *Page) SetFeat(feat Feat)

SetFeat sets the Feat struct for the page.

func (*Page) SetFlash

func (p *Page) SetFlash(flash Flash)

SetFlash sets the fm message for the page.

func (*Page) SetForm

func (p *Page) SetForm(form Form)

SetForm sets the entire Form for the page.

func (*Page) SetMenuItems

func (p *Page) SetMenuItems(items []MenuItem)

SetMenuItems sets the menu items for the page.

func (*Page) SetSelects

func (p *Page) SetSelects(selects map[string][]SelectOpt)

type QueryManager

type QueryManager struct {
	Core
	// contains filtered or unexported fields
}

func NewQueryManager

func NewQueryManager(assetsFS embed.FS, engine string, params XParams) *QueryManager

func (*QueryManager) Debug

func (qm *QueryManager) Debug()

func (*QueryManager) Get

func (qm *QueryManager) Get(feat, resource, queryName string) (string, error)

func (*QueryManager) Load

func (qm *QueryManager) Load()

func (*QueryManager) Setup

func (qm *QueryManager) Setup(ctx context.Context) error

type Repo

type Repo interface {
	Core
	Query() *QueryManager
	BeginTx(ctx context.Context) (context.Context, Tx, error)
}

type Response

type Response struct {
	Status  string      `json:"status"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
	Error   *APIError   `json:"error,omitempty"`
}

func NewErrorResponse

func NewErrorResponse(message, code, details string) Response

func NewSuccessResponse

func NewSuccessResponse(message string, data interface{}) Response

type Router

type Router struct {
	Core
	chi.Router
}

func NewAPIRouter

func NewAPIRouter(name string, params XParams) *Router

func NewRouter

func NewRouter(name string, params XParams) *Router

func NewWebRouter

func NewWebRouter(name string, params XParams) *Router

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*Router) SetMiddlewares

func (r *Router) SetMiddlewares(mws []Middleware)

type Seedable

type Seedable interface {
	// Ref returns the reference string for this entity (used in seed data for relationships).
	Ref() string
	// SetRef sets the reference string for this entity.
	SetRef(ref string)
}

Seedable is an interface for entities that need special logic before being inserted into the database during seeding.

type SelectOpt

type SelectOpt struct {
	Value string
	Label string
}

SelectOpt struct represents an option for select/dropdown lists.

func ToSelectOpt

func ToSelectOpt[T Selectable](in []T) []SelectOpt

type Selectable

type Selectable interface {
	OptValue() string
	OptLabel() string
}

type Server

type Server struct {
	Core
	// contains filtered or unexported fields
}

func NewServer

func NewServer(hostKey, portKey string, handler http.Handler, params XParams) *Server

NewServer creates a new Server instance with the provided options.

Parameters: - hostKey: The configuration key for the server host (e.g., "server.web.host"). - portKey: The configuration key for the server port (e.g., "server.web.port"). - handler: The HTTP handler to use for the server. - opts: Variadic options to configure the server.

Example usage:

webServer := am.NewServer("server.web.host", "server.web.port", webRouter, opts...)
apiServer := am.NewServer("server.api.host", "server.api.port", apiRouter, opts...)

Note: This is a WIP and an improved way of configuring the server will be provided in future updates.

func (*Server) Start

func (s *Server) Start()

type Service

type Service struct {
	Core
	Crypto *Crypto
}

func NewService

func NewService(name string, params XParams) *Service

type SessionStore

type SessionStore interface {
	GetUserFromSession(ctx context.Context, sessionID string) (uuid.UUID, error)
}

SessionStore is a placeholder interface for session management.

type Stampable

type Stampable interface {
	GenCreateValues(userID ...uuid.UUID) // Modified
	GenUpdateValues(userID ...uuid.UUID) // Modified
}

type Status

type Status string
const (
	Disabled    Status = "disabled"
	Initialized Status = "initialized"
	Started     Status = "started"
	Stopped     Status = "stopped"
)

type TemplateManager

type TemplateManager struct {
	Core
	// contains filtered or unexported fields
}

func NewTemplateManager

func NewTemplateManager(assetsFS embed.FS, params XParams) *TemplateManager

func (*TemplateManager) Debug

func (tm *TemplateManager) Debug()

func (*TemplateManager) Get

func (tm *TemplateManager) Get(handler, action string) (*template.Template, error)

func (*TemplateManager) Load

func (tm *TemplateManager) Load()

func (*TemplateManager) RegisterFuncs

func (tm *TemplateManager) RegisterFuncs(tmpl *template.Template) *template.Template

RegisterFuncs registers both base and custom template functions.

func (*TemplateManager) RegisterFunctions

func (tm *TemplateManager) RegisterFunctions(funcs template.FuncMap)

RegisterFunctions allows injection of custom template functions from applications

func (*TemplateManager) Setup

func (tm *TemplateManager) Setup(ctx context.Context) error

type Tx

type Tx interface {
	Commit() error
	Rollback() error
}

type TypeConverter

type TypeConverter func(string) (interface{}, error)

TypeConverter converts a string form value to a specific type

type UserCtxData

type UserCtxData struct {
	ID                    uuid.UUID
	Permissions           []uuid.UUID
	ContextualPermissions map[uuid.UUID]uuid.UUID
}

UserCtxData represents authenticated user data stored in the request context.

func GetUserCtxData

func GetUserCtxData(ctx context.Context) *UserCtxData

GetUserCtxData retrieves the authenticated user data from the request context.

type UserService

type UserService interface {
	GetUserByID(ctx context.Context, userID uuid.UUID) (*UserCtxData, error)
}

UserService is a placeholder interface for user retrieval.

type Validate

type Validate func(entity any) error

type Validation

type Validation struct {
	Errors []string
	Fields map[string]ValidationField
}

Validation holds the result of one or many validation checks. It can collect multiple error messages unless strict mode is enabled. Use IsValid() to check result, and Error() or JSON() to report.

func (*Validation) Add

func (v *Validation) Add(err string)

Add adds an error message to the validation result.

func (*Validation) AddFieldError

func (v *Validation) AddFieldError(field, value, message string)

AddFieldError adds a field-specific error to the validation result.

func (Validation) Error

func (v Validation) Error() string

Error returns all validation errors as a comma-separated string.

func (Validation) FieldMsg

func (v Validation) FieldMsg(field string) string

FieldMsg returns the message for a given field tag name, or an empty string if none exists.

func (Validation) HasErrors

func (v Validation) HasErrors() bool

HasErrors returns true if there are validation errors. This is the inverse of IsValid and can make code more readable by avoiding negations.

func (Validation) IsValid

func (v Validation) IsValid() bool

IsValid returns true if there are no validation errors.

func (Validation) JSON

func (v Validation) JSON() string

JSON returns all validation errors as a JSON string.

type ValidationField

type ValidationField struct {
	Name    string
	Value   string
	Message string
}

ValidationField represents a field-specific validation error.

type Validator

type Validator func(v any) (Validation, error)

Validator is a function type that performs validation on any input.

func ComposeValidators

func ComposeValidators(fns ...Validator) Validator

ComposeValidators allows combining multiple Validator functions into one. By default, it will collect all validation errors. If strict is true, it will stop after the first error.

func ComposeValidatorsStrict

func ComposeValidatorsStrict(fns ...Validator) Validator

ComposeValidatorsStrict allows combining multiple Validator functions into one and stops after the first error is found.

func Equals

func Equals(field, a, b string) Validator

Equals validates that two string fields are equal.

func GreaterThan

func GreaterThan(field string, a, b int) Validator

GreaterThan validates that an integer field is greater than a value.

func MaxLength

func MaxLength(field, val string, max int) Validator

MaxLength validates that a string field has a maximum length.

func MinLength

func MinLength(field, val string, min int) Validator

MinLength validates that a string field has a minimum length.

type WebHandler

type WebHandler struct {
	*Handler
	// contains filtered or unexported fields
}

func NewWebHandler

func NewWebHandler(tm *TemplateManager, fm *FlashManager, params XParams) *WebHandler

func (*WebHandler) Debug

func (h *WebHandler) Debug(w http.ResponseWriter, r *http.Request, msg string)

func (*WebHandler) FlashError

func (h *WebHandler) FlashError(w http.ResponseWriter, r *http.Request, msg string)

func (*WebHandler) FlashInfo

func (h *WebHandler) FlashInfo(w http.ResponseWriter, r *http.Request, msg string)

func (*WebHandler) FlashManager

func (h *WebHandler) FlashManager() *FlashManager

func (*WebHandler) FlashSuccess

func (h *WebHandler) FlashSuccess(w http.ResponseWriter, r *http.Request, msg string)

func (*WebHandler) FlashWarn

func (h *WebHandler) FlashWarn(w http.ResponseWriter, r *http.Request, msg string)

func (*WebHandler) GetFlash

func (h *WebHandler) GetFlash(r *http.Request) Flash

func (*WebHandler) OK

func (h *WebHandler) OK(w http.ResponseWriter, r *http.Request, buf *bytes.Buffer, statusCode int)

func (*WebHandler) Redir

func (h *WebHandler) Redir(w http.ResponseWriter, r *http.Request, path string, status int)

func (*WebHandler) Tmpl

func (h *WebHandler) Tmpl() *TemplateManager

type XParams

type XParams struct {
	Cfg *Config
	Log Logger
}

XParams contains the essential dependencies for most components.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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