xutil

package module
v0.1.2-20240111 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2024 License: GPL-3.0 Imports: 51 Imported by: 2

README

xutil

utils for golang but for personal use only

Documentation

Index

Constants

View Source
const MaxInt = int(MaxUint >> 1)
View Source
const MaxUint = ^uint(0)
View Source
const MinInt = -MaxInt - 1
View Source
const MinUint = 0

Variables

View Source
var (
	Green = xpretty.Green
	Red   = xpretty.Red
)
View Source
var ErrEnvVarEmpty = errors.New("getenv: environment variable empty")
View Source
var ErrorNoNumbers = errors.New("no number found")

Functions

func A2B

func A2B(val interface{}) []byte

A2B

convert any types to byte

func AddFileIfNotExisted

func AddFileIfNotExisted(name, data string) string

func AnyJoin

func AnyJoin(sep string, args ...interface{}) string

AnyJoin: join all args with sep, even value in args is zero if you don't want zero values, use `AnyJoinNon0` instead

func AnyJoinNon0

func AnyJoinNon0(sep string, args ...interface{}) string

AnyJoinNon0: all zero valid will be skipped but " " is allowed

func AnyJoinNon0ToUpper

func AnyJoinNon0ToUpper(sep string, args ...interface{}) string

AnyJoinNon0ToUpper

@return string.ToUpper

func AorB

func AorB[T General](a, b T) T

AorB returns the first non zero value

func ArrA2B

func ArrA2B(fields ...interface{}) [][]byte

ArrA2B

convert interface array to byte array

func ArrB2A

func ArrB2A(args ...[]byte) []interface{}

ArrB2A

convert byte array to interface array

func ArrB2S

func ArrB2S(args ...[]byte) []string

ArrB2S

convert byte array to string

func ArrS2B

func ArrS2B(fields ...string) [][]byte

ArrS2B

convert string array to byte array

func B2A

func B2A(v []byte, args ...interface{}) interface{}

B2A

convert byte to other type

func BindOpts

func BindOpts(opt *WArgs, opts ...WArgFunc)

func Bytes2GB

func Bytes2GB(n uint64) float64

func Bytes2MB

func Bytes2MB(n uint64) float64

func Caller

func Caller(skip int) (string, int)

Caller wraps runtime.Caller and returns file and line number information

Returns: filename, linenum

func CallerStack

func CallerStack() []byte

func CatchPanicAsErr

func CatchPanicAsErr(fn func()) (err error)

CatchPanicAsErr

try fn with recover, return the panic as error

func CeilInt

func CeilInt(a, b int) int

CeilInt:

@return int(Ceil(a / b))

func CharToNum

func CharToNum(s string, opts ...NumOptFunc) (v interface{}, e error)

CharToNum: substract `number+Chars` from source str returns int by default

func ConcatSlice

func ConcatSlice[T General](a []T, b []T) []T

func DecodeUrl

func DecodeUrl(baseurl string) url.Values

func DecodeUrlToMap

func DecodeUrlToMap(baseurl string) (got map[string]string)

func DecodeUrlToMapIface

func DecodeUrlToMapIface(baseurl string) (got map[string]interface{})

func DefaultIfNil

func DefaultIfNil(value interface{}, defaultValue interface{}) interface{}

DefaultIfNil checks if the value is nil, if true returns the default value otherwise the original

func DiffRate

func DiffRate(a, b int) float64

DiffRate

@return float(a-b) / b

func DummyErrorLog deprecated

func DummyErrorLog(msg ...interface{})

DummyErrorLog will print a dummy log with red bg

Deprecated: use xpretty.DummyErrorLog instead

func DummyLog

func DummyLog(msg ...interface{})

DummyLog will print a dummy log with green bg Deprecated: use xpretty.DummyLog instead

func DumpCallerStack

func DumpCallerStack()

func DumpCallerWithKey

func DumpCallerWithKey(args ...string)

DumpCallerStack

print the caller tree

func Duration

func Duration(msg string, start time.Time)

Duration

usage: `xutil.Duration(xutil.Track("doing sth"))`

func ElapsedSeconds

func ElapsedSeconds(start time.Time, args ...int) float64

func EncodeUrl

func EncodeUrl(baseurl string, kv map[string]interface{}, pathArgs ...string) *url.URL

func EnsureByRetry

func EnsureByRetry(fn func() error, args ...int) (tried int, err error)

EnsureByRetry

Params:

  • fn
  • args: tries, delay, showLogOrNot

wrapper of retry.Do with default - total try 3 times

  • overwritten by args[0]
  • WARN: if args[0] == 0, the "fn" will be skipped
  • if args[0] < 0, will use default 3

- retry delay of 0 millisecond

  • overwritten by args[1]

