A Set of useful functions for working with files, errors and strings.
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")
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
},
)
Check if slice contains item.
// Signature:
func Contains[T comparable](items []T, item T) bool
// Example:
res := Contains[string](items, "john")
Return fallback if value is empty.
// Signature:
func Alter[T comparable](value T, fallback T) T
// Example:
name := ""
res := Alter(name, "John") // "John"
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!
Check if error has tag.
// Signature:
IsErrorOf(tag string, err error) bool
// Example:
IsErrorOf("MyLib", err) // true
Check if error is nil or not.
// Signature:
HasError(err error) bool
Generate panic from error if error not nil.
// Signature:
PanicOnError(err error)
Get function result (T, error), panic error if result has error and return T otherwise.
// Signature:
VarOrPanic[T any](res T, err error) T
Log data to output using json format.
// Signature
PrettyLog(data any)
Log data to output using json format with indent.
// Signature
PrettyLogIndent(data any)
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")
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")
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
Delete all files and sub-directory in directory.
// Signature:
ClearDirectory(dir string) error
Get list of sub directories.
// Signature:
GetSubDirectory(dir string) ([]string, error)
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
Detect file mime info from content
// Signature:
DetectMime(data []byte) *mimetype.MIME
// Example:
if mime := DetectMime(myFileData); mime != nil {
// do something
}
Get file extension.
// Signature:
Extension(file string) string
// Example
Extension("file") // ""
Extension("file.JPG") // ".jpg"
Extension("file.png") // ".png"
Extension("file.") // "."
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")
Extract numbers from string.
import "github.com/gomig/utils"
numbers := utils.ExtractNumbers("(+1) 234-56789") // => 123456789
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"
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 مجتبی"
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"
Generate random string from Alpha-Num Chars
import "github.com/gomig/utils"
str, err := utils.RandomString(5) // => "AB5S2"
Generate dash separated string.
import "github.com/gomig/utils"
str := utils.Slugify("welcome to", "my site") // => "welcome-to-my-site"
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-گچپژ"
Join strings with separator.
// Signature:
ConcatStr(sep string, str ...string) string
// Example:
import "github.com/gomig/utils"
str := utils.ConcatStr(" ", "John", "", "Doe") // => "John Doe"
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]"