utils

package
v1.12.2 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2025 License: MIT Imports: 17 Imported by: 27

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 ComparePasswords added in v1.10.4

func ComparePasswords(hashedPwd, inputPwd string) bool

ComparePasswords func for a comparing password.

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

func ReflectType(obj interface{}) 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 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 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 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.

Types

This section is empty.

Jump to

Keyboard shortcuts

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