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 ¶
- Variables
- func DisableDebugLogging()
- func EnableDebugLogging()
- func FromContext(ctx context.Context) *log.Logger
- func InitializeLogger()
- 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 ParseQueryInt(r *http.Request, key string, defaultValue int) int
- func ParseQueryStringPtr(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 ResponseEnvelope
- type ValidationError
- type ValidationErrorResponse
Constants ¶
This section is empty.
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()
InitializeLogger configures the global charmbracelet/log logger for beautiful, colorized output with proper formatting. This should be called once at application startup.
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 ParseQueryInt ¶
ParseQueryInt extracts an integer 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 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 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. Returns a ValidationErrorResponse with structured error details suitable for API responses.