utils

package
v1.16.0 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2025 License: MIT Imports: 21 Imported by: 22

README

Utilities

Common utils

Usage

Quick usage

import "github.com/gflydev/core/utils"

newHello := utils.CopyStr("Hello world")
Bytes
// Random byte
myBytes := utils.RandByte(make([]byte, 15))

// Extend bytes
myBytes := utils.ExtendByte(myBytes, 5)
Token
// Random UNIQUE token
myToken := utils.Token()

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddDays added in v1.13.1

func AddDays(t time.Time, days int) time.Time

AddDays adds the specified number of days to the given time.

Parameters:

  • t time.Time: The time to add days to.
  • days int: The number of days to add.

Returns:

  • time.Time: The resulting time after adding the days.

func All added in v1.13.1

func All[T any](slice []T, predicate func(T) bool) bool

All returns true if all elements in the slice satisfy the predicate.

Parameters:

  • slice []T: The input slice to check.
  • predicate func(T) bool: A function that returns true for matching elements.

Returns:

  • bool: True if all elements satisfy the predicate, false otherwise.

func Any added in v1.13.1

func Any[T any](slice []T, predicate func(T) bool) bool

Any returns true if any element in the slice satisfies the predicate.

Parameters:

  • slice []T: The input slice to check.
  • predicate func(T) bool: A function that returns true for matching elements.

Returns:

  • bool: True if any element satisfies the predicate, false otherwise.

func Chunk added in v1.13.1

func Chunk[T any](slice []T, size int) [][]T

Chunk splits a slice into chunks of the specified size.

Parameters:

  • slice []T: The input slice to split.
  • size int: The size of each chunk.

Returns:

  • [][]T: A slice of slices, where each inner slice has at most 'size' elements.

func Clamp added in v1.13.1

func Clamp(value, min, max int) int

Clamp constrains a value to a specified range.

Parameters:

  • value int: The value to constrain.
  • min int: The minimum value of the range.
  • max int: The maximum value of the range.

Returns:

  • int: The constrained value.

func ComparePasswords added in v1.10.4

func ComparePasswords(hashedPwd, inputPwd string) bool

ComparePasswords func for a comparing password.

func Contains added in v1.13.1

func Contains[T comparable](slice []T, element T) bool

Contains checks if a slice contains a specific element.

Parameters:

  • slice []T: The slice to search in.
  • element T: The element to search for.

Returns:

  • bool: True if the element is found in the slice, false otherwise.

func CopyByte

func CopyByte(b []byte) []byte

CopyByte creates a new copy of the given byte slice.

Parameters:

  • b []byte: The input slice to copy.

Returns:

  • []byte: A new slice with copied data from the input slice.

func CopyFile added in v1.13.1

func CopyFile(src, dst string, perm os.FileMode) error

CopyFile copies a file from src to dst.

Parameters:

  • src (string): The path to the source file.
  • dst (string): The path to the destination file.
  • perm (os.FileMode): The file permissions to use for the destination file.

Returns:

  • error: An error if the file couldn't be copied.

func CopyStr

func CopyStr(s string) string

CopyStr creates a new copy of the input string to ensure immutability.

Parameters:

  • s string: The input string to copy.

Returns:

  • string: A new immutable copy of the input string.

func DaysBetween added in v1.13.1

func DaysBetween(t1, t2 time.Time) int

DaysBetween calculates the number of days between two times.

Parameters:

  • t1 time.Time: The first time.
  • t2 time.Time: The second time.

Returns:

  • int: The number of days between the two times.

func DaysInMonth added in v1.13.1

func DaysInMonth(t time.Time) int

DaysInMonth returns the number of days in the month for the given time.

Parameters:

  • t time.Time: The time to get the number of days in the month for.

Returns:

  • int: The number of days in the month.

func DirExists added in v1.13.1

func DirExists(path string) bool

DirExists checks if a directory exists.

Parameters:

  • path (string): The path to the directory to check.

Returns:

  • bool: True if the directory exists, false otherwise.

func EndOfDay added in v1.13.1

