utils

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2023 License: ISC Imports: 13 Imported by: 15

README

Utils

A Set of useful functions for working with files, errors and strings.

Functions

If

Generate quick if result.

// Signature:
func If[T any](cond bool, yes T, no T) T

// Example:
res := If[string](name == "john", "it's john", "anonymous")
Try

Simulate try catch block.

// Signature:
func Try(e error, fail func(e error), pass func(), finally ...func(e error))

// Example:
Try(
    someErr,
    func(e) {
        // e error happend!
    },
    func() {
        // no error happend
    },
    func(e) {
        // call on all state
    },
)
Contains

Check if slice contains item.

// Signature:
func Contains[T comparable](items []T, item T) bool

// Example:
res := Contains[string](items, "john")
Alter

Return fallback if value is empty.

// Signature:
func Alter[T comparable](value T, fallback T) T

// Example:
name := ""
res := Alter(name, "John") // "John"

Error

TaggedError

Generate a tagged error.

// Signature:
TaggedError(tags []string, format string, args ...any) error

// Example:
TaggedError([]string{"MyLib","MyMethod"}, "failed on %s file!", "main.json")
// [MyLib] [MyMethod] failed on main.json file!
IsErrorOf

Check if error has tag.

// Signature:
IsErrorOf(tag string, err error) bool

// Example:
IsErrorOf("MyLib", err) // true
HasError

Check if error is nil or not.

// Signature:
HasError(err error) bool
PanicOnError

Generate panic from error if error not nil.

// Signature:
PanicOnError(err error)
VarOrPanic

Get function result (T, error), panic error if result has error and return T otherwise.

// Signature:
VarOrPanic[T any](res T, err error) T
PrettyLog

Log data to output using json format.

// Signature
PrettyLog(data any)
PrettyLogIndent

Log data to output using json format with indent.

// Signature
PrettyLogIndent(data any)

File

FileExists

Check if file exists or not.

// Signature:
FileExists(path string) (bool, error)

// Example:
import "github.com/gomig/utils"
exists, err := utils.FileExists("path/to/file")
IsDirectory

Check if path is a directory.

// Signature:
IsDirectory(path string) (bool, error)

// Example
import "github.com/gomig/utils"
ok, err := utils.IsDirectory("path/to/dir")
FindFile

Search for files in directory by a regex pattern.

// Signature:
FindFile(dir string, pattern string) []string

// Example:
import "github.com/gomig/utils"
files := utils.FindFile("path/to/dir", ".+\.sql") // => Get All file with sql extension
ClearDirectory

Delete all files and sub-directory in directory.

// Signature:
ClearDirectory(dir string) error
GetSubDirectory

Get list of sub directories.

// Signature:
GetSubDirectory(dir string) ([]string, error)
CreateDirectory

Create nested directory.

// Signature:
CreateDirectory(path string) error

// Example:
import "github.com/gomig/utils"
err := utils.CreateDirectory("a/b/c/d") // => Create all a, b, c and d directory
DetectMime

Detect file mime info from content

// Signature:
DetectMime(data []byte) *mimetype.MIME

// Example:
if mime := DetectMime(myFileData); mime != nil {
    // do something
}
Extension

Get file extension.

// Signature:
Extension(file string) string

// Example
Extension("file") // ""
Extension("file.JPG") // ".jpg"
Extension("file.png") // ".png"
Extension("file.") // "."
NumberedFile

Generate unique numbered file until 10000000, e.g. file.txt file-1.txt, file-2.txt

// Signature:
NumberedFile(dir, name, file string) (string, error)

// Example:
import "github.com/gomig/utils"
files := utils.NumberedFile("path/to/dist", "my-file" ,"tempfile-abcd.zip")

String

ExtractNumbers

Extract numbers from string.

import "github.com/gomig/utils"
numbers := utils.ExtractNumbers("(+1) 234-56789") // => 123456789
ExtractAlphaNum

Extract alpha and numbers from string [a-zA-Z0-9]. You can add extra character to add in extraction.

import "github.com/gomig/utils"
numbers := utils.ExtractAlphaNum("this is a: 123", ":") // => "thisisa:123"
ExtractAlphaNumPersian

Extract persian alpha, alpha and numbers from string [ا-یa-zA-Z0-9]. You can add extra character to add in extraction.

