utils

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2026 License: MIT Imports: 28 Imported by: 0

README

Utils

Common utilities for hashing, encryption, encoding, strings, validation, time, pagination, sorting, file operations, and CLI helpers.

Import:

import "github.com/mithril-framework/mithril/pkg/utils"

Hashing

Password (bcrypt)

hash, err := utils.HashPassword("secret")
// err == nil
ok := utils.CheckPasswordHash("secret", hash) // true

Password (Argon2)

hash, err := utils.HashPasswordArgon2("secret")
ok := utils.CheckPasswordArgon2("secret", hash)

SHA / HMAC

hex := utils.SHA256("data")
hex := utils.SHA512("data")
mac := utils.HMACSHA256("data", "key")
mac := utils.HMACSHA512("data", "key")

File hashes

md5, err := utils.MD5File("/path/to/file")
sha1, err := utils.SHA1File("/path/to/file")
sha256, err := utils.SHA256File("/path/to/file")

Encryption

AES-256-GCM; key must be exactly 32 bytes.

enc, err := utils.EncryptAES256GCM("plaintext", string(key32))
dec, err := utils.DecryptAES256GCM(enc, string(key32))

Base64

encoded := utils.EncodeBase64("hello")
decoded, err := utils.DecodeBase64(encoded)

urlEnc := utils.EncodeBase64URL("data")
urlSafe := utils.EncodeBase64URLSafe("data")  // no padding
decoded, err := utils.DecodeBase64URLSafe(urlSafe)

String

Random

s := utils.GenerateRandomString(16)
b := utils.GenerateRandomBytes(32)
id := utils.GenerateUUID()           // UUID v4
short := utils.GenerateShortUUID()  // 12-char hex

Transform

slug := utils.Slugify("Hello World!")     // "hello-world"
s := utils.Truncate("long text", 10)      // "long te..."
s := utils.TruncateWords("one two three", 2) // "one two..."
s := utils.Capitalize("hello")            // "Hello"
s := utils.TitleCase("hello world")       // "Hello World"
s := utils.SnakeCase("HelloWorld")        // "hello_world"
s := utils.CamelCase("hello_world")       // "helloWorld"
s := utils.PascalCase("hello world")      // "HelloWorld"

Helpers

list := utils.RemoveDuplicates([]string{"a", "b", "a"}) // ["a", "b"]
utils.IsEmpty("  ")   // true
utils.IsNotEmpty("x") // true

Validation

utils.IsValidEmail("user@example.com")
utils.IsValidPhone("+1 234 567 8900")
utils.IsValidURL("https://example.com")
utils.IsStrongPassword("MyP@ss1")   // needs upper, lower, digit, special, len >= 8
utils.IsValidUsername("user_1")     // 3–20 chars, alphanumeric + underscore
utils.IsValidSlug("my-post-title")   // [a-z0-9-]+ or empty

Time

d, err := utils.ParseDuration("1d")    // 24h; also "3600", "1h30m"
s := utils.FormatDuration(d)            // "1.0d", "90.0m", etc.

offset, err := utils.GetTimezoneOffset("America/New_York")
s := utils.FormatTime(t, "rfc3339")    // or "rfc822", "rfc1123", "unix", "unix_milli", etc.
s := utils.TimeAgo(t)                   // "2 hours ago", "1 day ago", etc.

start := utils.StartOfDay(t)
end := utils.EndOfDay(t)
start = utils.StartOfWeek(t)   // Monday 00:00
end = utils.EndOfWeek(t)        // Sunday 23:59
start = utils.StartOfMonth(t)
end = utils.EndOfMonth(t)

Pagination

For use with Fiber handlers:

page, perPage := utils.ParsePaginationParams(c)
meta := utils.NewPagination(page, perPage, totalCount)
links := utils.GeneratePaginationLinks("/api/items", meta)

resp := utils.PaginationResponse{
    Data:       items,
    Pagination: meta,
    Links:      links,
}
c.JSON(resp)

Sorting

Parse query sort string (e.g. "name,-created_at") and sort a slice of structs by field names:

fields := utils.ParseSortParams("name,-created_at")  // name asc, created_at desc
utils.SortSlice(mySlice, fields)

File

ext := utils.GetFileExtension("file.pdf")       // ".pdf"
size, err := utils.GetFileSize("/path/to/file")
ok := utils.FileExists("/path/to/file")
err := utils.EnsureDir("/path/to/dir")
err := utils.CopyFile("/src", "/dst")
mime := utils.GetMIMEType("image.png")          // "image/png"
s := utils.FormatFileSize(1536)                 // "1.5 KB"

