utils

package module
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2021 License: MIT Imports: 10 Imported by: 13

README

Utils

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

Error

TaggedError

Generate a tagged error.

// Signature:
TaggedError(tags []string, format string, args ...interface{}) 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)
Handle Functions Return Value

This set of functions help you to handle output of function that have a return type with error value. this functions generate panic on error or return value. You can use this functions instead of if else block for checking error.

// Signature:
UIntOrPanic(res uint, err error) uint
UInt8OrPanic(res uint8, err error) uint8
UInt16OrPanic(res uint16, err error) uint16
UInt32OrPanic(res uint32, err error) uint32
UInt64OrPanic(res uint64, err error) uint64
IntOrPanic(res int, err error) int
Int8OrPanic(res int8, err error) int8
Int16OrPanic(res int16, err error) int16
Int32OrPanic(res int32, err error) int32
Int64OrPanic(res int64, err error) int64
Float32OrPanic(res float32, err error) float32
Float64OrPanic(res float64, err error) float64
StringOrPanic(res string, err error) string
BoolOrPanic(res bool, err error) bool
InterfaceOrPanic(res interface{}, err error) interface{}

// Example:
import "github.com/bopher/utils"
func TestIt(a int, b int) (int, error) { ... }
res = utils.IntOrPanic(TestIt(1, 3))

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

String

ExtractNumbers

Extract numbers from string.

import "github.com/bopher/utils"
numbers := utils.ExtractNumbers("(+1) 234-56789") // => 123456789
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"
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"
str := utils.FormatNumber("total: $ %d", 12500000) // => "total: $ 12,500,000"

Mongo DB

MongoArray

Generate primitive.A array from args.

import "github.com/bopher/utils"
m := utils.MongoArray("John", "Kim", "Jimmy") // => ["John", "Kim", "Jimmy"]
MongoMap

Generate primitive.M structure from args. Args count must be even!

import "github.com/bopher/utils"
m := utils.MongoMap("_id", 1, "name", "John") // => { _id: 1, name: "John"}
MongoMaps

generate []primitive.M from args. Args count must be even!

import "github.com/bopher/utils"
m := utils.MongoMaps("_id", 1, "name", "John") // => [{ _id: 1}, {name: "John"}]
MongoDoc

Generate primitive.D from args. Args count must be even!

import "github.com/bopher/utils"
m := utils.MongoDoc("_id", 1, "name", "John") // => [{Key: "_id", Value: 1}, {Key: "name", Value: "John"}]
MongoOr

Generate mongo $or.

import "github.com/bopher/utils"
orCond := utils.MongoOr(utils.MongoMaps("_id", 1, "name", "John")) // => {$or: [{ _id: 1}, {name: "John"}]}
MongoAnd

Generate mongo $and.

import "github.com/bopher/utils"
andCond := utils.MongoAnd(utils.MongoMaps("_id", 1, "name", "John")) // => {$and: [{ _id: 1}, {name: "John"}]}
MongoIn

Generate mongo $in.

import "github.com/bopher/utils"
inCond := utils.MongoIn("name", []int{1,2,3}) // => {name: {$in: [1,2,3]}}
MongoSet

Generate mongo $set.

import "github.com/bopher/utils"
setVal := utils.MongoSet(utils.MongoMap("name", "John")) // => {$set: {name: "John"}}
MongoNestedSet

Generate nested mongo $set with key/value.

import "github.com/bopher/utils"
setVal := utils.MongoNestedSet("name", "John") // => {$set: {name: "John"}}
MongoMatch

Generate mongo $match.

import "github.com/bopher/utils"
match := utils.MongoMatch(utils.MongoMap("name", "John")) // => {$match: {name: "John"}}
MongoLimit

Generate mongo $limit.

import "github.com/bopher/utils"
limit := utils.MongoLimit(2) // => {$limit: 2}
MongoSort

Generate mongo $sort.

import "github.com/bopher/utils"
sorts := utils.MongoSort(utils.MongoMap({"_id", 1})) // => {$sort: {_id:1}}
MongoSkip

Generate mongo $skip.