import "github.com/gomig/utils"
numbers := utils.ExtractAlphaNumPersian("My name is: مجتبی", " ") // => "My name is مجتبی"
RandomStringFromCharset

Generate random string from character list.

import "github.com/gomig/utils"
str, err := utils.RandomStringFromCharset(5, "1234567890") // => "59102"
str2, err2 := utils.RandomStringFromCharset(3, "ABCDEFGH") // => "DFC"
RandomString

Generate random string from Alpha-Num Chars

import "github.com/gomig/utils"
str, err := utils.RandomString(5) // => "AB5S2"
Slugify

Generate dash separated string.

import "github.com/gomig/utils"
str := utils.Slugify("welcome to", "my site") // => "welcome-to-my-site"
SlugifyPersian

Make slugify string for persian string. this function only keep persian alphabet, a-z, A-Z and 0-9 characters.

import "github.com/gomig/utils"
str := utils.SlugifyPersian("خوش آمدید \n \r \t - to گچپژ") // => "خوش-آمدید-to-گچپژ"
ConcatStr

Join strings with separator.

// Signature:
ConcatStr(sep string, str ...string) string

// Example:
import "github.com/gomig/utils"
str := utils.ConcatStr(" ", "John", "", "Doe") // => "John Doe"
FormatNumber

Format number with comma separator.

import "github.com/gomig/utils"
func FormatNumber(format string, v ...any) string {
str := utils.FormatNumber("$ %d [total] $ %d [remain]", 10000, 2500) // => "$ 10,000 [total] $ 2,500 [remain]"

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Alter added in v1.0.1

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

Alter return fallback if value is empty

func ClearDirectory

func ClearDirectory(dir string) error

ClearDirectory delete all files and sub-directory in directory

func ConcatStr

func ConcatStr(sep string, str ...string) string

ConcatStr join strings with separator

func Contains

func Contains[T comparable](items []T, item T) bool

Contains check if slice contains item

func CreateDirectory

func CreateDirectory(path string) error

CreateDirectory create nested directory

func DetectMime

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

DetectMime detect file mime info from content

func ErrorOf

func ErrorOf(res any, err error) error

ErrorOf get error of function result

func Extension

func Extension(file string) string

Extension get file extension

func ExtractAlphaNum

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

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

func ExtractAlphaNumPersian

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

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

func ExtractNumbers

func ExtractNumbers(str 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 find files in directory with pattern

func FormatNumber

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

FormatNumber format number with comma separator

func FormatRx

func FormatRx(data, pattern, repl string) string

FormatRx format string using regex pattern use () for group and $1, $2 for output placeholder example FormatRx("123456", `^(\d{3})(\d{2})(\d{1})$`, "($1) $2-$3")

func GetSubDirectory

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

GetSubDirectory get list of sub directories

func HasError

func HasError(err error) bool

HasError return true if error not nil, otherwise return false

func If

func If[T any](cond bool, yes T, no T) T

If generate quick if

func IsDirectory

func IsDirectory(path string) (bool, error)

IsDirectory check if path is directory

func IsErrorOf

func IsErrorOf(tag string, err error) bool

IsErrorOf check if error has tag

func NumberedFile

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

NumberedFile generate unique numbered file until 10000000, e.g. file.txt file-1.txt, file-2.txt

func PanicOnError

func PanicOnError(err error)

PanicOnError generate panic if error is not null

func PrettyLog

func PrettyLog(data any)

PrettyLog log data to output using json format

func PrettyLogIndent

func PrettyLogIndent(data any)

PrettyLogIndent log data to output using json format with indent

func RandomString

func RandomString(n uint) (string, error)

RandomString generate random string from Alpha-Num Chars

func RandomStringFromCharset

func RandomStringFromCharset(n uint, letters string) (res string, err error)

RandomStringFromCharset generate random string from character list

func Slugify

func Slugify(str ...string) string

Slugify make slugify string

func SlugifyPersian

func SlugifyPersian(str ...string) string

SlugifyPersian make slugify string for persian string

func TaggedError

func TaggedError(tags []string, format string, args ...any) error

TaggedError generate a tagged error

func Try

func Try(e error, fail func(e error), pass func(), finally ...func(e error))

Try simulate try catch block

func VarOrPanic

func VarOrPanic[T any](res T, err error) T

VarOrPanic get function result (T, error)

if result has error generate panic return T otherwise

Types

This section is empty.

Jump to

Keyboard shortcuts

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