CLI

Colored output and prompts (for CLI tools):

utils.PrintSuccess("Done")
utils.PrintError("Failed")
utils.PrintWarning("Careful")
utils.PrintInfo("Hint")

input := utils.AskInput("Name")
ok := utils.AskConfirmation("Continue?")
utils.ShowProgress(50, 100, "Processing")

Documentation

Overview

Package utils provides common utilities for hashing, encryption, encoding, string manipulation, validation, time, pagination, sorting, file operations, and CLI helpers.

Hashing: HashPassword, CheckPasswordHash (bcrypt); HashPasswordArgon2, CheckPasswordArgon2 (Argon2); SHA256, SHA512, HMACSHA256, HMACSHA512; MD5File, SHA1File, SHA256File for files.

Encryption: EncryptAES256GCM, DecryptAES256GCM (AES-256-GCM, 32-byte key).

Encoding: EncodeBase64, DecodeBase64; EncodeBase64URL, DecodeBase64URL; EncodeBase64URLSafe, DecodeBase64URLSafe.

String: GenerateRandomString, GenerateRandomBytes, Slugify, Truncate, TruncateWords, Capitalize, TitleCase, SnakeCase, CamelCase, PascalCase, RemoveDuplicates, IsEmpty, IsNotEmpty, GenerateUUID, GenerateShortUUID.

Validation: IsValidEmail, IsValidPhone, IsValidURL, IsStrongPassword, IsValidUsername, IsValidSlug.

Time: ParseDuration, FormatDuration, GetTimezoneOffset, FormatTime, TimeAgo, StartOfDay, EndOfDay, StartOfWeek, EndOfWeek, StartOfMonth, EndOfMonth.

Pagination: PaginationMeta, PaginationLinks, PaginationResponse, NewPagination, GeneratePaginationLinks, ParsePaginationParams (Fiber).

Sorting: SortField, ParseSortParams, SortSlice (reflect-based).

File: GetFileExtension, GetFileSize, FileExists, EnsureDir, CopyFile, GetMIMEType, FormatFileSize.

CLI: PrintSuccess, PrintError, PrintWarning, PrintInfo, AskInput, AskConfirmation, ShowProgress.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AskConfirmation added in v1.0.0

func AskConfirmation(prompt string) bool

AskConfirmation returns true if user answers y/yes (case-insensitive).

func AskInput added in v1.0.0

func AskInput(prompt string) string

AskInput prompts and reads a trimmed line of input.

func CamelCase added in v1.0.0

func CamelCase(s string) string

CamelCase converts to camelCase.

func Capitalize added in v1.0.0

func Capitalize(s string) string

Capitalize uppercases the first rune of s.

func CheckPasswordArgon2 added in v1.0.0

func CheckPasswordArgon2(password, hash string) bool

CheckPasswordArgon2 returns true if password matches the Argon2 hash (combined salt+hash hex).

func CheckPasswordHash added in v1.0.0

func CheckPasswordHash(password, hash string) bool

CheckPasswordHash returns true if password matches the bcrypt hash.

func CopyFile added in v1.0.0

func CopyFile(src, dst string) error

CopyFile copies src to dst (overwrites dst if it exists).

func DecodeBase64 added in v1.0.0

func DecodeBase64(data string) (string, error)

DecodeBase64 decodes standard base64 data.

func DecodeBase64URL added in v1.0.0

func DecodeBase64URL(data string) (string, error)

DecodeBase64URL decodes URL-safe base64 data.

func DecodeBase64URLSafe added in v1.0.0

func DecodeBase64URLSafe(data string) (string, error)

DecodeBase64URLSafe decodes URL-safe base64 (adds padding if needed).

func DecryptAES256GCM added in v1.0.0

func DecryptAES256GCM(ciphertext, key string) (string, error)

DecryptAES256GCM decrypts base64-encoded ciphertext with the given 32-byte key (AES-256-GCM).

func EncodeBase64 added in v1.0.0

func EncodeBase64(data string) string

EncodeBase64 returns standard base64 encoding of data.

func EncodeBase64URL added in v1.0.0

func EncodeBase64URL(data string) string

EncodeBase64URL returns URL-safe base64 encoding (no padding issues in URLs).

func EncodeBase64URLSafe added in v1.0.0

func EncodeBase64URLSafe(data string) string

EncodeBase64URLSafe returns URL-safe base64 without trailing padding.

func EncryptAES256GCM added in v1.0.0

func EncryptAES256GCM(plaintext, key string) (string, error)