func EndOfDay(t time.Time) time.Time

EndOfDay returns the end of the day (23:59:59.999999999) for the given time.

Parameters:

  • t time.Time: The time to get the end of the day for.

Returns:

  • time.Time: The end of the day for the given time.

func EndOfMonth added in v1.13.1

func EndOfMonth(t time.Time) time.Time

EndOfMonth returns the end of the month (last day 23:59:59.999999999) for the given time.

Parameters:

  • t time.Time: The time to get the end of the month for.

Returns:

  • time.Time: The end of the month for the given time.

func EndOfWeek added in v1.13.1

func EndOfWeek(t time.Time) time.Time

EndOfWeek returns the end of the week (Sunday 23:59:59.999999999) for the given time.

Parameters:

  • t time.Time: The time to get the end of the week for.

Returns:

  • time.Time: The end of the week for the given time.

func Entries added in v1.13.1

func Entries[K comparable, V any](m map[K]V) []struct {
	Key   K
	Value V
}

Entries returns a slice of key-value pairs from the map.

Parameters:

  • m map[K]V: The input map.

Returns:

  • []struct{Key K; Value V}: A slice of key-value pairs.

func EqualByte

func EqualByte(a, b []byte) bool

EqualByte compares two byte slices for equality.

Parameters:

  • a []byte: The first byte slice.
  • b []byte: The second byte slice.

Returns:

  • bool: True if the slices have the same length and identical contents, false otherwise.

func ExtendByte

func ExtendByte(b []byte, needLen int) []byte

ExtendByte extends or truncates the provided slice to match the required length.

Parameters:

  • b []byte: The input slice to be extended or truncated.
  • needLen int: The desired length of the resulting slice.

Returns:

  • []byte: The modified slice extended or truncated to the requested length.

func FileExists added in v1.13.1

func FileExists(path string) bool

FileExists checks if a file exists and is not a directory.

Parameters:

  • path (string): The path to the file to check.

Returns:

  • bool: True if the file exists and is not a directory, false otherwise.

func FileExt

func FileExt(fileName string) string

FileExt extracts the extension of a file from its name or path.

Parameters:

  • fileName (string): The file name or path from which to extract the extension.

Returns:

  • string: The file extension without the leading dot, or an empty string if none is found.

Examples:

func FileModTime added in v1.13.1

func FileModTime(path string) (time.Time, error)

FileModTime returns the modification time of a file.

Parameters:

  • path (string): The path to the file.

Returns:

  • time.Time: The modification time of the file, or the zero time if there's an error.
  • error: An error if the file information couldn't be retrieved.

func FileSize added in v1.13.1

func FileSize(path string) int64

FileSize returns the size of a file in bytes.

Parameters:

  • path (string): The path to the file.

Returns:

  • int64: The size of the file in bytes, or -1 if the file doesn't exist or there's an error.

func Filter added in v1.13.1

func Filter[T any](slice []T, predicate func(T) bool) []T

Filter creates a new slice containing only the elements that satisfy the predicate function.

Parameters:

  • slice []T: The input slice to filter.
  • predicate func(T) bool: A function that returns true for elements to include.

Returns:

  • []T: A new slice containing only the elements for which the predicate returns true.

func FilterKeys added in v1.13.1

func FilterKeys[K comparable, V any](m map[K]V, predicate func(K) bool) map[K]V

FilterKeys creates a new map with only the key-value pairs whose keys satisfy the predicate.

Parameters:

  • m map[K]V: The input map.
  • predicate func(K) bool: A function that returns true for keys to include.

Returns:

  • map[K]V: A new map containing only the key-value pairs whose keys satisfy the predicate.

func FilterValues added in v1.13.1

func FilterValues[K comparable, V any](m map[K]V, predicate func(V) bool) map[K]V

FilterValues creates a new map with only the key-value pairs whose values satisfy the predicate.

Parameters:

  • m map[K]V: The input map.
  • predicate func(V) bool: A function that returns true for values to include.

