gutil

package module
v0.0.0-...-64de879 Latest Latest
Warning

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

Go to latest
Published: May 25, 2022 License: MIT Imports: 26 Imported by: 64

README

Gutil contains Go utilities.

Install

go get github.com/kamva/gutil

Todo:

  • Use jsonp instead of json package to marshal and unmarshal jsons.
  • Tests
  • Add badges to readme.
  • CI

Documentation

Index

Constants

View Source
const (
	KeyFormatPKCS1 = 1
	KeyFormatPKCS8 = 2
	KeyFormatPKIX  = 3
)

Variables

This section is empty.

Functions

func AnyErr

func AnyErr(errors ...error) error

AnyErr returns first error that is not nil.

func AnyNil

func AnyNil(val ...interface{}) bool

AnyNil check if any value of provided values is nil, returns true, otherwise returns false.

func AnyString

func AnyString(values ...string) string

AnyString returns first found non-empty string value in the provided values.

func CauseErr

func CauseErr(err error) error

CauseErr returns the root error by unwrapping the errors chain

func Contains

func Contains(haystack []string, needle string) bool

Contains check that needle exists in the haystack or not.

func ExtendMap

func ExtendMap(dest, src map[string]interface{}, overwrite bool)

ExtendMap extend dest map by src map. overwrite argument set overwrite policy.

func ExtendStrMap

func ExtendStrMap(dest, src map[string]string, overwrite bool)

ExtendMap extend dest map by src map. overwrite argument set overwrite policy.

func FileExists

func FileExists(f string) bool

FileExists checks if a file exists and is not a directory before we try using it to prevent further errors.

func FormatDateStuckTogether

func FormatDateStuckTogether(t time.Time) string

func IP

func IP(r *http.Request) string

GetIP gets the provided requests IP address by reading off the forwarded-for header (for proxies) and falls back to use the remote address.

func IndirectType

func IndirectType(val interface{}) (reflect.Type, error)

IndirectType returns indirect value's reflection type.

func IndirectValue

func IndirectValue(value interface{}) interface{}

Indirect returns the value that the given interface or pointer references to. A boolean value is also returned to indicate if the value is nil or not (only applicable to interface, pointer, map, and slice). If the value is neither an interface nor a pointer, it will be returned back. reference: https://github.com/go-ozzo/ozzo-validation/blob/master/util.go

func InterfaceDefault

func InterfaceDefault(val, def interface{}) interface{}

InterfaceDefault returns value if it's not nil, otherwise returns the default value.

func InterfaceToSlice

func InterfaceToSlice(slice interface{}) []interface{}

InterfaceToSlice converts interface to slices. If provided value is not list, it will panic.

func Intersect

func Intersect(s1 []string, s2 []string) []string

Intersect returns intersect of two slices. e.g., intersect of [1,2,3] & [2,3,4] = [2,3]

func IsNil

func IsNil(val interface{}) (result bool)

IsNil function check value is nil or no. To check real value of interface is nil or not, should using reflection, check this https://play.golang.org/p/Isoo0CcAvr. Firstly check `val==nil` because reflection can not get value of zero val.

func KeyValuesToMap

func KeyValuesToMap(keyValues ...interface{}) (map[string]interface{}, error)

KeyValuesToMap convert each pair of slice to a key/value of map.

func MapToKeyValue

func MapToKeyValue(m map[string]interface{}) []interface{}

MapToKeyValue convert map to slice that contain map key and value pairs.

func MapToStruct

func MapToStruct(m map[string]interface{}, s interface{}) error

MapToStruct convert map to struct by json marshal and Unmarshal

func Marshal

func Marshal(in interface{}) ([]byte, error)

func Max

func Max(vars ...int) int

func Max64

func Max64(vars ...int64) int64

func MaxDuration

func MaxDuration(vars ...time.Duration) time.Duration

func Min

func Min(vars ...int) int

func Min64

func Min64(vars ...int64) int64

func MinDuration

func MinDuration(vars ...time.Duration) time.Duration

func Must

func Must(val interface{}, err error) interface{}

Must check if error is not nil, so panic, otherwise return value.

func MustValuePtr

func MustValuePtr(v interface{}) interface{}

MustValuePtr returns pointer to the provided value and panic if occurred error.

func NewBool

func NewBool(b bool) *bool

func NewInt

func NewInt(i int) *int

func NewInt32

func NewInt32(i int32) *int32

func NewInt64

func NewInt64(i int64) *int64

func NewString

func NewString(s string) *string

func NewTime

func NewTime(t time.Time) *time.Time

func PanicErr

func PanicErr(err error)

PanicErr panic if error value is not nil.

func PanicNil

func PanicNil(val interface{}, err error)

PanicNil will panic error param if value is nil.

func ParseInt

func ParseInt(val string, def int) int

ParseInt parse integer and returns value if string value is a valid integer or default value

func ParsePrivateKey

