utils

package module
v1.39.0 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2024 License: MIT Imports: 38 Imported by: 15

README

Utils Open in Gitpod

tests

Various utility functions.

Array Functions

  • ArrayContains(array interface{}, val interface{}) (exists bool, index int)
  • ArrayMerge(array ...[]interface{}) []interface{}
  • ArrayEqualsInt(a []int, b []int) bool - checks whether 2 int arrays are the same
  • ArrayEqualsStr(a []int, b []int) bool - checks whether 2 string arrays are the same
  • ArrayReverse[T any](arr []T) []T - returns a new reversed array
arr := []string{"one", "two", "three"}
newArr := ArrayReverse(arr)
// newArr is: []string{"three", "two", "one"}
  • ArrayToArrayAny[T any](arr []T) []any - converts an array of any type to array of interfaces
  • IsStringArrayEqual(a, b []string) bool - Deprecated. new code should use ArrayEqualsStr

Email Functions

  • EmailSend(from string, to []string, subject string, htmlMessage string) (bool, error)

Environment Variables Functions

  • AppAddress() string - returns the URL address the app is running under (APP_URL:APP:PORT)
  • AppEnv() string - returns the environment the app is running in (APP_ENV)
  • AppInDevelopment() bool - return whether app is in development
  • AppInLive() bool - return whether app is in production / live
  • AppInProduction() bool - return whether app is in production / live
  • AppInTesting() bool - return whether app is being tested
  • AppName() string - returns the name the app is running under (APP_NAME)
  • AppPort() string - returns the port the app is running under (APP_PORT)
  • AppURL() string - returns the URL the app is running under (APP_URL)
  • DbDriver() string - returns the database driver (DB_DRIVER)
  • DbHost() string - returns the database host (DB_HOST)
  • DbPort() string - returns the database port (DB_PORT)
  • DbDatabase() string - returns the database name driver (DB_DATABASE)
  • DbUsername() string - returns the database username (DB_USERNAME)
  • DbPassword() string - returns the database password (DB_PASSWORD)
  • EmailFromAddress() string - returns the mail from address (MAIL_FROM)
  • EmailFromName() string - returns the mail from name (MAIL_NAME)
  • Env(key string) string - returns an environment variable (i.e. Env("DB_DRIVER"))
  • EnvInitialize(key string) string - Initializes an .env file, if exists. Fails loudly if the file is invalid and cannot be parsed
utils.EnvInitialize()
  • EnvEncInitialize(password string)</> - Initializes an .env.vault file, if it exists
utils.EnvEncInitialize("abc")

File Functions

  • FileExists(filePath string) bool
  • FileGetContents(filename string) (string, error)
  • FilePutContents(filename string, data string, mode os.FileMode) error - writes a string to file
  • FileToBase64(filePath string) string - converts a file to Base64 encoded string
  • ImgToBase64Url(filePath string) string - converts an image file to Base64 encoded URL string

HTML Functions

This functionality is moved to github.com/gouniverse/htmlutils and can be used from there

HTTP Functions

  • IP(r *http.Request) string - Returns the IP address of the user
  • Req(r *http.Request, key string, defaultValue string) string - Returns a POST or GET value for a key, or default if not exists
  • ReqAll(r *http.Request) url.Values - Returns all request variables
  • ReqArray(r *http.Request, key string, defaultValue []string) []string - return an array for a key from the request
  • ReqMap(r *http.Request, key string) map[string]string - returns a map for a key from the request
  • RespondJSON(w http.ResponseWriter, response api.Response) - DEPRECATED. use https://github.com/gouniverse/api

Images

  • BytesToBase64Url(imgBytes []byte) string - converts bytes to Base64 encode URL string
  • ImgPlaceholderURL(width, height, text string) - returns a placeholder image
  • ImgToBase64Url(filePath string) string - converts an image file to Base64 encoded URL string
  • PicsumURL(width int, height int, opt PicsumURLOptions) - returns an image from the online service Lorem Picsum

Interface Functions

  • InterfaceToStringArray(v interface{}) []string
  • LinkWebsite() string

Map Functions

  • MapToColumn(inputMap []map[string]string, keyName string) []string - returns a column from map
  • MapToKeyValue(inputMap []map[string]string, keyName string, valueName string) map[string]string - returns a key-value array from an array of maps

