goutils

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2025 License: ISC Imports: 15 Imported by: 0

README

Go Utils Library

This library provides a collection of utility functions for Go, covering various domains such as pointers, numbers, strings, web, and file operations.

Installation

To install the library, use the following command:

go get github.com/mekramy/goutils

Usage

Pointer Utilities
PointerOf

Returns the pointer of a given value.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    value := 42
    ptr := goutils.PointerOf(value)
    fmt.Println(*ptr) // Output: 42
}
SafeValue

Returns the value of a pointer or an empty value if the pointer is nil.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    var ptr *int
    value := goutils.SafeValue(ptr)
    fmt.Println(value) // Output: 0
}
ValueOf

Returns the value of a pointer or a fallback value if the pointer is nil.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    var ptr *int
    value := goutils.ValueOf(ptr, 10)
    fmt.Println(value) // Output: 10
}
Alter

Returns the value of a pointer or a fallback value if the pointer is nil or zero.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    var ptr int
    value := goutils.Alter(ptr, 10)
    fmt.Println(value) // Output: 10
}
NullableOf

Returns nil if the value is zero.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    value := 0
    ptr := goutils.NullableOf(&value)
    fmt.Println(ptr) // Output: <nil>
}
IsEmpty

Checks if a pointer is nil or zero.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    var ptr *int
    isEmpty := goutils.IsEmpty(ptr)
    fmt.Println(isEmpty) // Output: true
}
IsSame

Checks if two pointer values are equal.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    a := 42
    b := 42
    isSame := goutils.IsSame(&a, &b)
    fmt.Println(isSame) // Output: true
}
Number Utilities
Abs

Returns the absolute value of a number.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    value := -42
    absValue := goutils.Abs(value)
    fmt.Println(absValue) // Output: 42
}
RoundUp

Returns the nearest larger integer (ceil).

package main

import (
    "fmt"
    "goutils"
)

func main() {
    value := 42.3
    roundedValue := goutils.RoundUp[int](value)
    fmt.Println(roundedValue) // Output: 43
}
Round

Returns the nearest integer, rounding half away from zero.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    value := 42.5
    roundedValue := goutils.Round[int](value)
    fmt.Println(roundedValue) // Output: 43
}
RoundDown

Returns the nearest smaller integer.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    value := 42.9
    roundedValue := goutils.RoundDown[int](value)
    fmt.Println(roundedValue) // Output: 42
}
Min

Returns the smallest value among the given numbers or zero.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    values := []int{42, 10, 56}
    minValue := goutils.Min(values...)
    fmt.Println(minValue) // Output: 10
}
Max

Returns the largest value among the given numbers or zero.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    values := []int{42, 10, 56}
    maxValue := goutils.Max(values...)
    fmt.Println(maxValue) // Output: 56
}
String Utilities
ExtractNumbers

Extracts numbers from a string.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    str := "abc123def"
    numbers := goutils.ExtractNumbers(str)
    fmt.Println(numbers) // Output: 123
}
ExtractAlphaNum

Extracts alphanumeric characters from a string.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    str := "abc123!@#"
    alphaNum := goutils.ExtractAlphaNum(str)
    fmt.Println(alphaNum) // Output: abc123
}
RandomString

Returns a random string from a character set.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    randomStr := goutils.RandomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    fmt.Println(randomStr) // Output: Random 10 character string
}
RandomNumeric

Returns a random numeric string.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    randomNum := goutils.RandomNumeric(10)
    fmt.Println(randomNum) // Output: Random 10 digit number
}
RandomAlphaNum

Returns a random alphanumeric string.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    randomAlphaNum := goutils.RandomAlphaNum(10)
    fmt.Println(randomAlphaNum) // Output: Random 10 character alphanumeric string
}
Slugify

Makes a URL-friendly slug from strings.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    slug := goutils.Slugify("Hello World!")
    fmt.Println(slug) // Output: hello-world
}
Concat

Returns concatenated non-empty strings with a separator.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    concatenated := goutils.Concat("-", "Hello", "", "World")
    fmt.Println(concatenated) // Output: Hello-World
}
FormatNumber

Formats a number with a comma separator.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    formatted := goutils.FormatNumber("%d Dollars", 100000)
    fmt.Println(formatted) // Output: 100,000 Dollars
}
FormatRx

Formats a string using a regex pattern.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    formatted, _ := goutils.FormatRx("123456", `(\d{3})(\d{2})(\d{1})`, "($1) $2-$3")
    fmt.Println(formatted) // Output: (123) 45-6
}
Web Utilities
RelativeURL