Returns:

  • map[K]V: A new map containing only the key-value pairs whose values satisfy the predicate.

func ForEach added in v1.13.1

func ForEach[T any](slice []T, action func(T))

ForEach applies a function to each element in the slice.

Parameters:

  • slice []T: The input slice to iterate over.
  • action func(T): A function to apply to each element.

func FormatThousands added in v1.13.1

func FormatThousands(value int) string

FormatThousands formats an integer with thousand separators.

Parameters:

  • value int: The integer to format.

Returns:

  • string: The formatted string with thousand separators.

func FormatTime added in v1.13.1

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

FormatTime formats a time.Time value according to the specified layout.

Parameters:

  • t time.Time: The time value to format.
  • layout string: The layout string to use for formatting (e.g., "2006-01-02").

Returns:

  • string: The formatted time string.

func GeneratePassword added in v1.10.4

func GeneratePassword(p string) string

GeneratePassword func for a making hash & salt with user password.

func Getenv

func Getenv[V any](key string, init V) V

Getenv retrieves an environment variable and parses it into the specified type, falling back to a default value if the variable is not found.

Parameters:

  • key (string): The name of the environment variable.
  • init (V): The default value to use if the environment variable is not set.

Returns:

  • V: The value of the environment variable parsed into the specified type, or the default value if the variable is not found.

func HasKey added in v1.13.1

func HasKey[K comparable, V any](m map[K]V, key K) bool

HasKey checks if a map contains a specific key.

Parameters:

  • m map[K]V: The input map.
  • key K: The key to check for.

Returns:

  • bool: True if the map contains the key, false otherwise.

func InRange added in v1.13.1

func InRange(value, min, max int) bool

InRange checks if a number is within the specified range (inclusive).

Parameters:

  • value int: The value to check.
  • min int: The minimum value of the range.
  • max int: The maximum value of the range.

Returns:

  • bool: True if the value is within the range, false otherwise.

func IncludeStr

func IncludeStr(slice []string, s string) bool

IncludeStr checks if a given string is present in a slice of strings.

Parameters:

  • slice []string: The slice of strings to search in.
  • s string: The string to look for in the slice.

Returns:

  • bool: True if the string is present in the slice, false otherwise.

func IndexOf added in v1.13.1

func IndexOf[T comparable](slice []T, element T) int

IndexOf finds the index of an element in a slice.

Parameters:

  • slice []T: The slice to search in.
  • element T: The element to search for.

Returns:

  • int: The index of the element in the slice, or -1 if not found.

func IndexOfStr

func IndexOfStr(slice []string, s string) int

IndexOfStr finds the index of a given string in a slice of strings.

Parameters:

  • slice []string: The slice of strings to search in.
  • s string: The string to look for in the slice.

Returns:

  • int: The index of the string in the slice, or -1 if the string is not found.

func IsBlank added in v1.13.1

func IsBlank(s string) bool

IsBlank checks if a string is empty or contains only whitespace.

Parameters:

  • s string: The input string to check.

Returns:

  • bool: True if the string is empty or contains only whitespace, false otherwise.

func IsFileNewer added in v1.13.1

func IsFileNewer(file1, file2 string) (bool, error)

IsFileNewer checks if file1 is newer than file2.

Parameters:

  • file1 (string): The path to the first file.
  • file2 (string): The path to the second file.

Returns:

  • bool: True if file1 is newer than file2, false otherwise or if there's an error.
  • error: An error if the file information couldn't be retrieved.

func IsSameDay added in v1.13.1

func IsSameDay(t1, t2 time.Time) bool

IsSameDay checks if two times fall on the same day.

Parameters:

  • t1 time.Time: The first time.
  • t2 time.Time: The second time.

Returns:

  • bool: True if the two times fall on the same day, false otherwise.

func IsSameMonth added in v1.13.1

func IsSameMonth(t1, t2 time.Time) bool

IsSameMonth checks if two times fall in the same month.

Parameters:

  • t1 time.Time: The first time.
  • t2 time.Time: The second time.

Returns:

  • bool: True if the two times fall in the same month, false otherwise.

