common

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2026 License: GPL-3.0 Imports: 12 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-common

CI Go Report Card Go Reference

A simple little go library of utils I use in just about every go project from small to large.

Installation

go get github.com/wispberry-tech/go-common

Usage

import "github.com/wispberry-tech/go-common/pkg/common"
HTTP Utilities
// Query parameter parsing
page := common.ParseQueryInt(r, "page", 1)
active := common.ParseQueryBool(r, "active", false)
timestamp := common.ParseQueryTime(r, "created_at")
name := common.ParseQueryStringPtr(r, "name") // returns *string

// JSON responses
common.WriteJSONResponse(w, http.StatusOK, data)
common.WriteJSONError(w, http.StatusBadRequest, "INVALID_INPUT", "Invalid request", nil)

// Request body parsing
var req MyRequest
if err := common.ReadJSONBody(r, &req); err != nil {
    common.WriteJSONError(w, http.StatusBadRequest, "INVALID_JSON", "Invalid JSON body", nil)
    return
}
Logging
// Initialize at startup
common.InitializeLogger()
common.SetLogLevel("debug") // debug, info, warn, error

// Log messages
common.LogInfo("User logged in", "user_id", 123)
common.LogError("Database error", "error", err)
common.LogWarn("Rate limit approaching", "requests", 950)

// Formatted logging
common.LogInfof("Processing %d items", count)

// Context-aware logging
ctx := common.WithContext(context.Background(), logger)
logger := common.FromContext(ctx)
Validation
type CreateUserRequest struct {
    Email    string `json:"email" validate:"required,email"`
    Name     string `json:"name" validate:"required,min=2,max=100"`
    Password string `json:"password" validate:"required,min=8"`
}

if err := common.Validate.Struct(req); err != nil {
    response := common.FormatValidationErrors(err)
    common.WriteJSONError(w, http.StatusBadRequest, "VALIDATION_ERROR", response.Error, response.Details)
    return
}

Available Utilities

Utility Description
HTTP Helpers Query parsing, JSON request/response handling
Logging Structured, colorized logging with charmbracelet/log
Validation Request validation with go-playground/validator

Dependencies

License

GPL-3.0

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

This section is empty.

Variables

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 EnableDebugLogging

func EnableDebugLogging()

EnableDebugLogging enables debug level logging.

func FromContext

func FromContext(ctx context.Context) *log.Logger

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

func ParseQueryBool(r *http.Request, key string, defaultValue bool) bool

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

func ParseQueryInt(r *http.Request, key string, defaultValue int) int

ParseQueryInt extracts an integer from query parameters. Returns defaultValue if the key is missing or invalid.

func ParseQueryStringPtr

func ParseQueryStringPtr(r *http.Request, key string) *string

ParseQueryStringPtr extracts a string pointer from query parameters. Returns nil if the key is missing or empty.

func ParseQueryTime

func ParseQueryTime(r *http.Request, key string) time.Time

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

func ReadJSONBody(r *http.Request, v any) error

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

func WithContext(ctx context.Context, logger *log.Logger) context.Context

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.

Jump to

Keyboard shortcuts

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