Documentation
¶
Overview ¶
Package app ...
Index ¶
- Constants
- Variables
- func ApplyPatch(text, patch string) (result string, err error)
- func CamelCaseToSnakeCase(str string) string
- func ErrBadRequest(message string, args ...any) error
- func ErrForbidden(message string) error
- func ErrInternal(message string) error
- func ErrNotFound(message string) error
- func ErrUnauthorized() error
- func ErrUnprocessable(message string) error
- func HumanTime(t time.Time, relOpt ...time.Time) string
- func IsNil(v any) bool
- func IsUniqueViolation(err error) (column string, ok bool)
- func MakePatch(text1, text2 string) string
- func MarkdownToHTML(in string) (out string, err error)
- func MigrateDB(ctx context.Context, db *DB) (err error)
- func NewError(code int, message string, params ...any) error
- func RelativeFilePath(basePath, fullPath string) string
- func RunInTx(ctx context.Context, db *DB, f func(ctx context.Context, tx pgx.Tx) error) (err error)
- func ServerURL(rel string) string
- func Slug(s string) string
- func String(v any) string
- func StringSliceFromAny(v any) (out []string, err error)
- func Token(lengthOpt ...int) (string, error)
- func Validate(schema z.Shape, data any) (err error)
- type ConfigT
- type DB
- type Error
- type InputError
- type LoggingQueryTracer
Constants ¶
const ( // DevEnv is used for the local development environment. DevEnv = "dev" // TestEnv is used for running automated tests and quality assurance (QA) checks. TestEnv = "test" // StagingEnv is a production-like environment used for final testing before a full public release. StagingEnv = "staging" // ProductionEnv refers to the final production environment serving live users. ProductionEnv = "production" )
const ( // CodeBadRequest corresponds to HTTP 400 Bad Request. CodeBadRequest = http.StatusBadRequest CodeUnauthorized = http.StatusUnauthorized // CodeForbidden corresponds to HTTP 403 Forbidden (Authorization denied). CodeForbidden = http.StatusForbidden // CodeNotFound corresponds to HTTP 404 Not Found. CodeNotFound = http.StatusNotFound // CodeUnprocessable corresponds to HTTP 422 Unprocessable Entity (Semantic error in the request body). CodeUnprocessable = http.StatusUnprocessableEntity // CodeInternal corresponds to HTTP 500 Internal Server Error. CodeInternal = http.StatusInternalServerError )
const DefaultBCryptCost = bcrypt.DefaultCost
DefaultBCryptCost defines the default complexity (cost factor) used when hashing passwords with the bcrypt algorithm.
Variables ¶
var ( // ErrInvalidJWT is returned when an authentication token is malformed, // invalidly signed, or contains unexpected claims. ErrInvalidJWT = ErrForbidden("invalid token") // ErrNotString indicates that a value is not of string type. ErrNotString = ErrForbidden("is not string") // ErrExpectedStringSliceOrAny indicates that a value is not a slice of strings or a slice of any type. ErrExpectedStringSliceOrAny = ErrForbidden("expected []string or []any") // ErrUniqueViolation indicates a violation of a uniqueness constraint. ErrUniqueViolation = errors.New("UNIQUE VIOLATION") )
var ( // ErrNoFilenameSeparator indicates a migration filename is missing the required '_' separator. ErrNoFilenameSeparator = errors.New("no required filename separator '_' found") // ErrMultipleSameVersion indicates two or more migration files share the same version number. ErrMultipleSameVersion = errors.New("multiple migrations of same version found") )
Functions ¶
func ApplyPatch ¶
ApplyPatch applies a patch string to the given text and returns the result.
func CamelCaseToSnakeCase ¶
CamelCaseToSnakeCase converts a string from CamelCase to snake_case.
func ErrBadRequest ¶
ErrBadRequest is a convenience function to create a new Error with the CodeBadRequest (HTTP 400) status.
func ErrForbidden ¶
ErrForbidden is a convenience function to create a new Error with the CodeForbidden (HTTP 403) status.
func ErrInternal ¶
ErrInternal is a convenience function to create a new Error with the CodeInternal (HTTP 500) status.
func ErrNotFound ¶
ErrNotFound is a convenience function to create a new Error with the CodeNotFound (HTTP 404) status.
func ErrUnauthorized ¶
func ErrUnauthorized() error
ErrUnauthorized is a convenience function to create a new Error with the CodeUnauthorized (HTTP 401) status and a default message.
func ErrUnprocessable ¶
ErrUnprocessable is a convenience function to create a new Error with the CodeUnprocessable (HTTP 422) status.
func HumanTime ¶
HumanTime formats a timestamp into a human-readable relative time string.
The function compares the given time with the current time and returns a concise, user-friendly representation (e.g. "just now", "yesterday, 15:04"). An optional reference time may be provided for deterministic output.
func IsUniqueViolation ¶
IsUniqueViolation checks if an error is a PostgreSQL unique constraint violation. It returns the column name that caused the violation and a boolean indicating success. If the column name is not directly available in the error, it attempts to parse it from the error detail message (e.g., "Key (username)=(test) already exists."). For composite keys, it returns only the first column name (e.g., "public_id" from "Key (public_id, type)=(things-fall-apart, book) already exists.").
func MakePatch ¶
MakePatch generates a patch string representing the differences between text1 and text2.
func MarkdownToHTML ¶
MarkdownToHTML renders Markdown input into safe HTML.
func MigrateDB ¶
MigrateDB runs SQL scripts from the './migrations' directory that haven't been committed yet. It reads migration files, compares them with the migrations already applied to the database, and executes the new migrations in a transaction.
func RelativeFilePath ¶
RelativeFilePath computes the relative path of a full path with respect to a base path, and converts the path to use forward slashes.
func ServerURL ¶
ServerURL constructs an absolute URL by joining a relative path with the configured server URL.
func StringSliceFromAny ¶
StringSliceFromAny converts a dynamically typed value into a []string.
Types ¶
type ConfigT ¶
type ConfigT struct {
App struct {
ID string `yaml:"id"`
Name string `yaml:"name"`
Version string `yaml:"version"`
Env string `yaml:"env"`
} `yaml:"app"`
Server struct {
Port string `yaml:"port"`
Host string `yaml:"host"`
APIBasePath string `yaml:"api_base_path"`
Addr string `yaml:"addr"`
AutocertHosts string `yaml:"autocert_hosts"`
} `yaml:"server"`
DB struct {
Host string `yaml:"host"`
Port string `yaml:"port"`
User string `yaml:"user"`
Password string `yaml:"password"` //nolint:gosec
Name string `yaml:"name"`
LogQueries bool `yaml:"log_queries"`
} `yaml:"db"`
Tracing struct {
Enabled bool `yaml:"enabled"`
// uptrace | log
Driver string `yaml:"driver"`
// https://uptrace.dev/
UptraceDSN string `yaml:"uptrace_dsn"`
} `yaml:"tracing"`
Files struct {
StorageDriver string `yaml:"storage_driver"`
MaxUploadSizeMB int64 `yaml:"max_upload_size_mb"`
ImageMaxWidth int `yaml:"image_max_width"`
ImageMaxHeight int `yaml:"image_max_height"`
PreviewWidth int `yaml:"preview_width"`
PreviewHeight int `yaml:"preview_height"`
LocalFS struct {
StoragePath string `yaml:"storage_path"`
} `yaml:"local_fs"`
} `yaml:"files"`
Entities struct {
Books struct {
Covers struct {
Path string `yaml:"path"`
} `yaml:"covers"`
} `yaml:"books"`
} `yaml:"entities"`
Email struct {
// Driver can be: smtp or test
Driver string `yaml:"driver"`
From string `yaml:"from"`
Host string `yaml:"host"`
Port int `yaml:"port"`
Username string `yaml:"username"`
Password string `yaml:"password"` //nolint:gosec
} `yaml:"email"`
Session struct {
DurationHours int `yaml:"duration_hours"`
Key string `yaml:"key"`
} `yaml:"session"`
OpenAPI struct {
Enabled bool `yaml:"enabled"`
ServePath string `yaml:"serve_path"`
} `yaml:"openapi"`
GoogleOAuth struct {
ClientID string `yaml:"client_id"`
ClientSecret string `yaml:"client_secret"` //nolint:gosec
} `yaml:"google_oauth"`
GithubOAuth struct {
ClientID string `yaml:"client_id"`
ClientSecret string `yaml:"client_secret"` //nolint:gosec
} `yaml:"github_oauth"`
// Admins is a list of user IDs with administrative privileges.
// This is a temporary solution until ACL is implemented.
Admins []string `yaml:"admins"`
}
ConfigT ...
func ConfigFromFile ¶
ConfigFromFile returns new config from given YAML file.
type Error ¶
Error is a custom application error type that includes an HTTP status code for use in API responses, allowing the handler to return a structured error.
type InputError ¶
InputError is a custom error type represented by a map, specifically used to report multiple validation failures, mapping input field names to their corresponding error messages.
func NewInputError ¶
func NewInputError(kvOpt ...string) InputError
NewInputError creates and returns an empty InputError map.
func (InputError) Add ¶
func (i InputError) Add(k, v string, args ...any)
Add inserts a key-value pair (field name and error message) into the InputError map.
func (InputError) AddIf ¶
func (i InputError) AddIf(cond bool, k, v string)
AddIf conditionally inserts a key-value pair into the InputError map only if the provided boolean condition is true.
func (InputError) Error ¶
func (i InputError) Error() string
Error implements the standard Go error interface. It returns a multi-line string representation of all collected input errors.
func (InputError) Has ¶
func (i InputError) Has() bool
Has checks if the InputError map contains any validation errors. Returns true if the map's length is greater than zero.
type LoggingQueryTracer ¶
type LoggingQueryTracer struct{}
LoggingQueryTracer ...
func NewLoggingQueryTracer ¶
func NewLoggingQueryTracer() *LoggingQueryTracer
NewLoggingQueryTracer creates and returns a new LoggingQueryTracer instance.
func (*LoggingQueryTracer) TraceQueryEnd ¶
func (l *LoggingQueryTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, endData pgx.TraceQueryEndData)
TraceQueryEnd is called after a query has completed. It retrieves the start time and SQL from the context, calculates the duration, and logs the complete query information.
func (*LoggingQueryTracer) TraceQueryStart ¶
func (l *LoggingQueryTracer) TraceQueryStart( ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryStartData, ) context.Context
TraceQueryStart is called before a query is sent to the database. It records the query SQL and start time into the context.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package ds (Data Structure) All data models belonging to the app are stored here.
|
Package ds (Data Structure) All data models belonging to the app are stored here. |
|
prop
Package prop provides property type definitions and utilities for handling different kinds of properties .
|
Package prop provides property type definitions and utilities for handling different kinds of properties . |
|
Package repo ...
|
Package repo ... |
|
Package service ...
|
Package service ... |
|
Package session provides primitives for managing user sessions using JSON Web Tokens (JWT).
|
Package session provides primitives for managing user sessions using JSON Web Tokens (JWT). |