- on retry not print logs

  • overwritten by args[2]

func F64KMFromStr

func F64KMFromStr(str string, opts ...NumOptFunc) (i float64, err error)

func FileGetGz

func FileGetGz(filename string) ([]byte, error)

func FirstIface

func FirstIface(args ...interface{}) interface{}

func FirstNonNil

func FirstNonNil(values ...interface{}) interface{}

FirstNonNil returns the first non nil parameter

func FirstNonZero

func FirstNonZero[T General](args ...T) T

FirstNonZero returns the first non zero values, and if all are zero vlaues, return the first value in args

func FirstOrDefaultArgs

func FirstOrDefaultArgs[T General](dft T, args ...T) (val T)

FirstOrDefaultArgs

return the first args value, if args not empty else return default value

func GbkToUtf8

func GbkToUtf8(s []byte) ([]byte, error)

func GetAllTags

func GetAllTags(structIn interface{}, tag string) (tags []string)

func GetAttr

func GetAttr(o interface{}, key string) reflect.Value

GetAttr beware `o` should be the pointer

func GetCharNumOr

func GetCharNumOr(s string, opts ...NumOptFunc) (v interface{})

GetCharNumOr returns parsed number or keep original

func GetHostPublicIp

func GetHostPublicIp(url string) string

func GetIntByIndex

func GetIntByIndex(arr []int, index int) int

GetIntByIndex

index can be less than 0

func GetKind

func GetKind(o interface{}) reflect.Kind

func GetLocalIpAddr

func GetLocalIpAddr() (ip, port string)

GetLocalIpAddr

@return ip:port

func GetPublicIp

func GetPublicIp(args ...string) (ip string)

func GetStrByIndex

func GetStrByIndex(arr []string, index int) string

GetStrByIndex

index can be less than 0

func GetStrBySplit

func GetStrBySplit(raw string, sep string, offset int) (string, bool)

GetStrBySplit: split raw str with separator and join from offset

example:
 raw = "a,b,c,d,e"
 v, b := GetStrBySplit(raw, ",", 1)
 // v = "bcde", b = true

 v, b := GetStrBySplit(raw, "_", 1)
 // v = "a,b,c,d,e", b = false

 v, b := GetStrBySplit(raw, ",", -1)
 // v = "e", b = false

@return string @return bool

func GetStrBySplitAtIndex

func GetStrBySplitAtIndex(raw interface{}, sep string, index int) string

GetStrBySplitAtIndex split raw to slice and then return element at index

  • if sep not in raw, returns raw
  • if index < 0, reset index to len() + index
  • if index > total length, returns the last one
  • else returns element at index

func GetUrlParam

func GetUrlParam(baseurl string, key string) (bool, string)

func GetenvBool

func GetenvBool(key string) (bool, error)

func GetenvInt

func GetenvInt(key string) (int, error)

func GetenvStr

func GetenvStr(key string) (string, error)

func HostUUID

func HostUUID() string

func IfThen

func IfThen(condition bool, a interface{}) interface{}

IfThen evaluates a condition, if true returns the parameters otherwise nil

func IfThenElse

func IfThenElse(condition bool, a interface{}, b interface{}) interface{}

IfThenElse evaluates a condition, if true returns the first parameter otherwise the second

func IfThenElseStr

func IfThenElseStr(condition bool, a, b string) string

IfThenElse evaluates a condition, if true returns the first parameter otherwise the second

func IfaceAorB

func IfaceAorB(a, b interface{}) interface{}

func InitializeXOpts

func InitializeXOpts(opts ...XOptFunc)

InitializeXOpts setups

  • debug: used in `PauseToDebug`
  • recover: used in `RecoverAndDumpOnly`
  • dummyLog: used in `DummyLog`
  • pauseInPanic: use in `PanicIfErr`

func Insert

func Insert[T General](arr []T, index int, value T) []T

Insert insert value to arr at index

  • if index >= len(arr), append to arr
  • else insert at index

func IntKMFromStr

func IntKMFromStr(str string, opts ...NumOptFunc) (int, bool)

func IsDefaultVal

func IsDefaultVal(x interface{}) bool

IsDefaultVal alias of IsZeroVal

func IsGzip

func IsGzip(filename string) bool

func IsJSON

func IsJSON(str string) bool

func IsZeroVal

func IsZeroVal(x interface{}) bool

IsZeroVal check if any type is its zero value

func KillProcess

func KillProcess(name string) error

func LogFatalIfErr

func LogFatalIfErr(err error, msg string)

LogFatalIfErr logs error with level fatal if `err!=nil`, else do nothing

func LogIfErr

func LogIfErr(err error, msg string) bool