import "github.com/bopher/utils"
sorts := utils.MongoSkip(30)) // => {$skip: 30}
MongoLookup

Generate mongo $lookup.

import "github.com/bopher/utils"
lookup := utils.MongoLookup("users", "user_id", "_id", "user"))
// => {
//     $lookup: {
//         from: "users",
//         localField: "user_id",
//         foreignField: "_id",
//         as: "user"
//     }
// }
MongoUnwind

Generate mongo $unwind (with preserveNull).

import "github.com/bopher/utils"
unwind := utils.MongoUnwind("invoices"))
// => {
//     $unwind: {
//         path: "invoices",
//         preserveNullAndEmptyArrays: true,
//     }
// }
MongoUnwrap

Get first item of array and insert to doc using $addFields.

import "github.com/bopher/utils"
unwrapped := utils.MongoUnwrap("logins", "first_login")) // => {$addFields: {first_login: {$first: logins}}}
MongoGroup

Generate mongo $group.

import "github.com/bopher/utils"
group := utils.MongoGroup(utils.MongoMap("_id", "$_id", "last_login", utils.MongoMap("$last", "$logins"))))
// => {
//     $group:{
//         _id: $_id,
//         last_login: {$last: $logins}
//     }
// }
MongoSetRoot

Generate mongo $replaceRoot.

import "github.com/bopher/utils"
setRoot := utils.MongoSetRoot("$_record")) // => {$replaceRoot: {newRoot: $_record}}
MongoMergeRoot

Generate $replaceRoot with $mergeObject.

import "github.com/bopher/utils"
mergeRoot := utils.MongoMergeRoot("$_record", "$$ROOT")) // => {$replaceRoot: {newRoot: {$mergeObjects: ["$_record", "$$ROOT"]}}}
MongoUnProject

Generate $project to remove fields from result.

import "github.com/bopher/utils"
unProject := utils.MongoUnProject("_record", "referral")) // => {$project: {_record:0, referral: 0 }}
ParseObjectID

Parse object id from string. This function return nil if object id is invalid!

import "github.com/bopher/utils"
oId := utils.ParseObjectID("6184011af9530d2ec143ae38")
IsValidOId

Check if object id is valid and not zero.

import "github.com/bopher/utils"
valid := utils.IsValidOId(oIdObject)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BoolOrPanic

func BoolOrPanic(res bool, err error) bool

BoolOrPanic get function result (bool, error) if error is not null generate panic otherwise return result

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 CreateDirectory

func CreateDirectory(path string) error

CreateDirectory create nested directory

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 Float32OrPanic

func Float32OrPanic(res float32, err error) float32

Float32OrPanic get function result (float32, error) if error is not null generate panic otherwise return result

func Float64OrPanic

func Float64OrPanic(res float64, err error) float64

Float64OrPanic get function result (float64, error) if error is not null generate panic otherwise return result

func FormatNumber added in v1.3.0

func FormatNumber(format string, value int64) string

FormatNumber format number with comma separator

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 Int16OrPanic

func Int16OrPanic(res int16, err error) int16

Int16OrPanic get function result (int16, error) if error is not null generate panic otherwise return result

func Int32OrPanic

func Int32OrPanic(res int32, err error) int32

Int32OrPanic get function result (int32, error) if error is not null generate panic otherwise return result

func Int64OrPanic

func Int64OrPanic(res int64, err error) int64

Int64OrPanic get function result (int64, error) if error is not null generate panic otherwise return result

func Int8OrPanic

func Int8OrPanic(res int8, err error) int8

Int8OrPanic get function result (int8, error) if error is not null generate panic otherwise return result

func IntOrPanic

func IntOrPanic(res int, err error) int

IntOrPanic get function result (int, error) if error is not null generate panic otherwise return result

func InterfaceOrPanic

func InterfaceOrPanic(res interface{}, err error) interface{}

InterfaceOrPanic get function result (interface{}, error) if error is not null generate panic otherwise return result

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

func IsValidOId(id *primitive.ObjectID) bool

IsValidOId check if object id is valid and not zero

func MongoAnd added in v1.2.0

func MongoAnd(v interface{}) primitive.D