String Functions

  • AddSlashes(str string) string - adds slashes
  • Base64Decode(src string) ([]byte, error) - decodes a string from Base64
  • Base64Encode(src []byte) string - encodes a string to Base64
  • StrBetween(str string, startNeedle string, endNeedle string) (result string, found bool) - returns the substring between two needles
  • StrContainsOnlySpecifiedCharacters(str string, chars string) bool - checks string contains character from the specified in the chars parameter
  • StrLeftFrom(s string, needle, string) string - returns the substring on the left side of the needle
  • StrPadLeftFrom(s string, padLength int, pad string) string - returns the string padded on the left side
  • StrRandom(len int) string - generates a random string
  • StrRandomFromGamma(length int, gamma string) string - generates random string of specified length with the characters specified in the gamma string
  • StrRightFrom(s string, needle, string) string - returns the substring on the right side of the needle
  • StrSlugify(s string, replaceWith rune) string - converts a string to slug
  • StrToBcryptHash(str string) (string, error) - converts a string to bcrypt hash
  • StrToBcryptHashCompare(str string, hash string) - compares a string to a bcrypt hash
  • StrToFloat(s string) (int, error) - converts a string to Float32
  • StrToFloat64(s string) (int64, error) - converts a string to Float64
  • StrToInt(s string) (int, error) - converts a string to Int32
  • StrToInt64(s string) (int64, error) - converts a string to Int64
  • StrToMD5Hash(text string) string - StrToMD5Hash converts a string to MD5 hash
  • StrToSHA1Hash(text string) string - StrToSHA1Hash converts a string to SHA1 hash
  • StrToSHA256Hash(text string) string - converts a string to SHA256 hash
  • TemplateParseString(template string, data) string - parses a template file and returns as string
  • ToString(v interface{}) string - converts an interface to string

Time Functions

  • StrToTimeUnix(str string) (int64, error) - converts string to Unix time
time, err := StrToTimeUnix("2020-12-29 11:00:00")

Other Functions

  • ArgsToMap([]string) map[string]string - converts an CLI arguments array to map
  • CookieGet(r *http.Request, name string) string - gets a cookie
  • CookieRemove(w http.ResponseWriter, r *http.Request, name string) - removes a cookie
  • CookieSet(w http.ResponseWriter, r *http.Request, name string, value string, seconds int) - sets a cookie
  • Exec(cms string, args... string) map[string]string - executes a CLI command
  • ExecLine(cmd string) map[string]string - executes a full CLI command
  • IsInt(s string) bool - checks if a string is integer
  • IsFloat(s string) bool - checks if a string is float
  • IsJSON(s string) bool - naive implementation for rough and fast check if a string is JSON
  • IsNumeric(s string) bool - checks if a string is numeric
  • IsZero[T comparable](v T) bool
  • FromJSON(jsonString string, valueDefault interface{}) (interface{}, error) - JSON decodes a string
  • RandBool() bool - returns a random boolean value
random := RandBool()
  • ToJSON(value interface{}) (string, error) - JSON encodes a value
  • ToBool(str string) bool - converts a string with common names ("yes", "true", "1") to boolean
  • ZeroT any (ret T)
isDebugEnabled := ToBool("yes")
  • ToFloat(value str) (float64, error) - converts a string to float
  • ToInt(value str) (int64, error) - converts a string to int
  • XOREncode(buffer []byte, key []byte) []byte - XOR encodes a byte array
  • XORDencode(buffer []byte, key []byte) []byte - XOR decodes a byte array

Change Log

2024-02-10 - Added EnvEncInitialize functions

2024-01-20 - Added RandBool, ReqMap, BytesToBase64Url functions

2023-10-13 - Added function IsJSON, IsZero, Zero, removed deprecations

2023-01-27 - Added function PicsumURL

2022-09-10 - Added function StrContainsOnlySpecifiedCharacters

2022-08-28 - Added function StrToInt, StrToInt64, StrToFloat, StrToFloat64

2022-08-27 - Added function ToInt, ToFloat, IsInt, IsFloat, IsEmpty

2022-08-17 - Added functions ImgPlaceholderURL

2022-08-11 - Added functions StrToBcryptHash, StrToBcryptHashCompare

2022-08-06 - Added function ToBool

2022-08-04 - Added functions CookieGet, CookieSet, FromJSON, ToJSON, XORDecode, XOREncode

2022-08-02 - Added function ArrayReverse

2022-07-31 - Added functions ArrayEqualsInt, ArrayEqualsStr

2022-07-30 - Added functions StrBetween, StrRandom, StrRandomFromGamma, StrToBytes. Deprecated RandStr, RandStrFromGamma