func IsSameYear added in v1.13.1

func IsSameYear(t1, t2 time.Time) bool

IsSameYear checks if two times fall in the same year.

Parameters:

  • t1 time.Time: The first time.
  • t2 time.Time: The second time.

Returns:

  • bool: True if the two times fall in the same year, false otherwise.

func IsWeekday added in v1.13.1

func IsWeekday(t time.Time) bool

IsWeekday checks if the given time falls on a weekday (Monday through Friday).

Parameters:

  • t time.Time: The time to check.

Returns:

  • bool: True if the time falls on a weekday, false otherwise.

func IsWeekend added in v1.13.1

func IsWeekend(t time.Time) bool

IsWeekend checks if the given time falls on a weekend (Saturday or Sunday).

Parameters:

  • t time.Time: The time to check.

Returns:

  • bool: True if the time falls on a weekend, false otherwise.

func Keys added in v1.13.1

func Keys[K comparable, V any](m map[K]V) []K

Keys returns a slice containing all the keys in the map.

Parameters:

  • m map[K]V: The input map.

Returns:

  • []K: A slice containing all the keys in the map.

func MD5

func MD5(s string) string

MD5 generates an MD5 hash from a string.

Parameters:

  • s string: The input string to be hashed.

Returns:

  • string: The resulting MD5 hash as a hexadecimal-encoded string.

func Map added in v1.13.1

func Map[T any, U any](slice []T, mapper func(T) U) []U

Map creates a new slice by applying a function to each element of the input slice.

Parameters:

  • slice []T: The input slice to transform.
  • mapper func(T) U: A function that transforms elements of type T to type U.

Returns:

  • []U: A new slice containing the transformed elements.

func MapKeys added in v1.13.1

func MapKeys[K comparable, L comparable, V any](m map[K]V, mapper func(K) L) map[L]V

MapKeys creates a new map by applying a function to each key in the input map.

Parameters:

  • m map[K]V: The input map.
  • mapper func(K) L: A function that transforms keys of type K to type L.

Returns:

  • map[L]V: A new map with transformed keys and the same values.

func MapValues added in v1.13.1

func MapValues[K comparable, V any, W any](m map[K]V, mapper func(V) W) map[K]W

MapValues creates a new map by applying a function to each value in the input map.

Parameters:

  • m map[K]V: The input map.
  • mapper func(V) W: A function that transforms values of type V to type W.

Returns:

  • map[K]W: A new map with the same keys and transformed values.

func Max added in v1.13.1

func Max(a, b int) int

Max returns the larger of two integers.

Parameters:

  • a int: The first integer.
  • b int: The second integer.

Returns:

  • int: The larger of the two integers.

func Merge added in v1.13.1

func Merge[K comparable, V any](m1, m2 map[K]V) map[K]V

Merge combines two maps into a new map. If a key exists in both maps, the value from the second map is used.

Parameters:

  • m1 map[K]V: The first input map.
  • m2 map[K]V: The second input map.

Returns:

  • map[K]V: A new map containing all key-value pairs from both input maps.

func Min added in v1.13.1

func Min(a, b int) int

Min returns the smaller of two integers.

Parameters:

  • a int: The first integer.
  • b int: The second integer.

Returns:

  • int: The smaller of the two integers.

func MkdirIfNotExists added in v1.13.1

func MkdirIfNotExists(path string, perm os.FileMode) error

MkdirIfNotExists creates a directory if it doesn't exist.

Parameters:

  • path (string): The path to the directory to create.
  • perm (os.FileMode): The directory permissions to use if the directory is created.

Returns:

  • error: An error if the directory couldn't be created.

func Now added in v1.13.1

func Now() time.Time

Now returns the current local time.

Returns:

  • time.Time: The current local time.

func Omit added in v1.13.1

func Omit[K comparable, V any](m map[K]V, keys []K) map[K]V

Omit creates a new map without the specified keys from the input map.

Parameters:

  • m map[K]V: The input map.
  • keys []K: The keys to exclude from the new map.