func ParsePrivateKey(pemBytes []byte, keyFormat KeyFormat) (key interface{}, err error)

func ParsePublicKey

func ParsePublicKey(pemBytes []byte, keyFormat KeyFormat) (key interface{}, err error)

func ParseRSAPrivateKey

func ParseRSAPrivateKey(pemBytes []byte, keyFormat KeyFormat) (*rsa.PrivateKey, error)

ParsePrivateKeyFromPem parses private key from the pem value.

func ParseRSAPublicKey

func ParseRSAPublicKey(pemBytes []byte, format KeyFormat) (*rsa.PublicKey, error)

func ParseUint64

func ParseUint64(val string, def uint64) uint64

ParseUint64 parse unsigned integer and returns it if the value is valid, otherwise returns the default value.

func Percent

func Percent(total int64, percent float64) float64

func PercentFloat

func PercentFloat(total float64, percent float64) float64

func PercentInt

func PercentInt(total int64, percent int) float64

func PercentOf

func PercentOf(total int64, part int64) float64

PercentOf calculate what percent [part] is of [total]. ex. 300 is 12.5% of 2400

func RandNumber

func RandNumber(min, max int64) int64

RandNumber generate secure random number in range of [min,max).

func RandString

func RandString(n int) string

RandString returns random string with length of n.

func RandStringWithType

func RandStringWithType(size int, t RandType) string

func RandWithDate

func RandWithDate(t time.Time, size int) string

func ReadAll

func ReadAll(filePath string) ([]byte, error)

ReadAll read file content and return it as byte slice.

func RemoveFromStrings

func RemoveFromStrings(values []string, removal ...string) []string

func RenderText

func RenderText(text string, data interface{}) (string, error)

RenderText parses the provided text and then execute it.

func ReplaceAt

func ReplaceAt(str string, replace string, begin int, end int) string

ReplaceAt replace provided string in specific index to another index. removal part is [begin,end). e.g., to replace char "a" in the "salam" word, call ReplaceAt("salam","b",1,2) // result will be "sblam".

func ReplaceRune

func ReplaceRune(str string, new rune, index int) string

ReplaceRune replace single rune in specific index

func SourcePath

func SourcePath() string

SourcePath returns the directory containing the source code that is calling this function.

func StringDefault

func StringDefault(val, def string) string

StringDefault return default value if provided value is empty.

func StructTags

func StructTags(val interface{}) ([]reflect.StructTag, error)

StructTags return struct all fields tags.

func StructToMap

func StructToMap(input interface{}) map[string]interface{}

StructToMap convert the struct to a map by marshall and un-marshall

func Sub

func Sub(s1 []string, s2 []string) []string

Sub subtracts two slices. returns s1 - s2. e.g., [1,2,3] - [2,3,4] = [1]

func ToSnakeCase

func ToSnakeCase(str string) string

ToSnakeCase returns snake_case of the provided value.

func UUID

func UUID() string

func UniqueStrings

func UniqueStrings(values []string) []string

func Unmarshal

func Unmarshal(in []byte, out interface{}) error

func UnmarshalStruct

func UnmarshalStruct(from, to interface{}) error

UnmarshalStruct marshal provided input to json and then unmarshal json bytes to provided output. input and output can be regular struct, map or struct of protobuf message type.

func ValuePtr

func ValuePtr(v interface{}) (interface{}, error)

ValuePtr returns pointer to the provided value. Provided value can be either by reference or by value.

func Wait

func Wait(callback func(s os.Signal) error, signals ...os.Signal) (err error)

Wait waits until get one signal of your specified signals, then calls to the callback and return result of callback as result of the Wait function.

func WaitForSignals

func WaitForSignals(signals ...os.Signal)

WaitForSignals simply wait until get a signal which match with your provided signals.

Types

type Bits

type Bits uint32

func (Bits) Clear

func (b Bits) Clear(f Bits) Bits

func (Bits) Has

func (b Bits) Has(f Bits) bool

func (Bits) Set

func (b Bits) Set(f Bits) Bits

func (Bits) Toggle

func (b Bits) Toggle(f Bits) Bits

type KeyFormat

type KeyFormat int

type MapPathExtractor

type MapPathExtractor struct {
	// Depth is depth of the keys. set to 1 to get just first level of keys.
	Depth int

	// Separator defines separator string between keys on each depth.
	// e.g if we set "." separator set to "." so we will have a.b for
	// {a:{b:"hello"}} map.
	Separator string
}

MapPathExtractor extract the map paths recursively.

func (MapPathExtractor) Extract

func (e MapPathExtractor) Extract(m map[string]interface{}) []string

type RandType

type RandType int
const (
	RandTypeAlphaNum RandType = iota + 1
	RandTypeLowercaseAlphaNum
	RandTypeAlpha
	RandTypeLowercaseAlpha
	RandTypeNumber
)

Jump to

Keyboard shortcuts

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