utils

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2025 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Base64Decode

func Base64Decode(encoded string) (string, error)

Base64Decode decodes a base64 string

func Base64Encode

func Base64Encode(data string) string

Base64Encode encodes a string to base64

func Base64URLDecode

func Base64URLDecode(encoded string) (string, error)

Base64URLDecode decodes a base64 URL-safe string

func Base64URLEncode

func Base64URLEncode(data string) string

Base64URLEncode encodes a string to base64 URL-safe encoding

func CalculateOffset

func CalculateOffset(page, pageSize int) int

CalculateOffset calculates the offset for database queries

func Chunk

func Chunk(slice interface{}, chunkSize int) interface{}

Chunk splits a slice into chunks of specified size

func Clamp

func Clamp(value, min, max int) int

Clamp clamps a value between min and max

func Contains

func Contains(s, substr string) bool

Contains checks if a string contains a substring (case-insensitive)

func ContainsAny

func ContainsAny(s string, substrings []string) bool

ContainsAny checks if a string contains any of the substrings

func Filter

func Filter(slice interface{}, predicate func(interface{}) bool) interface{}

Filter filters a slice based on a predicate function

func FormatBytes

func FormatBytes(bytes int64) string

FormatBytes formats bytes into human-readable format

func FormatDuration

func FormatDuration(d time.Duration) string

FormatDuration formats a duration into human-readable format

func GenerateKey

func GenerateKey() (string, error)

GenerateKey generates a random encryption key

func GenerateRandomBytes

func GenerateRandomBytes(length int) ([]byte, error)

GenerateRandomBytes generates random bytes of specified length

func GenerateRandomString

func GenerateRandomString(length int) (string, error)

GenerateRandomString generates a random string of specified length

func GenerateSecret

func GenerateSecret() (string, error)

GenerateSecret generates a random secret for HMAC

func GetPaginationLinks(meta PaginationMeta, baseURL string) map[string]interface{}

GetPaginationLinks generates pagination links for API responses

func GetSortString

func GetSortString(sortFields []SortField) string

GetSortString converts sort fields back to query string format

func IsEmpty

func IsEmpty(s string) bool

IsEmpty checks if a string is empty or contains only whitespace

func IsNotEmpty

func IsNotEmpty(s string) bool

IsNotEmpty checks if a string is not empty and contains non-whitespace characters

func IsStrongPassword

func IsStrongPassword(password string) bool

IsStrongPassword checks if a password meets strength requirements

func IsValidEmail

func IsValidEmail(email string) bool

IsValidEmail checks if a string is a valid email address

func IsValidPhoneNumber

func IsValidPhoneNumber(phone string) bool

IsValidPhoneNumber checks if a string is a valid phone number

func IsValidURL

func IsValidURL(url string) bool

IsValidURL checks if a string is a valid URL

func IsValidUUID

func IsValidUUID(uuid string) bool

IsValidUUID checks if a string is a valid UUID

func Map

func Map(slice interface{}, mapper func(interface{}) interface{}) interface{}

Map applies a function to each element of a slice

func Max

func Max(a, b int) int

Max returns the maximum of two integers

func Min

func Min(a, b int) int

Min returns the minimum of two integers

func ParseBool

func ParseBool(s string, defaultValue bool) bool

ParseBool safely parses a string to bool with default value

func ParseFloat

func ParseFloat(s string, defaultValue float64) float64

ParseFloat safely parses a string to float64 with default value

func ParseInt

func ParseInt(s string, defaultValue int) int

ParseInt safely parses a string to int with default value

func Reduce

func Reduce(slice interface{}, initial interface{}, reducer func(interface{}, interface{}) interface{}) interface{}

Reduce reduces a slice to a single value

func RemoveDuplicates

func RemoveDuplicates(slice []string) []string

RemoveDuplicates removes duplicate strings from a slice

func Round

func Round(value float64, places int) float64

Round rounds a float64 to the specified number of decimal places

func Sign

func Sign(data, secret string) string

Sign signs data using HMAC-SHA256

func SliceContains

func SliceContains(slice interface{}, value interface{}) bool

Contains checks if a slice contains a value

func SortSlice