Returns:

  • map[K]V: A new map containing all key-value pairs except those with the specified keys.

func ParseTime added in v1.13.1

func ParseTime(value, layout string) (time.Time, error)

ParseTime parses a time string according to the specified layout.

Parameters:

  • value string: The time string to parse.
  • layout string: The layout string to use for parsing (e.g., "2006-01-02").

Returns:

  • time.Time: The parsed time value.
  • error: An error if the time string couldn't be parsed.

func Pick added in v1.13.1

func Pick[K comparable, V any](m map[K]V, keys []K) map[K]V

Pick creates a new map with only the specified keys from the input map.

Parameters:

  • m map[K]V: The input map.
  • keys []K: The keys to include in the new map.

Returns:

  • map[K]V: A new map containing only the specified keys and their values.

func PrependByte

func PrependByte(dst []byte, src ...byte) []byte

PrependByte prepends the provided bytes to the destination slice.

Parameters:

  • dst []byte: The destination slice to prepend bytes to.
  • src ...byte: The source bytes to prepend to the destination slice.

Returns:

  • []byte: The new slice with the source bytes prepended to the destination slice.

func PrependByteStr

func PrependByteStr(dst []byte, src string) []byte

PrependByteStr prepends a string to the given byte slice.

Parameters:

  • dst []byte: The destination slice to prepend the string to.
  • src string: The source string to prepend to the destination slice.

Returns:

  • []byte: The new slice with the source string prepended to the destination slice.

func QuoteStr

func QuoteStr(raw string) string

QuoteStr escapes special characters in a given string.

Parameters:

  • raw string: The input string to escape.

Returns:

  • string: The escaped string with special characters properly quoted.

Variables:

  • bb *bytebufferpool.ByteBuffer: A byte buffer obtained from the bytebufferpool for temporary storage.
  • quoted string: The resulting escaped string.

func RandByte

func RandByte(dst []byte) []byte

RandByte returns a byte slice filled with cryptographically secure random bytes mapped to a specific character set.

Parameters:

  • dst []byte: The destination slice that will be filled with random bytes.

Returns:

  • []byte: The modified destination slice containing random bytes.

func RandInt64

func RandInt64(m int64) int64

RandInt64 generates a cryptographically secure random integer within the range [0, m).

Parameters:

  • m int64: The upper limit (exclusive) for the random integer.

Returns:

  • int64: A random integer within the specified range.

NOTE:

Get error `G404 (CWE-338): Use of weak random number generator (math/rand instead of crypto/rand)
(Confidence: MEDIUM, Severity: HIGH)` when use `rand.Intn(max)` from "math/rand".
Fixed Refer https://github.com/securego/gosec/issues/294#issuecomment-487452731

func ReadFileAsString added in v1.13.1

func ReadFileAsString(path string) (string, error)

ReadFileAsString reads the contents of a file as a string.

Parameters:

  • path (string): The path to the file to read.

Returns:

  • string: The contents of the file as a string.
  • error: An error if the file couldn't be read.

func Reduce added in v1.13.1

func Reduce[T any, U any](slice []T, initialValue U, reducer func(U, T) U) U

Reduce applies a function to each element in the slice, accumulating a single result.

Parameters:

  • slice []T: The input slice to reduce.
  • initialValue U: The initial value for the accumulator.
  • reducer func(U, T) U: A function that combines the accumulator with each element.

Returns:

  • U: The final accumulated value.

func ReflectType

func ReflectType(obj any) string

ReflectType Get the name of a struct instance.

func RenameFile

func RenameFile(fileName, newName string) string

RenameFile generates a new file path by replacing the file name with a new name while preserving the extension.

Parameters:

  • fileName (string): The original file name or full file path.
  • newName (string): The new base name to replace the old file name.

Returns:

  • string: The new file path with the same directory and extension as the original.

Examples:

  • Input: "Avatar2023.jpeg", "hello", Output: "hello.jpeg"
  • Input: "path/to/file.png", "newname", Output: "path/to/newname.png"
  • Input: "file_without_extension", "name", Output: "name"

