stringutil

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 5 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README ¶

stringutil Package

The stringutil package provides domain-agnostic string manipulation helpers, UTF-8 rune-safe truncation, and privacy-compliant PII masking for email and phone numbers in structured logs.

When to Use

  • PII Masking for Telemetry & Logging: Masking sensitive customer email addresses and phone numbers before passing them to slog or APM spans.
  • Input Sanitization: Trimming whitespace and normalizing case for emails and usernames prior to database queries.
  • UTF-8 Safe Truncation: Truncating descriptions or message previews by runes rather than raw bytes to avoid corrupting multi-byte unicode characters.

Why It Is Written Like That

  • Unicode / UTF-8 Boundary Safety: Truncate operates on rune boundaries rather than raw byte slices, preventing corrupted half-characters or invalid UTF-8 sequences.
  • GDPR & Privacy Compliance: Provides standardized MaskEmail and MaskPhone routines so all microservices mask PII identically without accidental data leakage.
  • Zero Allocations for Identity Cases: When input strings do not require truncation or modification, functions return the existing string slice without allocating new heap memory.

Alternatives Evaluated

Alternative Pros Cons Why We Chose go-libs/stringutil
Standard Library strings alone Built-in Go package Lacks PII masking; s[:n] byte-slicing panics on multi-byte UTF-8; no OrDefault helper Fills missing utility gaps while remaining 100% compliant with standard library idioms
Ad-hoc Regex Masking in Handlers Flexible Regex evaluation is slow (thousands of ns); prone to incomplete masking or developer bugs Fast, zero-regex string scanning with audited masking rules
Heavy String Manipulation Libraries Hundreds of text helpers Huge dependency bloat; unnecessary formatting overhead Focused set of essential utilities with 100% statement coverage

API

import "github.com/abeta-dev/go-libs/stringutil"

// Fallback: returns s if non-empty, otherwise defaultVal
name := stringutil.OrDefault(user.DisplayName, "Unknown User")

// Truncate to n runes (safe for UTF-8)
short := stringutil.Truncate(longDescription, 160)

// PII masking for structured logs
log.Info("login attempt", "email", stringutil.MaskEmail(req.Email))
// "john.doe@example.com" → "jo**@example.com"

log.Info("OTP sent", "phone", stringutil.MaskPhone(req.Phone))
// "+12025550199" → "+*******0199"
// "9876543210"   → "******3210"

// Normalise before DB lookup (always lowercase + trim)
email := stringutil.TrimAndLower(req.Email)

// Blank check (empty or whitespace-only)
if stringutil.IsBlank(req.Remarks) {
    req.Remarks = "No remarks"
}

// Match any of a set of substrings
if stringutil.ContainsAny(filename, ".exe", ".sh", ".bat") {
    return ErrDangerousFileType
}

Why not use strings directly?

  • MaskEmail / MaskPhone are non-trivial to get right — one shared implementation prevents inconsistent masking across 30+ handler files.
  • TrimAndLower is a one-liner, but forgetting it causes login failures for "John@Example.COM" vs "john@example.com".
  • OrDefault reads more clearly than ternary idioms.

📊 Test Coverage Status

  • Coverage: 100.0% of statements
  • Tests: stringutil_test.go, export_test.go

Documentation ¶

Overview ¶

Package stringutil provides domain-agnostic string utilities including sensitive PII masking (MaskEmail, MaskPhone) and cryptographically secure random string generation.

Package stringutil provides domain-agnostic string helper functions.

Has zero knowledge of any business domain. Suitable for use in any service that imports go-libs.

Index ¶

Examples ¶

Constants ¶

This section is empty.

Variables ¶

This section is empty.

Functions ¶

func ContainsAny ¶

func ContainsAny(s string, subs ...string) bool

ContainsAny returns true if s contains any of the given substrings.

func IsBlank ¶

func IsBlank(s string) bool

IsBlank returns true if the string is empty or contains only whitespace.

func MaskEmail ¶

func MaskEmail(email string) string

MaskEmail masks an email address for safe logging. "john.doe@example.com" → "jo******@example.com"

Example ¶
package main

import (
	"fmt"

	"github.com/abeta-dev/go-libs/stringutil"
)

func main() {
	fmt.Println(stringutil.MaskEmail("alice.smith@example.com"))
}
Output:
al*********@example.com

func MaskPhone ¶

func MaskPhone(phone string) string

MaskPhone masks a phone number for safe logging. Preserves leading '+' if present and masks all characters except the last 4 digits.

func OrDefault ¶

func OrDefault(s, defaultVal string) string

OrDefault returns s if non-empty, otherwise returns the defaultVal. Replaces ad-hoc ternary patterns across the codebase.

Example ¶
package main

import (
	"fmt"

	"github.com/abeta-dev/go-libs/stringutil"
)

func main() {
	fmt.Println(stringutil.OrDefault("", "default_value"))
	fmt.Println(stringutil.OrDefault("custom_value", "default_value"))
}
Output:
default_value
custom_value

func RandomAlphanumeric ¶

func RandomAlphanumeric(length int) (string, error)

RandomAlphanumeric returns a cryptographically secure random string of the specified length strictly consisting of alphanumeric characters ([a-zA-Z0-9]).

func RandomSecureString ¶

func RandomSecureString(length int) (string, error)

RandomSecureString returns a random string of the specified length containing alphanumeric characters and symbols (!@#$). Uses crypto/rand for cryptographic security.

func RandomStringFromCharset ¶

func RandomStringFromCharset(length int, charset string) (string, error)

RandomStringFromCharset returns a cryptographically secure random string of length n drawn from charset.

func RandomStringFromReader ¶

func RandomStringFromReader(r io.Reader, length int, charset string) (string, error)

RandomStringFromReader returns a random string of length n drawn from charset using reader r.

func TrimAndLower ¶

func TrimAndLower(s string) string

TrimAndLower trims whitespace and lowercases a string. Useful for normalising email addresses before DB lookup.

func Truncate ¶

func Truncate(s string, n int) string

Truncate returns the first n runes of s. If s is shorter than n, returns s unchanged. If n <= 0, returns an empty string. Safe for multi-byte UTF-8 strings.

Types ¶

This section is empty.

Jump to

Keyboard shortcuts

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