Help us shape the future of Go! Take the 2026 Go Developer Survey

util

package
v0.0.0-...-5d89b11 Latest Latest
Warning

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

Go to latest
Published: Dec 26, 2025 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppURL

func AppURL(path string) string

AppURL returns the configured app URL joined with a relative path.

func ComparePassword

func ComparePassword(hashedPassword, password string) bool

ComparePassword compares a bcrypt hashed password with a plain text password.

func CurrentMonthPeriod

func CurrentMonthPeriod() (time.Time, time.Time)

CurrentMonthPeriod returns the UTC start and end of the current calendar month.

func DecodeAndValidate

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

DecodeAndValidate decodes JSON and validates the struct in one step.

func DecodeJSON

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

DecodeJSON reads and decodes JSON from the request body.

func Decrypt

func Decrypt(secret, ciphertext string) (string, error)

Decrypt opens AES-256-GCM ciphertext produced by Encrypt.

func DeleteCookie

func DeleteCookie(w http.ResponseWriter, name string)

DeleteCookie deletes a cookie by setting its MaxAge to -1.

func DeleteDir

func DeleteDir(dir string) error

DeleteDir deletes a dir

func DirExists

func DirExists(path string) bool

DirExists reports whether the dir exists

func Encrypt

func Encrypt(secret, plaintext string) (string, error)

Encrypt seals plaintext with AES-256-GCM using a key derived from secret.

func EnsureDir

func EnsureDir(dirName string, mode int) error

EnsureDir ensures that directory exists

func FileExists

func FileExists(path string) bool

FileExists reports whether the named file exists

func FormatValidationErrors

func FormatValidationErrors(err error) string

FormatValidationErrors returns the first validation error message

func GenerateSecureToken

func GenerateSecureToken(length int) (string, error)

GenerateSecureToken returns a cryptographically secure random token.

func GenerateUUID

func GenerateUUID() (string, error)

GenerateUUID returns a new random UUID string.

func GetBaseDir

func GetBaseDir(dirName string) string

GetBaseDir returns the project base dir

func GetCookie

func GetCookie(r *http.Request, name string) string

GetCookie retrieves a cookie value by name.

func GetValidator

func GetValidator() *validator.Validate

GetValidator returns the shared validator instance.

func GravatarURL

func GravatarURL(email string, size int) string

GravatarURL returns the Gravatar avatar URL for the given email.

func HandleFromName

func HandleFromName(name string, maxLength int) string

HandleFromName derives a dash-separated lowercase handle from a display name.

func HasCookie

func HasCookie(r *http.Request, name string) bool

HasCookie checks if a cookie with the given name exists.

func HashPassword

func HashPassword(password string) (string, error)

HashPassword generates a bcrypt hash from a plain text password at the default cost.

func JSONRawFromString

func JSONRawFromString(raw *string) json.RawMessage

JSONRawFromString returns stored JSON text as a RawMessage for API responses.

func JSONSliceFromString

func JSONSliceFromString[T any](raw *string) []T

JSONSliceFromString unmarshals a JSON-encoded slice from a stored string pointer.

func LoadConfigs

func LoadConfigs(path string) error

LoadConfigs load configs for testing purposes using viper

func MapChecksum

func MapChecksum(m map[string]any) (string, error)

MapChecksum returns a deterministic SHA-256 hex checksum of a map.

func ParsePagination

func ParsePagination(r *http.Request) (limit, offset int)

ParsePagination parses limit and offset from query parameters.

func ParseQueryLabels

func ParseQueryLabels(r *http.Request) map[string]string

ParseQueryLabels extracts label pairs from query parameters, skipping reserved keys.

func RandInt

func RandInt(min, max int) (int, error)

RandInt returns a random integer in [0, n).

func RandomHandle

func RandomHandle(min, max int) (string, error)

RandomHandle returns a handle like abcd-1234 (min–max letters, dash, min–max digits).

func RandomHash

func RandomHash() (string, error)

RandomHash returns a 12-character cryptographically secure random hex string.

func RemoveLabelFromJSON

func RemoveLabelFromJSON(labels *string, label string) (*string, bool)

RemoveLabelFromJSON removes a label from a JSON-encoded string array.

func SetCookie

func SetCookie(w http.ResponseWriter, name, value string, options *CookieOptions)

SetCookie sets a cookie with the given name, value, and options.

func ValidateStruct

func ValidateStruct(s interface{}) error

ValidateStruct validates the struct and returns any validation errors.

func WriteJSON

func WriteJSON(w http.ResponseWriter, statusCode int, data interface{}) error

WriteJSON writes a value as JSON to an HTTP response.

func WriteValidationError

func WriteValidationError(w http.ResponseWriter, err error)

WriteValidationError writes a decode or validation error as a 400 JSON response.

Types

type CookieOptions

type CookieOptions struct {
	// MaxAge is the cookie age in seconds; zero is a session cookie and negative deletes it now.
	MaxAge int

	// Path specifies the cookie path. Defaults to "/".
	Path string

	// Domain specifies the cookie domain.
	Domain string

	// Secure indicates if the cookie should only be sent over HTTPS.
	Secure bool

	// HTTPOnly makes the cookie inaccessible to JavaScript.
	HTTPOnly bool

	// SameSite is the cookie's SameSite attribute, such as SameSiteLaxMode.
	SameSite http.SameSite
}

CookieOptions holds configuration for cookie creation.

func DefaultCookieOptions

func DefaultCookieOptions() *CookieOptions

DefaultCookieOptions returns sensible default options for cookies.

func SecureCookieOptions

func SecureCookieOptions() *CookieOptions

SecureCookieOptions returns secure cookie options for production use.

type ValidationError

type ValidationError struct {
	Field   string `json:"field"`
	Message string `json:"message"`
	Tag     string `json:"tag,omitempty"`
	Value   string `json:"value,omitempty"`
}

ValidationError is one field error.

type ValidationErrors

type ValidationErrors struct {
	Errors []ValidationError `json:"errors"`
}

ValidationErrors is a list of validation errors.

Jump to

Keyboard shortcuts

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