EncryptAES256GCM encrypts plaintext with the given 32-byte key using AES-256-GCM; returns base64-encoded ciphertext.

func EndOfDay added in v1.0.0

func EndOfDay(t time.Time) time.Time

EndOfDay returns t with time set to 23:59:59.999999999.

func EndOfMonth added in v1.0.0

func EndOfMonth(t time.Time) time.Time

EndOfMonth returns the last day of t's month at 23:59:59.

func EndOfWeek added in v1.0.0

func EndOfWeek(t time.Time) time.Time

EndOfWeek returns the end of the week (Sunday 23:59:59).

func EnsureDir added in v1.0.0

func EnsureDir(dirPath string) error

EnsureDir creates dirPath and parents if they do not exist (0755).

func FileExists added in v1.0.0

func FileExists(filePath string) bool

FileExists returns true if filePath exists.

func FormatDuration

func FormatDuration(d time.Duration) string

FormatDuration formats d in a human-readable short form (s, m, h, d).

func FormatFileSize added in v1.0.0

func FormatFileSize(bytes int64) string

FormatFileSize formats a byte count as human-readable (B, KB, MB, GB, TB, PB).

func FormatTime added in v1.0.0

func FormatTime(t time.Time, format string) string

FormatTime formats t according to the named format (rfc3339, rfc822, rfc1123, unix, unix_milli, unix_micro, unix_nano) or custom layout.

func GenerateRandomBytes

func GenerateRandomBytes(length int) []byte

GenerateRandomBytes returns n random bytes from crypto/rand.

func GenerateRandomString

func GenerateRandomString(length int) string

GenerateRandomString returns a random string of the given length from alphanumeric charset.

func GenerateShortUUID added in v1.0.0

func GenerateShortUUID() string

GenerateShortUUID returns the first 12 characters of a UUID without hyphens.

func GenerateUUID added in v1.0.0

func GenerateUUID() string

GenerateUUID returns a new UUID v4 string.

func GetFileExtension added in v1.0.0

func GetFileExtension(filename string) string

GetFileExtension returns the lowercased file extension (e.g. ".txt").

func GetFileSize added in v1.0.0

func GetFileSize(filePath string) (int64, error)

GetFileSize returns the size in bytes of the file at filePath.

func GetMIMEType added in v1.0.0

func GetMIMEType(filePath string) string

GetMIMEType returns a MIME type for the file extension (or application/octet-stream).

func GetTimezoneOffset added in v1.0.0

func GetTimezoneOffset(tz string) (int, error)

GetTimezoneOffset returns the offset in seconds for the given timezone name.

func HMACSHA256 added in v1.0.0

func HMACSHA256(data, key string) string

HMACSHA256 returns HMAC-SHA256 of data with key as hex string.

func HMACSHA512 added in v1.0.0

func HMACSHA512(data, key string) string

HMACSHA512 returns HMAC-SHA512 of data with key as hex string.

func HashPassword added in v1.0.0

func HashPassword(password string) (string, error)

HashPassword hashes a password using bcrypt (DefaultCost).

func HashPasswordArgon2 added in v1.0.0

func HashPasswordArgon2(password string) (string, error)

HashPasswordArgon2 hashes a password using Argon2id (salt + hash combined, hex-encoded).

func IsEmpty

func IsEmpty(s string) bool

IsEmpty returns true if s is empty or only whitespace.

func IsNotEmpty

func IsNotEmpty(s string) bool

IsNotEmpty returns true if s has non-whitespace content.

func IsStrongPassword

func IsStrongPassword(password string) bool

IsStrongPassword returns true if password has at least 8 chars and upper, lower, digit, special.

func IsValidEmail

func IsValidEmail(email string) bool

IsValidEmail returns true if email matches a common email pattern.

func IsValidPhone added in v1.0.0

func IsValidPhone(phone string) bool

IsValidPhone returns true if phone has 10–15 digits (after stripping non-digits).

func IsValidSlug added in v1.0.0

func IsValidSlug(slug string) bool

IsValidSlug returns true if slug is empty or matches [a-z0-9-]+.

func IsValidURL

func IsValidURL(url string) bool

IsValidURL returns true if url looks like http(s) URL.

func IsValidUsername added in v1.0.0

func IsValidUsername(username string) bool

IsValidUsername returns true if username is 3–20 chars and alphanumeric/underscore.

func MD5File added in v1.0.0

func MD5File(filePath string) (string, error)

MD5File returns the MD5 hash of the file at filePath as hex string.

func ParseDuration added in v1.0.0

func ParseDuration(s string) (time.Duration, error)