MongoAnd generate $and

func MongoArray added in v1.3.0

func MongoArray(args ...interface{}) primitive.A

MongoArray generate primitive.A

func MongoDoc added in v1.2.0

func MongoDoc(args ...interface{}) primitive.D

MongoDoc generate primitive.D from args

Args count must even Example: MongoDoc("_id", 1, "name", "John")

func MongoGroup added in v1.2.0

func MongoGroup(fields interface{}) primitive.D

MongoGroup generate $group

func MongoIn added in v1.2.0

func MongoIn(k string, v interface{}) primitive.D

MongoIn generate $in

func MongoLimit added in v1.2.0

func MongoLimit(limit uint) primitive.D

MongoLimit generate $limit

func MongoLookup added in v1.2.0

func MongoLookup(from string, local string, foreign string, as string) primitive.D

MongoLookup generate $lookup

func MongoMap added in v1.2.0

func MongoMap(args ...interface{}) primitive.M

MongoMap generate primitive.M

Args count must even

func MongoMaps added in v1.2.0

func MongoMaps(args ...interface{}) []primitive.M

MongoMaps generate []primitive.M

Args count must even

func MongoMatch added in v1.2.0

func MongoMatch(v interface{}) primitive.D

MongoMatch generate $match

func MongoMergeRoot added in v1.2.0

func MongoMergeRoot(fields ...interface{}) primitive.D

MongoMergeRoot generate $replaceRoot with $mergeObject

func MongoNestedSet added in v1.2.0

func MongoNestedSet(k string, v interface{}) primitive.D

MongoNestedSet generate nested $set

func MongoOr added in v1.2.0

func MongoOr(v interface{}) primitive.D

MongoOr generate $or

func MongoSet added in v1.2.0

func MongoSet(v interface{}) primitive.D

MongoSet generate $set

func MongoSetRoot added in v1.2.0

func MongoSetRoot(newRoot interface{}) primitive.D

MongoSetRoot generate $replaceRoot

func MongoSkip added in v1.2.0

func MongoSkip(skip uint64) primitive.D

MongoSkip generate $skip

func MongoSort added in v1.2.0

func MongoSort(sorts interface{}) primitive.D

MongoSort generate $sort

func MongoUnProject added in v1.2.0

func MongoUnProject(fields ...string) primitive.D

MongoUnProject generate $project to remove fields from result

func MongoUnwind added in v1.2.0

func MongoUnwind(path string) primitive.D

MongoUnwind generate $unwind (with preserveNull)

func MongoUnwrap added in v1.2.0

func MongoUnwrap(field string, as string) primitive.D

MongoUnwrap get first item of array and insert to doc using $addFields.

func PanicOnError

func PanicOnError(err error)

PanicOnError generate panic if error is not null

func ParseObjectID added in v1.2.0

func ParseObjectID(id string) *primitive.ObjectID

ParseObjectID parse object id from string

@returns ObjectID @fail nil

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 StringOrPanic

func StringOrPanic(res string, err error) string

StringOrPanic get function result (string, error) if error is not null generate panic otherwise return result

func TaggedError added in v1.3.0

func TaggedError(tags []string, format string, args ...interface{}) error

TaggedError generate a tagged error

func UInt16OrPanic

func UInt16OrPanic(res uint16, err error) uint16

UInt16OrPanic get function result (uint16, error) if error is not null generate panic otherwise return result

func UInt32OrPanic

func UInt32OrPanic(res uint32, err error) uint32

UInt32OrPanic get function result (uint32, error) if error is not null generate panic otherwise return result

func UInt64OrPanic

func UInt64OrPanic(res uint64, err error) uint64

UInt64OrPanic get function result (uint64, error) if error is not null generate panic otherwise return result

func UInt8OrPanic

func UInt8OrPanic(res uint8, err error) uint8

UInt8OrPanic get function result (uint8, error) if error is not null generate panic otherwise return result

func UIntOrPanic

func UIntOrPanic(res uint, err error) uint

UIntOrPanic get function result (uint, error) if error is not null generate panic otherwise return result

Types

This section is empty.

Jump to

Keyboard shortcuts

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