Documentation
¶
Index ¶
- func BetweenTime(col string, start, end time.Time) func(db *gorm.DB) *gorm.DB
- func BindRequest[T any](ctx *gin.Context, bindType binding.Binding) (T, error)
- func Capitalize(word string) string
- func CompareUUID(a, b uuid.UUID) int
- func DefaultOrder() func(*gorm.DB) *gorm.DB
- func ForUpdate(enable bool) func(*gorm.DB) *gorm.DB
- func FormatTimeNullable(t time.Time, layout string) string
- func GenerateRandomString(length int) (string, error)
- func GetAndParseFromContext[T any](ctx *gin.Context, key string) (T, error)
- func GetEndOfDay(year int, month int, day int) (time.Time, error)
- func GetFromContext[T any](ctx *gin.Context, key string) (T, error)
- func GetPathParam[T any](ctx *gin.Context, key string) (T, bool, error)
- func GetRequiredPathParam[T any](ctx *gin.Context, key string) (T, error)
- func GetStartOfDay(year int, month int, day int) (time.Time, error)
- func GetTemplSafeUrl(format string, args ...any) templ.SafeURL
- func GetTimeRangeClause(timeCol string, start, end time.Time) (string, []any)
- func GetTxFromContext(ctx context.Context) (*gorm.DB, error)
- func MapSlice[T any, U any](input []T, mapperFunc func(T) U) []U
- func MapSliceWithError[T any, U any](input []T, mapperFunc func(T) (U, error)) ([]U, error)
- func NewAuthMiddleware(authStrategy string, ...) gin.HandlerFunc
- func NewCorsMiddleware(corsConfig *cors.Config) gin.HandlerFunc
- func NewErrorMiddleware() gin.HandlerFunc
- func NewPermissionMiddleware(roleContextKey string, requiredPermission string, ...) gin.HandlerFunc
- func OrderBy(field string, ascending bool) func(db *gorm.DB) *gorm.DB
- func Paginate(page, limit int) func(db *gorm.DB) *gorm.DB
- func Parse[T any](value string) (T, error)
- func PreloadRelations(relations []string) func(db *gorm.DB) *gorm.DB
- func RunServer(defaultConfigs Config, serverSetupFunc func(*Config) *http.Server)
- func SetupRoutes(router *gin.Engine, routeConfigs []RouteConfig)
- func WhereBySpec[T any](spec T) func(db *gorm.DB) *gorm.DB
- type App
- type AppError
- func BadRequestError(details any) AppError
- func ConflictError(details any) AppError
- func ForbiddenError(details any) AppError
- func InternalServerError() AppError
- func NotFoundError(details any) AppError
- func UnauthorizedError(details any) AppError
- func UnprocessableEntityError(details any) AppError
- func ValidationError(details any) AppError
- type Auth
- type CRUDRepository
- type Config
- type EndpointConfig
- type GenericConfig
- type HashService
- type JSONResponse
- type JWTClaims
- type JWTService
- type Logger
- type Pagination
- type QueryOptions
- type RouteConfig
- type RouteGroupConfig
- type RouteVersionConfig
- type SQLDB
- type Specification
- type Transactor
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BetweenTime ¶ added in v0.10.0
BetweenTime returns a GORM scope that filters records between two time values. It uses GetTimeRangeClause to generate the appropriate SQL WHERE clause. Handles open-ended ranges when either start or end time is zero.
func BindRequest ¶
BindRequest binds the incoming HTTP request to a struct of type T using the specified binding type. It supports various Gin binding types such as JSON, XML, Query, etc. Returns the bound struct or an error if binding fails.
func Capitalize ¶ added in v1.0.0
Capitalize converts the first character of a word to uppercase and the rest to lowercase. Returns an empty string if the input is empty. Useful for formatting names and titles consistently.
func CompareUUID ¶ added in v1.0.0
CompareUUID compares two UUID values byte by byte. Returns -1 if a < b, 0 if a == b, and 1 if a > b. Useful for sorting UUIDs or implementing custom comparison logic.
func DefaultOrder ¶ added in v1.0.0
DefaultOrder returns a GORM scope that applies default ordering by created_at DESC. This provides consistent ordering for queries that don't specify explicit ordering. Assumes the model has a created_at field.
func ForUpdate ¶ added in v1.0.0
ForUpdate returns a GORM scope that conditionally adds FOR UPDATE locking to queries. When enable is true, it adds SELECT ... FOR UPDATE to prevent concurrent modifications. Used for pessimistic locking in transaction-critical operations.
func FormatTimeNullable ¶ added in v0.10.0
FormatTimeNullable formats a time.Time using the specified layout, handling zero values gracefully. Returns an empty string if the time is zero (uninitialized), otherwise returns the formatted time. Useful for optional time fields in JSON responses and templates.
func GenerateRandomString ¶
GenerateRandomString creates a cryptographically secure random string of the specified length. The string is base64-encoded using URL-safe encoding without padding. Returns an error if length is non-positive or random generation fails.
func GetAndParseFromContext ¶ added in v0.10.0
GetAndParseFromContext retrieves a string value from the Gin context and parses it to type T. It combines GetFromContext and Parse operations in a single function call. Returns the parsed value or an error if the key doesn't exist or parsing fails.
func GetEndOfDay ¶
GetEndOfDay creates a time.Time representing the end of the specified date (23:59:59.999999999 UTC). It validates the date parameters and returns an error for invalid dates. The returned time is in UTC timezone with maximum precision.
func GetFromContext ¶
GetFromContext retrieves a value from the Gin context and type-asserts it to type T. Returns the typed value or an error if the key does not exist or type assertion fails. Useful for retrieving typed data stored in context by middleware.
func GetPathParam ¶
GetPathParam extracts and parses a path parameter from the Gin context. It returns the parsed value of type T, a boolean indicating if the parameter exists, and an error if parsing fails. If the parameter does not exist, it returns the zero value with false. Supports parsing to string, int, bool, and UUID types.
func GetRequiredPathParam ¶ added in v0.10.0
GetRequiredPathParam extracts and parses a required path parameter from the Gin context. It returns the parsed value of type T or an error if the parameter is missing or parsing fails. Unlike GetPathParam, this function treats missing parameters as an error condition.
func GetStartOfDay ¶
GetStartOfDay creates a time.Time representing the start of the specified date (00:00:00 UTC). It validates the date parameters and returns an error for invalid dates. The returned time is in UTC timezone.
func GetTemplSafeUrl ¶ added in v0.10.0
GetTemplSafeUrl creates a templ.SafeURL from a format string and arguments. It uses fmt.Sprintf to format the URL and wraps it in templ.URL for safe template rendering. This prevents XSS attacks by ensuring URLs are properly escaped in templates.
func GetTimeRangeClause ¶ added in v0.10.0
GetTimeRangeClause generates a SQL WHERE clause for time range filtering. It handles various combinations of start and end times, including open-ended ranges. Returns the SQL clause string and corresponding parameter values for prepared statements.
func GetTxFromContext ¶
GetTxFromContext retrieves the current GORM transaction from the context. Returns an error if no transaction is found or if the stored value is not a *gorm.DB.
func MapSlice ¶
MapSlice applies a mapping function to each element of an input slice and returns a new slice. The function transforms elements of type T to type U using the provided mapperFunc. This is a generic utility for functional-style slice transformations.
func MapSliceWithError ¶ added in v0.10.0
MapSliceWithError applies a mapping function to each element of an input slice with error handling. The function transforms elements of type T to type U using the provided mapperFunc. Returns an error immediately if any transformation fails, providing fail-fast behavior.
func NewAuthMiddleware ¶
func NewAuthMiddleware( authStrategy string, tokenCheckFunc func(ctx *gin.Context, token string) (bool, map[string]any, error), ) gin.HandlerFunc
NewAuthMiddleware creates an authentication middleware for Gin. It extracts a token using the given strategy (e.g., "header" or "cookie") via internal.ExtractToken, calls tokenCheckFunc to validate the token and retrieve user data, stores user data in the Gin context, and aborts the request on errors. Returns a Gin HandlerFunc for authentication handling.
func NewCorsMiddleware ¶
func NewCorsMiddleware(corsConfig *cors.Config) gin.HandlerFunc
NewCorsMiddleware creates a CORS middleware for Gin with the provided configuration. If corsConfig is nil, default settings are used (via cors.Default()). The middleware validates the configuration and logs a fatal error if invalid. Returns a Gin HandlerFunc to handle CORS according to the specified config.
func NewErrorMiddleware ¶
func NewErrorMiddleware() gin.HandlerFunc
NewErrorMiddleware creates an error handling middleware for Gin. It should be registered last and captures errors from previous handlers, converts them into AppError or validation errors, and sends a structured JSON response with the appropriate HTTP status code. Returns a Gin HandlerFunc.
func NewPermissionMiddleware ¶
func NewPermissionMiddleware( roleContextKey string, requiredPermission string, permissionMap map[string][]string, ) gin.HandlerFunc
NewPermissionMiddleware creates a permission-checking middleware for Gin. It retrieves the user role from context using the provided roleContextKey, checks if the role exists in permissionMap and includes the requiredPermission, and aborts the request with a ForbiddenError if permission is missing. Returns a Gin HandlerFunc for permission enforcement.
func OrderBy ¶
OrderBy returns a GORM scope that orders query results by the specified field. It uses internal.IsValidFieldName to validate the field name and prevent SQL injection. Set ascending to true for ascending order, false for descending.
func Paginate ¶
Paginate returns a GORM scope that applies pagination to a query. It calculates the appropriate offset based on the page number and limit. The page parameter is 1-indexed (minimum value of 1).
func Parse ¶
Parse converts a string value to the specified type T. Supported types include string, int, bool, and uuid.UUID. Returns an error if parsing fails or the type is unsupported.
func PreloadRelations ¶
PreloadRelations returns a GORM scope that preloads the specified relations. It eager loads related data to avoid N+1 query problems.
func RunServer ¶
RunServer initializes and runs an HTTP server with graceful shutdown support. It loads configuration using the provided defaults, invokes serverSetupFunc, and handles shutdown.
func SetupRoutes ¶
func SetupRoutes(router *gin.Engine, routeConfigs []RouteConfig)
SetupRoutes configures Gin routes based on the provided RouteConfig slice. It creates a hierarchical route structure with groups, versions, and endpoints. The function applies middleware handlers at each level of the hierarchy. Panics if router is nil.
Types ¶
type App ¶
type App struct {
Env string
Port string
Timeout time.Duration
ClientUrls []string
Timezone string
}
App holds application-level settings such as environment name, server port, request timeout, allowed client URLs, and timezone. These values are populated from environment variables.
type AppError ¶
type AppError struct {
Type string `json:"type"`
Message string `json:"message"`
HttpStatusCode int `json:"-"`
Details any `json:"details,omitempty"`
}
AppError represents an application-specific error with HTTP context. It includes Type, Message, HttpStatusCode, and optional Details. AppError implements the error interface by returning a formatted error string.
func BadRequestError ¶
BadRequestError returns an AppError with HTTP 400 status. Use this when the client sends a malformed or invalid request.
func ConflictError ¶
ConflictError returns an AppError with HTTP 409 status. Use this when a request conflicts with the current state of the server, such as attempting to create a duplicate resource.
func ForbiddenError ¶
ForbiddenError returns an AppError with HTTP 403 status. Use this when an authenticated user lacks permission for the requested action.
func InternalServerError ¶
func InternalServerError() AppError
InternalServerError returns an AppError with HTTP 500 status. Use this for unexpected server-side errors that should be logged and investigated.
func NotFoundError ¶
NotFoundError returns an AppError with HTTP 404 status. Use this when a requested resource cannot be found.
func UnauthorizedError ¶
UnauthorizedError returns an AppError with HTTP 401 status. Use this when authentication is required but missing or invalid.
func UnprocessableEntityError ¶
UnprocessableEntityError returns an AppError with HTTP 422 status. Use this when a well-formed request cannot be processed due to semantic errors.
func ValidationError ¶
ValidationError returns an AppError with HTTP 422 status. Use this for input validation failures, providing details about the invalid fields.
type Auth ¶
type Auth struct {
SecretKey string
TokenDuration time.Duration
CookieDuration time.Duration
Issuer string
URL string
}
Auth holds authentication configuration including JWT secret key, token and cookie durations, issuer identifier, and authentication service URL. Values are sourced from environment variables.
type CRUDRepository ¶ added in v1.0.0
type CRUDRepository[T any] interface { // Insert creates a new record in the database. Insert(ctx context.Context, model T) (T, error) // FindAll retrieves multiple records based on the specification. FindAll(ctx context.Context, spec Specification[T]) ([]T, error) // FindFirst retrieves the first record matching the specification. FindFirst(ctx context.Context, spec Specification[T]) (T, error) // Update modifies an existing record in the database. Update(ctx context.Context, model T) (T, error) // Delete removes a record from the database (hard delete). Delete(ctx context.Context, model T) error // BatchInsert creates multiple records in a single database operation. BatchInsert(ctx context.Context, models []T) ([]T, error) // GetGormInstance returns the appropriate GORM DB instance (transaction-aware). GetGormInstance(ctx context.Context) (*gorm.DB, error) }
CRUDRepository defines a generic interface for basic CRUD operations on entities of type T. It provides standard database operations with context support and transaction awareness. The interface abstracts the underlying database implementation for easier testing and flexibility.
func NewCRUDRepository ¶ added in v1.0.0
func NewCRUDRepository[T any](db *gorm.DB) CRUDRepository[T]
NewCRUDRepository creates a new CRUD repository implementation using GORM. The repository provides transaction-aware database operations for the specified entity type T.
type Config ¶
Config represents the complete application configuration loaded from environment variables. It aggregates all configuration sections including app settings, authentication, database parameters, and the initialized GORM DB instance.
func LoadConfig ¶
LoadConfig reads environment variables into the default Config, loads sub-configuration for App, Auth, and SQLDB, establishes a GORM connection, and returns the fully initialized Config.
func LoadConfigWithDB ¶ added in v1.0.0
LoadConfigWithDB reads environment variables into the default Config with optional database connection. If connectDB is false, the GORM field will be nil, allowing for testing without database dependency.
func LoadConfigWithoutDB ¶ added in v1.0.0
LoadConfigWithoutDB loads configuration without establishing database connection. This is useful for testing or when database connection is not needed.
type EndpointConfig ¶
type EndpointConfig struct {
Method string
Endpoint string
Handlers []gin.HandlerFunc
}
EndpointConfig represents an individual HTTP endpoint. It specifies the HTTP method, endpoint path, and handlers for a specific route. This is the leaf level of the routing hierarchy.
type GenericConfig ¶ added in v1.1.1
type GenericConfig interface {
Prefix() string
}
type HashService ¶ added in v0.10.0
type HashService interface {
// Hash generates a secure hash of the input value.
Hash(val string) (string, error)
// CheckHash verifies if a value matches the provided hash.
CheckHash(hash, val string) (bool, error)
}
HashService provides an interface for password hashing and verification. It abstracts different hashing algorithms for secure password storage.
func NewHashService ¶ added in v0.10.0
func NewHashService(cost int) HashService
NewHashService creates a new hash service implementation using bcrypt. The cost parameter determines the computational cost of hashing (defaults to 10 if negative). Higher cost values provide better security but slower performance.
type JSONResponse ¶
type JSONResponse struct {
Message string `json:"message"`
Data any `json:"data,omitzero"`
Errors error `json:"errors,omitempty"`
Pagination Pagination `json:"pagination,omitzero"`
}
JSONResponse represents a standardized HTTP JSON response structure. It can include a message, data payload, error information, and pagination metadata.
func NewErrorResponse ¶
func NewErrorResponse(err error) JSONResponse
NewErrorResponse creates a JSONResponse for error cases. It sets the message to the error text and populates the Errors field.
func NewResponse ¶
func NewResponse(message string) JSONResponse
NewResponse creates a basic JSONResponse with the specified message. Additional data, errors, or pagination can be added using the With* methods.
func (JSONResponse) WithData ¶
func (jr JSONResponse) WithData(data any) JSONResponse
WithData adds a data payload to the JSONResponse. Returns a new JSONResponse with the Data field populated.
func (JSONResponse) WithError ¶
func (jr JSONResponse) WithError(err error) JSONResponse
WithError adds error information to the JSONResponse. Returns a new JSONResponse with the Errors field populated.
func (JSONResponse) WithPagination ¶
func (jr JSONResponse) WithPagination(queryOptions QueryOptions, totalData int) JSONResponse
WithPagination calculates and adds pagination metadata to the JSONResponse. It computes total pages and next/previous flags based on query options and total data count. Returns a new JSONResponse with pagination metadata included.
type JWTClaims ¶ added in v0.10.0
type JWTClaims struct {
jwt.RegisteredClaims
Data map[string]any `json:"data"` // Custom application data
}
JWTClaims represents the claims structure for JWT tokens. It extends jwt.RegisteredClaims with custom data payload for application-specific information.
type JWTService ¶ added in v0.10.0
type JWTService interface {
// CreateToken generates a new JWT token with the provided data payload.
CreateToken(data map[string]any) (string, error)
// VerifyToken validates a JWT token string and returns the claims.
VerifyToken(tokenstr string) (JWTClaims, error)
}
JWTService provides an interface for JWT token operations. It abstracts token creation and verification for different signing algorithms.
func NewJwtService ¶ added in v0.10.0
func NewJwtService(configs *Auth) JWTService
NewJwtService creates a new JWT service implementation using HMAC SHA256 signing. It uses the provided Auth configuration for token settings and validation.
type Logger ¶ added in v1.2.0
type Pagination ¶
type Pagination struct {
TotalData int `json:"totalData"`
CurrentPage int `json:"currentPage"`
TotalPages int `json:"totalPages"`
HasNextPage bool `json:"hasNextPage"`
HasPrevPage bool `json:"hasPrevPage"`
}
Pagination contains metadata about paginated results. It provides information about the current page, total pages, and navigation flags.
func (*Pagination) IsZero ¶
func (p *Pagination) IsZero() bool
IsZero checks if all pagination fields are at their zero values. Returns true if the pagination data is uninitialized or empty.
type QueryOptions ¶
type QueryOptions struct {
Page int `query:"page" binding:"required,min=1"`
Limit int `query:"limit" binding:"required,min=1"`
}
QueryOptions represents common pagination query parameters for HTTP requests. It includes validation tags to ensure proper values for page and limit parameters.
type RouteConfig ¶
type RouteConfig struct {
Group string
Versions []RouteVersionConfig
Handlers []gin.HandlerFunc
}
RouteConfig represents a top-level route group configuration. It defines a route group with optional versioned subgroups and middleware handlers. Used by SetupRoutes to create hierarchical route structures.
type RouteGroupConfig ¶
type RouteGroupConfig struct {
Group string
Endpoints []EndpointConfig
Handlers []gin.HandlerFunc
}
RouteGroupConfig represents a route group within a versioned section. It contains individual endpoints and middleware handlers specific to this group. Groups help organize related endpoints under a common path prefix.
type RouteVersionConfig ¶
type RouteVersionConfig struct {
Version int
Groups []RouteGroupConfig
Handlers []gin.HandlerFunc
}
RouteVersionConfig represents a versioned route group within a RouteConfig. It contains version-specific route groups and middleware handlers. Versions are typically represented as integers (e.g., 1 for "/v1").
type SQLDB ¶
type SQLDB struct {
Host string `required:"true"`
User string `required:"true"`
Password string `required:"true"`
Name string `required:"true"`
Port string `required:"true"`
Driver string `required:"true"`
}
SQLDB holds SQL database connection parameters loaded from environment variables, including host, user credentials, database name, port, and driver type for GORM.
type Specification ¶ added in v1.0.0
type Specification[T any] struct { Model T // Model with fields set for WHERE conditions PreloadRelations []string // Relations to eager load ForUpdate bool // Whether to use SELECT ... FOR UPDATE }
Specification defines query parameters for database operations. It includes the model for WHERE conditions, relations to preload, and locking options.
type Transactor ¶
type Transactor interface {
// Begin starts a new database transaction and returns a context containing the transaction.
Begin(ctx context.Context) (context.Context, error)
// Commit commits the current transaction in the context.
Commit(ctx context.Context) error
// Rollback rolls back the current transaction in the context without returning an error.
Rollback(ctx context.Context)
// WithinTransaction executes a service function within a database transaction.
WithinTransaction(ctx context.Context, serviceFn func(ctx context.Context) error) error
}
Transactor provides an interface for managing database transactions with context. It abstracts transaction operations to allow for easier testing and different implementations.
func NewTransactor ¶
func NewTransactor(db *gorm.DB) Transactor
NewTransactor creates a new Transactor implementation using GORM. The returned Transactor can be used to manage database transactions with context propagation.