Documentation ¶
Overview ¶
Package utils 一些常用工具
Index ¶
- Constants
- Variables
- func CheckResp(resp *http.Response) error
- func EnableCpuPprof()
- func EnableMemPprof()
- func EnableTracePprof()
- func FallBack(orig func() interface{}, fallback interface{}) (ret interface{})
- func FlattenMap(data map[string]interface{}, delimiter string)
- func FloorDivision(val int, divisor int) int
- func GeneratePasswordHash(password []byte) ([]byte, error)
- func GetFuncName(f interface{}) string
- func HTTPInvalidStatusError(statusCode int) error
- func ParseTs2String(ts int64, layout string) string
- func ParseTs2Time(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 SetupClock(refreshInterval time.Duration)
- func SetupLogger(level string)
- func UTCNow() time.Time
- func ValidatePasswordHash(hashedPassword, password []byte) bool
- type ClockType
- type Config
- type ConfigServerCfg
- type ConfigSource
- type ConfigSrv
- func (c *ConfigSrv) Fetch() error
- func (c *ConfigSrv) Get(name string) (interface{}, bool)
- func (c *ConfigSrv) GetBool(name string) (bool, bool)
- func (c *ConfigSrv) GetInt(name string) (int, bool)
- func (c *ConfigSrv) GetString(name string) (string, bool)
- func (c *ConfigSrv) Map(set func(string, interface{}))
- type Counter
- type JWT
- func (j *JWT) Generate(expiresAt int64, payload map[string]interface{}) (string, error)deprecated
- func (j *JWT) GenerateToken(userId string, expiresAt time.Time, payload map[string]interface{}) (tokenStr string, err error)
- func (j *JWT) Setup(secret string)
- func (j *JWT) Validate(tokenStr string) (payload map[string]interface{}, err error)
- type LoggerType
- type Mail
- type MonotonicRotateCounter
- type PairList
- type RequestData
- type RotateCounter
- type SettingsConst
- 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) GetStringSlice(key string) []string
- func (s *SettingsType) LoadSettings()
- func (s *SettingsType) Set(key string, val interface{})
- func (s *SettingsType) Setup(configPath string) error
- func (s *SettingsType) SetupFromConfigServer(cfg *ConfigServerCfg) (err error)
- func (s *SettingsType) SetupFromConfigServerWithRawYaml(cfg *ConfigServerCfg, 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 ¶
Constants ¶
const ( HTTPJSONHeader = "Content-Type" HTTPJSONHeaderVal = "application/json" )
HTTP defines
const CFG_FNAME = "settings.yml"
const SampleRateDenominator = 1000
sample rate = sample / SampleRateDenominator
Variables ¶
var Clock = NewClock(defaultClockInterval)
Clock high performance time utils
var Settings = &SettingsType{ SettingsConst: &SettingsConst{ YAML_TYPE: "yaml", }, }
Settings is the settings for this project
Functions ¶
func EnableCpuPprof ¶
func EnableCpuPprof()
func EnableMemPprof ¶
func EnableMemPprof()
func EnableTracePprof ¶
func EnableTracePprof()
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") } utils.FallBack(targetFunc, 10) // got 10
Output:
func FlattenMap ¶
func GeneratePasswordHash ¶ added in v1.2.0
GeneratePasswordHash generate hashed password by origin password
func HTTPInvalidStatusError ¶
HTTPInvalidStatusError return error about status code
func ParseTs2String ¶
ParseTs2String can parse unix timestamp(int64) to string
func ParseTs2Time ¶
ParseTs2Time can parse unix timestamp(int64) to time.Time
func RandomStringWithLength ¶
func RegexNamedSubMatch ¶
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)
func SetupClock ¶
func ValidatePasswordHash ¶ added in v1.2.0
ValidatePasswordHash validate password is match with hashedPassword
Types ¶
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"` }
type ConfigServerCfg ¶
type ConfigSource ¶
type ConfigSrv ¶
type ConfigSrv struct { *ConfigServerCfg Cfg *Config }
ConfigSrv can load configuration from Spring-Cloud-Config-Server
Example ¶
package main import ( utils "github.com/Laisky/go-utils" ) func main() { var ( url = "http://config-server.un.org" app = "appname" profile = "sit" label = "master" ) c := utils.NewConfigSrv(&utils.ConfigServerCfg{ URL: url, App: app, Profile: profile, Label: 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 ¶
func NewConfigSrv(cfg *ConfigServerCfg) *ConfigSrv
NewConfigSrv create ConfigSrv
type Counter ¶
Example ¶
package main import ( utils "github.com/Laisky/go-utils" ) func main() { counter := utils.NewCounter() counter.Count() counter.CountN(10) counter.Get() // get current count }
Output:
func NewCounter ¶
func NewCounter() *Counter
func NewCounterFromN ¶
type JWT ¶
JWT struct to generate and validate jwt tokens
type LoggerType ¶
LoggerType extend from zap.Logger
var (
Logger *LoggerType
)
func (*LoggerType) DebugSample ¶
func (l *LoggerType) DebugSample(sample int, msg string, fields ...zap.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 ...zap.Field)
InfoSample emit info log with propability sample/SampleRateDenominator
func (*LoggerType) WarnSample ¶
func (l *LoggerType) WarnSample(sample int, msg string, fields ...zap.Field)
type Mail ¶
type Mail struct {
// contains filtered or unexported fields
}
func (*Mail) BuildMessage ¶
type MonotonicRotateCounter ¶
type MonotonicRotateCounter struct {
// contains filtered or unexported fields
}
MonotonicRotateCounter monotonic increse counter uncontinuity, has much better performance than RotateCounter.
func NewMonotonicCounterFromN ¶
func NewMonotonicCounterFromN(n, rotatePoint int64) (*MonotonicRotateCounter, error)
func NewMonotonicRotateCounter ¶
func NewMonotonicRotateCounter(rotatePoint int64) (*MonotonicRotateCounter, error)
func (*MonotonicRotateCounter) Count ¶
func (c *MonotonicRotateCounter) Count() (n int64)
func (*MonotonicRotateCounter) CountN ¶
func (c *MonotonicRotateCounter) CountN(n int64) (r int64)
type RequestData ¶
RequestData 发起请求的结构体
type RotateCounter ¶
type RotateCounter struct {
// contains filtered or unexported fields
}
Example ¶
package main import ( utils "github.com/Laisky/go-utils" ) func main() { counter, err := utils.NewRotateCounter(10) if err != nil { panic(err) } counter.Count() // 1 counter.CountN(10) // 1 }
Output:
func NewRotateCounter ¶
func NewRotateCounter(rotatePoint int64) (*RotateCounter, error)
func NewRotateCounterFromN ¶
func NewRotateCounterFromN(n, rotatePoint int64) (*RotateCounter, error)
func (*RotateCounter) Count ¶
func (c *RotateCounter) Count() int64
func (*RotateCounter) CountN ¶
func (c *RotateCounter) CountN(n int64) (r int64)
type SettingsConst ¶
type SettingsConst struct {
YAML_TYPE string
}
type SettingsType ¶
type SettingsType struct { *SettingsConst sync.Mutex }
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) GetStringSlice ¶
func (s *SettingsType) GetStringSlice(key string) []string
GetStringSlice get setting by key
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(cfg *ConfigServerCfg) (err error)
SetupFromConfigServer load configs from config-server, endpoint `{url}/{app}/{profile}/{label}`
func (*SettingsType) SetupFromConfigServerWithRawYaml ¶
func (s *SettingsType) SetupFromConfigServerWithRawYaml(cfg *ConfigServerCfg, 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{} }
type Throttle ¶
type Throttle struct { *ThrottleCfg // contains filtered or unexported fields }
func NewThrottle ¶
func NewThrottle(cfg *ThrottleCfg) *Throttle
type ThrottleCfg ¶
type ThrottleCfg struct {
Max, NPerSec int
}
type Uint32Counter ¶
type Uint32Counter struct {
// contains filtered or unexported fields
}
func NewUint32Counter ¶
func NewUint32Counter() *Uint32Counter
func NewUint32CounterFromN ¶
func NewUint32CounterFromN(n uint32) *Uint32Counter
func (*Uint32Counter) Count ¶
func (c *Uint32Counter) Count() uint32
func (*Uint32Counter) CountN ¶
func (c *Uint32Counter) CountN(n uint32) uint32
func (*Uint32Counter) Get ¶
func (c *Uint32Counter) Get() uint32
func (*Uint32Counter) Set ¶
func (c *Uint32Counter) Set(n uint32)
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package consistenthash contains some implementation of consistent hashing.
|
Package consistenthash contains some implementation of consistent hashing. |