Documentation ¶
Overview ¶
Package utils some useful tools fo Golang
Modules ¶
Contains some useful tools in different directories:
- `color.go`: colorful code
- `compressor.go`: compress and extract dir/files
- `configserver.go`: load configs from file or config-server
- `email.go`: SMTP email sdk
- `encrypt.go`: some tools for encrypt and decrypt, support AES, RSA, ECDSA, MD5, SHA128, SHA256
- `fs.go`: some tools to read, move, walk dir/files
- `http.go`: some tools to send http request
- `jwt.go`: some tools to generate and parse JWT
- `logger.go`: enhanched zap logger
- `math.go`: some math tools to deal with int, round
- `net.go`: some tools to deal with tcp/udp
- `random.go`: generate random string, int
- `settings.go`: read configs from file or config-server
- `sort.go`: easier to sort
- `sync.go`: some locks depends on atomic
- `throttle.go`: faster rate limiter
- `time.go`: faster clock (if you do not enable vdso)
- `utils`: some useful tools
Index ¶
- Constants
- Variables
- func AbsInt32(v int32) int32
- func AbsInt64(v int64) int64
- func AutoGC(ctx context.Context, opts ...GcOptFunc) (err error)
- func Base64Decode(encoded string) ([]byte, error)
- func Base64Encode(raw []byte) string
- func Bytes2Str(b []byte) string
- func CheckResp(resp *http.Response) error
- func Color(color int, s string) string
- func Contains[V comparable](collection []V, ele V) bool
- func ConvertMap2StringKey(inputMap any) map[string]any
- func CopyFile(src, dst string, optfs ...CopyFileOptionFunc) (err error)
- func CostSecs(cost time.Duration) string
- func Dedent(v string, optfs ...DedentOptFunc) string
- func DeepClone(src any) (dst any)
- func DirSize(path string) (size int64, err error)
- func EmptyAllChans[T any](chans ...chan T)
- func FallBack(orig func() any, fallback any) (ret any)
- func FileExists(path string) (bool, error)
- func FileMD5(path string) (hashed string, err error)
- func FileSHA1(path string) (hashed string, err error)
- func FlattenMap(data map[string]any, delimiter string)
- func ForceGCBlocking()
- func ForceGCUnBlocking()
- func GetFuncName(f any) string
- func GetStructFieldByName(st any, fieldName string) any
- func GracefulCancel(cancel func())
- func HTTPInvalidStatusError(statusCode int) error
- func HasField(st any, fieldName string) bool
- func HasMethod(st any, methodName string) bool
- func HumanReadableByteCount(bytes int64, si bool) (ret string)
- func InArray(collection any, ele any) booldeprecated
- func IntersectSortedChans[T Sortable](chans ...chan T) (result chan T, err error)
- func IsDir(path string) (bool, error)
- func IsDirWritable(dir string) (err error)
- func IsEmpty(val any) bool
- func IsFile(path string) (bool, error)
- func IsFileATimeChanged(path string, expectATime time.Time) (changed bool, newATime time.Time, err error)
- func IsPanic(f func()) (isPanic bool)
- func IsPtr(t any) bool
- func IsRemoteUDPPortOpen(addr string) error
- func JumpHash(key uint64, numBuckets int) (int32, error)
- func ListFilesInDir(dir string, optfs ...ListFilesInDirOptionFunc) (files []string, err error)
- func MD5JSON(data any) (string, error)
- func Max[T Sortable](vals ...T) T
- func Min[T Sortable](vals ...T) T
- func MoveFile(src, dst string) (err error)
- func NewHTTPClient(opts ...HTTPClientOptFunc) (c *http.Client, err error)
- func NewRand() *rand.Rand
- func NewTmpFileForContent(content []byte) (path string, err error)
- func NilInterface(data any) bool
- func NotEmpty(val any, name string) error
- func OptionalVal[T any](ptr *T, optionalVal T) T
- func PanicIfErr(err error)
- func ParseHex2UTC(ts string) (t time.Time, err error)
- func ParseHexNano2UTC(ts string) (t time.Time, err error)
- func ParseUnix2String(ts int64, layout string) string
- func ParseUnix2UTC(ts int64) time.Time
- func ParseUnixNano2UTC(ts int64) time.Time
- func Pipeline[T any](funcs []func(T) error, v T) (T, error)
- func PrettyBuildInfo() string
- func Race(gs ...func())deprecated
- func RaceErr(gs ...func() error) (err error)
- func RaceErrWithCtx(ctx context.Context, gs ...func(context.Context) error) error
- func RandomBytesWithLength(n int) ([]byte, error)
- func RandomStringWithLength(n int) string
- func RegexNamedSubMatch(r *regexp.Regexp, str string, subMatchMap map[string]string) error
- func RemoveEmpty(vs []string) (r []string)
- func RenderTemplate(tplContent string, args any) ([]byte, error)
- func RenderTemplateFile(tplFile string, args any) ([]byte, error)
- func RequestJSON(method, url string, request *RequestData, resp any) (err error)
- func RequestJSONWithClient(httpClient *http.Client, method, url string, request *RequestData, resp any) (err error)
- func Round(val float64, d int) float64
- func RunCMD(ctx context.Context, app string, args ...string) (stdout []byte, err error)
- func RunCMDWithEnv(ctx context.Context, app string, args []string, envs []string) (stdout []byte, err error)
- func RunWithTimeout(timeout time.Duration, f func())
- func SecRandInt(n int) (int, error)
- func SecRandomBytesWithLength(n int) ([]byte, error)
- func SecRandomStringWithLength(n int) (string, error)
- func SetInternalClock(interval time.Duration)
- func SetStructFieldsBySlice(structs, vals any) (err error)
- func SilentClose(v interface{ ... })
- func SilentFlush(v interface{ ... })
- func SleepWithContext(ctx context.Context, duration time.Duration)
- func StopSignal(optfs ...StopSignalOptFunc) (stopCh <-chan struct{})
- func Str2Bytes(s string) []byte
- func TemplateWithMap(tpl string, data map[string]any) string
- func TemplateWithMapAndRegexp(tplReg *regexp.Regexp, tpl string, data map[string]any) string
- func TrimEleSpaceAndRemoveEmpty(vs []string) (r []string)
- func URLMasking(url, mask string) string
- func UTCNow() time.Time
- func UniqueStrings(vs []string) (r []string)
- func ValidateFileHash(filepath string, hashed string) error
- func WatchFileChanging(ctx context.Context, files []string, callback func(fsnotify.Event)) error
- type AsyncTask
- type AsyncTaskResult
- type AsyncTaskStatus
- type AsyncTaskStore
- type ClockItf
- type ClockT
- func (c *ClockT) Close()
- func (c *ClockT) GetDate() (time.Time, error)
- func (c *ClockT) GetNanoTimeInHex() string
- func (c *ClockT) GetTimeInHex() string
- func (c *ClockT) GetTimeInRFC3339Nano() string
- func (c *ClockT) GetUTCNow() time.Time
- func (c *ClockT) Interval() time.Duration
- func (c *ClockT) SetInterval(interval time.Duration)
- type CopyFileOptionFunc
- type DedentOptFunc
- type ExpCache
- type ExpCacheInterface
- type ExpiredRLock
- type FLock
- type GcOptFunc
- type GoroutineTest
- type HTTPClientOptFunc
- type LRUExpiredMap
- type ListFilesInDirOptionFunc
- type Mutex
- type Number
- type PairList
- type RBACPermFullKey
- type RBACPermKey
- type RBACPermissionElem
- func (p *RBACPermissionElem) Clone() *RBACPermissionElem
- func (p *RBACPermissionElem) Cut(key RBACPermFullKey)
- func (p *RBACPermissionElem) FillDefault(ancesterKey RBACPermFullKey) error
- func (p *RBACPermissionElem) GetElemByKey(key RBACPermFullKey) *RBACPermissionElem
- func (p *RBACPermissionElem) HasPerm(acquiredKey RBACPermFullKey) bool
- func (p *RBACPermissionElem) Intersection(other *RBACPermissionElem)
- func (p *RBACPermissionElem) OverwriteBy(another *RBACPermissionElem, intersection bool)
- func (p *RBACPermissionElem) Scan(input any) error
- func (p *RBACPermissionElem) UnionAndOverwriteBy(other *RBACPermissionElem)
- func (p *RBACPermissionElem) Valid() error
- func (p RBACPermissionElem) Value() (driver.Value, error)
- type RequestData
- type SingleItemExpCache
- type SortItemItf
- type Sortable
- type StopSignalOptFunc
- type Throttle
- type ThrottleCfg
Examples ¶
Constants ¶
const ( ANSIColorReset int = iota ANSIColorBold ANSIColorFaint ANSIColorItalic ANSIColorUnderline ANSIColorBlinkSlow ANSIColorBlinkRapid ANSIColorReverseVideo ANSIColorConcealed ANSIColorCrossedOut )
Base attributes
const ( ANSIColorFgBlack int = iota + 30 ANSIColorFgRed ANSIColorFgGreen ANSIColorFgYellow ANSIColorFgBlue ANSIColorFgMagenta ANSIColorFgCyan ANSIColorFgWhite )
Foreground text colors
const ( ANSIColorFgHiBlack int = iota + 90 ANSIColorFgHiRed ANSIColorFgHiGreen ANSIColorFgHiYellow ANSIColorFgHiBlue ANSIColorFgHiMagenta ANSIColorFgHiCyan ANSIColorFgHiWhite )
Foreground Hi-Intensity text colors
const ( ANSIColorBgBlack int = iota + 40 ANSIColorBgRed ANSIColorBgGreen ANSIColorBgYellow ANSIColorBgBlue ANSIColorBgMagenta ANSIColorBgCyan ANSIColorBgWhite )
Background text colors
const ( ANSIColorBgHiBlack int = iota + 100 ANSIColorBgHiRed ANSIColorBgHiGreen ANSIColorBgHiYellow ANSIColorBgHiBlue ANSIColorBgHiMagenta ANSIColorBgHiCyan ANSIColorBgHiWhite )
Background Hi-Intensity text colors
const ( // HTTPHeaderHost HTTP header name HTTPHeaderHost = "Host" // HTTPHeaderReferer HTTP header name HTTPHeaderReferer = "Referer" // HTTPHeaderContentType HTTP header name HTTPHeaderContentType = "Content-Type" // HTTPHeaderContentTypeValJSON HTTP header value HTTPHeaderContentTypeValJSON = "application/json" )
const ( // TimeFormatDate "2006-01-02" TimeFormatDate = "2006-01-02" // Nano2Sec 1e9 Nano2Sec = 1e9 // BitSize64 64 BitSize64 = 64 // BaseHex 16 BaseHex = 16 )
const ANSIColorEscape = "\x1b"
ANSIColorEscape escape string for ANSI color
Variables ¶
var ( // ParseTs2UTC can parse unix timestamp(int64) to time.Time ParseTs2UTC = ParseUnix2UTC // ParseTs2String can parse unix timestamp(int64) to string ParseTs2String = ParseUnix2String )
var ( // ParseTs2Time can parse unix timestamp(int64) to time.Time ParseTs2Time = ParseTs2UTC // UnixNano2UTC convert unixnano to UTC time UnixNano2UTC = ParseUnixNano2UTC )
var ( // TimeZoneUTC timezone UTC TimeZoneUTC = time.UTC // TimeZoneShanghai timezone Shanghai // TimeZoneShanghai = time.FixedZone("Asia/Shanghai", 8*3600) TimeZoneShanghai *time.Location )
var ( // ForceGC force to start gc blocking ForceGC = ForceGCBlocking // TriggerGC force to start gc unblocking TriggerGC = ForceGCUnBlocking )
var ( // Clock high performance time utils, replace Clock1 Clock = NewClock(context.Background(), defaultClockInterval) )
var ( // ErrAsyncTask root error for async tasks ErrAsyncTask = errors.New("async task error") )
var (
// JSON effective json
JSON = json
)
Functions ¶
func AutoGC ¶
AutoGC auto trigger GC when memory usage exceeds the custom ration
default to /sys/fs/cgroup/memory/memory.limit_in_bytes
Example ¶
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) defer cancel() if err := AutoGC( ctx, WithGCMemRatio(85), // default WithGCMemLimitFilePath("/sys/fs/cgroup/memory/memory.limit_in_bytes"), // default ); err != nil { log.Shared.Error("enable autogc", zap.Error(err)) }
Output:
func Base64Decode ¶
Base64Decode decode string to bytes use base64
func Base64Encode ¶
Base64Encode encode bytes to string use base64
func Contains ¶
func Contains[V comparable](collection []V, ele V) bool
Contains if collection contains ele
func ConvertMap2StringKey ¶
ConvertMap2StringKey convert any map to `map[string]any`
func CopyFile ¶
func CopyFile(src, dst string, optfs ...CopyFileOptionFunc) (err error)
CopyFile copy file content from src to dst
func Dedent ¶
func Dedent(v string, optfs ...DedentOptFunc) string
Dedent removes leading whitespace or tab from the beginning of each line
will replace all tab to 4 blanks.
func DirSize ¶
DirSize calculate directory size
inspired by https://stackoverflow.com/a/32482941/2368737
Example ¶
dirPath := "." size, err := DirSize(dirPath) if err != nil { log.Shared.Error("get dir size", zap.Error(err), zap.String("path", dirPath)) } log.Shared.Info("got size", zap.Int64("size", size), zap.String("path", dirPath))
Output:
func EmptyAllChans ¶
func EmptyAllChans[T any](chans ...chan T)
EmptyAllChans receive all thins in all chans
func FallBack ¶
FallBack return the fallback when orig got error utils.FallBack(func() any { return getIOStatMetric(fs) }, &IOStat{}).(*IOStat)
Example ¶
targetFunc := func() any { panic("someting wrong") } FallBack(targetFunc, 10) // got 10
Output:
func FileExists ¶ added in v3.1.1
FileExists is path a valid file
func FlattenMap ¶
FlattenMap make embedded map into flatten map
Example ¶
data := map[string]any{ "a": "1", "b": map[string]any{ "c": 2, "d": map[string]any{ "e": 3, }, }, } FlattenMap(data, "__") fmt.Println(data)
Output: map[a:1 b__c:2 b__d__e:3]
func ForceGCBlocking ¶
func ForceGCBlocking()
ForceGCBlocking force to run blocking manual gc.
Example ¶
ForceGCBlocking()
Output:
func ForceGCUnBlocking ¶
func ForceGCUnBlocking()
ForceGCUnBlocking trigger GC unblocking
Example ¶
ForceGCUnBlocking()
Output:
func GetFuncName ¶
GetFuncName return the name of func
Example ¶
GetFuncName(testFoo) // "github.com/Laisky/go-utils.testFoo"
Output:
func GetStructFieldByName ¶
GetStructFieldByName get struct field by name
func GracefulCancel ¶
func GracefulCancel(cancel func())
GracefulCancel is a function that will be called when the process is about to be terminated.
func HTTPInvalidStatusError ¶
HTTPInvalidStatusError return error about status code
func HasField ¶
HasField check is struct has field
inspired by https://mrwaggel.be/post/golang-reflect-if-initialized-struct-has-member-method-or-fields/
func HasMethod ¶
HasMethod check is struct has method
inspired by https://mrwaggel.be/post/golang-reflect-if-initialized-struct-has-member-method-or-fields/
func HumanReadableByteCount ¶
HumanReadableByteCount convert bytes to human readable string
Args:
- bytes:
- si: `si ? 1024 : 1000`
Example:
`HumanReadableByteCount(1005, false) -> "1.01KB"`
func IntersectSortedChans ¶
IntersectSortedChans return the intersection of multiple sorted chans
func IsFileATimeChanged ¶
func IsFileATimeChanged(path string, expectATime time.Time) (changed bool, newATime time.Time, err error)
IsFileATimeChanged check is file's atime equal to expectATime
func IsRemoteUDPPortOpen ¶
IsRemoteUDPPortOpen check is remote udp port open. return err if remote port is not open.
Args:
addr: "scanme.nmap.org:53"
func JumpHash ¶
JumpHash fatest consistent hashing created by google. inspired by https://medium.com/@dgryski/consistent-hashing-algorithmic-tradeoffs-ef6b8e2fcae8
func ListFilesInDir ¶
func ListFilesInDir(dir string, optfs ...ListFilesInDirOptionFunc) (files []string, err error)
ListFilesInDir list files in dir
func MoveFile ¶
MoveFile move file from src to dst by copy
sometimes move file by `rename` not work. for example, you can not move file between docker volumes by `rename`.
func NewHTTPClient ¶
func NewHTTPClient(opts ...HTTPClientOptFunc) (c *http.Client, err error)
NewHTTPClient create http client
func NewTmpFileForContent ¶
NewTmpFileForContent write content to tmp file and return path
func NilInterface ¶
NilInterface make sure data is nil interface or another type with nil value
Example:
type foo struct{} var f *foo var v any v = f v == nil // false NilInterface(v) // true
func OptionalVal ¶ added in v3.1.2
func OptionalVal[T any](ptr *T, optionalVal T) T
OptionalVal return optionval if not empty
func ParseHex2UTC ¶
ParseHex2UTC parse hex to UTC time
func ParseHexNano2UTC ¶
ParseHexNano2UTC parse hex contains nano to UTC time
func ParseUnix2String ¶
ParseUnix2String can parse unix timestamp(int64) to string
func ParseUnixNano2UTC ¶
ParseUnixNano2UTC convert unixnano to UTC time
func PrettyBuildInfo ¶
func PrettyBuildInfo() string
PrettyBuildInfo get build info in formatted json
Print:
{ "Path": "github.com/Laisky/go-ramjet", "Version": "v0.0.0-20220718014224-2b10e57735f1", "Sum": "h1:08Ty2gR+Xxz0B3djHVuV71boW4lpNdQ9hFn4ZIGrhec=", "Replace": null }
func Race
deprecated
func Race(gs ...func())
Race return when any goroutine returned
Deprecated: use RaceErr instead
Example ¶
startAt := time.Now() Race( func() { time.Sleep(time.Millisecond) }, func() { time.Sleep(time.Second) }, func() { time.Sleep(time.Minute) }, ) fmt.Println(time.Since(startAt) < time.Second)
Output: true
func RaceErrWithCtx ¶
RaceErrWithCtx return when any goroutine returned or ctx canceled
func RandomBytesWithLength ¶
RandomBytesWithLength generate random bytes
func RandomStringWithLength ¶
RandomStringWithLength generate random string with specific length
func RegexNamedSubMatch ¶
RegexNamedSubMatch extract key:val map from string by group match
Example ¶
reg := regexp.MustCompile(`(?P<key>\d+.*)`) str := "12345abcde" groups := map[string]string{} if err := RegexNamedSubMatch(reg, str, groups); err != nil { log.Shared.Error("try to group match got error", zap.Error(err)) } fmt.Println(groups)
Output: map[key:12345abcde]
func RemoveEmpty ¶
RemoveEmpty remove duplicate string in slice
func RenderTemplate ¶ added in v3.3.0
RenderTemplate render template with args
func RenderTemplateFile ¶ added in v3.3.0
RenderTemplateFile render template file with args
func RequestJSON ¶
func RequestJSON(method, url string, request *RequestData, resp any) (err error)
RequestJSON request JSON and return JSON by default client
func RequestJSONWithClient ¶
func RequestJSONWithClient(httpClient *http.Client, method, url string, request *RequestData, resp any, ) (err error)
RequestJSONWithClient request JSON and return JSON with specific client
func RunCMDWithEnv ¶ added in v3.1.4
func RunCMDWithEnv(ctx context.Context, app string, args []string, envs []string) (stdout []byte, err error)
RunCMDWithEnv run command with environments
Args ¶
- envs: []string{"FOO=BAR"}
func RunWithTimeout ¶
RunWithTimeout run func with timeout
Example ¶
slow := func() { time.Sleep(10 * time.Second) } startAt := time.Now() RunWithTimeout(5*time.Millisecond, slow) fmt.Println(time.Since(startAt) < 10*time.Second)
Output: true
func SecRandomBytesWithLength ¶
SecRandomBytesWithLength generate crypto random bytes
func SecRandomStringWithLength ¶
SecRandomStringWithLength generate random string with specific length
func SetInternalClock ¶
SetInternalClock set internal Clock with refresh interval
func SetStructFieldsBySlice ¶
SetStructFieldsBySlice set field value of structs slice by values slice
Example ¶
type ST struct{ A, B string } var ( err error ss = []*ST{{}, {}} vs = [][]string{ {"x0", "y0"}, {"x1", "y1"}, } ) if err = SetStructFieldsBySlice(ss, vs); err != nil { log.Shared.Error("set struct val", zap.Error(err)) return } fmt.Printf("%+v\n", ss) // ss = []*ST{{A: "x0", B: "y0"}, {A: "x1", B: "y1"}}
Output:
func SilentClose ¶
func SilentClose(v interface{ Close() error })
SilentClose close and ignore error
Example
defer SilentClose(fp)
func SilentFlush ¶
func SilentFlush(v interface{ Flush() error })
SilentFlush flush and ignore error
func SleepWithContext ¶
SleepWithContext sleep duration with context, if context is done, return
func StopSignal ¶
func StopSignal(optfs ...StopSignalOptFunc) (stopCh <-chan struct{})
StopSignal registered for SIGTERM and SIGINT. A stop channel is returned which is closed on one of these signals. If a second signal is caught, the program is terminated with exit code 1.
Copied from https://github.com/kubernetes/sample-controller
func TemplateWithMap ¶
TemplateWithMap replace `${var}` in template string
func TemplateWithMapAndRegexp ¶
TemplateWithMapAndRegexp replace `${var}` in template string
func TrimEleSpaceAndRemoveEmpty ¶
TrimEleSpaceAndRemoveEmpty remove duplicate string in slice
func URLMasking ¶
URLMasking masking password in url
Example ¶
originURL := "http://12ijij:3j23irj@jfjlwef.ffe.com" newURL := URLMasking(originURL, "*****") fmt.Println(newURL)
Output: http://12ijij:*****@jfjlwef.ffe.com
func UniqueStrings ¶
UniqueStrings remove duplicate string in slice
func ValidateFileHash ¶
ValidateFileHash validate file content with hashed string
Args:
- filepath: file path to check
- hashed: hashed string, like `sha256: xxxx`
func WatchFileChanging ¶
WatchFileChanging watch file changing
when file changed, callback will be called, callback will only received fsnotify.Write no matter what happened to changing a file.
TODO: only calculate hash when file's folder got fsnotiy
Types ¶
type AsyncTask ¶
type AsyncTask interface { // ID get task id ID() string // Status get task status, pending/done/failed Status() AsyncTaskStatus // SetDone set task done with result data SetDone(ctx context.Context, data string) (err error) // SetError set task error with err message SetError(ctx context.Context, errMsg string) (err error) }
asyncTask async task
func NewAsyncTask ¶
func NewAsyncTask(ctx context.Context, store AsyncTaskStore) (AsyncTask, error)
NewTask new async task
type AsyncTaskResult ¶
type AsyncTaskResult struct { TaskID string `json:"task_id"` Status AsyncTaskStatus `json:"status"` Data string `json:"data"` Err string `json:"err"` }
AsyncTaskResult result of async task
type AsyncTaskStatus ¶
type AsyncTaskStatus string
AsyncTaskStatus status of async task
const ( // AsyncTaskStatusPending task pending AsyncTaskStatusPending AsyncTaskStatus = "pending" // AsyncTaskStatusDone task done AsyncTaskStatusDone AsyncTaskStatus = "done" // AsyncTaskStatusFailed task failed AsyncTaskStatusFailed AsyncTaskStatus = "failed" )
func (AsyncTaskStatus) String ¶
func (s AsyncTaskStatus) String() string
String convert status to string
type AsyncTaskStore ¶
type AsyncTaskStore interface { // New create new AsyncTaskResult with id New(ctx context.Context) (result *AsyncTaskResult, err error) // Set set AsyncTaskResult Set(ctx context.Context, taskID string, result *AsyncTaskResult) (err error) // Heartbeat refresh async task's updated time to mark this task is still alive Heartbeat(ctx context.Context, taskID string) (alived bool, err error) }
AsyncTaskStore persistency storage for async task
type ClockItf ¶
type ClockItf interface { Close() GetUTCNow() time.Time GetDate() (time.Time, error) GetTimeInRFC3339Nano() string SetInterval(interval time.Duration) GetTimeInHex() string GetNanoTimeInHex() string Interval() time.Duration // contains filtered or unexported methods }
ClockItf high performance lazy clock
type ClockT ¶ added in v3.1.0
ClockT high performance ClockT with lazy refreshing
func (*ClockT) GetNanoTimeInHex ¶ added in v3.1.0
GetNanoTimeInHex return current time with nano in hex
func (*ClockT) GetTimeInHex ¶ added in v3.1.0
GetTimeInHex return current time in hex
func (*ClockT) GetTimeInRFC3339Nano ¶ added in v3.1.0
GetTimeInRFC3339Nano return Clock current time in string
func (*ClockT) SetInterval ¶ added in v3.1.0
SetInterval setup update interval
type CopyFileOptionFunc ¶ added in v3.1.2
type CopyFileOptionFunc func(o *copyFileOption) error
CopyFileOptionFunc set options for copy file
func Overwrite ¶ added in v3.1.2
func Overwrite() CopyFileOptionFunc
Overwrite overwrite file if target existed
func WithFileFlag ¶ added in v3.1.1
func WithFileFlag(flag int) CopyFileOptionFunc
WithFileFlag how to write dst file
func WithFileMode ¶ added in v3.1.1
func WithFileMode(perm fs.FileMode) CopyFileOptionFunc
WithFileMode if create new dst file, set the file's mode
type DedentOptFunc ¶
type DedentOptFunc func(opt *dedentOpt)
DedentOptFunc dedent option
func WithReplaceTabBySpaces ¶
func WithReplaceTabBySpaces(spaces int) DedentOptFunc
WithReplaceTabBySpaces replace tab to spaces
type ExpCache ¶
type ExpCache[T any] struct { // contains filtered or unexported fields }
ExpCache cache with expires
can Store/Load like map
Example ¶
cc := NewExpCache[string](context.Background(), 100*time.Millisecond) cc.Store("key", "val") cc.Load("key") // return "val" // data expired time.Sleep(200 * time.Millisecond) data, ok := cc.Load("key") fmt.Println(data) fmt.Println(ok)
Output: <nil> false
func NewExpCache ¶
NewExpCache new cache manager
use with generic:
cc := NewExpCache[string](context.Background(), 100*time.Millisecond) cc.Store("key", "val") val, ok := cc.Load("key")
func (*ExpCache[T]) LoadAndDelete ¶ added in v3.3.0
LoadAndDelete load and delete val from cache
type ExpCacheInterface ¶ added in v3.3.0
type ExpCacheInterface[T any] interface { // Store store new key and val into cache Store(key string, val T) // Delete remove key Delete(key string) // LoadAndDelete load and delete val from cache LoadAndDelete(key string) (data T, ok bool) // Load load val from cache Load(key string) (data T, ok bool) }
ExpCacheInterface cache with expire duration
type ExpiredRLock ¶
type ExpiredRLock struct {
// contains filtered or unexported fields
}
ExpiredRLock Lock with expire time
func NewExpiredRLock ¶
NewExpiredRLock new ExpiredRLock
type GcOptFunc ¶
type GcOptFunc func(*gcOption) error
GcOptFunc option for GC utils
func WithGCMemLimitFilePath ¶
WithGCMemLimitFilePath set memory limit file
type GoroutineTest ¶ added in v3.1.0
GoroutineTest testing.T support goroutine
func NewGoroutineTest ¶ added in v3.1.0
func NewGoroutineTest(t testing.TB, cancel func()) *GoroutineTest
NewGoroutineTest new test for goroutine
any fail will call cancel()
func (*GoroutineTest) FailNow ¶ added in v3.1.0
func (t *GoroutineTest) FailNow()
FailNow call cancal and exit current goroutine
type HTTPClientOptFunc ¶
type HTTPClientOptFunc func(*httpClientOption) error
HTTPClientOptFunc http client options
func WithHTTPClientInsecure ¶
func WithHTTPClientInsecure() HTTPClientOptFunc
WithHTTPClientInsecure set http client igonre ssl issue
default to false
func WithHTTPClientMaxConn ¶
func WithHTTPClientMaxConn(maxConn int) HTTPClientOptFunc
WithHTTPClientMaxConn set http client max connection
default to 20
func WithHTTPClientTimeout ¶
func WithHTTPClientTimeout(timeout time.Duration) HTTPClientOptFunc
WithHTTPClientTimeout set http client timeout
default to 30s
type LRUExpiredMap ¶
type LRUExpiredMap struct {
// contains filtered or unexported fields
}
LRUExpiredMap map with expire time, auto delete expired item.
`Get` will auto refresh item's expires.
func NewLRUExpiredMap ¶
func NewLRUExpiredMap(ctx context.Context, ttl time.Duration, new func() any) (el *LRUExpiredMap, err error)
NewLRUExpiredMap new ExpiredMap
func (*LRUExpiredMap) Get ¶
func (e *LRUExpiredMap) Get(key string) any
Get get item
will auto refresh key's ttl
type ListFilesInDirOptionFunc ¶ added in v3.1.2
type ListFilesInDirOptionFunc func(*listFilesInDirOption) error
ListFilesInDirOptionFunc options for ListFilesInDir
func Recursive ¶ added in v3.1.2
func Recursive() ListFilesInDirOptionFunc
Recursive list files recursively
type Mutex ¶
type Mutex struct {
// contains filtered or unexported fields
}
Mutex mutex that support unblocking lock
Example ¶
l := NewMutex() if !l.TryLock() { log.Shared.Info("can not acquire lock") return } defer l.ForceRelease()
Output:
func (*Mutex) TryRelease ¶
TryRelease return true if succeed release
type Number ¶
type Number interface { int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | float32 | float64 }
Number is a number type
type PairList ¶
type PairList []SortItemItf
PairList array of sort items
func SortBiggest ¶
SortBiggest sort from biggest to smallest
func SortSmallest ¶
SortSmallest sort from smallest to biggest
type RBACPermFullKey ¶
type RBACPermFullKey string
RBACPermFullKey key with ancesters
func (RBACPermFullKey) Append ¶
func (p RBACPermFullKey) Append(key RBACPermKey) RBACPermFullKey
Append new key to full key
func (RBACPermFullKey) Contains ¶
func (p RBACPermFullKey) Contains(acquire RBACPermFullKey) bool
Contains is contains acquire permission
func (RBACPermFullKey) Parent ¶
func (p RBACPermFullKey) Parent() RBACPermFullKey
Parent get element parent key
type RBACPermissionElem ¶
type RBACPermissionElem struct { // Title display name of this element Title string `json:"title" binding:"min=1"` // Key element's identity Key RBACPermKey `json:"key,omitempty"` // FullKey within all ancester keys, demilite by rbacPermKeyDelimiter FullKey RBACPermFullKey `json:"full_key,omitempty"` Children []*RBACPermissionElem `json:"children,omitempty"` }
RBACPermissionElem element node of permission tree
the whole permission tree can represented by the head node
func NewPermissionTree ¶
func NewPermissionTree() *RBACPermissionElem
NewPermissionTree new permission tree only contains root node
func (*RBACPermissionElem) Clone ¶
func (p *RBACPermissionElem) Clone() *RBACPermissionElem
Clone clone permission tree
func (*RBACPermissionElem) Cut ¶
func (p *RBACPermissionElem) Cut(key RBACPermFullKey)
Cut 剪除指定节点
Args:
key: 形如 `root.sys.a.b`,或 `root.sys.a.*`
头节点不允许剪除。 可以使用 `*` 作为通配符,代表剪除所有子节点。
func (*RBACPermissionElem) FillDefault ¶
func (p *RBACPermissionElem) FillDefault(ancesterKey RBACPermFullKey) error
FillDefault auto filling some default valus
it is best to call this function immediately after initialization
func (*RBACPermissionElem) GetElemByKey ¶
func (p *RBACPermissionElem) GetElemByKey(key RBACPermFullKey) *RBACPermissionElem
GetElemByKey 通过 key 获取指定的权限树节点
Args:
- key: 权限树路径,形如 `root.sys`
func (*RBACPermissionElem) HasPerm ¶
func (p *RBACPermissionElem) HasPerm(acquiredKey RBACPermFullKey) bool
HasPerm check whether has specified key
| user prems | acquired key | match | | :----------: | :----------: | :---: | | `"root"` | `"root"` | ✅ | | `""` | `"root"` | ❌ | | `"root"` | `""` | ✅ | | `"root.sys"` | `"root"` | ✅ | | `"root"` | `"root.sys"` | ❌ |
func (*RBACPermissionElem) Intersection ¶
func (p *RBACPermissionElem) Intersection(other *RBACPermissionElem)
Intersection intersect with other permission tree
func (*RBACPermissionElem) OverwriteBy ¶
func (p *RBACPermissionElem) OverwriteBy(another *RBACPermissionElem, intersection bool)
OverwriteBy overwrite element's content by another tree, but do not append any element from another tree if not exists in current tree.
Args:
- intersection: if set to true, will intersect by another tree
func (*RBACPermissionElem) Scan ¶
func (p *RBACPermissionElem) Scan(input any) error
Scan implement GORM interface
func (*RBACPermissionElem) UnionAndOverwriteBy ¶
func (p *RBACPermissionElem) UnionAndOverwriteBy(other *RBACPermissionElem)
UnionAndOverwriteBy merge(union) another tree into this tree by key comparison
func (*RBACPermissionElem) Valid ¶
func (p *RBACPermissionElem) Valid() error
Valid valid permission tree
type RequestData ¶
RequestData http request
type SingleItemExpCache ¶
type SingleItemExpCache struct {
// contains filtered or unexported fields
}
SingleItemExpCache single item with expires
func NewSingleItemExpCache ¶
func NewSingleItemExpCache(ttl time.Duration) *SingleItemExpCache
NewSingleItemExpCache new expcache contains single data
func (*SingleItemExpCache) Get ¶
func (c *SingleItemExpCache) Get() (data any, ok bool)
Get get data
if data is expired, ok=false
func (*SingleItemExpCache) GetString ¶
func (c *SingleItemExpCache) GetString() (data string, ok bool)
GetString same as Get, but return string
func (*SingleItemExpCache) GetUintSlice ¶
func (c *SingleItemExpCache) GetUintSlice() (data []uint, ok bool)
GetUintSlice same as Get, but return []uint
func (*SingleItemExpCache) Set ¶
func (c *SingleItemExpCache) Set(data any)
Set set data and refresh expires
type SortItemItf ¶
SortItemItf interface of sort item
type StopSignalOptFunc ¶
type StopSignalOptFunc func(*stopSignalOpt)
StopSignalOptFunc options for StopSignal
func WithStopSignalCloseSignals ¶
func WithStopSignalCloseSignals(signals ...os.Signal) StopSignalOptFunc
WithStopSignalCloseSignals set signals that will trigger close
type Throttle ¶
type Throttle struct { *ThrottleCfg // contains filtered or unexported fields }
Throttle current limitor
Example ¶
ctx := context.Background() throttle, err := NewThrottleWithCtx(ctx, &ThrottleCfg{ NPerSec: 10, Max: 100, }) if err != nil { panic("new throttle") } defer throttle.Close() inChan := make(chan int) for msg := range inChan { if !throttle.Allow() { continue } // do something with msg fmt.Println(msg) }
Output:
func NewThrottleWithCtx ¶
func NewThrottleWithCtx(ctx context.Context, cfg *ThrottleCfg) (t *Throttle, err error)
NewThrottleWithCtx create new Throttle
90x faster than `rate.NewLimiter`
type ThrottleCfg ¶
type ThrottleCfg struct {
Max, NPerSec int
}
ThrottleCfg Throttle's configuration
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package algorithm contains some useful algorithms
|
Package algorithm contains some useful algorithms |
Package cmd some useful tools for command argument
|
Package cmd some useful tools for command argument |
gutils
Package main gutils' command line tool
|
Package main gutils' command line tool |
Package compress contains some useful tools to compress/decompress data or files
|
Package compress contains some useful tools to compress/decompress data or files |
Package counter contains varias counter tools
|
Package counter contains varias counter tools |
Package email simple email sender
|
Package email simple email sender |
Package encrypt contains some useful tools to deal with encryption/decryption
|
Package encrypt contains some useful tools to deal with encryption/decryption |
Package gorm some useful tools for gorm
|
Package gorm some useful tools for gorm |
Package jwt all in one JWT sdk
|
Package jwt all in one JWT sdk |
Package log enhanced zap logger
|
Package log enhanced zap logger |