func RequestParam added in v1.10.1

func RequestParam(urlStr, param string) (string, error)

RequestParam parses a specific parameter from a given URL string.

Parameters:

Eg:

Returns:

  • string: The value of the specified query parameter. If the parameter is not found, an empty string is returned.
  • error: An error if the URL parsing fails.

Variables in function:

  • u *url.URL: Parsed URL object obtained from the input string.
  • err error: Stores any error that occurs during the URL parsing process.

func RequestPath added in v1.10.1

func RequestPath(urlStr string) (string, error)

RequestPath parses the request path string from a given URL.

Parameters:

Eg:

Returns: - string: The extracted path from the given URL string. - error: An error if the URL parsing fails.

Variables in function: - u *url.URL: Parsed URL object obtained from the input string. - err error: Stores any error that occurs during URL parsing.

func RequestURL added in v1.10.4

func RequestURL(urlStr string) (string, error)

RequestURL parses the request URL string and constructs the URL using the scheme, host, and path.

Parameters:

Returns:

  • string: The reconstructed URL string in the format "scheme://host/path".
  • error: An error if the URL parsing fails.

func Reverse added in v1.13.1

func Reverse[T any](slice []T) []T

Reverse returns a new slice with the elements in reverse order.

Parameters:

  • slice []T: The input slice to reverse.

Returns:

  • []T: A new slice with the elements in reverse order.

func SafeAtoi added in v1.13.1

func SafeAtoi(s string, defaultValue int) int

SafeAtoi converts a string to an integer with error handling.

Parameters:

  • s string: The string to convert.
  • defaultValue int: The default value to return if conversion fails.

Returns:

  • int: The converted integer or the default value if conversion fails.

func SafeInt32ToInt64 added in v1.13.1

func SafeInt32ToInt64(value int32) int64

SafeInt32ToInt64 safely converts an int32 to int64.

Parameters:

  • value int32: The int32 value to convert.

Returns:

  • int64: The converted int64 value.

func SafeInt64ToInt32 added in v1.13.1

func SafeInt64ToInt32(value int64) (int32, error)

SafeInt64ToInt32 safely converts an int64 to int32 with overflow checking.

Parameters:

  • value int64: The int64 value to convert.

Returns:

  • int32: The converted int32 value.
  • error: An error if the value is outside the int32 range.

func SafeParseFloat added in v1.13.1

func SafeParseFloat(s string, defaultValue float64) float64

SafeParseFloat converts a string to a float64 with error handling.

Parameters:

  • s string: The string to convert.
  • defaultValue float64: The default value to return if conversion fails.

Returns:

  • float64: The converted float64 or the default value if conversion fails.

func Sha256

func Sha256(args ...any) string

Sha256 generates a SHA256 hash from a list of arguments.

Parameters:

  • args ...any: Variadic arguments to be hashed. The arguments are concatenated into a single string, separated by hyphens ("-").

Returns:

  • string: The resulting SHA256 hash as a hexadecimal-encoded string.

func Shuffle added in v1.13.1

func Shuffle[T any](slice []T) []T

Shuffle returns a new slice with the elements randomly shuffled.

Parameters:

  • slice []T: The input slice to shuffle.

Returns:

  • []T: A new slice with the elements randomly shuffled.

func StartOfDay added in v1.13.1

func StartOfDay(t time.Time) time.Time

StartOfDay returns the start of the day (00:00:00) for the given time.

Parameters:

  • t time.Time: The time to get the start of the day for.

Returns:

  • time.Time: The start of the day for the given time.

func StartOfMonth added in v1.13.1

func StartOfMonth(t time.Time) time.Time

StartOfMonth returns the start of the month (1st day 00:00:00) for the given time.

Parameters:

  • t time.Time: The time to get the start of the month for.

Returns:

  • time.Time: The start of the month for the given time.

func StartOfWeek added in v1.13.1

func StartOfWeek(t time.Time) time.Time

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

Parameters:

  • t time.Time: The time to get the start of the week for.