Returns the relative URL path of a file with respect to the root directory.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    relativeURL := goutils.RelativeURL("/root", "/root/path/to/file")
    fmt.Println(relativeURL) // Output: path/to/file
}
AbsoluteURL

Returns the absolute URL path of a file with respect to the root directory.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    absoluteURL := goutils.AbsoluteURL("/root", "/root/path/to/file")
    fmt.Println(absoluteURL) // Output: /path/to/file
}
SanitizeRaw

Sanitizes input to raw text.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    sanitized := goutils.SanitizeRaw("<script>alert('xss')</script> and more", true)
    fmt.Println(sanitized) // Output: and more
}
SanitizeCommon

Sanitizes input to HTML with common allowed tags.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    sanitized := goutils.SanitizeCommon("<b>bold</b><script>alert('xss')</script>", true)
    fmt.Println(sanitized) // Output: <b>bold</b>
}
File Utilities
NormalizePath

Joins and normalizes a file path.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    path := goutils.NormalizePath("/root", "path//to\\some", "file")
    fmt.Println(path) // Output: /root/path/to/some/file
}
CreateDirectory

Creates a nested directory.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    err := goutils.CreateDirectory("/path/to/dir")
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Directory created")
    }
}
IsDirectory

Checks if a path is a directory.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    isDir, err := goutils.IsDirectory("/path/to/dir")
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(isDir) // Output: true or false
    }
}
GetSubDirectory

Returns a list of subdirectories.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    subDirs, err := goutils.GetSubDirectory("/path/to/dir")
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(subDirs) // Output: [subdir1 subdir2 ...]
    }
}
ClearDirectory

Deletes all files and subdirectories in a directory.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    err := goutils.ClearDirectory("/path/to/dir")
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Directory cleared")
    }
}
FileExists

Checks if a file exists.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    exists, err := goutils.FileExists("/path/to/file")
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(exists) // Output: true or false
    }
}
FindFile

Searches a directory for a file with a pattern and returns the first file.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    file := goutils.FindFile("/path/to/dir", `admin[\d]*\.txt`)
    if file != nil {
        fmt.Println(*file) // Output: /path/to/dir/admin32.txt
    } else {
        fmt.Println("File not found")
    }
}
FindFiles

Searches a directory for files with a pattern.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    files := goutils.FindFiles("/path/to/dir", `user.*\.txt`)
    fmt.Println(files) // Output: [/path/to/dir/user23.txt /path/to/dir/userjohn.txt ...]
}
GetMime

Returns file MIME info from content.

package main

import (
    "fmt"
    "goutils"
    "os"
)

func main() {
    data, _ := os.ReadFile("/path/to/file.txt")
    mime := goutils.GetMime(data)
    fmt.Println(mime.String()) // Output: text/plain; charset=utf-8
}
GetExtension

Returns the file extension.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    ext := goutils.GetExtension("/path/to/file.txt")
    fmt.Println(ext) // Output: txt
}
GetFilename

Returns the file name without extension.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    filename := goutils.GetFilename("/path/to/file.txt")
    fmt.Println(filename) // Output: file
}
TimestampedFile

Returns a file name with a timestamp prefix.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    timestamped := goutils.TimestampedFile("file.txt")
    fmt.Println(timestamped) // Output: file-1633024800000.txt
}
NumberedFile

Generates a unique numbered file name.

package main

import (
    "fmt"
    "goutils"
)

func main() {
    numbered, err := goutils.NumberedFile("/path/to/dir", "file.txt")
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(numbered) // Output: file-1.txt
    }
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Abs

func Abs[T constraints.Integer | constraints.Float](x T) T

Abs returns the absolute value of x.

func AbsoluteURL

func AbsoluteURL(root string, path ...string) string

AbsoluteURL returns the absolute URL path of file with respect to the root directory.

func Alter

func Alter[T comparable](value *T, fallback T) T

Alter returns value of pointer or return fallback if value is nil or zero.

func ClearDirectory

func ClearDirectory(dir string) error

ClearDirectory delete all files and sub-directory in directory.

func Concat

func Concat(sep string, parts ...string) string

Concat return concatinated not-empty strings with separator.

func CreateDirectory

func CreateDirectory(path string) error

CreateDirectory create nested directory.

func ExtractAlphaNum

func ExtractAlphaNum(s string, includes ...string) string