func SortSlice(slice interface{}, sortFields []SortField) error

SortSlice sorts a slice of structs based on sort fields

func SortStructs

func SortStructs(slice interface{}, sortFields []SortField) error

SortStructs sorts a slice of structs by multiple fields

func TimeAgo

func TimeAgo(t time.Time) string

TimeAgo returns a human-readable time ago string

func Truncate

func Truncate(s string, length int) string

Truncate truncates a string to the specified length

func TruncateWords

func TruncateWords(s string, wordCount int) string

TruncateWords truncates a string to the specified number of words

func ValidatePaginationRequest

func ValidatePaginationRequest(req *PaginationRequest, config *PaginationConfig) error

ValidatePaginationRequest validates pagination parameters

func ValidateSortFields

func ValidateSortFields(sortFields []SortField, config *SortConfig) error

ValidateSortFields validates that all sort fields are allowed

func Verify

func Verify(password, hash string, config *HashConfig) (bool, error)

Verify verifies a password against a hash

func VerifySignature

func VerifySignature(data, signature, secret string) bool

VerifySignature verifies an HMAC signature

Types

type DecryptResult

type DecryptResult struct {
	Data  string `json:"data"`            // Decrypted data
	Valid bool   `json:"valid"`           // Whether the signature is valid
	Error string `json:"error,omitempty"` // Error message if decryption failed
}

DecryptResult represents the result of a decryption operation

func Decrypt

func Decrypt(encryptedData, signature, nonce string, config *EncryptionConfig) (*DecryptResult, error)

Decrypt decrypts data using AES-256-GCM with HMAC verification

func DecryptWithPassword

func DecryptWithPassword(encryptedData, signature, nonce, password string) (*DecryptResult, error)

DecryptWithPassword decrypts data using a password-derived key

type EncryptResult

type EncryptResult struct {
	Data      string `json:"data"`      // Encrypted data (base64 encoded)
	Signature string `json:"signature"` // HMAC signature (hex encoded)
	Nonce     string `json:"nonce"`     // Nonce used for encryption (hex encoded)
}

EncryptResult represents the result of an encryption operation

func Encrypt

func Encrypt(data string, config *EncryptionConfig) (*EncryptResult, error)

Encrypt encrypts data using AES-256-GCM with HMAC signing

func EncryptWithPassword

func EncryptWithPassword(data, password string) (*EncryptResult, error)

EncryptWithPassword encrypts data using a password-derived key

type EncryptionConfig

type EncryptionConfig struct {
	Key    string `json:"key"`    // 32-byte key for AES-256
	Secret string `json:"secret"` // Secret for HMAC signing
}

EncryptionConfig holds configuration for encryption

func NewEncryptionConfig

func NewEncryptionConfig() (*EncryptionConfig, error)

NewEncryptionConfig creates a new encryption configuration with a random key

func NewEncryptionConfigWithKey

func NewEncryptionConfigWithKey(key, secret string) *EncryptionConfig

NewEncryptionConfigWithKey creates a new encryption configuration with provided key and secret

type HashAlgorithm

type HashAlgorithm string

HashAlgorithm represents the available hashing algorithms

const (
	Bcrypt HashAlgorithm = "bcrypt"
	Argon2 HashAlgorithm = "argon2"
	SHA256 HashAlgorithm = "sha256"
	SHA512 HashAlgorithm = "sha512"
	HMAC   HashAlgorithm = "hmac"
)

type HashConfig

type HashConfig struct {
	Algorithm HashAlgorithm `json:"algorithm"`
	Cost      int           `json:"cost"`       // For bcrypt
	Memory    uint32        `json:"memory"`     // For argon2 (in KB)
	Time      uint32        `json:"time"`       // For argon2
	Threads   uint8         `json:"threads"`    // For argon2
	KeyLength uint32        `json:"key_length"` // For argon2
	Secret    string        `json:"secret"`     // For HMAC
}

HashConfig holds configuration for hashing

func DefaultHashConfig

func DefaultHashConfig() *HashConfig

DefaultHashConfig returns the default hash configuration

type HashResult

type HashResult struct {
	Hash      string        `json:"hash"`
	Algorithm HashAlgorithm `json:"algorithm"`
	Salt      string        `json:"salt,omitempty"`
	Config    *HashConfig   `json:"config,omitempty"`
}

