utils

package module
v1.8.9 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2023 License: MIT Imports: 14 Imported by: 13

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")

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/bopher/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/bopher/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/bopher/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/bopher/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/bopher/utils"
files := utils.NumberedFile("path/to/dist", "my-file" ,"tempfile-abcd.zip")

String

ExtractNumbers

Extract numbers from string.

import "github.com/bopher/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/bopher/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/bopher/utils"
numbers := utils.ExtractAlphaNumPersian("My name is: مجتبی", " ") // => "My name is مجتبی"
RandomStringFromCharset

Generate random string from character list.

import "github.com/bopher/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/bopher/utils"
str, err := utils.RandomString(5) // => "AB5S2"
Slugify

Generate dash separated string.

import "github.com/bopher/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/bopher/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/bopher/utils"
str := utils.ConcatStr(" ", "John", "", "Doe") // => "John Doe"
FormatNumber

Format number with comma separator.

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

Jsoner

Utility function for marshal json with pattern. you can filter nested field with path using . separator (e.g. user.address will apply pattern to {"user" : { "address" : {...} } }.

NOTE: use "." as path pattern for root object.

NOTE: you can use "JsonerIndent" method to generate json with indent.

import "github.com/bopher/utils"
type Book struct {
    Title string
    ISBN  string `json:"isbn"`
}
type Author struct {
    Name      string `json:"name"`
    Family    string `json:"family"`
    Age       int    `json:"age,string,omitempty"`
    IsMariage bool   `json:",string"`
    Books     []Book `json:"author_books"`
    Skills    []string
    // ignored fields
    PrivateField string `json:"-"`
    ignored      string
}

john := Author{
    Name: "John",
    Family: "Doe",
    Age: 0,
    IsMariage: false,
    Books: []Book{
        {Title: "Basics Of C", ISBN: "12345"},
        {Title: "Golang", ISBN: "88888"},
    },
    Skills: []string{"Web dev", "System programming", "IOT"},
    PrivateField: "Some private information",
    ignored: "i'm ignored"
}
options := map[string]utils.JsonerOption{
    ".":            {Ignore: []string{"family"}}, // ignore family field from root struct
    "author_books": {Only: []string{"title"}},    // only marshal title field of author books
}
bytes, _ := utils.Jsoner(john, options)
fmt.Println(string(bytes))

/*
{
   "author_books": [
      {
         "Title": "Basics Of C"
      },
      {
         "Title": "Golang"
      }
   ],
   "IsMariage": "false",
   "name": "John",
   "Skills": [
      "Web dev",
      "System programming",
      "IOT"
   ]
}
*/

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClearDirectory

func ClearDirectory(dir string) error

ClearDirectory delete all files and sub-directory in directory

func ConcatStr added in v1.2.0

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

ConcatStr join strings with separator

func Contains added in v1.7.1

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

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

DetectMime detect file mime info from content

func ErrorOf added in v1.7.8

func ErrorOf(res any, err error) error

ErrorOf get error of function result

func Extension added in v1.6.1

func Extension(file string) string

Extension get file extension

func ExtractAlphaNum added in v1.6.3

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

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

func ExtractAlphaNumPersian added in v1.6.3

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

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

FormatNumber format number with comma separator

func FormatRx added in v1.7.6

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

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

func IsErrorOf(tag string, err error) bool

IsErrorOf check if error has tag

func Jsoner added in v1.8.0

func Jsoner(v any, opt map[string]JsonerOption) ([]byte, error)

Jsoner marshal json with dynamic ignores

you must pass path of json data as key and options as value. e.g. option to marshal isbn and title of author book, map[string]JsonerOption{"author.book": JsonerOption{Only: []string{"isbn", "title"}}} "." path used for root

func JsonerIndent added in v1.8.2

func JsonerIndent(v any, indent string, opt map[string]JsonerOption) ([]byte, error)

func NumberedFile added in v1.7.5

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

func PrettyLog(data any)

PrettyLog log data to output using json format

func PrettyLogIndent added in v1.7.7

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

func Slugify(str ...string) string

Slugify make slugify string

func SlugifyPersian added in v1.6.3

func SlugifyPersian(str ...string) string

SlugifyPersian make slugify string for persian string

func TaggedError added in v1.3.0

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

TaggedError generate a tagged error

func Try added in v1.7.4

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

Try simulate try catch block

func VarOrPanic added in v1.7.2

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

type JsonerOption added in v1.8.0

type JsonerOption struct {
	Only   []string
	Ignore []string
}

Jump to

Keyboard shortcuts

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