Documentation ¶
Overview ¶
Package utils 一些常用工具
Index ¶
- Constants
- Variables
- func AddFileToZip(zipWriter *zip.Writer, filename string) (err error)
- func AutoGC(ctx context.Context, opts ...GcOptFunc) (err error)
- func Base64(raw []byte) string
- func CheckResp(resp *http.Response) error
- func Color(color int, s string) string
- func DecodeECDSAPrivateKey(pemEncoded []byte) (*ecdsa.PrivateKey, error)
- func DecodeECDSAPublicKey(pemEncodedPub []byte) (*ecdsa.PublicKey, error)
- func DecodeES256SignByBase64(sign string) (a, b *big.Int, err error)
- func DecodeES256SignByHex(sign string) (a, b *big.Int, err error)
- func DecryptByAes(secret []byte, encrypted []byte) ([]byte, error)
- func DirSize(path string) (size int64, err error)
- func EncodeECDSAPrivateKey(privateKey *ecdsa.PrivateKey) ([]byte, error)
- func EncodeECDSAPublicKey(publicKey *ecdsa.PublicKey) ([]byte, error)
- func EncodeES256SignByBase64(a, b *big.Int) string
- func EncodeES256SignByHex(a, b *big.Int) string
- func EncryptByAES(secret []byte, cnt []byte) ([]byte, error)
- func FallBack(orig func() interface{}, fallback interface{}) (ret interface{})
- func FlattenMap(data map[string]interface{}, delimiter string)
- func ForceGCBlocking()
- func ForceGCUnBlocking()
- func FormatBig2Base64(b *big.Int) string
- func FormatBig2Hex(b *big.Int) string
- func GeneratePasswordHash(password []byte) ([]byte, error)
- func GetFuncName(f interface{}) string
- func HTTPInvalidStatusError(statusCode int) error
- func HashSHA128String(val string) string
- func HashSHA256String(val string) string
- func HashXxhashString(val string) string
- func IsHasField(st interface{}, fieldName string) bool
- func IsHasMethod(st interface{}, methodName string) bool
- func IsPtr(t interface{}) bool
- func MaxInt(a, b int) int
- func MinInt(a, b int) int
- func NewHTTPClient(opts ...HttpClientOptFunc) (c *http.Client, err error)
- func ParseBase642Big(raw string) (*big.Int, error)
- func ParseECDSASign(sign string) (a, b *big.Int, ok bool)
- func ParseHex2Big(hex string) (b *big.Int, ok bool)
- func ParseHex2UTC(ts string) (t time.Time, err error)
- func ParseHexNano2UTC(ts string) (t time.Time, err error)
- func ParseJWTTokenWithoutValidate(token string) (payload jwt.MapClaims, err error)
- func ParseUnix2String(ts int64, layout string) string
- func ParseUnix2UTC(ts int64) time.Time
- func ParseUnixNano2UTC(ts int64) time.Time
- func RandomStringWithLength(n int) string
- func RegexNamedSubMatch(r *regexp.Regexp, str string, subMatchMap map[string]string) error
- func RequestJSON(method, url string, request *RequestData, resp interface{}) (err error)
- func RequestJSONWithClient(httpClient *http.Client, method, url string, request *RequestData, ...) (err error)
- func Round(val float64, roundOn float64, places int) (newVal float64)
- func RunCMD(ctx context.Context, app string, args ...string) (stdout []byte, err error)
- func SetStructFieldsBySlice(structs, vals interface{}) (err error)
- func SetupClock(refreshInterval time.Duration)
- func SignByECDSAWithSHA256(priKey *ecdsa.PrivateKey, content []byte) (r, s *big.Int, err error)
- func SignReaderByECDSAWithSHA256(priKey *ecdsa.PrivateKey, reader io.Reader) (r, s *big.Int, err error)
- func TemplateWithMap(tpl string, data map[string]interface{}) string
- func TemplateWithMapAndRegexp(tplReg *regexp.Regexp, tpl string, data map[string]interface{}) string
- func URLMasking(url, mask string) string
- func UTCNow() time.Time
- func UniqueStrings(vs []string) (r []string)
- func Unzip(src string, dest string) (filenames []string, err error)
- func ValidateFileHash(filepath string, hashed string) error
- func ValidatePasswordHash(hashedPassword, password []byte) bool
- func VerifyByECDSAWithSHA256(pubKey *ecdsa.PublicKey, content []byte, r, s *big.Int) bool
- func VerifyReaderByECDSAWithSHA256(pubKey *ecdsa.PublicKey, reader io.Reader, r, s *big.Int) (bool, error)
- func ZipFiles(filename string, files []string) (err error)
- type AcquireLockOptFunc
- type AlertHookOptFunc
- type AlertPusher
- type ChildParallelCounter
- type Clock2Type
- type ClockItf
- type ClockType
- type CompressOptFunc
- type CompressorItf
- type Config
- type ConfigSource
- type ConfigSrv
- func (c *ConfigSrv) Fetch() error
- func (c *ConfigSrv) Get(name string) (interface{}, bool)
- func (c *ConfigSrv) GetBool(name string) (val bool, ok bool)
- func (c *ConfigSrv) GetInt(name string) (val int, ok bool)
- func (c *ConfigSrv) GetString(name string) (string, bool)
- func (c *ConfigSrv) Map(set func(string, interface{}))
- type Counter
- type CtxKeyT
- type GZCompressor
- type GcOptFunc
- type HttpClientOptFunc
- type Int64CounterItf
- type JWT
- func (e *JWT) ParseClaims(token string, claimsPtr jwt.Claims, opts ...JWTDiviceOptFunc) error
- func (e *JWT) ParseClaimsByES256(token string, claimsPtr jwt.Claims, opts ...JWTDiviceOptFunc) error
- func (e *JWT) ParseClaimsByHS256(token string, claimsPtr jwt.Claims, opts ...JWTDiviceOptFunc) error
- func (e *JWT) Sign(claims jwt.Claims, opts ...JWTDiviceOptFunc) (string, error)
- func (e *JWT) SignByES256(claims jwt.Claims, opts ...JWTDiviceOptFunc) (string, error)
- func (e *JWT) SignByHS256(claims jwt.Claims, opts ...JWTDiviceOptFunc) (string, error)
- type JWTDiviceOptFunc
- type JWTOptFunc
- type LaiskyRemoteLock
- type LaiskyRemoteLockOptFunc
- type LoggerType
- func CreateNewDefaultLogger(name, level string, opts ...zap.Option) (l *LoggerType, err error)
- func NewConsoleLoggerWithName(name, level string, opts ...zap.Option) (l *LoggerType, err error)
- func NewLogger(level string, opts ...zap.Option) (l *LoggerType, err error)
- func NewLoggerWithName(name, level string, opts ...zap.Option) (l *LoggerType, err error)
- func NewLoggerWithNameAndFormat(name, format, level string, opts ...zap.Option) (l *LoggerType, err error)
- func (l *LoggerType) ChangeLevel(level string) (err error)
- func (l *LoggerType) Clone() *LoggerType
- func (l *LoggerType) DebugSample(sample int, msg string, fields ...zapcore.Field)
- func (l *LoggerType) InfoSample(sample int, msg string, fields ...zapcore.Field)
- func (l *LoggerType) Named(s string) *LoggerType
- func (l *LoggerType) WarnSample(sample int, msg string, fields ...zapcore.Field)
- func (l *LoggerType) With(fields ...zapcore.Field) *LoggerType
- func (l *LoggerType) WithOptions(opts ...zap.Option) *LoggerType
- type Mail
- type Mutex
- type PGZCompressor
- type PairList
- type ParallelCounter
- type PateoAlertPusher
- type RequestData
- type RotateCounter
- func NewRotateCounter(rotatePoint int64) (*RotateCounter, error)
- func NewRotateCounterFromN(n, rotatePoint int64) (*RotateCounter, error)
- func NewRotateCounterFromNWithCtx(ctx context.Context, n, rotatePoint int64) (*RotateCounter, error)
- func NewRotateCounterWithCtx(ctx context.Context, rotatePoint int64) (*RotateCounter, error)
- type SettingsType
- func (s *SettingsType) BindPFlags(p *pflag.FlagSet) error
- func (s *SettingsType) Get(key string) interface{}
- func (s *SettingsType) GetBool(key string) bool
- func (s *SettingsType) GetDuration(key string) time.Duration
- func (s *SettingsType) GetInt(key string) int
- func (s *SettingsType) GetInt64(key string) int64
- func (s *SettingsType) GetString(key string) string
- func (s *SettingsType) GetStringMap(key string) map[string]interface{}
- func (s *SettingsType) GetStringMapString(key string) map[string]string
- func (s *SettingsType) GetStringSlice(key string) []string
- func (s *SettingsType) IsSet(key string) bool
- func (s *SettingsType) LoadSettings()
- func (s *SettingsType) Set(key string, val interface{})
- func (s *SettingsType) Setup(configPath string) error
- func (s *SettingsType) SetupFromConfigServer(url, app, profile, label string) (err error)
- func (s *SettingsType) SetupFromConfigServerWithRawYaml(url, app, profile, label, key string) (err error)
- func (s *SettingsType) SetupFromDir(dirPath string) error
- func (s *SettingsType) SetupFromFile(filePath string) error
- type SortItemItf
- type Throttle
- type ThrottleCfg
- type Uint32Counter
Examples ¶
- AlertPusher
- AutoGC
- ConfigSrv
- Counter
- DirSize
- FallBack
- FlattenMap
- ForceGCBlocking
- ForceGCUnBlocking
- GZCompressor
- GeneratePasswordHash
- GetFuncName
- HashSHA128String
- HashSHA256String
- HashXxhashString
- JWT
- Mutex
- PGZCompressor
- RegexNamedSubMatch
- RotateCounter
- Round
- SetStructFieldsBySlice
- SignByECDSAWithSHA256
- Throttle
- URLMasking
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 ( HTTPJSONHeader = "Content-Type" HTTPJSONHeaderVal = "application/json" )
HTTP defines
const ( // SampleRateDenominator sample rate = sample / SampleRateDenominator SampleRateDenominator = 1000 LoggerLevelInfo = "info" LoggerLevelDebug = "debug" LoggerLevelWarn = "warn" LoggerLevelError = "error" )
const ANSIColorEscape = "\x1b"
inspired by github.com/fatih/color
Variables ¶
var ( // SignMethodHS256 use HS256 for jwt SignMethodHS256 = jwt.SigningMethodHS256 // SignMethodES256 use ES256 for jwt SignMethodES256 = jwt.SigningMethodES256 )
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 ( // Clock high performance time utils, replace Clock1 Clock = NewClock(context.Background(), defaultClockInterval) // Clock2 high performance time utils Clock2 = Clock // NewClock2 create new Clock NewClock2 = NewClock )
var ( // ForceGC force to start gc blocking ForceGC = ForceGCBlocking // TriggerGC force to start gc unblocking TriggerGC = ForceGCUnBlocking )
var FormatECDSASign = EncodeES256SignByHex
FormatECDSASign
Deprecated: use EncodeES256SignByBase6e instead
var GetHTTPClient = NewHTTPClient
GetHTTPClient new http client
Deprecated: use NewHTTPClient replaced
var (
// JSON effective json
JSON = json
)
var Settings = &SettingsType{}
Settings is the settings for this project
Functions ¶
func AddFileToZip ¶ added in v1.11.5
AddFileToZip add file tp zip.Writer
func AutoGC ¶ added in v1.10.2
AutoGC auto trigger GC when memory usage exceeds the custom ration
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 { Logger.Error("enable autogc", zap.Error(err)) }
Output:
func DecodeECDSAPrivateKey ¶ added in v1.11.3
func DecodeECDSAPrivateKey(pemEncoded []byte) (*ecdsa.PrivateKey, error)
DecodeECDSAPrivateKey decode ecdsa private key from pem bytes
func DecodeECDSAPublicKey ¶ added in v1.11.3
DecodeECDSAPrivateKey decode ecdsa public key from pem bytes
func DecodeES256SignByBase64 ¶ added in v1.12.3
DecodeES256SignByBase64 parse ecdsa sign string to two *big.Int
func DecodeES256SignByHex ¶ added in v1.12.3
DecodeES256SignByHex parse ecdsa sign string to two *big.Int
func DecryptByAes ¶ added in v1.12.7
DecryptByAes encrypt bytes by aes with key
inspired by https://tutorialedge.net/golang/go-encrypt-decrypt-aes-tutorial/
func DirSize ¶ added in v1.10.1
DirSize calculate directory size. https://stackoverflow.com/a/32482941/2368737
Example ¶
dirPath := "." size, err := DirSize(dirPath) if err != nil { Logger.Error("get dir size", zap.Error(err), zap.String("path", dirPath)) } Logger.Info("got size", zap.Int64("size", size), zap.String("path", dirPath))
Output:
func EncodeECDSAPrivateKey ¶ added in v1.11.3
func EncodeECDSAPrivateKey(privateKey *ecdsa.PrivateKey) ([]byte, error)
EncodeECDSAPrivateKey encode ecdsa private key to pem bytes
func EncodeECDSAPublicKey ¶ added in v1.11.3
EncodeECDSAPublicKey encode ecdsa public key to pem bytes
func EncodeES256SignByBase64 ¶ added in v1.12.3
EncodeES256SignByBase64 format ecdsa sign to stirng
func EncodeES256SignByHex ¶ added in v1.12.3
EncodeES256SignByHex format ecdsa sign to stirng
func EncryptByAES ¶ added in v1.12.7
EncryptByAES encrypt bytes by aes with key
inspired by https://tutorialedge.net/golang/go-encrypt-decrypt-aes-tutorial/
func FallBack ¶
func FallBack(orig func() interface{}, fallback interface{}) (ret interface{})
FallBack return the fallback when orig got error utils.FallBack(func() interface{} { return getIOStatMetric(fs) }, &IOStat{}).(*IOStat)
Example ¶
targetFunc := func() interface{} { panic("someting wrong") } FallBack(targetFunc, 10) // got 10
Output:
func FlattenMap ¶
FlattenMap make embedded map into flatten map
Example ¶
data := map[string]interface{}{ "a": "1", "b": map[string]interface{}{ "c": 2, "d": map[string]interface{}{ "e": 3, }, }, } FlattenMap(data, "__") // {"a": "1", "b__c": 2, "b__d__e": 3}
Output:
func ForceGCBlocking ¶ added in v1.7.4
func ForceGCBlocking()
ForceGCBlocking force to run blocking manual gc.
Example ¶
ForceGCBlocking()
Output:
func ForceGCUnBlocking ¶ added in v1.7.4
func ForceGCUnBlocking()
ForceGCUnBlocking trigger GC unblocking
Example ¶
ForceGCUnBlocking()
Output:
func FormatBig2Base64 ¶ added in v1.12.6
FormatBig2Base64 format big to base64 string
func FormatBig2Hex ¶ added in v1.11.4
FormatBig2Hex format big to hex string
func GeneratePasswordHash ¶ added in v1.2.0
GeneratePasswordHash generate hashed password by origin password
Example ¶
// generate hashed password rawPassword := []byte("1234567890") hashedPassword, err := GeneratePasswordHash(rawPassword) if err != nil { Logger.Error("try to generate password got error", zap.Error(err)) return } fmt.Printf("got new hashed pasword: %v\n", string(hashedPassword)) // validate passowrd if !ValidatePasswordHash(hashedPassword, rawPassword) { Logger.Error("password invalidate", zap.Error(err)) return }
Output:
func GetFuncName ¶
func GetFuncName(f interface{}) string
GetFuncName return the name of func
Example ¶
GetFuncName(testFoo) // "github.com/Laisky/go-utils.testFoo"
Output:
func HTTPInvalidStatusError ¶
HTTPInvalidStatusError return error about status code
func HashSHA128String ¶ added in v1.10.2
HashSHA128String calculate string's hash by sha256
Example ¶
val := "dfij3ifj2jjl2jelkjdkwef" got := HashSHA128String(val) Logger.Info("hash", zap.String("got", got))
Output:
func HashSHA256String ¶ added in v1.10.1
HashSHA256String calculate string's hash by sha256
Example ¶
val := "dfij3ifj2jjl2jelkjdkwef" got := HashSHA256String(val) Logger.Info("hash", zap.String("got", got))
Output:
func HashXxhashString ¶ added in v1.10.1
HashXxhashString calculate string's hash by sha256
Example ¶
val := "dfij3ifj2jjl2jelkjdkwef" got := HashXxhashString(val) Logger.Info("hash", zap.String("got", got))
Output:
func IsHasField ¶ added in v1.12.2
IsHasField check is struct has field
inspired by https://mrwaggel.be/post/golang-reflect-if-initialized-struct-has-member-method-or-fields/
func IsHasMethod ¶ added in v1.12.2
IsHasMethod check is struct has method
inspired by https://mrwaggel.be/post/golang-reflect-if-initialized-struct-has-member-method-or-fields/
func NewHTTPClient ¶ added in v1.12.8
func NewHTTPClient(opts ...HttpClientOptFunc) (c *http.Client, err error)
NewHTTPClient create http client
func ParseBase642Big ¶ added in v1.12.6
ParseBase642Big parse base64 string to big
func ParseECDSASign ¶ added in v1.11.4
ParseECDSASign(Deprecated)
func ParseHex2Big ¶ added in v1.11.4
ParseHex2Big parse hex string to big
func ParseHex2UTC ¶ added in v1.8.0
ParseHex2UTC parse hex to UTC time
func ParseHexNano2UTC ¶ added in v1.8.0
ParseHexNano2UTC parse hex contains nano to UTC time
func ParseJWTTokenWithoutValidate ¶ added in v1.10.0
ParseJWTTokenWithoutValidate parse and get payload without validate jwt token
func ParseUnix2String ¶ added in v1.8.0
ParseUnix2String can parse unix timestamp(int64) to string
func ParseUnix2UTC ¶ added in v1.8.0
ParseUnix2UTC convert unix to UTC time
func ParseUnixNano2UTC ¶ added in v1.8.0
ParseUnixNano2UTC convert unixnano to UTC time
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 { Logger.Error("try to group match got error", zap.Error(err)) } fmt.Printf("got: %+v", groups) // map[string]string{"key": 12345}
Output:
func RequestJSON ¶
func RequestJSON(method, url string, request *RequestData, resp interface{}) (err error)
RequestJSON request JSON and return JSON by default client
func RequestJSONWithClient ¶
func RequestJSONWithClient(httpClient *http.Client, method, url string, request *RequestData, resp interface{}) (err error)
RequestJSONWithClient request JSON and return JSON with specific client
func Round ¶
Round Golang does not include a round function in the standard math package Round(123.555555, .5, 3) -> 123.556
Example ¶
Round(123.555555, .5, 3) // got 123.556
Output:
func SetStructFieldsBySlice ¶ added in v1.11.1
func SetStructFieldsBySlice(structs, vals interface{}) (err error)
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 { Logger.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 SetupClock ¶
SetupClock setup internal Clock with step
func SignByECDSAWithSHA256 ¶ added in v1.11.3
SignByECDSAWithSHA256 generate signature by ecdsa private key use sha256
Example ¶
priKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { Logger.Panic("generate key", zap.Error(err)) } priKey2, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { Logger.Panic("generate key", zap.Error(err)) } // case: correct key cnt := []byte("fjijf23lijfl23ijrl32jra9pfie9wpfi") r, s, err := SignByECDSAWithSHA256(priKey, cnt) if err != nil { Logger.Panic("sign", zap.Error(err)) } if !VerifyByECDSAWithSHA256(&priKey.PublicKey, cnt, r, s) { Logger.Panic("verify failed") } // generate string encoded := EncodeES256SignByBase64(r, s) if _, _, err = DecodeES256SignByBase64(encoded); err != nil { Logger.Panic("encode and decode", zap.Error(err)) } // case: incorrect cnt cnt = []byte("fjijf23lijfl23ijrl32jra9pfie9wpfi") r, s, err = SignByECDSAWithSHA256(priKey, cnt) if err != nil { Logger.Panic("sign", zap.Error(err)) } if VerifyByECDSAWithSHA256(&priKey.PublicKey, append(cnt, '2'), r, s) { Logger.Panic("should not verify") } // case: incorrect key r, s, err = SignByECDSAWithSHA256(priKey2, cnt) if err != nil { Logger.Panic("sign", zap.Error(err)) } if VerifyByECDSAWithSHA256(&priKey.PublicKey, cnt, r, s) { Logger.Panic("should not verify") }
Output:
func SignReaderByECDSAWithSHA256 ¶ added in v1.11.4
func SignReaderByECDSAWithSHA256(priKey *ecdsa.PrivateKey, reader io.Reader) (r, s *big.Int, err error)
SignReaderByECDSAWithSHA256 generate signature by ecdsa private key use sha256
func TemplateWithMap ¶ added in v1.5.4
TemplateWithMap replace `${var}` in template string
func TemplateWithMapAndRegexp ¶ added in v1.5.4
func TemplateWithMapAndRegexp(tplReg *regexp.Regexp, tpl string, data map[string]interface{}) string
TemplateWithMapAndRegexp replace `${var}` in template string
func URLMasking ¶ added in v1.9.3
URLMasking masking password in url
Example ¶
originURL := "http://12ijij:3j23irj@jfjlwef.ffe.com" newURL := URLMasking(originURL, "*****") fmt.Println(newURL) // http://12ijij:*****@jfjlwef.ffe.com
Output:
func UniqueStrings ¶ added in v1.11.2
UniqueStrings remove duplicate string in slice
func Unzip ¶ added in v1.11.5
Unzip will decompress a zip archive, moving all files and folders within the zip file (parameter 1) to an output directory (parameter 2).
func ValidateFileHash ¶ added in v1.12.1
ValidateFileHash validate file content with hashed string
func ValidatePasswordHash ¶ added in v1.2.0
ValidatePasswordHash validate password is match with hashedPassword
func VerifyByECDSAWithSHA256 ¶ added in v1.11.3
VerifyByECDSAWithSHA256 verify signature by ecdsa public key use sha256
func VerifyReaderByECDSAWithSHA256 ¶ added in v1.11.4
func VerifyReaderByECDSAWithSHA256(pubKey *ecdsa.PublicKey, reader io.Reader, r, s *big.Int) (bool, error)
VerifyReaderByECDSAWithSHA256 verify signature by ecdsa public key use sha256
Types ¶
type AcquireLockOptFunc ¶ added in v1.10.0
type AcquireLockOptFunc func(*acquireLockOption) error
AcquireLockOptFunc options for acquire lock
func WithAcquireLockDuration ¶ added in v1.10.0
func WithAcquireLockDuration(duration time.Duration) AcquireLockOptFunc
WithAcquireLockDuration set how long to extend lock
func WithAcquireLockIsRenewal ¶ added in v1.10.0
func WithAcquireLockIsRenewal(isRenewal bool) AcquireLockOptFunc
WithAcquireLockIsRenewal set whether to auto renewal lock
func WithAcquireLockMaxRetry ¶ added in v1.10.0
func WithAcquireLockMaxRetry(maxRetry int) AcquireLockOptFunc
WithAcquireLockMaxRetry set max retry to acquire lock
func WithAcquireLockRenewalInterval ¶ added in v1.10.0
func WithAcquireLockRenewalInterval(renewalInterval time.Duration) AcquireLockOptFunc
WithAcquireLockRenewalInterval set how ofter to renewal lock
type AlertHookOptFunc ¶ added in v1.10.0
type AlertHookOptFunc func(*alertHookOption)
AlertHookOptFunc option for create AlertHook
func WithAlertHookLevel ¶ added in v1.9.0
func WithAlertHookLevel(level zapcore.Level) AlertHookOptFunc
WithAlertHookLevel level to trigger AlertHook
func WithAlertPushTimeout ¶ added in v1.9.0
func WithAlertPushTimeout(timeout time.Duration) AlertHookOptFunc
WithAlertPushTimeout set AlertPusher HTTP timeout
type AlertPusher ¶ added in v1.9.0
type AlertPusher struct {
// contains filtered or unexported fields
}
AlertPusher send alert to laisky's alert API
https://github.com/Laisky/laisky-blog-graphql/tree/master/telegram
Example ¶
pusher, err := NewAlertPusherWithAlertType( context.Background(), "https://blog.laisky.com/graphql/query/", "hello", "rwkpVuAgaBZQBASKndHK", ) if err != nil { Logger.Panic("create alert pusher", zap.Error(err)) } defer pusher.Close() logger := Logger.WithOptions( zap.Fields(zap.String("logger", "test")), zap.HooksWithFields(pusher.GetZapHook()), ) logger.Debug("DEBUG", zap.String("yo", "hello")) logger.Info("Info", zap.String("yo", "hello")) logger.Warn("Warn", zap.String("yo", "hello")) logger.Error("Error", zap.String("yo", "hello")) time.Sleep(1 * time.Second)
Output:
func NewAlertPusher ¶ added in v1.9.0
func NewAlertPusher(ctx context.Context, pushAPI string, opts ...AlertHookOptFunc) (a *AlertPusher, err error)
NewAlertPusher create new AlertPusher
func NewAlertPusherWithAlertType ¶ added in v1.9.0
func NewAlertPusherWithAlertType(ctx context.Context, pushAPI string, alertType, pushToken string, opts ...AlertHookOptFunc) (a *AlertPusher, err error)
NewAlertPusherWithAlertType create new AlertPusher with default type and token
func (*AlertPusher) GetZapHook ¶ added in v1.10.1
GetZapHook get hook for zap logger
func (*AlertPusher) Send ¶ added in v1.9.0
func (a *AlertPusher) Send(msg string) (err error)
Send send with default alertType and pushToken
func (*AlertPusher) SendWithType ¶ added in v1.9.0
func (a *AlertPusher) SendWithType(alertType, pushToken, msg string) (err error)
SendWithType send alert with specific type, token and msg
type ChildParallelCounter ¶ added in v1.6.3
ChildParallelCounter child of ParallelCounter
func (*ChildParallelCounter) Count ¶ added in v1.6.3
func (c *ChildParallelCounter) Count() (r int64)
Count count 1
func (*ChildParallelCounter) CountN ¶ added in v1.6.3
func (c *ChildParallelCounter) CountN(n int64) (r int64)
CountN count n
func (*ChildParallelCounter) Get ¶ added in v1.6.3
func (c *ChildParallelCounter) Get() int64
Get get current count
type Clock2Type ¶ added in v1.7.3
type Clock2Type ClockType
Clock2Type high performance clock with lazy refreshing
type ClockItf ¶ added in v1.7.3
type ClockItf interface { GetTimeInRFC3339Nano() string GetUTCNow() time.Time SetupInterval(time.Duration) Close() }
ClockItf high performance lazy clock
type ClockType ¶
ClockType high performance clock with lazy refreshing
func (*ClockType) GetNanoTimeInHex ¶ added in v1.8.0
GetNanoTimeInHex return current time with nano in hex
func (*ClockType) GetTimeInHex ¶ added in v1.8.0
GetTimeInHex return current time in hex
func (*ClockType) GetTimeInRFC3339Nano ¶
GetTimeInRFC3339Nano return Clock current time in string
func (*ClockType) SetupInterval ¶
SetupInterval setup update interval
type CompressOptFunc ¶ added in v1.10.0
type CompressOptFunc func(*compressOption) error
CompressOptFunc options for compressor
func WithCompressBufSizeByte ¶ added in v1.10.0
func WithCompressBufSizeByte(n int) CompressOptFunc
WithCompressBufSizeByte set compressor buf size
func WithCompressLevel ¶ added in v1.10.0
func WithCompressLevel(n int) CompressOptFunc
WithCompressLevel set compressor compress level
func WithPGzipBlockSize ¶ added in v1.10.0
func WithPGzipBlockSize(bytes int) CompressOptFunc
WithPGzipBlockSize set compressor blocks
func WithPGzipNBlocks ¶ added in v1.10.0
func WithPGzipNBlocks(nBlock int) CompressOptFunc
WithPGzipNBlocks set compressor blocks
type CompressorItf ¶ added in v1.10.0
type CompressorItf interface { Write([]byte) (int, error) WriteString(string) (int, error) // write footer and flust to lower writer Flush() error WriteFooter() error }
CompressorItf interface of compressor
type Config ¶
type Config struct { Name string `json:"name"` Profiles []string `json:"profiles"` Label string `json:"label"` Version string `json:"version"` Sources []*ConfigSource `json:"propertySources"` }
Config whole configuation return by config-server
type ConfigSource ¶
type ConfigSource struct { Name string `json:"name"` Source map[string]interface{} `json:"source"` }
ConfigSource config item in config-server
type ConfigSrv ¶
type ConfigSrv struct { RemoteCfg *Config // contains filtered or unexported fields }
ConfigSrv can load configuration from Spring-Cloud-Config-Server
Example ¶
var ( url = "http://config-server.un.org" app = "appname" profile = "sit" label = "master" ) c := NewConfigSrv(url, app, profile, label) c.Get("management.context-path") c.GetString("management.context-path") c.GetBool("endpoints.health.sensitive") c.GetInt("spring.cloud.config.retry")
Output:
func NewConfigSrv ¶
NewConfigSrv create ConfigSrv
type Counter ¶
Counter int64 counter
Example ¶
counter := NewCounter() counter.Count() counter.CountN(10) counter.Get() // get current count
Output:
func NewCounterFromN ¶
NewCounterFromN create Counter from custom number
type GZCompressor ¶ added in v1.6.0
type GZCompressor struct {
// contains filtered or unexported fields
}
GZCompressor compress by gz with buf
Example ¶
originText := "fj2f32f9jp9wsif0weif20if320fi23if" writer := &bytes.Buffer{} var err error // writer c, err := NewGZCompressor( writer, WithCompressLevel(defaultGzCompressLevel), // default WithCompressBufSizeByte(defaultCompressBufSizeByte), // default ) if err != nil { Logger.Error("new compressor", zap.Error(err)) return } if _, err = c.WriteString(originText); err != nil { Logger.Error("write string to compressor", zap.Error(err)) return } if err = c.Flush(); err != nil { Logger.Error("flush compressor", zap.Error(err)) return } // reader var gz *gzip.Reader if gz, err = gzip.NewReader(writer); err != nil { Logger.Error("new compressor", zap.Error(err)) return } var bs []byte if bs, err = ioutil.ReadAll(gz); err != nil { Logger.Error("read from compressor", zap.Error(err)) return } got := string(bs) if got != originText { Logger.Error("extract compressed text invalidate", zap.String("got", got), zap.ByteString("expect", bs)) return }
Output:
func NewGZCompressor ¶ added in v1.6.0
func NewGZCompressor(writer io.Writer, opts ...CompressOptFunc) (c *GZCompressor, err error)
NewGZCompressor create new GZCompressor
func (*GZCompressor) Flush ¶ added in v1.6.0
func (c *GZCompressor) Flush() (err error)
Flush flush buffer bytes into bottom writer with gz meta footer
func (*GZCompressor) Write ¶ added in v1.6.0
func (c *GZCompressor) Write(d []byte) (int, error)
Write write bytes via compressor
func (*GZCompressor) WriteFooter ¶ added in v1.6.2
func (c *GZCompressor) WriteFooter() (err error)
WriteFooter write gz footer
func (*GZCompressor) WriteString ¶ added in v1.6.0
func (c *GZCompressor) WriteString(d string) (int, error)
WriteString write string via compressor
type GcOptFunc ¶ added in v1.10.2
type GcOptFunc func(*gcOption) error
GcOptFunc option for GC utils
func WithGCMemLimitFilePath ¶ added in v1.10.2
WithGCMemLimitFilePath set memory limit file
func WithGCMemRatio ¶ added in v1.10.2
WithGCMemRatio set mem ratio trigger for GC
type HttpClientOptFunc ¶ added in v1.12.3
type HttpClientOptFunc func(*httpClientOption) error
HttpClientOptFunc http client options
func WithHTTPClientInsecure ¶ added in v1.12.3
func WithHTTPClientInsecure(insecure bool) HttpClientOptFunc
WithHTTPClientInsecure set http client igonre ssl issue
func WithHTTPClientMaxConn ¶ added in v1.12.3
func WithHTTPClientMaxConn(maxConn int) HttpClientOptFunc
WithHTTPClientMaxConn set http client max connection
func WithHTTPClientTimeout ¶ added in v1.12.3
func WithHTTPClientTimeout(timeout time.Duration) HttpClientOptFunc
WithHTTPClientTimeout set http client timeout
type Int64CounterItf ¶ added in v1.7.8
Int64CounterItf counter for int64
type JWT ¶
type JWT struct {
// contains filtered or unexported fields
}
JWT is token utils that support HS256/ES256
Example ¶
secret = []byte("4738947328rh3ru23f32hf238f238fh28f") j, err := NewJWT( WithJWTSignMethod(SignMethodHS256), WithJWTSecretByte(secret), ) if err != nil { Logger.Panic("new jwt", zap.Error(err)) } type jwtClaims struct { jwt.StandardClaims } claims := &jwtClaims{ jwt.StandardClaims{ Subject: "laisky", }, } // signing token, err := j.Sign(claims) if err != nil { Logger.Panic("sign jwt", zap.Error(err)) } // verify claims = &jwtClaims{} if err := j.ParseClaims(token, claims); err != nil { Logger.Panic("sign jwt", zap.Error(err)) }
Output:
func NewJWT ¶ added in v1.3.3
func NewJWT(opts ...JWTOptFunc) (e *JWT, err error)
NewJWT create new JWT utils
func (*JWT) ParseClaims ¶ added in v1.12.0
func (e *JWT) ParseClaims(token string, claimsPtr jwt.Claims, opts ...JWTDiviceOptFunc) error
ParseClaims parse token to claims
func (*JWT) ParseClaimsByES256 ¶ added in v1.12.0
func (e *JWT) ParseClaimsByES256(token string, claimsPtr jwt.Claims, opts ...JWTDiviceOptFunc) error
ParseClaimsByES256 parse token to claims by ES256
func (*JWT) ParseClaimsByHS256 ¶ added in v1.12.0
func (e *JWT) ParseClaimsByHS256(token string, claimsPtr jwt.Claims, opts ...JWTDiviceOptFunc) error
ParseClaimsByHS256 parse token to claims by HS256
func (*JWT) Sign ¶ added in v1.12.0
func (e *JWT) Sign(claims jwt.Claims, opts ...JWTDiviceOptFunc) (string, error)
Sign sign claims to token
func (*JWT) SignByES256 ¶ added in v1.12.0
func (e *JWT) SignByES256(claims jwt.Claims, opts ...JWTDiviceOptFunc) (string, error)
SignByES256 signing claims by ES256
func (*JWT) SignByHS256 ¶ added in v1.12.0
func (e *JWT) SignByHS256(claims jwt.Claims, opts ...JWTDiviceOptFunc) (string, error)
SignByHS256 signing claims by HS256
type JWTDiviceOptFunc ¶ added in v1.12.0
type JWTDiviceOptFunc func(*jwtDivideOpt) error
JWTDiviceOptFunc options to use seperate secret for every user in parsing/signing
func WithJWTDividePriKey ¶ added in v1.12.0
func WithJWTDividePriKey(priKey []byte) JWTDiviceOptFunc
WithJWTDividePriKey set asymmetrical private key for each signning/verify
func WithJWTDividePubKey ¶ added in v1.12.0
func WithJWTDividePubKey(pubKey []byte) JWTDiviceOptFunc
WithJWTDividePubKey set asymmetrical public key for each signning/verify
func WithJWTDivideSecret ¶ added in v1.12.0
func WithJWTDivideSecret(secret []byte) JWTDiviceOptFunc
WithJWTDivideSecret set symmetric key for each signning/verify
type JWTOptFunc ¶ added in v1.10.0
JWTOptFunc options to setup JWT
func WithJWTPriKeyByte ¶ added in v1.12.0
func WithJWTPriKeyByte(prikey []byte) JWTOptFunc
WithJWTPriKeyByte set jwt asymmetrical private key
func WithJWTPubKeyByte ¶ added in v1.12.0
func WithJWTPubKeyByte(pubkey []byte) JWTOptFunc
WithJWTPubKeyByte set jwt asymmetrical public key
func WithJWTSecretByte ¶ added in v1.12.0
func WithJWTSecretByte(secret []byte) JWTOptFunc
WithJWTSecretByte set jwt symmetric signning key
func WithJWTSignMethod ¶ added in v1.10.0
func WithJWTSignMethod(method jwt.SigningMethod) JWTOptFunc
WithJWTSignMethod set jwt signing method
type LaiskyRemoteLock ¶ added in v1.10.0
type LaiskyRemoteLock struct {
// contains filtered or unexported fields
}
LaiskyRemoteLock acquire lock from Laisky's GraphQL API
func NewLaiskyRemoteLock ¶ added in v1.10.0
func NewLaiskyRemoteLock(api, token string, opts ...LaiskyRemoteLockOptFunc) (l *LaiskyRemoteLock, err error)
NewLaiskyRemoteLock create remote lock
func (*LaiskyRemoteLock) AcquireLock ¶ added in v1.10.0
func (l *LaiskyRemoteLock) AcquireLock(ctx context.Context, lockName string, opts ...AcquireLockOptFunc) (ok bool, err error)
AcquireLock acquire lock with lockname, if `isRenewal=true`, will automate refresh lock's lease until ctx done. duration to specify how much time each renewal will extend.
type LaiskyRemoteLockOptFunc ¶ added in v1.10.0
type LaiskyRemoteLockOptFunc func(*LaiskyRemoteLock) error
LaiskyRemoteLockOptFunc laisky's lock option
func WithLaiskyRemoteLockTimeout ¶ added in v1.10.0
func WithLaiskyRemoteLockTimeout(timeout time.Duration) LaiskyRemoteLockOptFunc
WithLaiskyRemoteLockTimeout set http client timeout
type LoggerType ¶
LoggerType extend from zap.Logger
var ( /*Logger logging tool. * Info(msg string, fields ...Field) * Debug(msg string, fields ...Field) * Warn(msg string, fields ...Field) * Error(msg string, fields ...Field) * Panic(msg string, fields ...Field) * DebugSample(sample int, msg string, fields ...zapcore.Field) * InfoSample(sample int, msg string, fields ...zapcore.Field) * WarnSample(sample int, msg string, fields ...zapcore.Field) */ Logger *LoggerType )
func CreateNewDefaultLogger ¶ added in v1.10.1
func CreateNewDefaultLogger(name, level string, opts ...zap.Option) (l *LoggerType, err error)
CreateNewDefaultLogger set default utils.Logger
func NewConsoleLoggerWithName ¶ added in v1.12.8
func NewConsoleLoggerWithName(name, level string, opts ...zap.Option) (l *LoggerType, err error)
NewConsoleLoggerWithName create new logger with name
func NewLogger ¶ added in v1.8.0
func NewLogger(level string, opts ...zap.Option) (l *LoggerType, err error)
NewLogger create new logger
func NewLoggerWithName ¶ added in v1.9.0
func NewLoggerWithName(name, level string, opts ...zap.Option) (l *LoggerType, err error)
NewLoggerWithName create new logger with name
func NewLoggerWithNameAndFormat ¶ added in v1.12.8
func NewLoggerWithNameAndFormat(name, format, level string, opts ...zap.Option) (l *LoggerType, err error)
NewLoggerWithNameAndFormat create new logger
func (*LoggerType) ChangeLevel ¶ added in v1.8.0
func (l *LoggerType) ChangeLevel(level string) (err error)
ChangeLevel change logger level
func (*LoggerType) Clone ¶ added in v1.10.1
func (l *LoggerType) Clone() *LoggerType
Clone clone new Logger that inherit all config
func (*LoggerType) DebugSample ¶
func (l *LoggerType) DebugSample(sample int, msg string, fields ...zapcore.Field)
DebugSample emit debug log with propability sample/SampleRateDenominator. sample could be [0, 1000], less than 0 means never, great than 1000 means certainly
func (*LoggerType) InfoSample ¶
func (l *LoggerType) InfoSample(sample int, msg string, fields ...zapcore.Field)
InfoSample emit info log with propability sample/SampleRateDenominator
func (*LoggerType) Named ¶ added in v1.10.1
func (l *LoggerType) Named(s string) *LoggerType
Named adds a new path segment to the logger's name. Segments are joined by periods. By default, Loggers are unnamed.
func (*LoggerType) WarnSample ¶
func (l *LoggerType) WarnSample(sample int, msg string, fields ...zapcore.Field)
WarnSample emit warn log with propability sample/SampleRateDenominator
func (*LoggerType) With ¶ added in v1.9.4
func (l *LoggerType) With(fields ...zapcore.Field) *LoggerType
With creates a child logger and adds structured context to it. Fields added to the child don't affect the parent, and vice versa.
func (*LoggerType) WithOptions ¶ added in v1.9.4
func (l *LoggerType) WithOptions(opts ...zap.Option) *LoggerType
WithOptions clones the current Logger, applies the supplied Options, and returns the resulting Logger. It's safe to use concurrently.
type Mail ¶
type Mail struct {
// contains filtered or unexported fields
}
Mail easy way to send basic email
Example ¶
sender := NewMail("smtp_host", 53) if err := sender.Send( "fromAddr", "toAddr", "frName", "toName", "Title", "Content", ); err != nil { Logger.Error("try to send email got error", zap.Error(err)) }
Output:
type Mutex ¶ added in v1.3.7
type Mutex struct {
// contains filtered or unexported fields
}
Mutex mutex that support unblocking lock
Example ¶
l := NewMutex() if !l.TryLock() { Logger.Info("can not acquire lock") return } defer l.ForceRelease()
Output:
func (*Mutex) ForceRelease ¶ added in v1.7.5
func (m *Mutex) ForceRelease()
ForceRelease force release lock
func (*Mutex) TryRelease ¶ added in v1.3.7
TryRelease return true if succeed release
type PGZCompressor ¶ added in v1.10.0
type PGZCompressor struct {
// contains filtered or unexported fields
}
PGZCompressor compress by gz with buf
Example ¶
originText := "fj2f32f9jp9wsif0weif20if320fi23if" writer := &bytes.Buffer{} var err error // writer c, err := NewPGZCompressor(writer) if err != nil { Logger.Error("new compressor", zap.Error(err)) return } if _, err = c.WriteString(originText); err != nil { Logger.Error("write string to compressor", zap.Error(err)) return } if err = c.Flush(); err != nil { Logger.Error("flush compressor", zap.Error(err)) return } // reader var gz *gzip.Reader if gz, err = gzip.NewReader(writer); err != nil { Logger.Error("new compressor", zap.Error(err)) return } var bs []byte if bs, err = ioutil.ReadAll(gz); err != nil { Logger.Error("read from compressor", zap.Error(err)) return } got := string(bs) if got != originText { Logger.Error("extract compressed text invalidate", zap.String("got", got), zap.ByteString("expect", bs)) return }
Output:
func NewPGZCompressor ¶ added in v1.10.0
func NewPGZCompressor(writer io.Writer, opts ...CompressOptFunc) (c *PGZCompressor, err error)
NewPGZCompressor create new PGZCompressor
func (*PGZCompressor) Flush ¶ added in v1.10.0
func (c *PGZCompressor) Flush() (err error)
Flush flush buffer bytes into bottom writer with gz meta footer
func (*PGZCompressor) Write ¶ added in v1.10.0
func (c *PGZCompressor) Write(d []byte) (int, error)
Write write bytes via compressor
func (*PGZCompressor) WriteFooter ¶ added in v1.10.0
func (c *PGZCompressor) WriteFooter() (err error)
WriteFooter write gz footer
func (*PGZCompressor) WriteString ¶ added in v1.10.0
func (c *PGZCompressor) WriteString(d string) (int, error)
WriteString write string via compressor
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 ParallelCounter ¶ added in v1.6.3
ParallelCounter parallel count with child counter
func NewParallelCounter ¶ added in v1.6.3
func NewParallelCounter(quoteStep, rotatePoint int64) (*ParallelCounter, error)
NewParallelCounter get new parallel counter
func NewParallelCounterFromN ¶ added in v1.6.3
func NewParallelCounterFromN(n, quoteStep, rotatePoint int64) (*ParallelCounter, error)
NewParallelCounterFromN get new parallel counter
func (*ParallelCounter) GetChild ¶ added in v1.6.3
func (c *ParallelCounter) GetChild() *ChildParallelCounter
GetChild create new child
func (*ParallelCounter) GetQuote ¶ added in v1.6.3
func (c *ParallelCounter) GetQuote(step int64) (from, to int64)
GetQuote child request new quote from parent
type PateoAlertPusher ¶ added in v1.10.1
type PateoAlertPusher struct {
// contains filtered or unexported fields
}
PateoAlertPusher alert pusher for pateo wechat service
func NewPateoAlertPusher ¶ added in v1.10.1
func NewPateoAlertPusher(ctx context.Context, api, token string, opts ...AlertHookOptFunc) (p *PateoAlertPusher, err error)
NewPateoAlertPusher create new PateoAlertPusher
func (*PateoAlertPusher) GetZapHook ¶ added in v1.10.1
GetZapHook get hook for zap logger
type RequestData ¶
RequestData 发起请求的结构体
type RotateCounter ¶
type RotateCounter struct { Mutex // contains filtered or unexported fields }
RotateCounter rotate counter
Example ¶
counter, err := NewRotateCounter(10) if err != nil { panic(err) } counter.Count() // 1 counter.CountN(10) // 1
Output:
func NewRotateCounter ¶
func NewRotateCounter(rotatePoint int64) (*RotateCounter, error)
NewRotateCounter create new RotateCounter with threshold from 0
func NewRotateCounterFromN ¶
func NewRotateCounterFromN(n, rotatePoint int64) (*RotateCounter, error)
NewRotateCounterFromN create new RotateCounter with threshold from N
func NewRotateCounterFromNWithCtx ¶ added in v1.7.5
func NewRotateCounterFromNWithCtx(ctx context.Context, n, rotatePoint int64) (*RotateCounter, error)
NewRotateCounterFromNWithCtx create new RotateCounter with threshold from N
func NewRotateCounterWithCtx ¶ added in v1.7.5
func NewRotateCounterWithCtx(ctx context.Context, rotatePoint int64) (*RotateCounter, error)
NewRotateCounterWithCtx create new RotateCounter with threshold from 0
func (*RotateCounter) Close ¶ added in v1.7.5
func (c *RotateCounter) Close()
Close stop rorate runner
func (*RotateCounter) Count ¶
func (c *RotateCounter) Count() int64
Count increse and return the result
func (*RotateCounter) CountN ¶
func (c *RotateCounter) CountN(n int64) (r int64)
CountN increse N and return the result
func (*RotateCounter) Get ¶ added in v1.7.8
func (c *RotateCounter) Get() int64
Get return current counter's number
type SettingsType ¶
SettingsType type of project settings
func (*SettingsType) BindPFlags ¶
func (s *SettingsType) BindPFlags(p *pflag.FlagSet) error
BindPFlags bind pflags to settings
func (*SettingsType) Get ¶
func (s *SettingsType) Get(key string) interface{}
Get get setting by key
func (*SettingsType) GetBool ¶
func (s *SettingsType) GetBool(key string) bool
GetBool get setting by key
func (*SettingsType) GetDuration ¶
func (s *SettingsType) GetDuration(key string) time.Duration
GetDuration get setting by key
func (*SettingsType) GetInt ¶
func (s *SettingsType) GetInt(key string) int
GetInt get setting by key
func (*SettingsType) GetInt64 ¶
func (s *SettingsType) GetInt64(key string) int64
GetInt64 get setting by key
func (*SettingsType) GetString ¶
func (s *SettingsType) GetString(key string) string
GetString get setting by key
func (*SettingsType) GetStringMap ¶ added in v1.5.4
func (s *SettingsType) GetStringMap(key string) map[string]interface{}
GetStringMap return map contains interface
func (*SettingsType) GetStringMapString ¶ added in v1.5.4
func (s *SettingsType) GetStringMapString(key string) map[string]string
GetStringMapString return map contains strings
func (*SettingsType) GetStringSlice ¶
func (s *SettingsType) GetStringSlice(key string) []string
GetStringSlice get setting by key
func (*SettingsType) IsSet ¶ added in v1.5.4
func (s *SettingsType) IsSet(key string) bool
IsSet check whether exists
func (*SettingsType) LoadSettings ¶
func (s *SettingsType) LoadSettings()
LoadSettings load settings file
func (*SettingsType) Set ¶
func (s *SettingsType) Set(key string, val interface{})
Set set setting by key
func (*SettingsType) Setup ¶
func (s *SettingsType) Setup(configPath string) error
Setup load config file settings.yml
func (*SettingsType) SetupFromConfigServer ¶
func (s *SettingsType) SetupFromConfigServer(url, app, profile, label string) (err error)
SetupFromConfigServer load configs from config-server, endpoint `{url}/{app}/{profile}/{label}`
func (*SettingsType) SetupFromConfigServerWithRawYaml ¶
func (s *SettingsType) SetupFromConfigServerWithRawYaml(url, app, profile, label, key string) (err error)
SetupFromConfigServerWithRawYaml load configs from config-server
endpoint `{url}/{app}/{profile}/{label}`
load raw yaml content and parse.
func (*SettingsType) SetupFromDir ¶
func (s *SettingsType) SetupFromDir(dirPath string) error
SetupFromDir load settings from dir, default fname is `settings.yml`
func (*SettingsType) SetupFromFile ¶
func (s *SettingsType) SetupFromFile(filePath string) error
SetupFromFile load settings from file
type SortItemItf ¶
type SortItemItf interface { GetValue() int GetKey() interface{} }
SortItemItf interface of sort item
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 { Logger.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 ¶ added in v1.9.0
func NewThrottleWithCtx(ctx context.Context, cfg *ThrottleCfg) (t *Throttle, err error)
NewThrottleWithCtx create new Throttle
type ThrottleCfg ¶
type ThrottleCfg struct {
Max, NPerSec int
}
ThrottleCfg Throttle's configuration
type Uint32Counter ¶
type Uint32Counter struct {
// contains filtered or unexported fields
}
Uint32Counter uint32 counter
func NewUint32Counter ¶
func NewUint32Counter() *Uint32Counter
NewUint32Counter return new Uint32Counter from 0
func NewUint32CounterFromN ¶
func NewUint32CounterFromN(n uint32) *Uint32Counter
NewUint32CounterFromN return new Uint32Counter from n
func (*Uint32Counter) Count ¶
func (c *Uint32Counter) Count() uint32
Count increse and return the result
func (*Uint32Counter) CountN ¶
func (c *Uint32Counter) CountN(n uint32) uint32
CountN increse N and return the result
func (*Uint32Counter) Get ¶
func (c *Uint32Counter) Get() uint32
Get return current counter's number
func (*Uint32Counter) Set ¶
func (c *Uint32Counter) Set(n uint32)
Set overwrite the counter's number
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package consistenthash contains some implementation of consistent hashing.
|
Package consistenthash contains some implementation of consistent hashing. |