2022-07-28 - Added functions StrLeftFrom, StrRightFrom

2022-06-01 - Moved Fiber functions into separate repo to remove extra dependencies on Fiber

2021-07-19 - Added functions AppInDevelopment, AppInLive, AppInProduction, AppInTesting

Other Similar Utility Libraries

Consider To Include (May Be)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddSlashes added in v1.4.5

func AddSlashes(str string) string

AddSlashes returns a string with backslashes added before characters that need to be escaped.

These characters are: single quote (') double quote (") backslash (\)

func AppAddress added in v1.2.1

func AppAddress() string

AppAddress return the full URL and PORT for the app

func AppEnv added in v1.2.1

func AppEnv() string

AppEnv returns the environment the app is running in

func AppInDevelopment added in v1.14.0

func AppInDevelopment() bool

AppInDevelopment return whether app is in development

func AppInLive added in v1.14.0

func AppInLive() bool

AppInProduction return whether app is in production / live

func AppInProduction added in v1.14.0

func AppInProduction() bool

AppInProduction return whether app is in production / live

func AppInTesting added in v1.14.0

func AppInTesting() bool

AppInTesting return whether app is being tested

func AppName added in v1.2.1

func AppName() string

AppName return the name for the app

func AppPort added in v1.2.1

func AppPort() string

AppPort return the port for the app

func AppURL added in v1.2.1

func AppURL() string

AppURL return the URL for the app

func ArgsToMap added in v1.29.0

func ArgsToMap(args []string) map[string]string

ArgsToMap converts command line arguments to a key value map supports filled (i.e. --user=12) and unfilled (i.e. --force) arguments

func ArrayContains added in v1.3.7

func ArrayContains(array interface{}, val interface{}) (exists bool, index int)

ArrayContains checks whether an array contains the specified value

func ArrayEqualsInt added in v1.18.0

func ArrayEqualsInt(a []int, b []int) bool

ArrayEquals checks whether 2 string arrays are the same

func ArrayEqualsStr added in v1.18.0

func ArrayEqualsStr(a, b []string) bool

ArrayEquals checks whether 2 string arrays are the same

func ArrayMerge added in v1.7.0

func ArrayMerge(array ...[]interface{}) []interface{}

ArrayMerge merges two arrays

func ArrayReverse added in v1.19.0

func ArrayReverse[T any](arr []T) []T

ArrayReverse creates a new reversed array

func ArrayToArrayAny added in v1.31.0

func ArrayToArrayAny[T any](arr []T) []any

ArrayToArrayAny converts an array of any type to array of interfaces

func ArrayUnique added in v1.22.0

func ArrayUnique(strSlice []string) []string

TODO. ArrayUnique removes duplicate strings from a string slice

func Base64Decode added in v1.13.0

func Base64Decode(src string) ([]byte, error)

Base64Encode decodes a string from Base64

func Base64Encode added in v1.13.0

func Base64Encode(src []byte) string

Base64Encode encodes a string to Base64

func BytesToBase64Url added in v1.38.0

func BytesToBase64Url(imgBytes []byte) string

func CookieGet added in v1.20.0

func CookieGet(r *http.Request, name string) string

func CookieRemove added in v1.35.0

func CookieRemove(w http.ResponseWriter, r *http.Request, name string)

func CookieSet added in v1.20.0

func CookieSet(w http.ResponseWriter, r *http.Request, name string, value string, seconds int)

func DbDatabase added in v1.2.2

func DbDatabase() string

DbDatabase return the name of the database

func DbDriver added in v1.2.2

func DbDriver() string

DbDriver returns the driver of the database

func DbHost added in v1.2.2

func DbHost() string

DbHost return the host of the database

func DbPassword added in v1.2.2

func DbPassword() string

DbPassword return the password for the database

func DbPort added in v1.2.2

func DbPort() string

DbPort return the port of the database

func DbQuery added in v1.22.0

func DbQuery(db *sql.DB, query string) (result map[int]map[string]string, err error)

DbQuery executes a SQL query and returns array of key value maps

func DbUsername added in v1.2.2

func DbUsername() string

DbUsername return the username of the database

func EmailFromAddress added in v1.2.1

func EmailFromAddress() string

EmailFromAddress return the URL for the app

func EmailFromName added in v1.2.1

func EmailFromName() string

EmailFromName return the URL for the app

func EmailSend added in v1.3.5

func EmailSend(from string, to []string, subject string, htmlMessage string) (bool, error)

EmailSend sends an email

func Env added in v1.2.1

func Env(key string) string

Env returns the value for an environment key

func EnvEncInitialize added in v1.39.0

func EnvEncInitialize(password string)

func EnvInitialize added in v1.4.7

func EnvInitialize()

EnvInitialize initializes the environment variables

func Exec added in v1.35.0

func Exec(cmd string, args ...string)

Exec executes a system command using the the standard package "os/exec".

func ExecLine added in v1.35.0

func ExecLine(cmd string)

ExecLine executes a full system command line string containing the arguments using for the standard package "os/exec".

func FileExists added in v1.2.4

func FileExists(filePath string) bool

FileExists checks if a file exists

func FileGetContents added in v1.2.4

func FileGetContents(filename string) (string, error)

FileGetContents reads entire file into a string

func FilePutContents added in v1.5.0

func FilePutContents(filename string, data string, mode os.FileMode) error

FilePutContents adds content to file

func FileSaveToTempDir added in v1.35.0

func FileSaveToTempDir(fileName string, file multipart.File) (string, error)

func FileToBase64 added in v1.4.12

func FileToBase64(filePath string) string

FileToBase64 converts a file to Base64 encoded string

func FromJSON added in v1.20.0

func FromJSON(jsonString string, valueDefault interface{}) (interface{}, error)

func IP added in v1.8.0

func IP(r *http.Request) string

IP gets the IP address for the user

func ImgPlaceholderURL added in v1.25.0

func ImgPlaceholderURL(width int, height int, text string) string

ImgPlaceholderURL returns a placeholder image

func ImgToBase64Url added in v1.4.12

func ImgToBase64Url(filePath string) string

ImgToBase64Url converts an image file to Base64 encoded URL string

func InArray added in v1.2.1

func InArray(val interface{}, array interface{}) (index int)

TODO. Update ArrayContents to use this style as its more readable

func InterfaceToStringArray added in v1.4.1

func InterfaceToStringArray(v interface{}) []string

InterfaceToStringArray converts an interface to String array

func IsEmpty added in v1.26.0

func IsEmpty(str string) bool

IsEmpty checks if the string is empty

func IsFloat added in v1.26.0

func IsFloat(str string) bool

IsFloat checks if the string is a float.

func IsInt added in v1.26.0

func IsInt(str string) bool

IsInt checks if the string is an integer. Empty string is valid.

func IsJSON added in v1.33.0

func IsJSON(str string) bool

IsJSON is naive implementation for superficial, rough and fast checking for JSON

func IsNumeric added in v1.3.5

func IsNumeric(s string) bool

IsNumeric checks if a string is numeric

func IsStringArrayEqual added in v1.4.1

func IsStringArrayEqual(a, b []string) bool

IsStringArrayEqual checks whether 2 string arrays are the same

func IsZero added in v1.34.0

func IsZero[T comparable](v T) bool

func JSONDecode added in v1.27.0

func JSONDecode(jsonString string, valueDefault interface{}) (interface{}, error)

JSONDecode shortcode for FromJSON

func JSONEncode added in v1.27.0

func JSONEncode(value interface{}) (string, error)

JSONEncode shortcut to ToJSON

func LinkWebsite added in v1.3.1

func LinkWebsite() string

LinkWebsite returns a URL to the current website

func MapToColumn added in v1.3.2

func MapToColumn(inputMap []map[string]string, keyName string) []string

MapToColumn Returns a column from map

func MapToKeyValue added in v1.3.2

func MapToKeyValue(inputMap []map[string]string, keyName string, valueName string) map[string]string

MapToKeyValue returns a key-value array an array of maps

func PicsumURL added in v1.28.0

func PicsumURL(width int, height int, opt PicsumURLOptions) string

PicsumURL generates an image URL for the Lorem Picsum online service More info can be found at its website: https://picsum.photos/

func PxToString added in v1.33.0

func PxToString(px int) string

PxToString converts int to string (i.e. 1px)

func RandBool added in v1.38.0

func RandBool() bool

RandBool returns a random boolean value

func Req added in v1.3.5

func Req(r *http.Request, key string, defaultValue string) string

Req returns a POST or GET key, or default if not exists

func ReqAll added in v1.37.0

func ReqAll(r *http.Request) url.Values

ReqAll returns all request variables

func ReqArray added in v1.32.0

func ReqArray(r *http.Request, key string, defaultValue []string) []string

func ReqMap added in v1.38.0

func ReqMap(r *http.Request, key string) map[string]string

ReqMap returns a map from the request

func RespondJSON added in v1.4.10

func RespondJSON(w http.ResponseWriter, response api.Response)

RespondJSON returns an API response as JSON

func StrBetween added in v1.17.0

func StrBetween(str string, startNeedle string, endNeedle string) (result string, found bool)

StrBetween returns the string between two needles

func StrContainsOnlySpecifiedCharacters added in v1.27.0

func StrContainsOnlySpecifiedCharacters(str string, chars string) bool

func StrLeftFrom added in v1.16.0

func StrLeftFrom(str, needle string) string

StrLeftFrom returns the substring on the left side of the needle

func StrPadLeft added in v1.24.0

func StrPadLeft(input string, padLength int, padString string) string

func StrRandom added in v1.17.0

func StrRandom(length int) string

StrRandom generates random string of specified length

func StrRandomFromGamma added in v1.17.0

func StrRandomFromGamma(length int, gamma string) string

StrRandomFromGamma generates random string of specified length with the characters specified in the gamma string

func StrRightFrom added in v1.16.0

func StrRightFrom(str, needle string) string

StrRightFrom returns the substring on the left side of the needle

func StrSlugify added in v1.18.0

func StrSlugify(s string, replaceWith rune) string

StrSlugify replaces each run of characters which are not ASCII letters or numbers with the Replacement character, except for leading or trailing runs. Letters will be stripped of diacritical marks and lowercased. Letter or number codepoints that do not have combining marks or a lower-cased variant will be passed through unaltered.

func StrToBcryptHash added in v1.22.0

func StrToBcryptHash(str string) (string, error)

StrToBcryptHash converts the string to bcrypt hash

func StrToBcryptHashCompare added in v1.22.0

func StrToBcryptHashCompare(str string, hash string) bool

StrToBcryptHashCompare compares the string to a bcrypt hash

func StrToBytes added in v1.17.0

func StrToBytes(s string) []byte

StrToBytes converts string to bytes

func StrToFloat added in v1.26.0

func StrToFloat(s string) (float32, error)

StrToFloat converts a string to Float32

func StrToFloat64 added in v1.26.0

func StrToFloat64(s string) (float64, error)

StrToFloat64 converts a string to Float64

func StrToInt added in v1.7.0

func StrToInt(s string) (int, error)

StrToInt converts a string to Int32

func StrToInt64 added in v1.7.0

func StrToInt64(s string) (int64, error)

StrToInt64 converts a string to Int64

func StrToMD5Hash added in v1.13.0

func StrToMD5Hash(text string) string

StrToMD5Hash converts a string to MD5 hash

func StrToSHA1Hash added in v1.13.0

func StrToSHA1Hash(text string) string

StrToSHA1Hash converts a string to SHA1 hash

func StrToSHA256Hash added in v1.13.0

func StrToSHA256Hash(text string) string

StrToSHA256Hash converts a string to SHA256 hash

func StrToTimeUnix added in v1.7.0

func StrToTimeUnix(str string) (int64, error)

StrToTimeUnix converts sting to Unix time

func TemplateParseString

func TemplateParseString(templateString string, data interface{}) string

TemplateParseString parses a template string with the passed data

func ToBool added in v1.21.0

func ToBool(str string) bool

ToBool converts a string with common names ("yes", "true", "1") to boolean

func ToFloat added in v1.26.0

func ToFloat(value interface{}) (res float64, err error)

ToFloat convert the input string to a float, or 0.0 if the input is not a float.

func ToInt added in v1.26.0

func ToInt(value interface{}) (res int64, err error)

ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer.

func ToJSON added in v1.20.0

func ToJSON(value interface{}) (string, error)

func ToString added in v1.6.0

func ToString(v interface{}) string

ToString converts an interface to string

func Unlink(filename string) error

Unlink deletes a file

func XORDencode added in v1.20.0

func XORDencode(buffer []byte, key []byte) []byte

func XOREncode added in v1.20.0

func XOREncode(buffer []byte, key []byte) []byte

func Zero added in v1.34.0

func Zero[T any]() (ret T)

Types

type PicsumURLOptions added in v1.28.0

type PicsumURLOptions struct {
	ID        int
	Blur      int // 1 to 10
	Grayscale bool
	Seed      string // if you want random image (but staying the same)
}

Jump to

Keyboard shortcuts

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