TODO:: need to improve this, ParseDuration parses a duration string (e.g. "1d", "3600", "1h30m").

func ParsePaginationParams added in v1.0.0

func ParsePaginationParams(c *fiber.Ctx) (page, perPage int)

ParsePaginationParams reads page and per_page from Fiber query (defaults 1, 15; per_page capped at 100).

func PascalCase added in v1.0.0

func PascalCase(s string) string

PascalCase converts to PascalCase.

func PrintError added in v1.0.0

func PrintError(message string)

PrintError prints message with red cross.

func PrintInfo added in v1.0.0

func PrintInfo(message string)

PrintInfo prints message with blue info.

func PrintSuccess added in v1.0.0

func PrintSuccess(message string)

PrintSuccess prints message with green checkmark.

func PrintWarning added in v1.0.0

func PrintWarning(message string)

PrintWarning prints message with yellow warning.

func RemoveDuplicates

func RemoveDuplicates(slice []string) []string

RemoveDuplicates returns a new slice with duplicate strings removed (order preserved).

func SHA1File added in v1.0.0

func SHA1File(filePath string) (string, error)

SHA1File returns the SHA-1 hash of the file at filePath as hex string.

func SHA256

func SHA256(data string) string

SHA256 returns the SHA-256 hash of data as a hex string.

func SHA256File added in v1.0.0

func SHA256File(filePath string) (string, error)

SHA256File returns the SHA-256 hash of the file at filePath as hex string.

func SHA512

func SHA512(data string) string

SHA512 returns the SHA-512 hash of data as a hex string.

func ShowProgress added in v1.0.0

func ShowProgress(current, total int, message string)

ShowProgress prints a progress bar for current/total with message (50-char bar).

func Slugify added in v1.0.0

func Slugify(s string) string

Slugify converts a string to a URL-friendly slug (lowercase, hyphens).

func SnakeCase added in v1.0.0

func SnakeCase(s string) string

SnakeCase converts to snake_case.

func SortSlice

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

SortSlice sorts slice in place by the given fields (struct field names).

func StartOfDay added in v1.0.0

func StartOfDay(t time.Time) time.Time

StartOfDay returns t with time set to 00:00:00.

func StartOfMonth added in v1.0.0

func StartOfMonth(t time.Time) time.Time

StartOfMonth returns the first day of t's month at 00:00:00.

func StartOfWeek added in v1.0.0

func StartOfWeek(t time.Time) time.Time

StartOfWeek returns the start of the week (Monday 00:00:00).

func TimeAgo

func TimeAgo(t time.Time) string

TimeAgo returns a human-readable "time ago" string for t.

func TitleCase added in v1.0.0

func TitleCase(s string) string

TitleCase capitalizes the first letter of each word.

func Truncate

func Truncate(s string, length int) string

Truncate truncates s to length and appends "..." if truncated.

func TruncateWords

func TruncateWords(s string, wordCount int) string

TruncateWords truncates to wordCount words and appends "..." if truncated.

Types

type PaginationLinks struct {
	First string `json:"first"`
	Last  string `json:"last"`
	Prev  string `json:"prev"`
	Next  string `json:"next"`
}

PaginationLinks holds first/last/prev/next URLs.

func GeneratePaginationLinks(baseURL string, meta PaginationMeta) PaginationLinks

GeneratePaginationLinks builds First/Last/Prev/Next URLs for the given baseURL and meta.

type PaginationMeta

type PaginationMeta struct {
	CurrentPage int   `json:"current_page"`
	PerPage     int   `json:"per_page"`
	Total       int64 `json:"total"`
	LastPage    int   `json:"last_page"`
	From        int   `json:"from"`
	To          int   `json:"to"`
	HasMore     bool  `json:"has_more"`
}

PaginationMeta holds pagination metadata.

func NewPagination added in v1.0.0

func NewPagination(page, perPage int, total int64) PaginationMeta

NewPagination builds PaginationMeta for the given page, perPage, and total.

type PaginationResponse

type PaginationResponse struct {
	Data       interface{}     `json:"data"`
	Pagination PaginationMeta  `json:"pagination"`
	Links      PaginationLinks `json:"links"`
}

PaginationResponse combines data with pagination and links.

type SortField

type SortField struct {
	Field string
	Order string // "asc" or "desc"
}

SortField represents a field name and sort order (asc/desc).

func ParseSortParams added in v1.0.0

func ParseSortParams(sortStr string) []SortField

ParseSortParams parses a sort string like "name,-created_at" into SortField slice.

Jump to

Keyboard shortcuts

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