LogIfErr logs error with level error, and return true if err!=nil, else false

@return bool

func Map2StructureByDefault

func Map2StructureByDefault(dat interface{}, dstStruct interface{})

Map2StructureByDefault

just a wrapper of commonly usage to mapstructure.DecoderConfig

func Map2StructureLoosely

func Map2StructureLoosely(dat interface{}, config *mapstructure.DecoderConfig)

Map2StructureLoosely wrapper of mapstructure.NewDecoder

this will convert map[interface{}]interface{} to struct WARN: remember to pass struct in config.Result e.g.

WeaklyTypedInput: true, Result: &st, TagName: "structs", // not required, but you can always customize it

func Max

func Max[T Number](args ...T) (max T)

func Min

func Min[T Number](args ...T) (min T)

func MkdirIfNotExist

func MkdirIfNotExist(dirPathName string) (b bool, dirAbsPath string)

func MkdirIfNotExistFromFile

func MkdirIfNotExistFromFile(filePath string) error

func MustCharToNum

func MustCharToNum(s string, opts ...NumOptFunc) (v interface{})

func MustF64KMFromStr

func MustF64KMFromStr(str string, opts ...NumOptFunc) float64

func MustFileAppendString

func MustFileAppendString(filename, data string)

func MustFileSetString

func MustFileSetString(filename, data string)

func MustGetKeys

func MustGetKeys(obj interface{}) []string

func MustGetStrBySplit

func MustGetStrBySplit(raw string, sep string, offset int) string

MustGetStrBySplit get str or ""

func MustIntKMFromStr

func MustIntKMFromStr(str string, opts ...NumOptFunc) int

func MustMarshal

func MustMarshal(data interface{}) []byte

func MustReadFile

func MustReadFile(filename string) (raw []byte)

func MustStrToGzip

func MustStrToGzip(raw string) []byte

func MustStrToGzipStr

func MustStrToGzipStr(raw string) string

func MustString

func MustString(obj interface{}) string

func MustStringify

func MustStringify(data interface{}) string

func MustStruct2Yaml

func MustStruct2Yaml(dat interface{}) (out string)

func MustStructToMap

func MustStructToMap(data interface{}) map[string]interface{}

func MustStructify

func MustStructify(data string, op interface{})

func MustUnGzip

func MustUnGzip(filename string) string

func MustUnGzipWithSameName

func MustUnGzipWithSameName(filename string) string

func MustUnGzipWithoutGz

func MustUnGzipWithoutGz(filename string) string

func MustWriteFile

func MustWriteFile(name, data string)

func MustYaml2Struct

func MustYaml2Struct(raw []byte, st interface{})

func NewChaos

func NewChaos(key, iv string) *chaos

NewChaos creates cipher with mode CBC, padding PKCS7

@return *chaos

func NewChromeExtension

func NewChromeExtension(line, savePath string) (string, string, string)

NewChromeExtension will create two files from line, and save to savePath

  • background.js
  • manifest.json

line format is: "host:port:username:password:<OTHER>"

func NewSlice

func NewSlice(start, end, step int) []int

func NewSliceByCount

func NewSliceByCount(start, count, step int) []int

func NewStringSlice

func NewStringSlice(raw string, fixStep int, randomStep ...bool) []string

NewStringSlice

raw: the raw string to be convert to slice fixStep: how many chars in each slice args: just add any one to enable random step mode

return:

str slice with each has (~)maxLen chars

func PanicIfErr

func PanicIfErr(args ...interface{})

PanicIfErr panics if has error

func PanicIfErrWithPause

func PanicIfErrWithPause(args ...interface{})

func Pause

func Pause(args ...string)

Pause: press enter to continue

func PauseToDebug

func PauseToDebug(msg ...string) bool

PauseToDebug block the normal workflow, and used for debug purpose only

this is triggered by ctrl.debug = true

func PlainTablelize

func PlainTablelize(s *csv.Reader)

func PrintArrayAsTable

func PrintArrayAsTable(header []string, rows [][]string)

func PrintStrAsTable

func PrintStrAsTable(header string, rows []string, sep string)

func QuietGetKeys

func QuietGetKeys(obj interface{}) []string

func RandFloatX1k

func RandFloatX1k(min, max float64) int

RandFloatX1k: return a value between (min, max) * 1000

func RandSleep

func RandSleep(min, max float64, msg ...string) int

RandSleep random sleep some seconds

@returns milliseconds

func ReadFile

func ReadFile(filename string) (raw []byte, err error)

func RealTimeInfo

func RealTimeInfo() map[string]interface{}

func RecoverAndDumpOnly

func RecoverAndDumpOnly()

func RecoverWithCb

func RecoverWithCb(fn func())

func RefineIndex

