Documentation
¶
Overview ¶
Package zstring provides string manipulation utilities.
Index ¶
- func AesDecrypt(cipherText []byte, key string, iv ...string) (plainText []byte, err error)
- func AesDecryptString(cipherText string, key string, iv ...string) (string, error)
- func AesEncrypt(plainText []byte, key string, iv ...string) (ciphertext []byte, err error)
- func AesEncryptString(plainText string, key string, iv ...string) (string, error)
- func AesGCMDecrypt(ciphertext []byte, key string) (plaintext []byte, err error)
- func AesGCMDecryptString(cipherText string, key string) (string, error)
- func AesGCMEncrypt(plaintext []byte, key string) (ciphertext []byte, err error)
- func AesGCMEncryptString(plainText string, key string) (string, error)
- func Base64Decode(data []byte) (value []byte, err error)
- func Base64DecodeString(data string) (value string, err error)
- func Base64Encode(value []byte) []byte
- func Base64EncodeString(value string) string
- func Buffer(size ...int) *strings.Builder
- func Bytes2String(b []byte) string
- func CamelCaseToSnakeCase(str string, delimiter ...string) string
- func Expand(s string, process func(key string) string) string
- func GenRSAKey(bits ...int) (prvkey, pubkey []byte, err error)
- func Img2Base64(path string) (string, error)
- func IsLcfirst(str string) bool
- func IsPattern(str string) bool
- func IsSpace(r rune) bool
- func IsUcfirst(str string) bool
- func Lcfirst(str string) string
- func Len(str string) int
- func Match(str, pattern string, equalFold ...bool) bool
- func Md5(s string) string
- func Md5Byte(s []byte) string
- func Md5File(path string) (encrypt string, err error)
- func NewFilter(words []string, mask ...rune) *filterNode
- func NewNanoID(size int, alphabet ...string) (string, error)
- func NewReplacer(mapping map[string]string) *replacer
- func PKCS7Padding(ciphertext []byte, blockSize int) []byte
- func PKCS7UnPadding(origData []byte) ([]byte, error)
- func Pad(raw string, length int, padStr string, padType PadType) string
- func ParseID(id int64) (t time.Time, ts int64, workerId int64, seq int64)
- func ProjectMd5() string
- func RSADecrypt(cipherText []byte, privateKey string, bits ...int) ([]byte, error)
- func RSADecryptString(cipherText string, privateKey string) (string, error)
- func RSAEncrypt(plainText []byte, publicKey string, bits ...int) ([]byte, error)
- func RSAEncryptString(plainText string, publicKey string) (string, error)
- func RSAKeyDecrypt(cipherText []byte, privateKey *rsa.PrivateKey, bits ...int) ([]byte, error)
- func RSAKeyEncrypt(plainText []byte, publicKey *rsa.PublicKey, bits ...int) ([]byte, error)
- func RSAPriKeyEncrypt(plainText []byte, privateKey string) ([]byte, error)
- func RSAPriKeyEncryptString(plainText string, privateKey string) (string, error)
- func RSAPubKeyDecrypt(cipherText []byte, publicKey string) ([]byte, error)
- func RSAPubKeyDecryptString(cipherText string, publicKey string) (string, error)
- func Rand(n int, tpl ...string) string
- func RandInt(min int, max int) int
- func RandUint32() uint32
- func RandUint32Max(max uint32) uint32
- func RegexExtract(pattern string, str string) ([]string, error)
- func RegexExtractAll(pattern string, str string, count ...int) ([][]string, error)
- func RegexFind(pattern string, str string, count int) [][]int
- func RegexMatch(pattern string, str string) bool
- func RegexReplace(pattern string, str, repl string) (string, error)
- func RegexReplaceFunc(pattern string, str string, repl func(string) string) (string, error)
- func RegexSplit(pattern string, str string) ([]string, error)
- func SecureRandInt(min, max int) (int, error)
- func SecureRandString(n int, tpl ...string) (string, error)
- func Serialize(value interface{}) ([]byte, error)
- func SnakeCaseToCamelCase(str string, ucfirst bool, delimiter ...string) string
- func String2Bytes(s string) []byte
- func Substr(str string, start int, length ...int) string
- func TrimBOM(fileBytes []byte) []byte
- func TrimLine(s string) string
- func TrimSpace(s string) string
- func UUID() string
- func Ucfirst(str string) string
- func UnSerialize(valueBytes []byte, registers ...interface{}) (value interface{}, err error)
- func UniqueID(n int) string
- func UrlDecode(str string) (string, error)
- func UrlEncode(str string) string
- func UrlRawDecode(str string) (string, error)
- func UrlRawEncode(str string) string
- func WeightedRand(choices map[interface{}]uint32) (interface{}, error)
- func XSSClean(str string) string
- type IDWorker
- type PadType
- type Template
- type Weighteder
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AesDecrypt ¶ added in v1.1.20
AesDecrypt decrypts data that was encrypted with AesEncrypt. If an IV is provided, it must match the IV used during encryption. If no IV is provided, the key is used as the IV.
func AesDecryptString ¶ added in v1.1.20
AesDecryptString decrypts a base64-encoded string that was encrypted with AesEncryptString. This is a convenience wrapper around AesDecrypt.
func AesEncrypt ¶ added in v1.1.20
AesEncrypt encrypts data using AES in CBC mode with PKCS#7 padding. If an IV is provided, it is used; otherwise, the key is used as the IV.
func AesEncryptString ¶ added in v1.1.20
AesEncryptString encrypts a string using AES and returns the result as a base64-encoded string. This is a convenience wrapper around AesEncrypt.
func AesGCMDecrypt ¶ added in v1.3.5
AesGCMDecrypt decrypts data that was encrypted with AesGCMEncrypt. It extracts the nonce from the beginning of the ciphertext.
func AesGCMDecryptString ¶ added in v1.3.5
AesGCMDecryptString decrypts a base64-encoded string that was encrypted with AesGCMEncryptString. This is a convenience wrapper around AesGCMDecrypt.
func AesGCMEncrypt ¶ added in v1.3.5
AesGCMEncrypt encrypts data using AES in GCM mode, which provides both confidentiality and authenticity. It generates a random nonce for each encryption operation.
func AesGCMEncryptString ¶ added in v1.3.5
AesGCMEncryptString encrypts a string using AES-GCM and returns the result as a base64-encoded string. This is a convenience wrapper around AesGCMEncrypt.
func Base64Decode ¶ added in v0.1.20
Base64Decode decodes a base64 encoded byte slice.
func Base64DecodeString ¶ added in v0.1.20
Base64DecodeString decodes a base64 encoded string.
func Base64Encode ¶ added in v0.1.20
Base64Encode encodes a byte slice using standard base64 encoding.
func Base64EncodeString ¶ added in v0.1.20
Base64EncodeString encodes a string using standard base64 encoding.
func Buffer ¶
Buffer creates a new strings.Builder with optional initial capacity. This implementation uses the more efficient strings.Builder available in Go 1.10+.
func Bytes2String ¶
Bytes2String converts a byte slice to a string without memory allocation. Note: This uses unsafe.Pointer and the returned string must not be modified.
func CamelCaseToSnakeCase ¶ added in v0.0.19
CamelCaseToSnakeCase converts a camelCase or PascalCase string to snake_case. Example: "helloWorld" or "HelloWorld" becomes "hello_world". The optional delimiter parameter specifies the separator character (default is "_").
func Expand ¶ added in v1.5.2
Expand replaces ${var} or $var in the string based on the mapping function. It's similar to shell variable expansion, supporting both ${var} and $var syntax.
func GenRSAKey ¶ added in v1.3.5
GenRSAKey generates a pair of RSA private and public keys. The optional bits parameter specifies the key size (defaults to 2048 bits). Minimum key size is 1024 bits.
func Img2Base64 ¶ added in v0.1.46
Img2Base64 reads an image file and converts it to a base64 encoded data URL. The returned string can be used directly in HTML img tags.
func IsLcfirst ¶ added in v0.0.19
IsLcfirst checks if the first letter of a string is lowercase. Returns false if the string is empty or the first character is not a letter.
func IsPattern ¶ added in v0.0.19
IsPattern checks if a string contains wildcard characters (* or ?). Returns true if the string is a pattern that would match differently than literal comparison.
func IsSpace ¶ added in v1.7.19
IsSpace checks if a rune is a whitespace character. This includes standard ASCII whitespace and additional Unicode whitespace characters.
func IsUcfirst ¶ added in v0.0.19
IsUcfirst checks if the first letter of a string is uppercase. Returns false if the string is empty or the first character is not a letter.
func Lcfirst ¶ added in v0.0.19
Lcfirst converts the first letter of a string to lowercase, leaving the rest unchanged. Returns an empty string if the input is empty.
func Len ¶
Len returns the number of characters (runes) in a UTF-8 encoded string. This differs from len(string) which returns the number of bytes.
func Match ¶ added in v0.0.19
Match checks if a string matches a given pattern with wildcard support. Patterns can include '*' (matches any sequence of characters) and '?' (matches any single character). Optional equalFold parameter enables case-insensitive matching when true.
func Md5 ¶ added in v0.1.20
Md5 calculates the MD5 hash of a string. It returns the hash as a hexadecimal encoded string.
func Md5Byte ¶ added in v1.2.0
Md5Byte calculates the MD5 hash of a byte slice. It returns the hash as a hexadecimal encoded string.
func Md5File ¶ added in v0.1.20
Md5File calculates the MD5 hash of a file at the given path. It returns the hash as a hexadecimal encoded string and any error encountered.
func NewFilter ¶ added in v0.1.59
NewFilter creates a new text filter that can identify and mask sensitive words. It accepts a list of words to filter and an optional mask character (defaults to '*').
func NewNanoID ¶ added in v1.7.18
NewNanoID generates a secure unique string ID of the specified size. It's similar to UUID but more compact and customizable. By default, it uses alphanumeric characters, but a custom alphabet can be provided.
func NewReplacer ¶ added in v0.1.59
NewReplacer creates a new string replacer that efficiently replaces multiple strings at once. It uses a trie structure for fast matching.
func PKCS7Padding ¶ added in v0.1.63
PKCS7Padding implements PKCS#7 padding for block cipher encryption. It adds padding bytes to ensure the data length is a multiple of the block size.
func PKCS7UnPadding ¶ added in v0.1.63
PKCS7UnPadding removes PKCS#7 padding from decrypted data. It returns an error if the padding is invalid.
func Pad ¶
Pad adds padding characters to a string to reach the specified length. The padType parameter controls where padding is added (left, right, or both sides). If the string is already longer than the specified length, it is returned unchanged.
func ParseID ¶ added in v0.1.35
ParseID extracts the components from a Snowflake ID. Returns the timestamp as a time.Time, raw timestamp value, worker ID, and sequence number.
func ProjectMd5 ¶ added in v1.5.1
func ProjectMd5() string
ProjectMd5 calculates the MD5 hash of the current executable. This is useful for checking if the application binary has been modified.
func RSADecrypt ¶ added in v1.1.20
RSADecrypt decrypts data using RSA with a private key. For large data encrypted in chunks, use the same bits parameter as during encryption.
func RSADecryptString ¶ added in v1.1.20
RSADecryptString decrypts a base64-encoded string using RSA with a private key and returns the result as a string.
func RSAEncrypt ¶ added in v1.1.20
RSAEncrypt encrypts data using RSA with a public key. For large data, use the bits parameter to enable chunked encryption.
func RSAEncryptString ¶ added in v1.1.20
RSAEncryptString encrypts a string using RSA and returns the result as a base64-encoded string.
func RSAKeyDecrypt ¶ added in v1.3.5
RSAKeyDecrypt decrypts data using RSA with a private key object. For large data encrypted in chunks, use the same bits parameter as during encryption.
func RSAKeyEncrypt ¶ added in v1.3.5
RSAKeyEncrypt encrypts data using RSA with a public key object. For large data, use the bits parameter to enable chunked encryption.
func RSAPriKeyEncrypt ¶ added in v1.1.21
RSAPriKeyEncrypt encrypts (signs) data using an RSA private key. This is typically used for digital signatures rather than encryption.
func RSAPriKeyEncryptString ¶ added in v1.1.21
RSAPriKeyEncryptString encrypts (signs) a string using an RSA private key and returns the result as a base64-encoded string.
func RSAPubKeyDecrypt ¶ added in v1.1.21
RSAPubKeyDecrypt decrypts (verifies) data that was encrypted with a private key using the corresponding public key. This is typically used for signature verification.
func RSAPubKeyDecryptString ¶ added in v1.1.21
RSAPubKeyDecryptString decrypts (verifies) a base64-encoded string that was encrypted with a private key using the corresponding public key, and returns the result as a string.
func Rand ¶
Rand generates a random string of the specified length. By default, it uses alphanumeric characters (0-9, a-z, A-Z). An optional template string can be provided to limit the characters used.
func RandInt ¶ added in v0.0.19
RandInt generates a random integer within the specified inclusive range [min..max]. If max is less than min, max will be set equal to min.
func RandUint32 ¶ added in v0.1.53
func RandUint32() uint32
RandUint32 returns a pseudorandom uint32 value using the Go runtime's internal random number generator, which is much faster than crypto/rand for non-security-critical uses.
func RandUint32Max ¶ added in v0.1.53
RandUint32Max returns a pseudorandom uint32 value in the range [0..max). It uses a fast algorithm to generate uniformly distributed random numbers within the specified range.
func RegexExtract ¶ added in v0.0.19
RegexExtract extracts the first matching substring and any capture groups defined in the regular expression pattern.
func RegexExtractAll ¶ added in v0.1.42
RegexExtractAll extracts all matching substrings and their capture groups. An optional count parameter limits the number of matches returned.
func RegexFind ¶ added in v0.0.19
RegexFind returns the positions (start and end indices) of all matches. The count parameter limits the number of matches returned.
func RegexMatch ¶ added in v0.0.19
RegexMatch checks if a string matches a regular expression pattern. Returns true if the pattern matches the string, false otherwise.
func RegexReplace ¶ added in v0.0.19
RegexReplace replaces all matches of the pattern with the replacement string. Returns the modified string and any error that occurred.
func RegexReplaceFunc ¶ added in v0.0.19
RegexReplaceFunc replaces all matches of the pattern using a replacement function. The function receives each match and returns the replacement string.
func RegexSplit ¶ added in v1.6.1
RegexSplit splits the string at each occurrence of the pattern. Returns the resulting string slices and any error that occurred.
func SecureRandInt ¶ added in v1.7.21
SecureRandInt generates a cryptographically secure random integer in the range [min, max]. This function uses crypto/rand and is suitable for security-sensitive scenarios such as: - Session IDs - Authentication tokens - CSRF tokens - Password reset tokens - API keys
For non-security-critical random numbers, use RandInt instead for better performance.
Returns an error if the range is invalid or crypto/rand fails.
func SecureRandString ¶ added in v1.7.21
SecureRandString generates a cryptographically secure random string of the specified length. By default, it uses alphanumeric characters (0-9, a-z, A-Z). An optional template string can be provided to limit the characters used.
This function is suitable for security-sensitive scenarios such as: - Session IDs - Authentication tokens - CSRF tokens - Password reset tokens - API keys
For non-security-critical random strings, use Rand instead for better performance.
Returns an error if crypto/rand fails.
func Serialize ¶ added in v0.1.43
Serialize converts a value to a byte slice using Go's gob encoding. The value must be gob-encodable.
func SnakeCaseToCamelCase ¶ added in v0.0.19
SnakeCaseToCamelCase converts a snake_case string to camelCase or PascalCase. Example: "hello_world" becomes "helloWorld" (or "HelloWorld" if ucfirst is true). The optional delimiter parameter specifies the separator character (default is "_").
func String2Bytes ¶
String2Bytes converts a string to a byte slice without memory allocation. Note: This uses unsafe.Pointer and the returned byte slice must be treated as read-only. Modifying the returned slice may cause undefined behavior as it shares memory with the original string.
func Substr ¶
Substr extracts a substring from a UTF-8 encoded string. The start parameter specifies the position of the first character (can be negative to count from the end). The optional length parameter specifies how many characters to include in the result. A negative length leaves that many characters off the end of the string (PHP substr semantics).
func TrimBOM ¶ added in v0.0.19
TrimBOM removes the UTF-8 Byte Order Mark (BOM) from the beginning of a byte slice if present. The BOM is the byte sequence 0xEF,0xBB,0xBF that sometimes appears at the start of UTF-8 encoded files.
func TrimLine ¶ added in v1.4.8
TrimLine removes leading and trailing whitespace from each line in a string, and removes empty lines. It preserves the newline characters between non-empty lines.
func TrimSpace ¶ added in v1.1.11
TrimSpace removes all leading and trailing whitespace from a string. Unlike the standard strings.TrimSpace, this function handles additional Unicode whitespace characters.
func Ucfirst ¶ added in v0.0.19
Ucfirst capitalizes the first letter of a string, leaving the rest unchanged. Returns an empty string if the input is empty.
func UnSerialize ¶ added in v0.1.43
UnSerialize converts a byte slice back to its original value using Go's gob decoding. Additional types that need to be registered with gob can be passed as registers.
func UniqueID ¶ added in v1.1.3
UniqueID generates a cryptographically secure unique ID with at least the specified length. The ID is generated using crypto/rand for better security and uniqueness. If crypto/rand fails, it falls back to a more robust alternative method that combines multiple entropy sources to maintain uniqueness.
func UrlDecode ¶ added in v0.1.20
UrlDecode decodes a URL-encoded string. It handles the conversion of '+' characters back to spaces.
func UrlEncode ¶ added in v0.1.20
UrlEncode encodes a string for use in a URL query. It uses the standard encoding where spaces are converted to '+' characters.
func UrlRawDecode ¶ added in v0.1.20
UrlRawDecode decodes a string that was encoded according to RFC 3986. It handles the conversion of '%20' sequences to spaces.
func UrlRawEncode ¶ added in v0.1.20
UrlRawEncode encodes a string according to RFC 3986. Unlike UrlEncode, it converts spaces to '%20' instead of '+'.
func WeightedRand ¶ added in v1.6.4
WeightedRand performs a single weighted random selection from the provided choices. Each key in the map is an item that can be selected, and its value is the weight that determines its probability of being selected.
Types ¶
type IDWorker ¶ added in v0.1.35
IDWorker represents a Snowflake ID generator instance. Each worker generates unique IDs based on its worker ID.
func NewIDWorker ¶ added in v0.1.35
NewIDWorker creates a new Snowflake ID generator with the given worker ID. Returns an error if the worker ID is invalid (outside the allowed range).
type PadType ¶ added in v1.3.2
type PadType uint8
PadType defines the padding strategy for string padding operations.
const ( // PadRight indicates padding should be added to the right side of the string. PadRight PadType = iota // PadLeft indicates padding should be added to the left side of the string. PadLeft // PadSides indicates padding should be added to both sides of the string. // If the padding cannot be distributed equally, the right side receives the extra character. PadSides )
type Template ¶ added in v1.7.1
type Template struct {
// contains filtered or unexported fields
}
Template implements a simple template engine that replaces tags in a template string. It supports custom start and end tag delimiters and efficient processing.
func NewTemplate ¶ added in v1.7.1
NewTemplate creates a new template with the specified template string and tag delimiters. It parses the template and returns an error if the template format is invalid.
func (*Template) Process ¶ added in v1.7.1
func (t *Template) Process(w io.Writer, fn func(w io.Writer, tag string) (int, error)) (int64, error)
Process executes the template, writing the result to the provided writer. For each tag encountered, it calls the provided function with the tag name. Returns the number of bytes written and any error encountered.
func (*Template) ResetTemplate ¶ added in v1.7.1
ResetTemplate changes the template string and re-parses it. Returns an error if the template format is invalid (e.g., missing end tags).
type Weighteder ¶ added in v1.6.4
type Weighteder struct {
// contains filtered or unexported fields
}
Weighteder implements weighted random selection from a set of choices. Each choice has an associated weight that determines its probability of being selected.
func NewWeightedRand ¶ added in v1.6.4
func NewWeightedRand(choices map[interface{}]uint32) (*Weighteder, error)
NewWeightedRand creates a new Weighteder for efficient repeated weighted random selections. It initializes the internal data structures needed for fast weighted selection.
func (*Weighteder) Pick ¶ added in v1.6.4
func (w *Weighteder) Pick() interface{}
Pick selects and returns a random item from the Weighteder based on the weights. Items with higher weights are more likely to be selected.