Documentation
¶
Overview ¶
Package common provides reusable utilities for building HTTP APIs in Go. It includes helpers for query parameter parsing, JSON request/response handling, structured logging, and request validation.
The package is designed to reduce boilerplate in HTTP handlers and provide consistent error handling and logging across services.
Index ¶
- Constants
- Variables
- func DisableDebugLogging()
- func EnableDebugLogging()
- func FromContext(ctx context.Context) *log.Logger
- func InitializeLogger(opts ...LoggerOption)
- func LogDebug(msg interface{}, keyvals ...interface{})
- func LogDebugf(format string, args ...interface{})
- func LogError(msg interface{}, keyvals ...interface{})
- func LogErrorf(format string, args ...interface{})
- func LogInfo(msg interface{}, keyvals ...interface{})
- func LogInfof(format string, args ...interface{})
- func LogWarn(msg interface{}, keyvals ...interface{})
- func LogWarnf(format string, args ...interface{})
- func ParseQueryBool(r *http.Request, key string, defaultValue bool) bool
- func ParseQueryFloat64(r *http.Request, key string, defaultValue float64) float64
- func ParseQueryInt(r *http.Request, key string, defaultValue int) int
- func ParseQueryInt64(r *http.Request, key string, defaultValue int64) int64
- func ParseQueryStringPtr(r *http.Request, key string) *string
- func ParseQueryStringSlice(r *http.Request, key string) []string
- func ParseQueryTime(r *http.Request, key string) time.Time
- func Print(msg interface{}, keyvals ...interface{})
- func Printf(format string, args ...interface{})
- func ReadJSONBody(r *http.Request, v any) error
- func SetLogLevel(level string)
- func WithContext(ctx context.Context, logger *log.Logger) context.Context
- func WriteJSONError(w http.ResponseWriter, statusCode int, code, message string, details any)
- func WriteJSONResponse(w http.ResponseWriter, statusCode int, data any)
- type ErrorBody
- type LoggerOption
- type PaginationParams
- type ResponseEnvelope
- type ValidationError
- type ValidationErrorResponse
Constants ¶
const ( ErrCodeValidationError = "VALIDATION_ERROR" ErrCodeInvalidJSON = "INVALID_JSON" ErrCodeNotFound = "NOT_FOUND" ErrCodeForbidden = "FORBIDDEN" ErrCodeInternalError = "INTERNAL_ERROR" )
Common error code constants for use with WriteJSONError.
Variables ¶
var Validate = validator.New(validator.WithRequiredStructEnabled())
Validate is the global validator instance with required struct validation enabled.
Functions ¶
func DisableDebugLogging ¶
func DisableDebugLogging()
DisableDebugLogging disables debug level logging (sets to info).
func FromContext ¶
FromContext returns a logger from the context.
func InitializeLogger ¶
func InitializeLogger(opts ...LoggerOption)
InitializeLogger configures the global charmbracelet/log logger for beautiful, colorized output with proper formatting. This should be called once at application startup. Options can be passed to override defaults.
func LogDebug ¶
func LogDebug(msg interface{}, keyvals ...interface{})
LogDebug logs a debug message with optional key-value pairs.
func LogDebugf ¶
func LogDebugf(format string, args ...interface{})
LogDebugf logs a formatted debug message.
func LogError ¶
func LogError(msg interface{}, keyvals ...interface{})
LogError logs an error message with optional key-value pairs.
func LogErrorf ¶
func LogErrorf(format string, args ...interface{})
LogErrorf logs a formatted error message.
func LogInfo ¶
func LogInfo(msg interface{}, keyvals ...interface{})
LogInfo logs an info message with optional key-value pairs.
func LogInfof ¶
func LogInfof(format string, args ...interface{})
LogInfof logs a formatted info message.
func LogWarn ¶
func LogWarn(msg interface{}, keyvals ...interface{})
LogWarn logs a warning message with optional key-value pairs.
func LogWarnf ¶
func LogWarnf(format string, args ...interface{})
LogWarnf logs a formatted warning message.
func ParseQueryBool ¶
ParseQueryBool extracts a boolean from query parameters. Accepts "true", "1", "yes" as true; "false", "0", "no" as false. Returns defaultValue if the key is missing or unrecognized.
func ParseQueryFloat64 ¶ added in v0.0.5
ParseQueryFloat64 extracts a float64 from query parameters. Returns defaultValue if the key is missing or invalid.
func ParseQueryInt ¶
ParseQueryInt extracts an integer from query parameters. Returns defaultValue if the key is missing or invalid.
func ParseQueryInt64 ¶ added in v0.0.5
ParseQueryInt64 extracts an int64 from query parameters. Returns defaultValue if the key is missing or invalid.
func ParseQueryStringPtr ¶
ParseQueryStringPtr extracts a string pointer from query parameters. Returns nil if the key is missing or empty.
func ParseQueryStringSlice ¶ added in v0.0.5
ParseQueryStringSlice extracts a string slice from query parameters. Supports repeated keys (e.g., ?tag=a&tag=b). Returns nil if the key is missing.
func ParseQueryTime ¶
ParseQueryTime extracts a time.Time from query parameters (RFC3339 format). Returns time.Time{} if the key is missing or invalid.
func Print ¶
func Print(msg interface{}, keyvals ...interface{})
Print logs a message at info level.
func Printf ¶
func Printf(format string, args ...interface{})
Printf logs a formatted message at info level.
func ReadJSONBody ¶
ReadJSONBody decodes the JSON request body into the provided value.
func SetLogLevel ¶
func SetLogLevel(level string)
SetLogLevel sets the global log level. Supports: debug, info, warn, error.
func WithContext ¶
WithContext adds a logger to the context.
func WriteJSONError ¶
func WriteJSONError(w http.ResponseWriter, statusCode int, code, message string, details any)
WriteJSONError writes a JSON error response with the given status code, error code, message, and optional details.
func WriteJSONResponse ¶
func WriteJSONResponse(w http.ResponseWriter, statusCode int, data any)
WriteJSONResponse writes a JSON response with the given status code and data. The response is wrapped in a ResponseEnvelope.
Types ¶
type ErrorBody ¶
type ErrorBody struct {
Code string `json:"code"`
Message string `json:"message"`
Details any `json:"details,omitempty"`
}
ErrorBody represents a structured error response.
type LoggerOption ¶ added in v0.0.5
type LoggerOption func(*loggerConfig)
LoggerOption configures the logger when passed to InitializeLogger.
func WithCaller ¶ added in v0.0.5
func WithCaller(enabled bool) LoggerOption
WithCaller enables or disables caller reporting in log output.
func WithLevel ¶ added in v0.0.5
func WithLevel(level string) LoggerOption
WithLevel sets the initial log level. Supports: "debug", "info", "warn", "error".
func WithTimeFormat ¶ added in v0.0.5
func WithTimeFormat(format string) LoggerOption
WithTimeFormat sets the time format string for log timestamps.
func WithTimestamp ¶ added in v0.0.5
func WithTimestamp(enabled bool) LoggerOption
WithTimestamp enables or disables timestamps in log output.
type PaginationParams ¶ added in v0.0.5
PaginationParams holds parsed pagination query parameters.
func ParsePaginationParams ¶ added in v0.0.5
func ParsePaginationParams(r *http.Request, defaultLimit, maxLimit int) PaginationParams
ParsePaginationParams extracts "limit" and "offset" from query parameters. Limit is clamped to [1, maxLimit]. Defaults: limit=defaultLimit, offset=0.
type ResponseEnvelope ¶
type ResponseEnvelope struct {
Data any `json:"data,omitempty"`
Error *ErrorBody `json:"error,omitempty"`
Meta any `json:"meta,omitempty"`
}
ResponseEnvelope wraps API responses in a consistent JSON structure. All responses include an optional Data, Error, and Meta field.
type ValidationError ¶
type ValidationError struct {
Field string `json:"field"`
Message string `json:"message"`
Value string `json:"value,omitempty"`
}
ValidationError represents a single field validation error.
type ValidationErrorResponse ¶
type ValidationErrorResponse struct {
Error string `json:"error"`
Details []ValidationError `json:"details"`
}
ValidationErrorResponse represents a structured response for validation errors.
func FormatValidationErrors ¶
func FormatValidationErrors(err error) ValidationErrorResponse
FormatValidationErrors converts validator.ValidationErrors to user-friendly messages. Field display names are derived by splitting camelCase field names into words.
func FormatValidationErrorsFor ¶ added in v0.0.5
func FormatValidationErrorsFor(err error, v any) ValidationErrorResponse
FormatValidationErrorsFor converts validator.ValidationErrors to user-friendly messages, using the "display" struct tag from v for field display names when available.
type Request struct {
Email string `validate:"required,email" display:"Email Address"`
}