ExtractAlphaNum extract alpha and numbers from string [a-zA-Z0-9].

func ExtractAlphaNumPersian

func ExtractAlphaNumPersian(s string, includes ...string) string

ExtractAlphaNumPersian extract english and persian alpha and numbers from string [ا-یa-zA-Z0-9].

func ExtractNumbers

func ExtractNumbers(s string) string

ExtractNumbers extract numbers from string.

func FileExists

func FileExists(path string) (bool, error)

FileExists check if file exists.

func FindFile

func FindFile(dir string, pattern string) *string

FindFile search directory for file with pattern and returns first file.

func FindFiles

func FindFiles(dir string, pattern string) []string

FindFiles search directory for files with pattern.

func FormatNumber

func FormatNumber(layout string, v ...any) string

FormatNumber format number with comma separator.

code block:

FormatNumber("%d Dollars", 100000)

output:

100,000 Dollars

func FormatRx

func FormatRx(data, pattern, repl string) (string, error)

FormatRx format string using regex pattern use () for match groups and $1, $2 for output placeholder.

code block:

FormatRx("123456", `(\d{3})(\d{2})(\d{1})`, "($1) $2-$3")

output:

(123) 45-6

func GetExtension

func GetExtension(file string) string

GetExtension returns file extension.

func GetFilename

func GetFilename(file string) string

GetFilename returns file name without extension.

func GetMime

func GetMime(data []byte) *mimetype.MIME

GetMime returns file mime info from content

func GetSubDirectory

func GetSubDirectory(dir string) ([]string, error)

GetSubDirectory returns list of sub directories.

func IsDirectory

func IsDirectory(path string) (bool, error)

IsDirectory check if path is directory

func IsEmpty

func IsEmpty[T comparable](value *T) bool

IsEmpty check if pointer is nil or zero.

func IsSame

func IsSame[T comparable](a, b *T) bool

IsSame check if two pointer value are equal.

func Max

func Max[T constraints.Integer | constraints.Float](numbers ...T) T

Max returns the largest value of numbers or zero.

func Min

func Min[T constraints.Integer | constraints.Float](numbers ...T) T

Min returns the smallest value of numbers or zero.

func NormalizePath

func NormalizePath(path ...string) string

NormalizePath join and normalize file path.

func NullableOf

func NullableOf[T comparable](v *T) *T

NullableOf return nil if value is zero.

func NumberedFile

func NumberedFile(dir, file string) (string, error)

NumberedFile generate unique numbered file name (e.g. file.txt file-1.txt, file-2.txt).

func PointerOf

func PointerOf[T any](value T) *T

PointerOf get pointer of value.

func RandomAlphaNum

func RandomAlphaNum(n uint) string

RandomAlphaNum returns random string from Alpha-Num uppercase characters.

func RandomNumeric

func RandomNumeric(n uint) string

RandomNumeric returns random numeric string.

func RandomString

func RandomString(n uint, characters string) string

RandomNumeric returns random string from character set.

func RelativeURL

func RelativeURL(root string, path ...string) string

RelativeURL returns the relative URL path of file with respect to the root directory.

func Round

func Round[T constraints.Integer](x float64) T

Round returns the nearest integer, rounding half away from zero.

func RoundDown

func RoundDown[T constraints.Integer](x float64) T

RoundDown returns the nearest small integer.

func RoundUp

func RoundUp[T constraints.Integer](x float64) T

RoundUp returns the nearest large integer (ceil).

func SafeValue

func SafeValue[T any](value *T) T

SafeValue get value of pointer or return empty value if pointer is nil.

func SanitizeCommon

func SanitizeCommon(data string, trim bool) string

SanitizeCommon sanitize input to html with common allowed tags.

func SanitizeRaw

func SanitizeRaw(data string, trim bool) string

SanitizeRaw sanitize input to raw text.

func Slugify

func Slugify(parts ...string) string

Slugify make url friendly slug from strings. Only Alpha-Num characters compiled to final result.

func SlugifyPersian

func SlugifyPersian(parts ...string) string

SlugifyPersian make url friendly slug from strings. Only english and persian alpha and numberic characters compiled to final result.

func TimestampedFile

func TimestampedFile(file string) string

TimestampedFile returns file name with timestamp prefix.

func ValueOf

func ValueOf[T any](value *T, fallback T) T

ValueOf get value of pointer or return fallback if value is nil.

Types

This section is empty.

Jump to

Keyboard shortcuts

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