sanitizer

package
v0.2.10 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2025 License: Apache-2.0 Imports: 13 Imported by: 0

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: "&lt;script&gt;alert('xss')&lt;/script&gt;"

// 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

Constants

This section is empty.

Variables

This section is empty.

Functions

func Abs

func Abs[T Signed](value T) T

Abs returns the absolute value of a signed numeric value.

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

func ClampPrecision[T Float](value T, min T, max T, decimalPlaces int) T

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

func CleanStringMap(m map[string]string) map[string]string

CleanStringMap applies standard form data cleanup: lowercase keys, trim values, remove empties.

func CleanStringSlice

func CleanStringSlice(slice []string) []string

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 DeduplicateStrings(slice []string) []string

func DeduplicateStringsIgnoreCase

func DeduplicateStringsIgnoreCase(slice []string) []string

DeduplicateStringsIgnoreCase preserves original casing of first occurrence.

func EscapeHTML

func EscapeHTML(s string) string

EscapeHTML escapes HTML special characters to prevent XSS attacks.

func EscapeSQLString

func EscapeSQLString(s string) string

EscapeSQLString escapes single quotes in SQL strings to prevent injection.

func ExtractDomain

func ExtractDomain(rawURL string) string

ExtractDomain assumes HTTPS protocol for parsing; validates host to prevent invalid domains.

func ExtractEmailDomain

func ExtractEmailDomain(email string) string

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

func ExtractNumbers(s string) string

ExtractNumbers concatenates all digit sequences, useful for ID extraction from mixed content.

func ExtractPhoneDigits

func ExtractPhoneDigits(phone string) string

func FilterEmpty

func FilterEmpty(slice []string) []string

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

func FilterMapByKeys[V any](m map[string]V, pattern string) map[string]V

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 FilterSlice[T any](slice []T, predicate func(T) bool) []T

func FilterSliceByPattern

func FilterSliceByPattern(slice []string, pattern string) []string

FilterSliceByPattern uses case-insensitive substring matching for user-friendly filtering.

func FormatCreditCard

func FormatCreditCard(cardNumber string) string

FormatCreditCard validates common card lengths (13-19 digits) before formatting for display.

func FormatPhoneUS

func FormatPhoneUS(phone string) string

FormatPhoneUS enforces NANP format; preserves original if not 10 digits to avoid data loss.

func FormatPostalCodeCA

func FormatPostalCodeCA(postalCode string) string

FormatPostalCodeCA enforces standard Canadian format (A1A 1A1); preserves invalid input.

func FormatPostalCodeUS

func FormatPostalCodeUS(postalCode string) string

FormatPostalCodeUS handles both ZIP and ZIP+4 formats; preserves invalid input.

func FormatSSN

func FormatSSN(ssn string) string

FormatSSN enforces standard 9-digit format; preserves original if invalid to avoid data loss.

func KeepAlpha

func KeepAlpha(s string) string

KeepAlpha keeps only letters and spaces, removing all other characters.

func KeepAlphanumeric

func KeepAlphanumeric(s string) string

KeepAlphanumeric preserves spaces for readability while removing special characters.

func KeepDigits

func KeepDigits(s string) string

KeepDigits keeps only numeric digits, removing all other characters.

func LimitLength

func LimitLength(s string, maxLength int) string

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

func LimitSliceLength[T any](slice []T, maxLength int) []T

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

func MaskCreditCard(cardNumber string) string

MaskCreditCard follows PCI DSS requirement to show only last 4 digits.

func MaskEmail

func MaskEmail(email string) string

MaskEmail preserves full domain for user recognition while hiding personal info.

func MaskPhone

func MaskPhone(phone string) string

MaskPhone follows PCI compliance pattern of showing last 4 digits for user recognition.

func MaskSSN

func MaskSSN(ssn string) string

MaskSSN follows privacy regulations requiring masking of all but last 4 digits.

func MaskString

func MaskString(s string, visibleChars int) string

MaskString preserves start/end characters for user recognition while hiding sensitive middle. Handles Unicode properly and prevents over-masking short strings.

func MaxLength

func MaxLength(s string, maxLen int) string

MaxLength handles Unicode properly and prevents buffer overflows from malicious input.

func MergeStringMaps

func MergeStringMaps(ms ...map[string]string) map[string]string

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

func NormalizeCreditCard(cardNumber string) string

NormalizeCreditCard strips formatting for PCI-compliant storage and validation.

func NormalizeEmail

func NormalizeEmail(email string) string

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

func NormalizePath(path string) string

NormalizePath normalizes a file path and prevents traversal attacks.

func NormalizePhone

func NormalizePhone(phone string) string

NormalizePhone strips formatting to enable consistent database storage and comparison.

func NormalizePostalCode

func NormalizePostalCode(postalCode string) string

NormalizePostalCode creates consistent format for database storage and comparison.

func NormalizeSSN

func NormalizeSSN(ssn string) string

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

func NormalizeURL(rawURL string) string

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

func NormalizeWhitespace(s string) string

NormalizeWhitespace prevents layout issues from multiple spaces, tabs, and newlines.

func Percentage

func Percentage[T Numeric](part T, whole T) float64

Percentage calculates what percentage 'part' is of 'whole', clamped between 0 and 100. Returns 0 if whole is zero.

func PreventHeaderInjection

func PreventHeaderInjection(s string) string

PreventHeaderInjection removes characters that could be used for HTTP header injection.

func PreventLDAPInjection

func PreventLDAPInjection(s string) string

PreventLDAPInjection removes LDAP injection characters.

func PreventPathTraversal

func PreventPathTraversal(path string) string

PreventPathTraversal removes path traversal attempts (../ and ..\).

func PreventXSS