Returns:

  • time.Time: The start of the week for the given time.

func SubtractDays added in v1.13.1

func SubtractDays(t time.Time, days int) time.Time

SubtractDays subtracts the specified number of days from the given time.

Parameters:

  • t time.Time: The time to subtract days from.
  • days int: The number of days to subtract.

Returns:

  • time.Time: The resulting time after subtracting the days.

func ToCamelCase added in v1.13.1

func ToCamelCase(s string) string

ToCamelCase converts a string to camelCase.

Parameters:

  • s string: The input string to convert.

Returns:

  • string: The camelCase version of the input string.

func ToPascalCase added in v1.13.1

func ToPascalCase(s string) string

ToPascalCase converts a string to PascalCase.

Parameters:

  • s string: The input string to convert.

Returns:

  • string: The PascalCase version of the input string.

func ToSnakeCase added in v1.13.1

func ToSnakeCase(s string) string

ToSnakeCase converts a string to snake_case.

Parameters:

  • s string: The input string to convert.

Returns:

  • string: The snake_case version of the input string.

func Token

func Token(object ...string) string

Token generates a unique token by combining input strings, the current timestamp, a random integer, and a random byte slice, hashed using SHA256.

Parameters:

  • object ...string: Optional variadic input strings that will be included in the token generation.

Returns:

  • string: A unique SHA256 hash representing the generated token.

func Truncate added in v1.13.1

func Truncate(s string, length int, withEllipsis bool) string

Truncate truncates a string to the specified length and adds an ellipsis if truncated.

Parameters:

  • s string: The input string to truncate.
  • length int: The maximum length of the truncated string (excluding ellipsis).
  • withEllipsis bool: Whether to add an ellipsis ("...") if the string is truncated.

Returns:

  • string: The truncated string, with an ellipsis if requested and if truncation occurred.

func UTC added in v1.13.1

func UTC() time.Time

UTC returns the current UTC time.

Returns:

  • time.Time: The current UTC time.

func Unique added in v1.13.1

func Unique[T comparable](slice []T) []T

Unique returns a new slice with duplicate elements removed.

Parameters:

  • slice []T: The input slice that may contain duplicates.

Returns:

  • []T: A new slice with duplicate elements removed.

func UnpackArray added in v1.7.1

func UnpackArray(arr any) []any

UnpackArray Unpack an `arr` argument `any` but is exactly a type `[]any` Eg: We have `args` type `any`. var args any args = []string{"my-file.pdf", "png"} utils.UnpackArray(args)

func UnpackArrayT added in v1.7.1

func UnpackArrayT[T any](arr any) (r []any)

UnpackArrayT Unpack an `a` argument `any` but is exactly a type `[]T` Eg: We have `args` type `any`. var args any args = []string{"my-file.pdf", "png"} utils.UnpackArrayT[string](args)

func UnsafeBytes

func UnsafeBytes(s string) []byte

UnsafeBytes returns a byte pointer without allocation.

Parameters:

  • s string: The input string to convert to a byte slice.

Returns:

  • []byte: A byte slice pointing to the same memory as the input string.

func UnsafeStr

func UnsafeStr(b []byte) string

UnsafeStr returns a string pointer without allocation.

Parameters:

  • b []byte: The input byte slice to convert to a string.

Returns:

  • string: A string pointing to the same memory as the input byte slice.

func Values added in v1.13.1

func Values[K comparable, V any](m map[K]V) []V

Values returns a slice containing all the values in the map.

Parameters:

  • m map[K]V: The input map.

Returns:

  • []V: A slice containing all the values in the map.

func WriteStringToFile added in v1.13.1

func WriteStringToFile(path, content string, perm os.FileMode) error

WriteStringToFile writes a string to a file.

Parameters:

  • path (string): The path to the file to write to.
  • content (string): The content to write to the file.
  • perm (os.FileMode): The file permissions to use if the file is created.

Returns:

  • error: An error if the file couldn't be written to.

Types

This section is empty.

Jump to

Keyboard shortcuts

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