Documentation
¶
Index ¶
- Constants
- Variables
- func Add(a, b int) int
- func AddPluralRule(plural, singular string)
- func AddRelatedPath(i Identifiable, j Identifiable) string
- func AddSingularRule(singular, plural string)
- func AddUncountableRule(word string)
- func AuthMw(app *App, sessionStore SessionStore, userService UserService) func(next http.Handler) http.Handler
- func CORSMw(next http.Handler) http.Handler
- func CSRFMw(cfg *Config) func(next http.Handler) http.Handler
- func Cap(s string) string
- func CreatePath(i Identifiable) string
- func DebugFS(efs embed.FS, root string) error
- func DefaultType(currentType string) string
- func DeletePath(i Identifiable, id uuid.UUID) string
- func EditPath(i Identifiable, id uuid.UUID) string
- func EncryptionKeyMw(app *App) func(next http.Handler) http.Handler
- func FieldMsg(form Form, field string, classes ...string) template.HTML
- func GenID(i Identifiable)
- func GenShortID(i Identifiable)
- func InternalAuthMiddleware(app *App) func(next http.Handler) http.Handler
- func IsHTMXRequest(r *http.Request) bool
- func IsPlural(s string) bool
- func IsSingular(s string) bool
- func ListPath(i Identifiable) string
- func ListRelatedPath(i Identifiable, j Identifiable, id uuid.UUID) string
- func LogHeadersMw(next http.Handler) http.Handler
- func MethodOverrideMw(next http.Handler) http.Handler
- func Min(a, b int) int
- func Mul(a, b int) int
- func NewPath(i Identifiable) string
- func Normalize(str string) string
- func ParseUUID(s string) uuid.UUID
- func PathID(r *http.Request, key string) (uuid.UUID, error)
- func Plural(s string) string
- func RemoveRelatedPath(i Identifiable, j Identifiable) string
- func ReqID(r *http.Request) string
- func RequestIDMw(next http.Handler) http.Handler
- func Respond(w http.ResponseWriter, status int, response Response)
- func SetCreateValues(m Model, userID ...uuid.UUID)
- func SetUpdateValues(m Model, userID ...uuid.UUID)
- func ShowPath(i Identifiable, id uuid.UUID) string
- func Singular(s string) string
- func StringPtr(s string) *string
- func StringVal(s *string) string
- func Sub(a, b int) int
- func TimePtr(t time.Time) *time.Time
- func TimeVal(t *time.Time) time.Time
- func ToForm(r *http.Request, v interface{}, config ...FormConfig) error
- func ToPtrSlice[T any](s []T) []*T
- func Truncate(s string, length int) string
- func TxFromContext(ctx context.Context) (interface{}, bool)
- func UUIDPtr(id uuid.UUID) *string
- func UUIDVal(s *string) uuid.UUID
- func UpdatePath(i Identifiable) string
- func ValidateEmail(email string) error
- func WithTx(ctx context.Context, tx interface{}) context.Context
- type APIClient
- func (c *APIClient) Delete(r *http.Request, path string) error
- func (c *APIClient) Get(r *http.Request, path string, target interface{}) error
- func (c *APIClient) Post(r *http.Request, path string, body, target interface{}) error
- func (c *APIClient) Put(r *http.Request, path string, body, target interface{}) error
- type APIError
- type APIHandler
- func (h *APIHandler) Created(w http.ResponseWriter, message string, data interface{})
- func (h *APIHandler) Err(w http.ResponseWriter, code int, message string, err error)
- func (h *APIHandler) ID(w http.ResponseWriter, r *http.Request) (uuid.UUID, error)
- func (h *APIHandler) OK(w http.ResponseWriter, message string, data interface{})
- func (h *APIHandler) Param(w http.ResponseWriter, r *http.Request, key string) (string, error)
- type Action
- type App
- func (a *App) Add(dep Core)
- func (a *App) Dep(name string) (*Dep, bool)
- func (a *App) InternalAuthToken() string
- func (a *App) MountAPI(path string, handler http.Handler)
- func (a *App) MountFileServer(path string, fs *FileServer)
- func (app *App) MountWeb(path string, handler http.Handler)
- func (app *App) SetAPIRouter(router *Router)
- func (app *App) SetWebRouter(router *Router)
- func (a *App) Setup(ctx context.Context) error
- func (a *App) Start(ctx context.Context) error
- func (a *App) StartServer(server *http.Server, addr string)
- func (a *App) Stop(ctx context.Context) error
- type Auditable
- type AuthMethod
- type BaseCore
- func (c *BaseCore) Cfg() *Config
- func (c *BaseCore) Log() Logger
- func (c *BaseCore) Name() string
- func (c *BaseCore) SetCfg(cfg *Config)
- func (c *BaseCore) SetLog(log Logger)
- func (c *BaseCore) SetName(name string)
- func (c *BaseCore) SetOpts(opts ...Option)
- func (c *BaseCore) Setup(ctx context.Context) error
- func (c *BaseCore) Start(ctx context.Context) error
- func (c *BaseCore) Stop(ctx context.Context) error
- type BaseForm
- func (f *BaseForm) Action() string
- func (f *BaseForm) Button() Button
- func (f *BaseForm) CSRF() string
- func (f *BaseForm) GenCSRFToken(r *http.Request)
- func (f *BaseForm) HasErrors() bool
- func (f *BaseForm) Method() string
- func (f *BaseForm) SetAction(action string)
- func (f *BaseForm) SetButton(button Button)
- func (f *BaseForm) SetCSRF(csrf string)
- func (f *BaseForm) SetMethod(method string)
- func (f *BaseForm) SetSubmitButtonStyle(style string)
- func (f *BaseForm) SetSubmitButtonText(text string)
- func (f *BaseForm) SetValidation(validation *Validation)
- func (f *BaseForm) Validation() *Validation
- type BaseLogger
- func (l *BaseLogger) Debug(v ...any)
- func (l *BaseLogger) Debugf(format string, a ...any)
- func (l *BaseLogger) Error(v ...any)
- func (l *BaseLogger) Errorf(format string, a ...any)
- func (l *BaseLogger) Info(v ...any)
- func (l *BaseLogger) Infof(format string, a ...any)
- func (l *BaseLogger) SetDebugOutput(debug *bytes.Buffer)
- func (l *BaseLogger) SetErrorOutput(error *bytes.Buffer)
- func (l *BaseLogger) SetInfoOutput(info *bytes.Buffer)
- func (l *BaseLogger) SetLogLevel(level LogLevel)
- type BaseRepo
- type Button
- type Config
- func (cfg *Config) APIAddr() string
- func (cfg *Config) BoolVal(key string, defVal bool, reload ...bool) (value bool)
- func (cfg *Config) ByteSliceVal(key string, reload ...bool) []byte
- func (cfg *Config) Debug()
- func (cfg *Config) FloatVal(key string, defVal float64, reload ...bool) (value float64)
- func (cfg *Config) Get(reload ...bool) map[string]string
- func (cfg *Config) GetStr(key string, reload ...bool) (string, error)
- func (cfg *Config) IntVal(key string, defVal int64, reload ...bool) (value int64)
- func (cfg *Config) PreviewAddr() string
- func (cfg *Config) Set(key string, value interface{})
- func (cfg *Config) SetNamespace(namespace string)
- func (cfg *Config) SetValues(values map[string]string)
- func (cfg *Config) StrVal(key string, reload ...bool) (value string, ok bool)
- func (cfg *Config) StrValOrDef(key, defVal string, reload ...bool) (value string)
- func (cfg *Config) WebAddr() string
- type Configuring
- type Core
- type Crypto
- type Dep
- type Feat
- type FileServer
- type Flash
- type FlashCtxKey
- type FlashManager
- func (fm *FlashManager) AddFlash(r *http.Request, typ, msg string)
- func (fm *FlashManager) ClearFlash(w http.ResponseWriter, r *http.Request)
- func (fm *FlashManager) ClearFlashCookie(w http.ResponseWriter)
- func (fm *FlashManager) GetFlash(r *http.Request) Flash
- func (fm *FlashManager) GetFlashFromCookie(r *http.Request) Flash
- func (fm *FlashManager) Middleware(next http.Handler) http.Handler
- func (fm *FlashManager) Middlewares() []Middleware
- func (fm *FlashManager) SaveFlash(r *http.Request, flash Flash)
- func (fm *FlashManager) SetFlashInCookie(w http.ResponseWriter, flash Flash)
- func (fm *FlashManager) Setup(ctx context.Context) error
- type Form
- type FormConfig
- type FormField
- type FormMapper
- type GitAuth
- type GitClient
- type GitCommit
- type HTTPMethods
- type Handler
- func (h *Handler) Err(w http.ResponseWriter, err error, msg string, code int)
- func (h *Handler) ID(w http.ResponseWriter, r *http.Request) (uuid.UUID, error)
- func (h *Handler) ParseUUIDFromQuery(r *http.Request, paramName string) (uuid.UUID, error)
- func (h *Handler) ParseUUIDsFromQuery(w http.ResponseWriter, r *http.Request, paramName string) ([]uuid.UUID, bool)
- func (h *Handler) Redir(w http.ResponseWriter, r *http.Request, path string)
- func (h *Handler) Render(w http.ResponseWriter, r *http.Request, template string, data any) error
- func (h *Handler) ShowItem(w http.ResponseWriter, r *http.Request, getter func(uuid.UUID) (any, error), ...) bool
- type Identifiable
- type JSONSeed
- type JSONSeeder
- type Keys
- type Lifecycle
- type LogLevel
- type Logger
- type Logging
- type Menu
- func (m *Menu) AddDeleteItem(i Identifiable, text ...string)
- func (m *Menu) AddEditItem(i Identifiable, text ...string)
- func (m *Menu) AddGenericItem(action, url string, text ...string)
- func (m *Menu) AddListItem(resource Identifiable, text ...string)
- func (m *Menu) AddNewItem(r Identifiable, text ...string)
- func (m *Menu) AddResDeleteItem(i Identifiable, text ...string)
- func (m *Menu) AddResEditItem(i Identifiable, text ...string)
- func (m *Menu) AddResGenericItem(action, id string, text ...string)
- func (m *Menu) AddResListItem(resource Identifiable, text ...string)
- func (m *Menu) AddResNewItem(resourceType string, text ...string)
- func (m *Menu) AddResShowItem(i Identifiable, text ...string)
- func (m *Menu) AddShowItem(i Identifiable, text ...string)
- type MenuItem
- type MenuItemStyle
- type Middleware
- type Migration
- type Migrator
- type Model
- type Naming
- type Notification
- type Option
- type Page
- func (p *Page) AddSelect(key string, values []SelectOpt)
- func (p *Page) GenCSRFToken(r *http.Request)
- func (p *Page) GetSelects(key string) []SelectOpt
- func (p *Page) NewMenu(paths ...string) *Menu
- func (p *Page) Path(feat Feat, item MenuItem) string
- func (p *Page) SetData(data interface{})
- func (p *Page) SetFeat(feat Feat)
- func (p *Page) SetFlash(flash Flash)
- func (p *Page) SetForm(form Form)
- func (p *Page) SetMenuItems(items []MenuItem)
- func (p *Page) SetSelects(selects map[string][]SelectOpt)
- type QueryManager
- type Repo
- type Response
- type Router
- type Seedable
- type SelectOpt
- type Selectable
- type Server
- type Service
- type SessionStore
- type Stampable
- type Status
- type TemplateManager
- func (tm *TemplateManager) Debug()
- func (tm *TemplateManager) Get(handler, action string) (*template.Template, error)
- func (tm *TemplateManager) Load()
- func (tm *TemplateManager) RegisterFuncs(tmpl *template.Template) *template.Template
- func (tm *TemplateManager) RegisterFunctions(funcs template.FuncMap)
- func (tm *TemplateManager) Setup(ctx context.Context) error
- type Tx
- type TypeConverter
- type UserCtxData
- type UserService
- type Validate
- type Validation
- type ValidationField
- type Validator
- func ComposeValidators(fns ...Validator) Validator
- func ComposeValidatorsStrict(fns ...Validator) Validator
- func Equals(field, a, b string) Validator
- func GreaterThan(field string, a, b int) Validator
- func MaxLength(field, val string, max int) Validator
- func MinLength(field, val string, min int) Validator
- type WebHandler
- func (h *WebHandler) Debug(w http.ResponseWriter, r *http.Request, msg string)
- func (h *WebHandler) FlashError(w http.ResponseWriter, r *http.Request, msg string)
- func (h *WebHandler) FlashInfo(w http.ResponseWriter, r *http.Request, msg string)
- func (h *WebHandler) FlashManager() *FlashManager
- func (h *WebHandler) FlashSuccess(w http.ResponseWriter, r *http.Request, msg string)
- func (h *WebHandler) FlashWarn(w http.ResponseWriter, r *http.Request, msg string)
- func (h *WebHandler) GetFlash(r *http.Request) Flash
- func (h *WebHandler) OK(w http.ResponseWriter, r *http.Request, buf *bytes.Buffer, statusCode int)
- func (h *WebHandler) Redir(w http.ResponseWriter, r *http.Request, path string, status int)
- func (h *WebHandler) Tmpl() *TemplateManager
- type XParams
Constants ¶
const ( CSRFFieldName = "aquamarine.csrf.token" TimeFormat = "2006-01-02T15:04:05Z07:00" InternalAuthHeader = "X-Internal-GitAuth" SecBypassAuth = "sec.bypass.auth" )
const ( NoSlug = "" Slug = "?slug=%s" )
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" )
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" )
const ( FlashKey FlashCtxKey = "aqmflash" FlashCookieName string = "aqmflash" )
const ( EngSQLite = "sqlite" EngPostgres = "postgres" MigrationPath = "assets/migration/%s" )
const ( StatusSuccess = "success" StatusError = "error" )
const ( ErrorCodeInternalError = "INTERNAL_ERROR" ErrorCodeBadRequest = "BAD_REQUEST" ErrorCodeNotFound = "NOT_FOUND" )
const (
EncryptionKeyCtxKey contextKey = "encryptionKey"
)
Variables ¶
var ( ErrEncryptionFailed = errors.New("encryption failed") ErrDecryptionFailed = errors.New("decryption failed") )
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", }
var HTTPMethod = HTTPMethods{
GET: "GET",
POST: "POST",
PUT: "PUT",
PATCH: "PATCH",
DELETE: "DELETE",
HEAD: "HEAD",
}
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",
}
var NotificationType = notificationTypes{
Success: "success",
Info: "info",
Warn: "warning",
Error: "danger",
Debug: "debug",
}
var ReqIDKey = contextKey("requestID")
ReqIDKey is the context key for the request ID.
var UserKey = contextKey("user")
UserKey is the context key for the authenticated user.
Functions ¶
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 CreatePath ¶
func CreatePath(i Identifiable) string
CreatePath returns the path for creating a resource
func DefaultType ¶
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 ¶
EncryptionKeyMw is a middleware that injects the encryption key into the request context.
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 ¶
InternalAuthMiddleware is a middleware that verifies the internal authentication token.
func IsHTMXRequest ¶
func IsSingular ¶
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 ¶
LogHeadersMw is a middleware that logs all request headers.
func MethodOverrideMw ¶
MethodOverrideMw is a middleware that checks for a _method form field and overrides the request method.
func NewPath ¶
func NewPath(i Identifiable) string
NewPath returns the path for creating a new resource
func RemoveRelatedPath ¶
func RemoveRelatedPath(i Identifiable, j Identifiable) string
RemoveRelatedPath returns the path for removing a related resource
func RequestIDMw ¶
RequestIDMw is a middleware that assigns a unique ID to each request and stores it in the context and as a header.
func SetCreateValues ¶
SetCreateValues sets the initial values for a new model.
func SetUpdateValues ¶
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 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 ¶
Truncate truncates a string to a specified length and appends an ellipsis if truncated.
func TxFromContext ¶
TxFromContext retrieves the transaction from the context, if present.
func UpdatePath ¶
func UpdatePath(i Identifiable) string
UpdatePath returns the path for updating a resource
func ValidateEmail ¶
Types ¶
type APIClient ¶
type APIClient struct {
Core
// contains filtered or unexported fields
}
func NewAPIClient ¶
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 (h *APIHandler) ID(w http.ResponseWriter, r *http.Request) (uuid.UUID, error)
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 ¶
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
type App ¶
type App struct {
Core
Version string
Router *Router
APIRouter *Router
PreviewHandler http.Handler
InternalToken string
// contains filtered or unexported fields
}
func (*App) InternalAuthToken ¶
func (*App) MountFileServer ¶
func (a *App) MountFileServer(path string, fs *FileServer)
func (*App) SetAPIRouter ¶
func (*App) SetWebRouter ¶
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
}
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 (*BaseForm) GenCSRFToken ¶
GenCSRFToken generates a csrf token and sets it in the form.
func (*BaseForm) SetSubmitButtonStyle ¶
func (*BaseForm) SetSubmitButtonText ¶
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 (*BaseRepo) Query ¶
func (r *BaseRepo) Query() *QueryManager
type Config ¶
type Config struct {
// contains filtered or unexported fields
}
Config manages configuration settings loaded from environment variables and CLI flags.
func LoadCfg ¶
LoadCfg initializes a Config instance with the specified namespace and loads the corresponding environment variables and CLI flags.
func (*Config) BoolVal ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 (*Config) SetNamespace ¶
SetNamespace sets the namespace for the configuration, converting it to uppercase.
func (*Config) StrVal ¶
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 ¶
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.
type Configuring ¶
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 FlashCtxKey ¶
type FlashCtxKey string
type FlashManager ¶
type FlashManager struct {
Core
// contains filtered or unexported fields
}
func NewFlashManager ¶
func NewFlashManager(params XParams) *FlashManager
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) 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) SetFlashInCookie ¶
func (fm *FlashManager) SetFlashInCookie(w http.ResponseWriter, flash Flash)
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
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 HTTPMethods ¶
type Handler ¶
type Handler struct {
Core
}
func NewHandler ¶
func (*Handler) Err ¶
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 ¶
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) Render ¶
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 JSONSeeder ¶
type JSONSeeder struct {
Core
// contains filtered or unexported fields
}
func NewJSONSeeder ¶
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)
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 Menu ¶
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 (*Menu) AddDeleteItem ¶
func (m *Menu) AddDeleteItem(i Identifiable, text ...string)
AddDeleteItem adds a new MenuItem for deleting a resource.
func (*Menu) AddEditItem ¶
func (m *Menu) AddEditItem(i Identifiable, text ...string)
AddEditItem adds a new MenuItem for editing a resource.
func (*Menu) AddGenericItem ¶
AddGenericItem adds a new generic MenuItem.
func (*Menu) AddListItem ¶
func (m *Menu) AddListItem(resource Identifiable, text ...string)
AddListItem adds a new MenuItem for listing resources.
func (*Menu) AddNewItem ¶
func (m *Menu) AddNewItem(r Identifiable, text ...string)
AddNewItem adds a new MenuItem for creating a new resource.
func (*Menu) AddResDeleteItem ¶
func (m *Menu) AddResDeleteItem(i Identifiable, text ...string)
AddResDeleteItem adds a new MenuItem for deleting a resource in a RESTful way.
func (*Menu) AddResEditItem ¶
func (m *Menu) AddResEditItem(i Identifiable, text ...string)
AddResEditItem adds a new MenuItem for editing a resource in a RESTful way.
func (*Menu) AddResGenericItem ¶
AddResGenericItem adds a new MenuItem for a generic RESTful action.
func (*Menu) AddResListItem ¶
func (m *Menu) AddResListItem(resource Identifiable, text ...string)
AddResListItem adds a new MenuItem for listing resources in a RESTful way.
func (*Menu) AddResNewItem ¶
AddResNewItem adds a new MenuItem for creating a new resource in a RESTful way.
func (*Menu) AddResShowItem ¶
func (m *Menu) AddResShowItem(i Identifiable, text ...string)
AddResShowItem adds a new MenuItem for showing a resource in a RESTful way.
func (*Menu) AddShowItem ¶
func (m *Menu) AddShowItem(i Identifiable, text ...string)
AddShowItem adds a new MenuItem for showing a resource.
type MenuItem ¶
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 (*MenuItem) GenLinkButton ¶
GenLinkButton generates an HTML link button.
type MenuItemStyle ¶
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 Migrator ¶
type Migrator struct {
Core
// contains filtered or unexported fields
}
func (*Migrator) SetupMigrations ¶
type Model ¶
type Model interface {
Identifiable
Auditable
Stampable
Seedable
}
Model interface composes Identifiable, Auditable, and Stampable interfaces.
type Notification ¶
type Option ¶
type Option func(Core)
Option defines a type for setting optional parameters in BaseCore.
func WithConfigValue ¶
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 (*Page) GenCSRFToken ¶
GenCSRFToken generates a csrf token and sets it in the form.
func (*Page) GetSelects ¶
func (*Page) NewMenu ¶
NewMenu returns a new menu associated with this page, configured with the given path
func (*Page) Path ¶
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) SetMenuItems ¶
SetMenuItems sets the menu items for the page.
func (*Page) SetSelects ¶
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()
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 NewSuccessResponse ¶
type Router ¶
func NewAPIRouter ¶
func NewWebRouter ¶
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 ¶
SelectOpt struct represents an option for select/dropdown lists.
func ToSelectOpt ¶
func ToSelectOpt[T Selectable](in []T) []SelectOpt
type Selectable ¶
type Server ¶
type Server struct {
Core
// contains filtered or unexported fields
}
func NewServer ¶
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.
type Service ¶
func NewService ¶
type SessionStore ¶
type SessionStore interface {
GetUserFromSession(ctx context.Context, sessionID string) (uuid.UUID, error)
}
SessionStore is a placeholder interface for session management.
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
type TypeConverter ¶
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 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 ¶
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 ¶
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 ¶
ComposeValidatorsStrict allows combining multiple Validator functions into one and stops after the first error is found.
func GreaterThan ¶
GreaterThan validates that an integer field is greater than a value.
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) 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
Source Files
¶
- action.go
- apiclient.go
- apihandler.go
- app.go
- config.go
- const.go
- context.go
- conv.go
- core.go
- crypto.go
- debug.go
- dep.go
- error.go
- fileserver.go
- flags.go
- flash.go
- form.go
- git.go
- handler.go
- http.go
- jsonseeder.go
- key.go
- log.go
- menu.go
- menures.go
- middleware.go
- migrator.go
- model.go
- page.go
- path.go
- pluralize.go
- ptr.go
- query.go
- repo.go
- response.go
- router.go
- server.go
- service.go
- strings.go
- template.go
- uuid.go
- validate.go
- validation.go
- webhandler.go