func PreventXSS(s string) string

PreventXSS applies comprehensive XSS prevention measures.

func RegisterSanitizer

func RegisterSanitizer(name string, fn func(string) string)

RegisterSanitizer adds a custom sanitizer function to the registry

func RemoveChars

func RemoveChars(s string, chars string) string

RemoveChars removes all occurrences of the specified characters from the string.

func RemoveControlChars

func RemoveControlChars(s string) string

RemoveControlChars prevents injection attacks while preserving common whitespace.

func RemoveControlSequences

func RemoveControlSequences(s string) string

RemoveControlSequences removes ANSI escape sequences and other control characters.

func RemoveExtraWhitespace

func RemoveExtraWhitespace(s string) string

RemoveExtraWhitespace prevents layout issues and normalizes user input formatting.

func RemoveFragment

func RemoveFragment(rawURL string) string

func RemoveJavaScriptEvents

func RemoveJavaScriptEvents(s string) string

RemoveJavaScriptEvents removes JavaScript event handlers from HTML attributes.

func RemoveNonAlphanumeric

func RemoveNonAlphanumeric(s string) string

func RemoveNullBytes

func RemoveNullBytes(s string) string

RemoveNullBytes removes null bytes that could cause issues in C-based systems.

func RemoveQueryParams

func RemoveQueryParams(rawURL string) string

RemoveQueryParams useful for URL comparison and preventing tracking parameter leakage.

func RemoveSQLKeywords

func RemoveSQLKeywords(s string) string

RemoveSQLKeywords removes common SQL keywords that could be used for injection.

func RemoveShellMetacharacters

func RemoveShellMetacharacters(s string) string

RemoveShellMetacharacters removes shell metacharacters that could be used for injection.

func ReplaceChars

func ReplaceChars(s string, old string, new string) string

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

func RoundToDecimalPlaces[T Float](value T, places int) T

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

func SanitizeEmail(email string) string

SanitizeEmail removes dangerous characters from email addresses while preserving valid format.

func SanitizeFilename

func SanitizeFilename(filename string) string

SanitizeFilename prevents filesystem vulnerabilities and ensures cross-platform compatibility. Enforces 255-byte limit and provides fallback for completely invalid names.

func SanitizeHTMLAttributes

func SanitizeHTMLAttributes(s string) string

SanitizeHTMLAttributes removes potentially dangerous HTML attributes.

func SanitizeMapKeys

func SanitizeMapKeys[V any](m map[string]V, sanitizer func(string) string) map[string]V

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

func SanitizePath(path string) string

SanitizePath cleans and normalizes file paths to prevent directory traversal.

func SanitizeSQLIdentifier

func SanitizeSQLIdentifier(s string) string

SanitizeSQLIdentifier ensures SQL identifiers (table names, column names) are safe.

func SanitizeSecureFilename

func SanitizeSecureFilename(filename string) string

SanitizeSecureFilename makes a filename safe by removing dangerous characters.

func SanitizeShellArgument

func SanitizeShellArgument(arg string) string

SanitizeShellArgument makes a string safe for use as a shell argument.

func SanitizeStruct

func SanitizeStruct(v any) error

SanitizeStruct applies sanitization to struct fields based on their tags

func SanitizeURL

func SanitizeURL(url string) string

SanitizeURL removes dangerous elements from URLs while preserving valid structure.

func SanitizeUserInput

func SanitizeUserInput(s string) string

SanitizeUserInput applies comprehensive sanitization for user input.

func SingleLine

func SingleLine(s string) string

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 SliceToMap[T any](slice []T) map[int]T

func SortStrings

func SortStrings(slice []string) []string

SortStrings creates sorted copy to avoid mutating input slice.

func SortStringsIgnoreCase

func SortStringsIgnoreCase(slice []string) []string

SortStringsIgnoreCase preserves original casing while sorting by lowercase comparison.

func StripHTML

func StripHTML(s string) string

StripHTML prevents XSS by removing tags and decoding entities for safe text extraction.

func StripScriptTags

func StripScriptTags(s string) string

StripScriptTags removes all <script> tags and their content.

func ToCamelCase

func ToCamelCase(s string) string

ToCamelCase follows JavaScript convention: first word lowercase, subsequent words capitalized.

func ToKebabCase

func ToKebabCase(s string) string

ToKebabCase prevents consecutive dashes and ensures clean URL-safe identifiers.

func ToLower

func ToLower(s string) string

ToLower converts the string to lowercase.

func ToLowerStringSlice

func ToLowerStringSlice(slice []string) []string

func ToSnakeCase

func ToSnakeCase(s string) string

ToSnakeCase prevents consecutive underscores for clean database column names.

func ToTitle

func ToTitle(s string) string

ToTitle converts the string to title case.

func ToUpper

func ToUpper(s string) string

ToUpper converts the string to uppercase.

func TransformSlice

func TransformSlice[T any, R any](slice []T, transform func(T) R) []R

func Trim

func Trim(s string) string

Trim removes leading and trailing whitespace from the string.

func TrimStringSlice

func TrimStringSlice(slice []string) []string

func TrimToLower

func TrimToLower(s string) string

TrimToLower trims whitespace and converts to lowercase in one operation.

func TrimToUpper

func TrimToUpper(s string) string

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 UnescapeHTML

func UnescapeHTML(s string) string

UnescapeHTML unescapes HTML entities.

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.

Types

type Float

type Float interface {
	~float32 | ~float64
}

Float represents floating-point numeric types.

type Numeric

type Numeric interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
		~float32 | ~float64
}

Numeric represents numeric types that support basic arithmetic operations.

type Signed

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 | ~float32 | ~float64
}

Signed represents signed numeric types.

Jump to

Keyboard shortcuts

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