app

package
v0.0.0-...-cafd142 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package app ...

Index

Constants

View Source
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"
)
View Source
const (
	// CodeBadRequest corresponds to HTTP 400 Bad Request.
	CodeBadRequest = http.StatusBadRequest

	// CodeUnauthorized corresponds to HTTP 401 Unauthorized (Authentication required).
	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
)
View Source
const DefaultBCryptCost = bcrypt.DefaultCost

DefaultBCryptCost defines the default complexity (cost factor) used when hashing passwords with the bcrypt algorithm.

Variables

View Source
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")
)
View Source
var (
	// ErrInvalidJWT is returned when an authentication token is malformed,
	// invalidly signed, or contains unexpected claims.
	ErrInvalidJWT = ErrForbidden("invalid token")
)

Functions

func CamelCaseToSnakeCase

func CamelCaseToSnakeCase(str string) string

CamelCaseToSnakeCase converts a string from CamelCase to snake_case.

func ErrBadRequest

func ErrBadRequest(message string) error

ErrBadRequest is a convenience function to create a new Error with the CodeBadRequest (HTTP 400) status.

func ErrForbidden

func ErrForbidden(message string) error

ErrForbidden is a convenience function to create a new Error with the CodeForbidden (HTTP 403) status.

func ErrInternal

func ErrInternal(message string) error

ErrInternal is a convenience function to create a new Error with the CodeInternal (HTTP 500) status.

func ErrNotFound

func ErrNotFound(message string) error

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

func ErrUnprocessable(message string) error

ErrUnprocessable is a convenience function to create a new Error with the CodeUnprocessable (HTTP 422) status.

func MigrateDB

func MigrateDB(ctx context.Context, db *DB) (err error)

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 NewError

func NewError(code int, message string, params ...any) error

NewError is a factory function that creates a new structured Error.

func Pointer

func Pointer[T any](v T) *T

Pointer is a generic helper function that returns a pointer to the value provided.

func RelativeFilePath

func RelativeFilePath(basePath, fullPath string) string

RelativeFilePath computes the relative path of a full path with respect to a base path, and converts the path to use forward slashes.

func RunInTx

func RunInTx(ctx context.Context, db *DB,
	f func(ctx context.Context, tx pgx.Tx) error) (err error)

RunInTx executes a function within transaction.

func Slug

func Slug(s string) string

Slug converts any string into a URL-friendly format.

func String

func String(v any) string

String converts the input value into a string representation.

func Token

func Token(lengthOpt ...int) (string, error)

Token creates a cryptographically secure random token.

func Validate

func Validate(schema z.Shape, data any) (err error)

Validate executes the validation rules defined in the provided 'schema' against the 'data' struct. It converts any validation issues into an InputError type for structured error handling.

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"`
	} `yaml:"server"`

	DB struct {
		Host       string `yaml:"host"`
		Port       string `yaml:"port"`
		User       string `yaml:"user"`
		Password   string `yaml:"password"`
		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"`

	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"`
	} `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"`
	} `yaml:"google_oauth"`

	GithubOAuth struct {
		ClientID     string `yaml:"client_id"`
		ClientSecret string `yaml:"client_secret"`
	} `yaml:"github_oauth"`

	// Admins is a list of user IDs with administrative privileges.
	// This is a temporary solution until  ACL is implemented.
	Admins []ds.ID `yaml:"admins"`
}

ConfigT ...

func Config

func Config() *ConfigT

Config returns config from .config.yaml.

func ConfigFromFile

func ConfigFromFile(filename string) (conf *ConfigT, err error)

ConfigFromFile returns config from given YAML file.

func (ConfigT) IsDevEnv

func (c ConfigT) IsDevEnv() bool

IsDevEnv ...

func (ConfigT) IsProductionEnv

func (c ConfigT) IsProductionEnv() bool

IsProductionEnv ...

func (ConfigT) IsTestEnv

func (c ConfigT) IsTestEnv() bool

IsTestEnv ...

func (ConfigT) TracingDisabled

func (c ConfigT) TracingDisabled() bool

TracingDisabled ...

type DB

type DB struct {
	*pgxpool.Pool
}

DB ...

func NewDB

func NewDB(ctx context.Context) (db *DB, err error)

NewDB creates a new PostgreSQL connection pool.

type Error

type Error struct {
	Code    int
	Message string
}

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.

func (Error) Error

func (e Error) Error() string

Error implements the standard Go error interface. It returns the error's descriptive message.

type InputError

type InputError map[string]string

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() InputError

NewInputError creates and returns an empty InputError map.

func (InputError) Add

func (i InputError) Add(k, v string)

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
ds
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.
user_activity
Package useractivity ...
Package useractivity ...
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).

Jump to

Keyboard shortcuts

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