HashResult represents the result of a hashing operation

func Hash

func Hash(password string, config *HashConfig) (*HashResult, error)

Hash hashes a password using the specified algorithm

type PaginationConfig

type PaginationConfig struct {
	DefaultPageSize int    `json:"default_page_size"` // Default page size
	MaxPageSize     int    `json:"max_page_size"`     // Maximum allowed page size
	MinPageSize     int    `json:"min_page_size"`     // Minimum allowed page size
	DefaultSortBy   string `json:"default_sort_by"`   // Default sort field
	DefaultSortDir  string `json:"default_sort_dir"`  // Default sort direction
}

PaginationConfig holds configuration for pagination

func DefaultPaginationConfig

func DefaultPaginationConfig() *PaginationConfig

DefaultPaginationConfig returns the default pagination configuration

type PaginationMeta

type PaginationMeta struct {
	Page       int   `json:"page"`        // Current page
	PageSize   int   `json:"page_size"`   // Items per page
	Total      int64 `json:"total"`       // Total number of items
	TotalPages int   `json:"total_pages"` // Total number of pages
	HasNext    bool  `json:"has_next"`    // Has next page
	HasPrev    bool  `json:"has_prev"`    // Has previous page
	NextPage   *int  `json:"next_page"`   // Next page number (null if no next page)
	PrevPage   *int  `json:"prev_page"`   // Previous page number (null if no prev page)
}

PaginationMeta represents pagination metadata

func CalculatePaginationMeta

func CalculatePaginationMeta(page, pageSize int, total int64) PaginationMeta

CalculatePaginationMeta calculates pagination metadata

type PaginationRequest

type PaginationRequest struct {
	Page     int    `json:"page"`      // Page number (1-based)
	PageSize int    `json:"page_size"` // Items per page
	SortBy   string `json:"sort_by"`   // Field to sort by
	SortDir  string `json:"sort_dir"`  // Sort direction (asc/desc)
}

PaginationRequest represents pagination parameters from request

func ParsePaginationRequest

func ParsePaginationRequest(pageStr, pageSizeStr, sortBy, sortDir string, config *PaginationConfig) *PaginationRequest

ParsePaginationRequest parses pagination parameters from query parameters

type PaginationResponse

type PaginationResponse struct {
	Data interface{}    `json:"data"` // The actual data
	Meta PaginationMeta `json:"meta"` // Pagination metadata
}

PaginationResponse represents a paginated response

func CreatePaginationResponse

func CreatePaginationResponse(data interface{}, page, pageSize int, total int64) *PaginationResponse

CreatePaginationResponse creates a paginated response

type PaginationResponseWithLinks struct {
	Data  interface{}            `json:"data"`
	Meta  PaginationMeta         `json:"meta"`
	Links map[string]interface{} `json:"links"`
}

PaginationResponseWithLinks represents a paginated response with links

func CreatePaginationResponseWithLinks(data interface{}, page, pageSize int, total int64, baseURL string) *PaginationResponseWithLinks

CreatePaginationResponseWithLinks creates a paginated response with navigation links

type SortConfig

type SortConfig struct {
	AllowedFields []string `json:"allowed_fields"` // Fields that can be sorted
	DefaultField  string   `json:"default_field"`  // Default sort field
	DefaultDir    string   `json:"default_dir"`    // Default sort direction
}

SortConfig holds configuration for sorting

func CreateSortConfig

func CreateSortConfig(allowedFields []string, defaultField, defaultDir string) *SortConfig

CreateSortConfig creates a sort configuration with allowed fields

func DefaultSortConfig

func DefaultSortConfig() *SortConfig

DefaultSortConfig returns the default sort configuration

type SortField

type SortField struct {
	Field     string `json:"field"`     // Field name to sort by
	Direction string `json:"direction"` // Sort direction (asc/desc)
}

SortField represents a single sort field

func ParseSortRequest

func ParseSortRequest(sortStr string, config *SortConfig) ([]SortField, error)

ParseSortRequest parses sort parameters from query string

Jump to

Keyboard shortcuts

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