Documentation
¶
Overview ¶
Package sanitizer provides comprehensive input sanitization and data cleaning utilities for web applications. It offers protection against XSS attacks, SQL injection, and other security vulnerabilities through string manipulation, HTML sanitization, collection processing, and structured data cleaning.
The package provides four main categories of functionality:
- String manipulation and normalization
- Format-specific sanitization (email, phone, URL, etc.)
- Security-focused protection (XSS, SQL injection, path traversal)
- Collection and structured data processing
Basic String Sanitization ¶
Core string cleaning functions for common transformations:
import "github.com/dmitrymomot/foundation/core/sanitizer" // Basic trimming and case conversion cleaned := sanitizer.Trim(" hello world ") // "hello world" lower := sanitizer.ToLower("HELLO") // "hello" upper := sanitizer.ToUpper("hello") // "HELLO" title := sanitizer.ToTitle("hello world") // "HELLO WORLD" // Combined operations clean := sanitizer.TrimToLower(" HELLO ") // "hello" clean = sanitizer.TrimToUpper(" hello ") // "HELLO" // Length and character filtering limited := sanitizer.MaxLength("very long text", 10) // "very long " alphanum := sanitizer.KeepAlphanumeric("hello@123!") // "hello123 " alpha := sanitizer.KeepAlpha("hello123!") // "hello " digits := sanitizer.KeepDigits("abc123def") // "123"
Case Conversion Functions ¶
Transform strings between different naming conventions:
// Convert to kebab-case (URL-friendly) slug := sanitizer.ToKebabCase("Hello World!") // "hello-world" // Convert to snake_case (database-friendly) field := sanitizer.ToSnakeCase("Hello World") // "hello_world" // Convert to camelCase (JavaScript-friendly) prop := sanitizer.ToCamelCase("hello world") // "helloWorld"
Whitespace and Control Character Handling ¶
Clean up problematic whitespace and control characters:
// Normalize multiple whitespace to single spaces normalized := sanitizer.RemoveExtraWhitespace("hello world") // "hello world" normalized = sanitizer.NormalizeWhitespace("hello\t\nworld") // "hello world" // Remove control characters but preserve basic whitespace safe := sanitizer.RemoveControlChars("hello\x00world") // "helloworld" // Convert to single line oneLine := sanitizer.SingleLine("line1\nline2\rline3") // "line1 line2 line3"
HTML and Security Sanitization ¶
Protect against XSS attacks and clean HTML content:
// Strip all HTML tags plainText := sanitizer.StripHTML("<p>Hello <script>alert('xss')</script>world</p>") // Result: "Hello world" // Escape HTML for safe display escaped := sanitizer.EscapeHTML("<script>alert('xss')</script>") // Result: "<script>alert('xss')</script>" // Comprehensive XSS prevention safe := sanitizer.PreventXSS(`<p onclick="evil()">Content</p>`) // Remove specific dangerous elements cleaned := sanitizer.StripScriptTags(`<p>Safe</p><script>alert('xss')</script>`) cleaned = sanitizer.RemoveJavaScriptEvents(`<div onclick="evil()">Content</div>`)
SQL Injection Prevention ¶
Sanitize inputs for database operations:
// Escape SQL strings (but prefer parameterized queries) escaped := sanitizer.EscapeSQLString("O'Connor") // "O''Connor" // Clean SQL identifiers (table/column names) safeTable := sanitizer.SanitizeSQLIdentifier("users-table!") // "users_table" // Remove dangerous SQL keywords cleaned := sanitizer.RemoveSQLKeywords("SELECT * FROM users") // " * users" // Example with parameterized queries (recommended approach) tableName := sanitizer.SanitizeSQLIdentifier(userTableName) query := fmt.Sprintf("SELECT * FROM %s WHERE id = ?", tableName) // Then use query with parameters
Format-Specific Sanitization ¶
Clean and normalize common data formats:
// Email processing email := sanitizer.NormalizeEmail(" JOHN.DOE@EXAMPLE.COM ") // "john.doe@example.com" domain := sanitizer.ExtractEmailDomain("user@domain.com") // "domain.com" masked := sanitizer.MaskEmail("john.doe@example.com") // "j*******@example.com" secure := sanitizer.SanitizeEmail("user<script>@example.com") // "userscript@example.com" // Phone number processing digits := sanitizer.NormalizePhone("(555) 123-4567") // "5551234567" formatted := sanitizer.FormatPhoneUS("5551234567") // "(555) 123-4567" masked := sanitizer.MaskPhone("5551234567") // "******4567" // URL processing normalized := sanitizer.NormalizeURL("example.com/path/") // "https://example.com/path" domain := sanitizer.ExtractDomain("https://example.com/path") // "example.com" cleaned := sanitizer.SanitizeURL("javascript:alert('xss')") // "" (removes dangerous URLs) noQuery := sanitizer.RemoveQueryParams("https://example.com?tracking=123")
File Path Sanitization ¶
Secure file path and filename handling:
// Clean filenames for safe storage safe := sanitizer.SanitizeFilename("my file<>:name.txt") // "my file___name.txt" secure := sanitizer.SanitizeSecureFilename("../../../etc/passwd") // ".._.._..._etc_passwd" // Prevent directory traversal attacks safePath := sanitizer.SanitizePath("../../../etc/passwd") // "etc/passwd" normalized := sanitizer.NormalizePath("folder\\..\\file.txt") // "file.txt" cleaned := sanitizer.PreventPathTraversal("folder/../file") // "folder/file"
Numeric Value Processing ¶
Type-safe numeric sanitization using Go generics:
// Clamp values within ranges clamped := sanitizer.Clamp(15, 0, 10) // 10 minClamped := sanitizer.ClampMin(-5, 0) // 0 maxClamped := sanitizer.ClampMax(15, 10) // 10 // Absolute values and sign handling abs := sanitizer.Abs(-42) // 42 positive := sanitizer.ZeroIfNegative(-5) // 0 nonZero := sanitizer.NonZero(0) // 1 // Floating-point operations rounded := sanitizer.Round(3.7) // 4.0 precise := sanitizer.RoundToDecimalPlaces(3.14159, 2) // 3.14 percentage := sanitizer.Percentage(25, 100) // 25.0 // Safe division result := sanitizer.SafeDivide(10, 0, -1) // -1 (fallback)
Collection Processing ¶
Clean and manipulate slices and maps:
// String slice operations trimmed := sanitizer.TrimStringSlice([]string{" hello ", " world "}) lower := sanitizer.ToLowerStringSlice([]string{"HELLO", "WORLD"}) clean := sanitizer.CleanStringSlice([]string{" hello ", "", " world "}) // clean result: ["hello", "world"] (trimmed, filtered, deduplicated) // Slice utilities filtered := sanitizer.FilterEmpty([]string{"hello", "", "world"}) // ["hello", "world"] unique := sanitizer.DeduplicateStrings([]string{"a", "b", "a"}) // ["a", "b"] limited := sanitizer.LimitSliceLength([]string{"a", "b", "c"}, 2) // ["a", "b"] sorted := sanitizer.SortStrings([]string{"c", "a", "b"}) // ["a", "b", "c"] // Map operations data := map[string]string{" NAME ": " John ", "email": "john@example.com"} cleaned := sanitizer.CleanStringMap(data) // Result: {"name": "John", "email": "john@example.com"} // Map utilities keys := sanitizer.ExtractMapKeys(data) values := sanitizer.ExtractMapValues(data) merged := sanitizer.MergeStringMaps(map1, map2, map3)
Struct Field Sanitization with Tags ¶
Automatically sanitize struct fields using reflection and tags:
type User struct { Name string `sanitize:"trim,title"` Email string `sanitize:"email"` Username string `sanitize:"trim,lower,alphanum,max:20"` Bio string `sanitize:"trim,safe_html"` Website string `sanitize:"url"` Tags []string `sanitize:"trim,lower"` // Use "-" to skip sanitization Password string `sanitize:"-"` } user := &User{ Name: " john doe ", Email: " JOHN@EXAMPLE.COM ", Username: " John123!@# ", Bio: `<p>Developer</p><script>alert('xss')</script>`, Website: "example.com/profile", Tags: []string{" GO ", " WEB "}, } err := sanitizer.SanitizeStruct(user) // user.Name becomes "JOHN DOE" // user.Email becomes "john@example.com" // user.Username becomes "john123" (limited to 20 chars) // user.Bio becomes safe HTML // user.Website becomes "https://example.com/profile" // user.Tags becomes ["go", "web"]
Available Sanitizer Tags ¶
The following tags can be used with SanitizeStruct:
// String operations "trim", "lower", "upper", "title", "trim_lower", "trim_upper" "kebab", "snake", "camel", "single_line", "no_spaces" "alphanum", "alpha", "digits", "max:N" // Format sanitizers "email", "phone", "url", "domain", "filename", "whitespace" "credit_card", "ssn", "postal_code" // Security sanitizers "strip_html", "escape_html", "xss", "sql_string", "sql_identifier" "path", "user_input", "secure_filename", "no_control", "no_null" // Composite sanitizers "username" (alphanum + lower + trim) "slug" (kebab + trim) "name" (title + no_spaces + trim) "text" (no_spaces + trim) "safe_text" (escape_html + no_spaces + trim) "safe_html" (xss + trim)
Custom Sanitizer Registration ¶
Register your own sanitization functions:
// Register a custom sanitizer sanitizer.RegisterSanitizer("remove_emoji", func(s string) string { // Implementation to remove emoji characters return removeEmoji(s) }) // Use in struct tags type Post struct { Title string `sanitize:"trim,remove_emoji"` }
Functional Composition ¶
Build sanitization pipelines using functional composition:
// Create a reusable sanitization pipeline cleanName := sanitizer.Compose( sanitizer.Trim, sanitizer.ToTitle, sanitizer.RemoveExtraWhitespace, ) // Apply pipeline to values result := cleanName(" john doe ") // "JOHN DOE" // Or apply transformations in sequence result = sanitizer.Apply(" HELLO WORLD ", sanitizer.Trim, sanitizer.ToLower, sanitizer.ToKebabCase, ) // "hello-world"
Security Best Practices ¶
When using this package for security:
- Always sanitize user input at application boundaries
- Use parameterized queries as primary SQL injection defense
- Apply context-appropriate sanitization (HTML vs SQL vs filename)
- Validate input lengths to prevent DoS attacks
- Log suspicious input patterns for monitoring
- Test sanitization with malicious inputs
- Keep security sanitization rules updated
- Use HTTPS when normalizing URLs
- Sanitize filenames before filesystem operations
- Remove control characters from user content
Index ¶
- func Abs[T Signed](value T) T
- func Apply[T any](value T, transforms ...func(T) T) T
- func Clamp[T Numeric](value T, min T, max T) T
- func ClampMax[T Numeric](value T, max T) T
- func ClampMin[T Numeric](value T, min T) T
- func ClampPrecision[T Float](value T, min T, max T, decimalPlaces int) T
- func ClampToNonNegative[T Signed](value T) T
- func ClampToPositive[T Numeric](value T) T
- func CleanStringMap(m map[string]string) map[string]string
- func CleanStringSlice(slice []string) []string
- func Compose[T any](transforms ...func(T) T) func(T) T
- func Deduplicate[T comparable](slice []T) []T
- func DeduplicateStrings(slice []string) []string
- func DeduplicateStringsIgnoreCase(slice []string) []string
- func EscapeHTML(s string) string
- func EscapeSQLString(s string) string
- func ExtractDomain(rawURL string) string
- func ExtractEmailDomain(email string) string
- func ExtractMapKeys[K comparable, V any](m map[K]V) []K
- func ExtractMapValues[K comparable, V any](m map[K]V) []V
- func ExtractNumbers(s string) string
- func ExtractPhoneDigits(phone string) string
- func FilterEmpty(slice []string) []string
- func FilterEmptyMapValues[K comparable](m map[K]string) map[K]string
- func FilterMapByKeys[V any](m map[string]V, pattern string) map[string]V
- func FilterMapByValues[K comparable](m map[K]string, pattern string) map[K]string
- func FilterSlice[T any](slice []T, predicate func(T) bool) []T
- func FilterSliceByPattern(slice []string, pattern string) []string
- func FormatCreditCard(cardNumber string) string
- func FormatPhoneUS(phone string) string
- func FormatPostalCodeCA(postalCode string) string
- func FormatPostalCodeUS(postalCode string) string
- func FormatSSN(ssn string) string
- func KeepAlpha(s string) string
- func KeepAlphanumeric(s string) string
- func KeepDigits(s string) string
- func LimitLength(s string, maxLength int) string
- func LimitMapSize[K comparable, V any](m map[K]V, maxSize int) map[K]V
- func LimitSliceLength[T any](slice []T, maxLength int) []T
- func MapToSlice[K comparable, V any](m map[K]V) []V
- func MaskCreditCard(cardNumber string) string
- func MaskEmail(email string) string
- func MaskPhone(phone string) string
- func MaskSSN(ssn string) string
- func MaskString(s string, visibleChars int) string
- func MaxLength(s string, maxLen int) string
- func MergeStringMaps(ms ...map[string]string) map[string]string
- func NonZero[T Numeric](value T) T
- func NormalizeCreditCard(cardNumber string) string
- func NormalizeEmail(email string) string
- func NormalizePath(path string) string
- func NormalizePhone(phone string) string
- func NormalizePostalCode(postalCode string) string
- func NormalizeSSN(ssn string) string
- func NormalizeToRange[T Float](value T, fromMin T, fromMax T, toMin T, toMax T) T
- func NormalizeURL(rawURL string) string
- func NormalizeWhitespace(s string) string
- func Percentage[T Numeric](part T, whole T) float64
- func PreventHeaderInjection(s string) string
- func PreventLDAPInjection(s string) string
- func PreventPathTraversal(path string) string
- func PreventXSS(s string) string
- func RegisterSanitizer(name string, fn func(string) string)
- func RemoveChars(s string, chars string) string
- func RemoveControlChars(s string) string
- func RemoveControlSequences(s string) string
- func RemoveExtraWhitespace(s string) string
- func RemoveFragment(rawURL string) string
- func RemoveJavaScriptEvents(s string) string
- func RemoveNonAlphanumeric(s string) string
- func RemoveNullBytes(s string) string
- func RemoveQueryParams(rawURL string) string
- func RemoveSQLKeywords(s string) string
- func RemoveShellMetacharacters(s string) string
- func ReplaceChars(s string, old string, new string) string
- func ReverseSlice[T any](slice []T) []T
- func Round[T Float](value T) T
- func RoundDown[T Float](value T) T
- func RoundToDecimalPlaces[T Float](value T, places int) T
- func RoundUp[T Float](value T) T
- func SafeDivide[T Numeric](numerator T, denominator T, fallback T) T
- func SanitizeEmail(email string) string
- func SanitizeFilename(filename string) string
- func SanitizeHTMLAttributes(s string) string
- func SanitizeMapKeys[V any](m map[string]V, sanitizer func(string) string) map[string]V
- func SanitizeMapValues[K comparable](m map[K]string, sanitizer func(string) string) map[K]string
- func SanitizePath(path string) string
- func SanitizeSQLIdentifier(s string) string
- func SanitizeSecureFilename(filename string) string
- func SanitizeShellArgument(arg string) string
- func SanitizeStruct(v any) error
- func SanitizeURL(url string) string
- func SanitizeUserInput(s string) string
- func SingleLine(s string) string
- func SliceToMap[T any](slice []T) map[int]T
- func SortStrings(slice []string) []string
- func SortStringsIgnoreCase(slice []string) []string
- func StripHTML(s string) string
- func StripScriptTags(s string) string
- func ToCamelCase(s string) string
- func ToKebabCase(s string) string
- func ToLower(s string) string
- func ToLowerStringSlice(slice []string) []string
- func ToSnakeCase(s string) string
- func ToTitle(s string) string
- func ToUpper(s string) string
- func TransformSlice[T any, R any](slice []T, transform func(T) R) []R
- func Trim(s string) string
- func TrimStringSlice(slice []string) []string
- func TrimToLower(s string) string
- func TrimToUpper(s string) string
- func TruncateToInt[T Float](value T) T
- func UnescapeHTML(s string) string
- func ZeroIfNegative[T Signed](value T) T
- func ZeroIfPositive[T Signed](value T) T
- type Float
- type Numeric
- type Signed
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Apply ¶
func Apply[T any](value T, transforms ...func(T) T) T
Apply creates functional composition pipeline for sanitization transformations. Useful for building complex sanitization chains while maintaining type safety.
func Clamp ¶
func Clamp[T Numeric](value T, min T, max T) T
Clamp constrains a numeric value to be within the specified range [min, max]. If the value is less than min, it returns min. If greater than max, it returns max.
func ClampMax ¶
func ClampMax[T Numeric](value T, max T) T
ClampMax ensures a numeric value is not greater than the specified maximum.
func ClampMin ¶
func ClampMin[T Numeric](value T, min T) T
ClampMin ensures a numeric value is not less than the specified minimum.
func ClampPrecision ¶
ClampPrecision limits floating-point precision by rounding to specified decimal places and ensuring the result is within the given range.
func ClampToNonNegative ¶
func ClampToNonNegative[T Signed](value T) T
ClampToNonNegative ensures the value is non-negative (>= 0). Returns 0 if value < 0.
func ClampToPositive ¶
func ClampToPositive[T Numeric](value T) T
ClampToPositive ensures the value is positive (> 0). Returns 1 if value <= 0.
func CleanStringMap ¶
CleanStringMap applies standard form data cleanup: lowercase keys, trim values, remove empties.
func CleanStringSlice ¶
CleanStringSlice applies standard form data cleanup pipeline.
func Compose ¶
func Compose[T any](transforms ...func(T) T) func(T) T
Compose creates reusable sanitization pipelines that can be stored and reused. Preferred over repeated Apply calls when the same transformation chain is used multiple times.
func Deduplicate ¶
func Deduplicate[T comparable](slice []T) []T
Deduplicate preserves first occurrence order to maintain user intent in form submissions.
func DeduplicateStrings ¶
func DeduplicateStringsIgnoreCase ¶
DeduplicateStringsIgnoreCase preserves original casing of first occurrence.
func EscapeHTML ¶
EscapeHTML escapes HTML special characters to prevent XSS attacks.
func EscapeSQLString ¶
EscapeSQLString escapes single quotes in SQL strings to prevent injection.
func ExtractDomain ¶
ExtractDomain assumes HTTPS protocol for parsing; validates host to prevent invalid domains.
func ExtractEmailDomain ¶
func ExtractMapKeys ¶
func ExtractMapKeys[K comparable, V any](m map[K]V) []K
func ExtractMapValues ¶
func ExtractMapValues[K comparable, V any](m map[K]V) []V
func ExtractNumbers ¶
ExtractNumbers concatenates all digit sequences, useful for ID extraction from mixed content.
func ExtractPhoneDigits ¶
func FilterEmpty ¶
FilterEmpty removes whitespace-only entries to prevent empty form fields from polluting data.
func FilterEmptyMapValues ¶
func FilterEmptyMapValues[K comparable](m map[K]string) map[K]string
FilterEmptyMapValues removes whitespace-only values to prevent empty data storage.
func FilterMapByKeys ¶
FilterMapByKeys uses case-insensitive substring matching for consistent behavior.
func FilterMapByValues ¶
func FilterMapByValues[K comparable](m map[K]string, pattern string) map[K]string
func FilterSlice ¶
func FilterSliceByPattern ¶
FilterSliceByPattern uses case-insensitive substring matching for user-friendly filtering.
func FormatCreditCard ¶
FormatCreditCard validates common card lengths (13-19 digits) before formatting for display.
func FormatPhoneUS ¶
FormatPhoneUS enforces NANP format; preserves original if not 10 digits to avoid data loss.
func FormatPostalCodeCA ¶
FormatPostalCodeCA enforces standard Canadian format (A1A 1A1); preserves invalid input.
func FormatPostalCodeUS ¶
FormatPostalCodeUS handles both ZIP and ZIP+4 formats; preserves invalid input.
func FormatSSN ¶
FormatSSN enforces standard 9-digit format; preserves original if invalid to avoid data loss.
func KeepAlphanumeric ¶
KeepAlphanumeric preserves spaces for readability while removing special characters.
func KeepDigits ¶
KeepDigits keeps only numeric digits, removing all other characters.
func LimitLength ¶
LimitLength truncates input to prevent DoS attacks through large inputs.
func LimitMapSize ¶
func LimitMapSize[K comparable, V any](m map[K]V, maxSize int) map[K]V
LimitMapSize prevents memory exhaustion from malicious input; iteration order is random.
func LimitSliceLength ¶
LimitSliceLength prevents memory exhaustion from malicious input arrays.
func MapToSlice ¶
func MapToSlice[K comparable, V any](m map[K]V) []V
MapToSlice order is non-deterministic due to Go's map iteration randomization.
func MaskCreditCard ¶
MaskCreditCard follows PCI DSS requirement to show only last 4 digits.
func MaskPhone ¶
MaskPhone follows PCI compliance pattern of showing last 4 digits for user recognition.
func MaskString ¶
MaskString preserves start/end characters for user recognition while hiding sensitive middle. Handles Unicode properly and prevents over-masking short strings.
func MaxLength ¶
MaxLength handles Unicode properly and prevents buffer overflows from malicious input.
func MergeStringMaps ¶
MergeStringMaps applies last-writer-wins semantics for duplicate keys.
func NonZero ¶
func NonZero[T Numeric](value T) T
NonZero returns 1 if the value is zero, otherwise returns the value unchanged.
func NormalizeCreditCard ¶
NormalizeCreditCard strips formatting for PCI-compliant storage and validation.
func NormalizeEmail ¶
NormalizeEmail prevents common email input errors but preserves original for invalid formats. Consolidates consecutive dots which can cause delivery issues with some email providers.
func NormalizePath ¶
NormalizePath normalizes a file path and prevents traversal attacks.
func NormalizePhone ¶
NormalizePhone strips formatting to enable consistent database storage and comparison.
func NormalizePostalCode ¶
NormalizePostalCode creates consistent format for database storage and comparison.
func NormalizeSSN ¶
NormalizeSSN strips formatting for consistent storage and validation of sensitive data.
func NormalizeToRange ¶
func NormalizeToRange[T Float](value T, fromMin T, fromMax T, toMin T, toMax T) T
NormalizeToRange maps a value from one range to another range proportionally. Maps value from [fromMin, fromMax] to [toMin, toMax].
func NormalizeURL ¶
NormalizeURL assumes HTTPS for security; preserves original on parse errors to avoid data loss. Removes trailing slash for consistent URL comparison and caching.
func NormalizeWhitespace ¶
NormalizeWhitespace prevents layout issues from multiple spaces, tabs, and newlines.
func Percentage ¶
Percentage calculates what percentage 'part' is of 'whole', clamped between 0 and 100. Returns 0 if whole is zero.
func PreventHeaderInjection ¶
PreventHeaderInjection removes characters that could be used for HTTP header injection.
func PreventLDAPInjection ¶
PreventLDAPInjection removes LDAP injection characters.
func PreventPathTraversal ¶
PreventPathTraversal removes path traversal attempts (../ and ..\).
func PreventXSS ¶
PreventXSS applies comprehensive XSS prevention measures.
func RegisterSanitizer ¶
RegisterSanitizer adds a custom sanitizer function to the registry
func RemoveChars ¶
RemoveChars removes all occurrences of the specified characters from the string.
func RemoveControlChars ¶
RemoveControlChars prevents injection attacks while preserving common whitespace.
func RemoveControlSequences ¶
RemoveControlSequences removes ANSI escape sequences and other control characters.
func RemoveExtraWhitespace ¶
RemoveExtraWhitespace prevents layout issues and normalizes user input formatting.
func RemoveFragment ¶
func RemoveJavaScriptEvents ¶
RemoveJavaScriptEvents removes JavaScript event handlers from HTML attributes.
func RemoveNonAlphanumeric ¶
func RemoveNullBytes ¶
RemoveNullBytes removes null bytes that could cause issues in C-based systems.
func RemoveQueryParams ¶
RemoveQueryParams useful for URL comparison and preventing tracking parameter leakage.
func RemoveSQLKeywords ¶
RemoveSQLKeywords removes common SQL keywords that could be used for injection.
func RemoveShellMetacharacters ¶
RemoveShellMetacharacters removes shell metacharacters that could be used for injection.
func ReplaceChars ¶
ReplaceChars replaces all occurrences of any character in old with the new string.
func ReverseSlice ¶
func ReverseSlice[T any](slice []T) []T
func Round ¶
func Round[T Float](value T) T
Round rounds a floating-point number to the nearest integer.
func RoundDown ¶
func RoundDown[T Float](value T) T
RoundDown rounds a floating-point number down to the nearest integer.
func RoundToDecimalPlaces ¶
RoundToDecimalPlaces rounds a floating-point number to the specified number of decimal places.
func RoundUp ¶
func RoundUp[T Float](value T) T
RoundUp rounds a floating-point number up to the nearest integer.
func SafeDivide ¶
func SafeDivide[T Numeric](numerator T, denominator T, fallback T) T
SafeDivide performs division with protection against division by zero. Returns the result of numerator/denominator, or fallback if denominator is zero.
func SanitizeEmail ¶
SanitizeEmail removes dangerous characters from email addresses while preserving valid format.
func SanitizeFilename ¶
SanitizeFilename prevents filesystem vulnerabilities and ensures cross-platform compatibility. Enforces 255-byte limit and provides fallback for completely invalid names.
func SanitizeHTMLAttributes ¶
SanitizeHTMLAttributes removes potentially dangerous HTML attributes.
func SanitizeMapKeys ¶
SanitizeMapKeys drops entries with empty keys after sanitization to prevent key collisions.
func SanitizeMapValues ¶
func SanitizeMapValues[K comparable](m map[K]string, sanitizer func(string) string) map[K]string
func SanitizePath ¶
SanitizePath cleans and normalizes file paths to prevent directory traversal.
func SanitizeSQLIdentifier ¶
SanitizeSQLIdentifier ensures SQL identifiers (table names, column names) are safe.
func SanitizeSecureFilename ¶
SanitizeSecureFilename makes a filename safe by removing dangerous characters.
func SanitizeShellArgument ¶
SanitizeShellArgument makes a string safe for use as a shell argument.
func SanitizeStruct ¶
SanitizeStruct applies sanitization to struct fields based on their tags
func SanitizeURL ¶
SanitizeURL removes dangerous elements from URLs while preserving valid structure.
func SanitizeUserInput ¶
SanitizeUserInput applies comprehensive sanitization for user input.
func SingleLine ¶
SingleLine converts multi-line strings to single line by replacing line breaks with spaces. Useful for form fields and log messages that need to be on one line.
func SliceToMap ¶
func SortStrings ¶
SortStrings creates sorted copy to avoid mutating input slice.
func SortStringsIgnoreCase ¶
SortStringsIgnoreCase preserves original casing while sorting by lowercase comparison.
func StripHTML ¶
StripHTML prevents XSS by removing tags and decoding entities for safe text extraction.
func StripScriptTags ¶
StripScriptTags removes all <script> tags and their content.
func ToCamelCase ¶
ToCamelCase follows JavaScript convention: first word lowercase, subsequent words capitalized.
func ToKebabCase ¶
ToKebabCase prevents consecutive dashes and ensures clean URL-safe identifiers.
func ToLowerStringSlice ¶
func ToSnakeCase ¶
ToSnakeCase prevents consecutive underscores for clean database column names.
func TransformSlice ¶
func TrimStringSlice ¶
func TrimToLower ¶
TrimToLower trims whitespace and converts to lowercase in one operation.
func TrimToUpper ¶
TrimToUpper trims whitespace and converts to uppercase in one operation.
func TruncateToInt ¶
func TruncateToInt[T Float](value T) T
TruncateToInt truncates a floating-point number to an integer, removing the decimal part.
func ZeroIfNegative ¶
func ZeroIfNegative[T Signed](value T) T
ZeroIfNegative returns zero if the value is negative, otherwise returns the value.
func ZeroIfPositive ¶
func ZeroIfPositive[T Signed](value T) T
ZeroIfPositive returns zero if the value is positive, otherwise returns the value.