func RefineIndex(i, length int) int

RefineIndex

  1. 0 <= i < length return i
  2. i < 0 return length+i
  3. i >= length return length-1

func RefineString

func RefineString(name string) string

RefineString replaces chars those not allowed in Windows `\/:*?"<>|`

func RefineWinFileName

func RefineWinFileName(name string) string

func Round

func Round(num float64) int

func SetAttr

func SetAttr(o interface{}, key string, val interface{})

SetAttr will set o.key to val same as GetAttr, o should be a pointer

func SliceToTable

func SliceToTable(header *[]string, data *[][]string)

func StrToArrWithNonEmpty

func StrToArrWithNonEmpty(raw string, sep string) (arr []string)

func StrToGzip

func StrToGzip(raw string) (*bytes.Buffer, error)

func Stringify

func Stringify(data interface{}) (string, error)

Stringify returns a string representation

func Structify

func Structify(data string, value interface{}) error

Structify returns the original representation

func Tablelize

func Tablelize(s *csv.Reader)

func ToFixed

func ToFixed(num float64, precision ...int) float64

func ToFixedStr

func ToFixedStr(num float64, precision ...int) string

func Track

func Track(msg string) (string, time.Time)

func TruncateString

func TruncateString(s string, max int) string

TruncateString

this will TruncateString with rune

func TruncateText

func TruncateText(s string, max int) string

func TruncateWord

func TruncateWord(s string, max int) string

func Utf8ToGbk

func Utf8ToGbk(s []byte) ([]byte, error)

func Walk

func Walk(root string, opts ...WArgFunc) []string

func WriteFile

func WriteFile(name string, data string) error

func Yaml2Config

func Yaml2Config(raw []byte, cfs ...*config.Config) (cf *config.Config, err error)

Types

type Any

type Any = interface{}

type ErrTry

type ErrTry struct {
	Value interface{}
}

ErrTry error

which is extracted from go-rod

func (*ErrTry) Error

func (e *ErrTry) Error() string

func (*ErrTry) Is

func (e *ErrTry) Is(err error) bool

Is interface

type Floats

type Floats interface {
	float32 | float64
}

type General

type General interface {
	bool | UInts | Ints | Floats | string
}

type Ints

type Ints interface {
	int | int8 | int16 | int32 | int64
}

type NumOptFunc

type NumOptFunc func(o *NumOpts)

func Chars

func Chars(s string) NumOptFunc

func Dft

func Dft(i interface{}) NumOptFunc

type NumOpts

type NumOpts struct {
	// contains filtered or unexported fields
}

type Number

type Number interface {
	UInts | Ints | Floats
}

type PsMetric

type PsMetric struct {
	// host info
	Uptime   uint64 `json:"uptime,omitempty"`
	Hostname string `json:"hostname,omitempty"`
	OS       string `json:"os,omitempty"`
	HostId   string `json:"host_id"`

	// mem
	Total       float64 `json:"total,omitempty"`
	UsedPercent float64 `json:"used_percent,omitempty"`

	// cpu
	Cores     int32  `json:"cores,omitempty"`
	ModelName string `json:"model_name,omitempty"`

	// load
	Load1  float64 `json:"load1,omitempty"`
	Load5  float64 `json:"load5,omitempty"`
	Load15 float64 `json:"load15,omitempty"`
}

func NewPsMetric

func NewPsMetric() *PsMetric

func (*PsMetric) CPU

func (p *PsMetric) CPU()

func (*PsMetric) LoadAvg

func (p *PsMetric) LoadAvg()

func (*PsMetric) Mem

func (p *PsMetric) Mem() *mem.VirtualMemoryStat

func (*PsMetric) OsInfo

func (p *PsMetric) OsInfo() *host.InfoStat

type UInts

type UInts interface {
	uint | uint8 | uint16 | uint32 | uint64
}

type WArgFunc

type WArgFunc func(o *WArgs)

func WExts

func WExts(val []string) WArgFunc

func WKv

func WKv(key string, val interface{}) WArgFunc

func WLimitDir

func WLimitDir(val string) WArgFunc

func WithInclude

func WithInclude(s string) WArgFunc

type WArgs

type WArgs struct {
	Root      string
	FilterDir string

	NameInclude string
	NameExclude string

	Exts []string
	Dirs []string
}

type XOptFunc

type XOptFunc func(o *XOpts)

func SetDebug

func SetDebug(b bool) XOptFunc

func SetDummyLog

func SetDummyLog(b bool) XOptFunc

func SetPauseInPanic

func SetPauseInPanic(b bool) XOptFunc

func SetRecover

func SetRecover(b bool) XOptFunc

type XOpts

type XOpts struct {
	// contains filtered or unexported fields
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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