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 AutoGC(ctx context.Context, opts ...GcOptFunc) (err error)
- func CheckResp(resp *http.Response) error
- func CloseWithLog(ins interface{ ... }, logger interface{ ... })
- func Color(color int, s string) string
- func CombineSortedChain[T Sortable](sortOrder common.SortOrder, chans ...chan T) (result chan T, err error)
- 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 DecodeByBase64(encoded string) ([]byte, error)
- func Dedent(v string, optfs ...DedentOptFunc) string
- func DeepClone[T any](src T) (dst T)
- func DirSize(path string) (size int64, err error)
- func EmptyAllChans[T any](chans ...chan T)
- func EncodeByBase64(raw []byte) string
- func FallBack(orig func() any, fallback any) (ret any)
- func FileExists(path string) (bool, error)
- func FileHash(hashType HashTypeInterface, filepath string) (signature []byte, err error)
- func FileHashSharding(fname string) string
- func FileMD5(path string) (hashed string, err error)deprecated
- func FileSHA1(path string) (hashed string, err error)deprecated
- func FilterSlice[T any](s []T, f func(v T) bool) []T
- func FlattenMap(data map[string]any, delimiter string)
- func FlushWithLog(ins interface{ ... }, logger interface{ ... })
- func ForceGCBlocking()
- func ForceGCUnBlocking()
- func GetEnvInsensitive(key string) (values []string)
- 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 Hash(hashType HashTypeInterface, content io.Reader) (signature []byte, err error)
- func HashSHA128String(val string) stringdeprecated
- func HashSHA256String(val string) stringdeprecated
- func HashVerify(hashType HashTypeInterface, content io.Reader, signature []byte) (err error)
- func HashXxhashString(val string) stringdeprecated
- func Input(hint string) (input string, err error)
- func InputPassword(hint string, validator func(string) error) (passwd string, err error)
- func InputYes(hint string) (ok bool, 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 IsPanic2(f func()) (err error)
- func IsPtr(t any) bool
- func IsRemoteUDPPortOpen(addr string) error
- func JoinFilepath(paths ...string) (result string, err error)
- func JumpHash(key uint64, numBuckets int) (int32, error)
- func ListFilesInDir(dir string, optfs ...ListFilesInDirOptionFunc) (files []string, err error)
- func LogErr(f func() error, logger interface{ ... })
- func MD5JSON(data any) (string, error)
- func Max[T Sortable](vals ...T) T
- func Min[T Sortable](vals ...T) T
- func MockStdout() (recoverFn func(), stdout *os.File, err error)
- func MoveFile(src, dst string) (err error)
- func NewHTTPClient(opts ...HTTPClientOptFunc) (c *http.Client, err error)
- func NewLruCache[K comparable, V any](size int, ttl time.Duration) *sieve.Sieve[K, V]
- func NewRand() *rand.Rand
- func NewTmpFile(reader io.Reader) (*os.File, error)
- func NewTmpFileForContent(content []byte) (path string, err error)
- func NilInterface(data any) bool
- func NotEmpty(val any, name string) error
- func OpenURLInDefaultBrowser(ctx context.Context, url string) error
- func OptionalVal[T any](ptr *T, optionalVal T) T
- func PaddingLeft(s string, padStr string, pLen int) string
- func PanicIfErr(err error)
- func ParseHex2UTC(ts string) (t time.Time, err error)
- func ParseHexNano2UTC(ts string) (t time.Time, err error)
- func ParseObjectIdentifier(val string) (oid asn1.ObjectIdentifier, err error)
- func ParseTimeWithTruncate(layout, value string, precision time.Duration) (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(opts ...PrettyBuildInfoOption) string
- 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 RandomChoice[T any](arr []T, n int) (got []T)
- func RandomNonZeroUint64() (uint64, error)
- func RandomStringWithLength(n int) string
- func RegexNamedSubMatch(r *regexp.Regexp, str string, subMatchMap map[string]string) errordeprecated
- func RegexNamedSubMatch2(r *regexp.Regexp, str string) (subMatchMap map[string]string, err error)
- func RemoveEmpty(vs []string) (r []string)
- func RemoveEmptyVal(m map[string]any) map[string]any
- func RenderTemplate(tplContent string, args any) ([]byte, error)
- func RenderTemplateFile(tplFile string, args any) ([]byte, error)
- func ReplaceFile(path string, content []byte, perm os.FileMode) error
- func ReplaceFileAtomic(path string, in io.ReadCloser, perm os.FileMode) 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 ReverseSlice[T any](s []T)
- func RunCMD(ctx context.Context, app string, args ...string) (stdout []byte, err error)
- func RunCMD2(ctx context.Context, app string, args []string, envs []string, ...) (err error)
- func RunCMDWithEnv(ctx context.Context, app string, args []string, envs []string) (stdout []byte, err error)
- func RunWithTimeout(timeout time.Duration, f func() error) error
- func SanitizeCMDArgs(args []string) (sanitizedArgs []string, err error)
- 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 TemplateWithMap(tpl string, data map[string]any) string
- func TemplateWithMapAndRegexp(tplReg *regexp.Regexp, tpl string, data map[string]any) string
- func TimeEqual(ts1, ts2 time.Time, difference time.Duration) bool
- func TrimEleSpaceAndRemoveEmpty(vs []string) (r []string)
- func URLMasking(url, mask string) string
- func UTCNow() time.Time
- func UUID1() stringdeprecated
- func UUID4() string
- func UUID7() string
- func UniqueStrings(vs []string) []string
- func ValidateFileHash(filepath string, hashed string) error
- func WaitComplete(ctx context.Context, goros ...func(ctx context.Context) error) (err error)
- func WaitTCPOpen(ctx context.Context, ip string, port int) error
- func WatchFileChanging(ctx context.Context, files []string, callback func(fsnotify.Event)) error
- func Wrap(err error, msg string) error
- type AsyncTask
- type AsyncTaskInterface
- type AsyncTaskResult
- type AsyncTaskStatus
- type AsyncTaskStoreInterface
- type AsyncTaskStoreMemory
- func (s *AsyncTaskStoreMemory) Delete(_ context.Context, taskID string) (err error)
- func (s *AsyncTaskStoreMemory) Get(_ context.Context, taskID string) (result *AsyncTaskResult, err error)
- func (s *AsyncTaskStoreMemory) Heartbeat(_ context.Context, _ string) (alived bool, err error)
- func (s *AsyncTaskStoreMemory) New(_ context.Context) (result *AsyncTaskResult, err error)
- func (s *AsyncTaskStoreMemory) Set(_ context.Context, taskID string, result *AsyncTaskResult) (err error)
- 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 Delayer
- type ExpCache
- type ExpCacheInterface
- type ExpiredRLock
- type FLock
- type GcOptFunc
- type GoroutineTest
- func (t *GoroutineTest) Cleanup(f func())
- func (t *GoroutineTest) Error(args ...any)
- func (t *GoroutineTest) Errorf(format string, args ...any)
- func (t *GoroutineTest) Fail()
- func (t *GoroutineTest) FailNow()
- func (t *GoroutineTest) Failed() bool
- func (t *GoroutineTest) Fatal(args ...any)
- func (t *GoroutineTest) Fatalf(format string, args ...any)
- func (t *GoroutineTest) Helper()
- func (t *GoroutineTest) Log(args ...any)
- func (t *GoroutineTest) Logf(format string, args ...any)
- func (t *GoroutineTest) Name() string
- func (t *GoroutineTest) Setenv(key, value string)
- func (t *GoroutineTest) Skip(args ...any)
- func (t *GoroutineTest) SkipNow()
- func (t *GoroutineTest) Skipf(format string, args ...any)
- func (t *GoroutineTest) Skipped() bool
- func (t *GoroutineTest) TempDir() string
- type HTTPClientOptFunc
- type HashType
- type HashTypeInterface
- type JaegerTracingID
- type LRUExpiredMap
- type ListFilesInDirOptionFunc
- type Mutex
- type Number
- type PairList
- type PrettyBuildInfoOption
- 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 RWManager
- type RWManagerInterface
- type RateLimiter
- type RateLimiterArgs
- type RequestData
- type SingleItemExpCache
- type SortItemItf
- type Sortable
- type StopSignalOptFunc
- type Throttledeprecated
- type ThrottleCfgdeprecated
- type TtlCache
- type UUID7Itf
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" // TracingKey default trace key // // https://www.jaegertracing.io/docs/1.22/client-libraries/#key // // `{trace-id}:{span-id}:{parent-span-id}:{flags}` TracingKey = "Uber-Trace-Id" )
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 ( // AbsInt64 abs(v) // // ignore int exceeds limit error, abs(MinInt64) == MaxInt64 AbsInt64 = common.AbsInt64 // AbsInt32 abs(v) // // ignore int exceeds limit error, abs(MinInt32) == MaxInt32 AbsInt32 = common.AbsInt32 // Round round float64 // // Round(1.005, 2) -> 1.01 Round = common.Round // HumanReadableByteCount convert bytes to human readable string // // Args: // - bytes: // - si: `si ? 1024 : 1000` // // Example: // // `HumanReadableByteCount(1005, false) -> "1.01KB"` HumanReadableByteCount = common.HumanReadableByteCount )
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 ( // JSON effective json // // Deprecated: use github.com/Laisky/go-utils/v4/json instead JSON = jsonT{API: jsoniter.ConfigCompatibleWithStandardLibrary} // Str2Bytes unsafe convert str to bytes Str2Bytes = common.Str2Bytes // Bytes2Str unsafe convert bytes to str Bytes2Str = common.Bytes2Str // Number2Roman convert number to roman Number2Roman = common.Number2Roman )
var ( // ForceGC force to start gc blocking ForceGC = ForceGCBlocking // TriggerGC force to start gc unblocking TriggerGC = ForceGCUnBlocking )
var ( // EncodeByHex encode bytes to string by hex EncodeByHex = hex.EncodeToString // DecodeByHex decode string to bytes by hex DecodeByHex = hex.DecodeString )
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 NewThrottleWithCtx = NewRateLimiter
NewThrottleWithCtx create new Throttle
Deprecated: use `NewRateLimiter` instead
var RegexpOidFormat = regexp.MustCompile(`^\d(?:\.\d+){0,}$`)
RegexpOidFormat check if oid is valid
var ReplaceFileStream = ReplaceFileAtomic
ReplaceFileStream replace file with content atomatically
Deprecated: use ReplaceFileAtomic instead
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 CloseWithLog ¶ added in v4.5.0
CloseWithLog close and log error. logger could be nil, then will use internal log.Shared logger instead.
func CombineSortedChain ¶ added in v4.7.1
func CombineSortedChain[T Sortable](sortOrder common.SortOrder, chans ...chan T) (result chan T, err error)
CombineSortedChain return the intersection of multiple sorted chans
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 DecodeByBase64 ¶
DecodeByBase64 decode string to bytes by base64
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 DeepClone ¶
func DeepClone[T any](src T) (dst T)
DeepClone deep clone a struct
will ignore all unexported fields
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 EncodeByBase64 ¶
EncodeByBase64 encode bytes to string by base64
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 FileHash ¶ added in v4.4.0
func FileHash(hashType HashTypeInterface, filepath string) (signature []byte, err error)
FileHash generate file signature by hash
func FileHashSharding ¶ added in v4.2.0
FileHashSharding get file hash sharding path
func FilterSlice ¶ added in v4.8.0
FilterSlice filters a slice inplace
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 FlushWithLog ¶ added in v4.5.0
FlushWithLog flush and log error. logger could be nil, then will use internal log.Shared logger instead.
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 GetEnvInsensitive ¶ added in v4.10.0
GetEnvInsensitive get env case insensitive
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 Hash ¶ added in v4.1.0
func Hash(hashType HashTypeInterface, content io.Reader) (signature []byte, err error)
Hash generate signature by hash
func HashSHA128String
deprecated
added in
v4.1.0
func HashSHA256String
deprecated
added in
v4.1.0
func HashVerify ¶ added in v4.1.0
func HashVerify(hashType HashTypeInterface, content io.Reader, signature []byte) (err error)
HashVerify verify by hash
func HashXxhashString
deprecated
added in
v4.1.0
func InputPassword ¶ added in v4.2.1
InputPassword reads password from stdin input and returns it as a string.
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 IsPanic ¶
func IsPanic(f func()) (isPanic bool)
IsPanic is `f()` throw panic
if you want to get the data throwed by panic, use `IsPanic2`
func IsPanic2 ¶ added in v4.6.0
func IsPanic2(f func()) (err error)
IsPanic2 check is `f()` throw panic, and return panic as error
func IsRemoteUDPPortOpen ¶
IsRemoteUDPPortOpen check is remote udp port open. return err if remote port is not open.
Args:
addr: "scanme.nmap.org:53"
func JoinFilepath ¶ added in v4.5.0
JoinFilepath join paths and check if result is escaped basedir
basedir is the first nonempty path in paths. this function could be used to prevent path escaping, make sure the result is under basedir. for example defend zip-slip: https://snyk.io/research/zip-slip-vulnerability#go
Notice: cannot deal with symlink
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 MockStdout ¶ added in v4.4.0
MockStdout mock stdout to a temp file
Example:
func TestMockStdout(t *testing.T) { recover, stdout, err := MockStdout() require.NoError(t, err) defer recover() fmt.Println("hello") stdout.Seek(0, 0) buf, err := io.ReadAll(stdout) require.NoError(t, err) require.Equal(t, "hello\n", string(buf)) }
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 NewLruCache ¶ added in v4.10.0
NewLruCache new lru cache
func NewTmpFile ¶ added in v4.2.1
NewTmpFile write content to tmp file and return path
func NewTmpFileForContent ¶
NewTmpFileForContent write content to tmp file and return path
deprecated: use NewTmpFileForReader instead
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 OpenURLInDefaultBrowser ¶ added in v4.10.0
OpenURLInDefaultBrowser opens the specified URL in the default browser of the user.
func OptionalVal ¶
func OptionalVal[T any](ptr *T, optionalVal T) T
OptionalVal return optionval if not empty
func PaddingLeft ¶ added in v4.6.0
PaddingLeft padding string to left
func ParseHex2UTC ¶
ParseHex2UTC parse hex to UTC time
func ParseHexNano2UTC ¶
ParseHexNano2UTC parse hex contains nano to UTC time
func ParseObjectIdentifier ¶ added in v4.10.0
func ParseObjectIdentifier(val string) (oid asn1.ObjectIdentifier, err error)
ParseObjectIdentifier parse oid
func ParseTimeWithTruncate ¶ added in v4.8.0
ParseTimeWithTruncate parse time with truncate
func ParseUnix2String ¶
ParseUnix2String can parse unix timestamp(int64) to string
func ParseUnixNano2UTC ¶
ParseUnixNano2UTC convert unixnano to UTC time
func PrettyBuildInfo ¶
func PrettyBuildInfo(opts ...PrettyBuildInfoOption) 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 RaceErr ¶
RaceErr return when any goroutine returned
Example ¶
startAt := time.Now() _ = RaceErr( func() error { time.Sleep(time.Millisecond) return nil }, func() error { time.Sleep(time.Second) return nil }, func() error { time.Sleep(time.Minute) return nil }, ) 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 RandomChoice ¶ added in v4.1.0
RandomChoice selects a random subset of elements from an input array of any type.
It takes in two parameters: the array and the number of elements to select from the array. The function uses a random number generator to select elements from the array and returns a new array containing the selected elements.
func RandomNonZeroUint64 ¶ added in v4.6.0
RandomNonZeroUint64 generate random uint64 number
func RandomStringWithLength ¶
RandomStringWithLength generate random string with specific length
func RegexNamedSubMatch
deprecated
RegexNamedSubMatch extract key:val map from string by group match
Deprecated: use RegexNamedSubMatch2 instead
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 RegexNamedSubMatch2 ¶ added in v4.6.0
RegexNamedSubMatch2 extract key:val map from string by group match
func RemoveEmpty ¶
RemoveEmpty remove duplicate string in slice
func RemoveEmptyVal ¶ added in v4.7.0
RemoveEmptyVal remove empty value in map
func RenderTemplate ¶
RenderTemplate render template with args
func RenderTemplateFile ¶
RenderTemplateFile render template file with args
func ReplaceFile ¶
ReplaceFile replace file with content atomatically
this function is not goroutine-safe
func ReplaceFileAtomic ¶ added in v4.5.0
ReplaceFileAtomic replace file with content atomatically
write content to a tmp file, then rename it to dst file.
Notice: this function is not goroutine-safe
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 RunCMD2 ¶ added in v4.5.0
func RunCMD2(ctx context.Context, app string, args []string, envs []string, stdoutHandler, stderrHandler func(string), ) (err error)
RunCMD2 run command script and handle stdout/stderr by pipe
func RunCMDWithEnv ¶
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() error { time.Sleep(10 * time.Second) return nil } startAt := time.Now() RunWithTimeout(5*time.Millisecond, slow) fmt.Println(time.Since(startAt) < 10*time.Second)
Output: true
func SanitizeCMDArgs ¶ added in v4.7.0
SanitizeCMDArgs sanitizes the given command arguments.
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 TimeEqual ¶ added in v4.8.0
TimeEqual compare two time with difference, return true if time difference less than difference
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 WaitComplete ¶ added in v4.2.1
WaitComplete wait all goroutines complete or ctx canceled, returns the first non-nil error (if any) from them, or return ctx.Err() if ctx canceled.
func WaitTCPOpen ¶ added in v4.5.0
WaitTCPOpen wait tcp open
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 struct {
// contains filtered or unexported fields
}
AsyncTask async task manager
func NewAsyncTask ¶
func NewAsyncTask(ctx context.Context, store AsyncTaskStoreInterface) ( *AsyncTask, error)
NewTask new async task
ctx must keep alive for whole lifecycle of AsyncTask
type AsyncTaskInterface ¶
type AsyncTaskInterface 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
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 uint
AsyncTaskStatus status of async task
const ( // AsyncTaskStatusUnspecified unknown AsyncTaskStatusUnspecified AsyncTaskStatus = iota // AsyncTaskStatusPending task pending AsyncTaskStatusPending // AsyncTaskStatusDone task done AsyncTaskStatusDone // AsyncTaskStatusFailed task failed AsyncTaskStatusFailed )
func (AsyncTaskStatus) String ¶
func (s AsyncTaskStatus) String() string
String convert status to string
type AsyncTaskStoreInterface ¶
type AsyncTaskStoreInterface interface { // New create new AsyncTaskResult with id New(ctx context.Context) (result *AsyncTaskResult, err error) // 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) // Get task by id Get(ctx context.Context, taskID string) (result *AsyncTaskResult, err error) // Delete task by id Delete(ctx context.Context, taskID string) (err error) }
AsyncTaskStoreInterface persistency storage for async task
type AsyncTaskStoreMemory ¶
type AsyncTaskStoreMemory struct {
// contains filtered or unexported fields
}
AsyncTaskStoreMemory example store in memory
func NewAsyncTaskStoreMemory ¶
func NewAsyncTaskStoreMemory() *AsyncTaskStoreMemory
NewAsyncTaskStoreMemory new default memory store
func (*AsyncTaskStoreMemory) Delete ¶
func (s *AsyncTaskStoreMemory) Delete(_ context.Context, taskID string) (err error)
Delete task by id
func (*AsyncTaskStoreMemory) Get ¶
func (s *AsyncTaskStoreMemory) Get(_ context.Context, taskID string) ( result *AsyncTaskResult, err error)
Get get task by id
func (*AsyncTaskStoreMemory) Heartbeat ¶
Heartbeat refresh async task's updated time to mark this task is still alive
func (*AsyncTaskStoreMemory) New ¶
func (s *AsyncTaskStoreMemory) New(_ context.Context) (result *AsyncTaskResult, err error)
New create new AsyncTaskResult with id
func (*AsyncTaskStoreMemory) Set ¶
func (s *AsyncTaskStoreMemory) Set(_ context.Context, taskID string, result *AsyncTaskResult) (err error)
Set set AsyncTaskResult
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 ¶
ClockT high performance ClockT with lazy refreshing
func (*ClockT) GetNanoTimeInHex ¶
GetNanoTimeInHex return current time with nano in hex
func (*ClockT) GetTimeInHex ¶
GetTimeInHex return current time in hex
func (*ClockT) GetTimeInRFC3339Nano ¶
GetTimeInRFC3339Nano return Clock current time in string
func (*ClockT) SetInterval ¶
SetInterval setup update interval
type CopyFileOptionFunc ¶
type CopyFileOptionFunc func(o *copyFileOption) error
CopyFileOptionFunc set options for copy file
func WithFileFlag ¶
func WithFileFlag(flag int) CopyFileOptionFunc
WithFileFlag how to write dst file
func WithFileMode ¶
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 Delayer ¶ added in v4.1.0
type Delayer struct {
// contains filtered or unexported fields
}
Delayer create by NewDelay
do not use this type directly.
func NewDelay ¶ added in v4.1.0
NewDelay ensures the execution time of a function is not less than a predefined threshold.
defer NewDelay(time.Second).Wait()
Example ¶
startAt := time.Now() delay := 10 * time.Millisecond func() { defer NewDelay(delay).Wait() }() fmt.Println(time.Since(startAt) >= delay)
Output: true
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: 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 ¶
LoadAndDelete load and delete val from cache
type ExpCacheInterface ¶
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 ¶
GoroutineTest testing.T support goroutine
func NewGoroutineTest ¶
func NewGoroutineTest(tb testing.TB, cancel func()) *GoroutineTest
NewGoroutineTest new test for goroutine
any fail will call cancel()
func (*GoroutineTest) Cleanup ¶ added in v4.2.1
func (t *GoroutineTest) Cleanup(f func())
Cleanup add cleanup func
func (*GoroutineTest) Error ¶ added in v4.2.1
func (t *GoroutineTest) Error(args ...any)
Error call cancal and exit current goroutine
func (*GoroutineTest) Errorf ¶ added in v4.2.1
func (t *GoroutineTest) Errorf(format string, args ...any)
Errorf call cancal and exit current goroutine
func (*GoroutineTest) Fail ¶ added in v4.2.1
func (t *GoroutineTest) Fail()
Fail call cancal and exit current goroutine
func (*GoroutineTest) FailNow ¶
func (t *GoroutineTest) FailNow()
FailNow call cancal and exit current goroutine
func (*GoroutineTest) Failed ¶ added in v4.2.1
func (t *GoroutineTest) Failed() bool
Failed call cancal and exit current goroutine
func (*GoroutineTest) Fatal ¶ added in v4.2.1
func (t *GoroutineTest) Fatal(args ...any)
Fatal call cancal and exit current goroutine
func (*GoroutineTest) Fatalf ¶ added in v4.2.1
func (t *GoroutineTest) Fatalf(format string, args ...any)
Fatalf call cancal and exit current goroutine
func (*GoroutineTest) Helper ¶ added in v4.2.1
func (t *GoroutineTest) Helper()
Helper call cancal and exit current goroutine
func (*GoroutineTest) Log ¶ added in v4.2.1
func (t *GoroutineTest) Log(args ...any)
Log call cancal and exit current goroutine
func (*GoroutineTest) Logf ¶ added in v4.2.1
func (t *GoroutineTest) Logf(format string, args ...any)
Logf call cancal and exit current goroutine
func (*GoroutineTest) Name ¶ added in v4.2.1
func (t *GoroutineTest) Name() string
Name call cancal and exit current goroutine
func (*GoroutineTest) Setenv ¶ added in v4.2.1
func (t *GoroutineTest) Setenv(key, value string)
Setenv call cancal and exit current goroutine
func (*GoroutineTest) Skip ¶ added in v4.2.1
func (t *GoroutineTest) Skip(args ...any)
Skip call cancal and exit current goroutine
func (*GoroutineTest) SkipNow ¶ added in v4.2.1
func (t *GoroutineTest) SkipNow()
SkipNow call cancal and exit current goroutine
func (*GoroutineTest) Skipf ¶ added in v4.2.1
func (t *GoroutineTest) Skipf(format string, args ...any)
Skipf call cancal and exit current goroutine
func (*GoroutineTest) Skipped ¶ added in v4.2.1
func (t *GoroutineTest) Skipped() bool
Skipped call cancal and exit current goroutine
func (*GoroutineTest) TempDir ¶ added in v4.2.1
func (t *GoroutineTest) TempDir() string
TempDir call cancal and exit current goroutine
type HTTPClientOptFunc ¶
type HTTPClientOptFunc func(*httpClientOption) error
HTTPClientOptFunc http client options
func WithHTTPClientInsecure
deprecated
func WithHTTPClientInsecure() HTTPClientOptFunc
WithHTTPClientInsecure set http client igonre ssl issue
default to false
Deprecated: use WithHTTPTlsConfig instead
func WithHTTPClientMaxConn ¶
func WithHTTPClientMaxConn(maxConn int) HTTPClientOptFunc
WithHTTPClientMaxConn set http client max connection
default to 20
func WithHTTPClientProxy ¶ added in v4.1.0
func WithHTTPClientProxy(proxy string) HTTPClientOptFunc
WithHTTPClientProxy set http client proxy
func WithHTTPClientTimeout ¶
func WithHTTPClientTimeout(timeout time.Duration) HTTPClientOptFunc
WithHTTPClientTimeout set http client timeout
default to 30s
func WithHTTPTlsConfig ¶ added in v4.1.0
func WithHTTPTlsConfig(cfg *tls.Config) HTTPClientOptFunc
WithHTTPTlsConfig set tls config
type HashType ¶ added in v4.1.0
type HashType string
HashType hashs
type HashTypeInterface ¶ added in v4.1.0
HashTypeInterface hashs
type JaegerTracingID ¶ added in v4.6.0
type JaegerTracingID string
JaegerTracingID jaeger tracing id
func NewJaegerTracingID ¶ added in v4.6.0
func NewJaegerTracingID(traceID, spanID, parentSpanID uint64, flag byte) (traceVal JaegerTracingID, err error)
NewJaegerTracingID generate jaeger tracing id
Args:
- traceID: trace id, 64bit number, will encode to hex string
- spanID: span id, 64bit number, will encode to hex string
- parentSpanID: parent span id, 64bit number, will encode to hex string
- flag: 8bit number, one byte bitmap, as one or two hex digits (leading zero may be omitted)
Even if some of the parameters have incorrect formatting, it won't result in an error; instead, it will generate a new random value.
func (JaegerTracingID) NewSpan ¶ added in v4.6.0
func (t JaegerTracingID) NewSpan() (JaegerTracingID, error)
NewSpan generate new span
func (JaegerTracingID) Parse ¶ added in v4.6.0
func (t JaegerTracingID) Parse() (traceID, spanID, parentSpanID uint64, flag byte, err error)
Parse parse jaeger tracing id from string
func (JaegerTracingID) String ¶ added in v4.6.0
func (t JaegerTracingID) String() string
String implement fmt.Stringer
type LRUExpiredMap ¶
type LRUExpiredMap[T any] struct { // contains filtered or unexported fields }
LRUExpiredMap map with expire time, auto delete expired item.
`Get` will auto refresh item's expires. `Get` will auto create new item if key not exists.
func NewLRUExpiredMap ¶
func NewLRUExpiredMap[T any](ctx context.Context, ttl time.Duration, newIns func() T) (el *LRUExpiredMap[T], err error)
NewLRUExpiredMap new ExpiredMap
func (*LRUExpiredMap[T]) Get ¶
func (e *LRUExpiredMap[T]) Get(key string) T
Get get item
will auto refresh key's ttl
type ListFilesInDirOptionFunc ¶
type ListFilesInDirOptionFunc func(*listFilesInDirOption) error
ListFilesInDirOptionFunc options for ListFilesInDir
func ListFilesInDirFilter ¶ added in v4.5.0
func ListFilesInDirFilter(filter func(fname string) bool) ListFilesInDirOptionFunc
ListFilesInDirFilter filter files, only return files that filter returns true
func ListFilesInDirRecursive ¶ added in v4.5.0
func ListFilesInDirRecursive() ListFilesInDirOptionFunc
ListFilesInDirRecursive list files in dir recursively
func Recursive
deprecated
func Recursive() ListFilesInDirOptionFunc
Recursive list files recursively
Deprecated: use ListFilesInDirRecursive instead
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 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 PrettyBuildInfoOption ¶ added in v4.9.0
type PrettyBuildInfoOption func(*prettyBuildInfoOption)
PrettyBuildInfoOption options for PrettyBuildInfo
func WithPrettyBuildInfoDeps ¶ added in v4.9.0
func WithPrettyBuildInfoDeps() PrettyBuildInfoOption
WithPrettyBuildInfoDeps include deps in build info
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 RWManager ¶ added in v4.2.1
type RWManager struct {
// contains filtered or unexported fields
}
RWManager auto create rwlock if not exists
type RWManagerInterface ¶ added in v4.2.1
type RWManagerInterface interface { RLock(name string) Lock(name string) RUnlock(name string) Unlock(name string) }
RWManagerInterface auto create rwlock if not exists
type RateLimiter ¶ added in v4.5.1
type RateLimiter struct { RateLimiterArgs // contains filtered or unexported fields }
RateLimiter current limitor
Example ¶
ctx := context.Background() RateLimiter, err := NewRateLimiter(ctx, RateLimiterArgs{ NPerSec: 10, Max: 100, }) if err != nil { panic("new RateLimiter") } defer RateLimiter.Close() inChan := make(chan int) for msg := range inChan { if !RateLimiter.Allow() { continue } // do something with msg fmt.Println(msg) }
Output:
func NewRateLimiter ¶ added in v4.5.1
func NewRateLimiter(ctx context.Context, args RateLimiterArgs) (ratelimiter *RateLimiter, err error)
NewRateLimiter create new Throttle
90x faster than `rate.NewLimiter`
func (*RateLimiter) Allow ¶ added in v4.5.1
func (t *RateLimiter) Allow() bool
Allow check whether is allowed
func (*RateLimiter) AllowN ¶ added in v4.5.1
func (t *RateLimiter) AllowN(n int) bool
AllowN check whether is allowed, default ratelimiter only allow 1 request per second at least, so if you want to allow less than 1 request per second, you should use `AllowN` to consume more tokens each time.
func (*RateLimiter) Len ¶ added in v4.5.2
func (t *RateLimiter) Len() int
Len return current tokens length
type RateLimiterArgs ¶ added in v4.5.1
type RateLimiterArgs struct {
Max, NPerSec int
}
RateLimiterArgs Throttle's configuration
type RequestData ¶
RequestData http request
type SingleItemExpCache ¶
type SingleItemExpCache[T any] struct { // contains filtered or unexported fields }
SingleItemExpCache single item with expires
func NewSingleItemExpCache ¶
func NewSingleItemExpCache[T any](ttl time.Duration) *SingleItemExpCache[T]
NewSingleItemExpCache new expcache contains single data
func (*SingleItemExpCache[T]) Get ¶
func (c *SingleItemExpCache[T]) Get() (data T, ok bool)
Get get data
if data is expired, ok=false
func (*SingleItemExpCache[T]) Set ¶
func (c *SingleItemExpCache[T]) Set(data T)
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
deprecated
type ThrottleCfg
deprecated
type ThrottleCfg RateLimiterArgs
ThrottleCfg Throttle's configuration
Deprecated: use `RateLimiterArgs` instead
type TtlCache ¶ added in v4.9.0
type TtlCache[T any] struct { // contains filtered or unexported fields }
TtlCache cache with ttl
func NewTtlCache ¶ added in v4.9.0
NewTtlCache new cache with ttl
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 common global shared utils
|
Package common global shared utils |
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 crypto is a collection of cryptographic algorithms and protocols, providing hash functions, block and stream ciphers, public key cryptography and authentication.
|
Package crypto is a collection of cryptographic algorithms and protocols, providing hash functions, block and stream ciphers, public key cryptography and authentication. |
kms
Package kms provides a simple kms interface.
|
Package kms provides a simple kms interface. |
kms/mem
Package mem is a multi-key KMS in pure memory
|
Package mem is a multi-key KMS in pure memory |
threshold
package Threshold cryptosystem
|
package Threshold cryptosystem |
threshold/shamir
Package shamir is Shamir’s Secret Sharing is a method for dividing a secret into multiple parts and distributing those parts among different participants.
|
Package shamir is Shamir’s Secret Sharing is a method for dividing a secret into multiple parts and distributing those parts among different participants. |
threshold/signature
Package signature provides an implementation of threshold signatures.
|
Package signature provides an implementation of threshold signatures. |
Package email simple email sender
|
Package email simple email sender |
Package gorm some useful tools for gorm
|
Package gorm some useful tools for gorm |
Package json implements encoding and decoding of JSON as defined in RFC 7159.
|
Package json implements encoding and decoding of JSON as defined in RFC 7159. |
Package jwt all in one JWT sdk
|
Package jwt all in one JWT sdk |
Package log enhanced zap logger
|
Package log enhanced zap logger |