本文整理汇总了Golang中Time.ParseDuration函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseDuration函数的具体用法?Golang ParseDuration怎么用?Golang ParseDuration使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ParseDuration函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ValidateNodeAuthConfig
func ValidateNodeAuthConfig(config api.NodeAuthConfig) fielderrors.ValidationErrorList {
allErrs := fielderrors.ValidationErrorList{}
if len(config.AuthenticationCacheTTL) == 0 {
allErrs = append(allErrs, fielderrors.NewFieldRequired("authenticationCacheTTL"))
} else if ttl, err := time.ParseDuration(config.AuthenticationCacheTTL); err != nil {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("authenticationCacheTTL", config.AuthenticationCacheTTL, fmt.Sprintf("%v", err)))
} else if ttl < 0 {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("authenticationCacheTTL", config.AuthenticationCacheTTL, fmt.Sprintf("cannot be less than zero")))
}
if config.AuthenticationCacheSize <= 0 {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("authenticationCacheSize", config.AuthenticationCacheSize, fmt.Sprintf("must be greater than zero")))
}
if len(config.AuthorizationCacheTTL) == 0 {
allErrs = append(allErrs, fielderrors.NewFieldRequired("authorizationCacheTTL"))
} else if ttl, err := time.ParseDuration(config.AuthorizationCacheTTL); err != nil {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("authorizationCacheTTL", config.AuthorizationCacheTTL, fmt.Sprintf("%v", err)))
} else if ttl < 0 {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("authorizationCacheTTL", config.AuthorizationCacheTTL, fmt.Sprintf("cannot be less than zero")))
}
if config.AuthorizationCacheSize <= 0 {
allErrs = append(allErrs, fielderrors.NewFieldInvalid("authorizationCacheSize", config.AuthorizationCacheSize, fmt.Sprintf("must be greater than zero")))
}
return allErrs
}
示例2: ParseWait
func ParseWait(s string) (*Wait, error) {
if len(strings.TrimSpace(s)) < 1 {
return &Wait{0, 0}, nil
}
parts := strings.Split(s, ":")
var (
min time.Duration
max time.Duration
err error
)
min, err = time.ParseDuration(strings.TrimSpace(parts[0]))
if err != nil {
return nil, err
}
if len(parts) > 1 {
max, err = time.ParseDuration(strings.TrimSpace(parts[1]))
if err != nil {
return nil, err
}
if max < min {
return nil, errors.New("Invalid wait interval: max must be larger than min")
}
} else {
max = 4 * min
}
return &Wait{min, max}, nil
}
示例3: extract
// extract a Message from bytes
func (m *Message) extract(b []byte) {
slices := bytes.Split(b, []byte{'|'})
i := bytes.Index(b, []byte{'|'})
m.Type = "default"
if i != -1 {
// well I know how I'd do it in python
// this seems a little awkward
m.dirtyfields = make(map[int]bool)
if res, err := get(0, slices); err == nil {
m.setField(0, string(res))
}
}
if res, err := get(1, slices); err == nil {
if string(res) != "" {
m.setField(1, string(res))
}
}
if res, err := get(2, slices); err == nil {
m.setField(2, string(res))
}
if res, err := get(3, slices); err == nil {
if t, err2 := strconv.Atoi(string(res)); err2 == nil {
Timeout, _ := time.ParseDuration(fmt.Sprintf("%ds", t))
m.setField(3, Timeout)
} else {
if d, err3 := time.ParseDuration(string(res)); err3 == nil {
m.setField(3, d)
}
}
}
}
示例4: pathConfigLeaseWrite
func (b *backend) pathConfigLeaseWrite(
req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
ttlRaw := d.Get("ttl").(string)
ttlMaxRaw := d.Get("max_ttl").(string)
if len(ttlMaxRaw) == 0 {
ttlMaxRaw = d.Get("ttl_max").(string)
}
ttl, err := time.ParseDuration(ttlRaw)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf(
"Invalid ttl: %s", err)), nil
}
ttlMax, err := time.ParseDuration(ttlMaxRaw)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf(
"Invalid max_ttl: %s", err)), nil
}
// Store it
entry, err := logical.StorageEntryJSON("config/lease", &configLease{
TTL: ttl,
TTLMax: ttlMax,
})
if err != nil {
return nil, err
}
if err := req.Storage.Put(entry); err != nil {
return nil, err
}
return nil, nil
}
示例5: ValidateNodeAuthConfig
func ValidateNodeAuthConfig(config api.NodeAuthConfig, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
authenticationCacheTTLPath := fldPath.Child("authenticationCacheTTL")
if len(config.AuthenticationCacheTTL) == 0 {
allErrs = append(allErrs, field.Required(authenticationCacheTTLPath, ""))
} else if ttl, err := time.ParseDuration(config.AuthenticationCacheTTL); err != nil {
allErrs = append(allErrs, field.Invalid(authenticationCacheTTLPath, config.AuthenticationCacheTTL, fmt.Sprintf("%v", err)))
} else if ttl < 0 {
allErrs = append(allErrs, field.Invalid(authenticationCacheTTLPath, config.AuthenticationCacheTTL, fmt.Sprintf("cannot be less than zero")))
}
if config.AuthenticationCacheSize <= 0 {
allErrs = append(allErrs, field.Invalid(fldPath.Child("authenticationCacheSize"), config.AuthenticationCacheSize, fmt.Sprintf("must be greater than zero")))
}
authorizationCacheTTLPath := fldPath.Child("authorizationCacheTTL")
if len(config.AuthorizationCacheTTL) == 0 {
allErrs = append(allErrs, field.Required(authorizationCacheTTLPath, ""))
} else if ttl, err := time.ParseDuration(config.AuthorizationCacheTTL); err != nil {
allErrs = append(allErrs, field.Invalid(authorizationCacheTTLPath, config.AuthorizationCacheTTL, fmt.Sprintf("%v", err)))
} else if ttl < 0 {
allErrs = append(allErrs, field.Invalid(authorizationCacheTTLPath, config.AuthorizationCacheTTL, fmt.Sprintf("cannot be less than zero")))
}
if config.AuthorizationCacheSize <= 0 {
allErrs = append(allErrs, field.Invalid(fldPath.Child("authorizationCacheSize"), config.AuthorizationCacheSize, fmt.Sprintf("must be greater than zero")))
}
return allErrs
}
示例6: statistics
func (server *server) statistics() serverStats {
stats := *server.stats
stats.Uptime = time.Since(server.startedAt).Seconds()
stats.CurrentTubes = len(server.tubes)
stats.TotalJobs = len(server.jobs)
for _, tube := range server.tubes {
stats.CurrentJobsBuried += tube.buried.Len()
stats.CurrentJobsDelayed += tube.delayed.Len()
stats.CurrentJobsReady += tube.ready.Len()
stats.CurrentJobsReserved += tube.reserved.Len()
}
var duration time.Duration
usage := new(syscall.Rusage)
err := syscall.Getrusage(syscall.RUSAGE_SELF, usage)
if err == nil {
s, ns := usage.Utime.Unix()
duration, err = time.ParseDuration(fmt.Sprintf("%d.%ds", s, ns))
stats.RusageStime = duration.Seconds()
s, ns = usage.Stime.Unix()
duration, err = time.ParseDuration(fmt.Sprintf("%d.%ds", s, ns))
stats.RusageUtime = duration.Seconds()
} else {
pf("failed to get rusage : %v", err)
}
return stats
}
示例7: New
func New(cookieName string, expires int, sessionDir string, timerDuration string) *SessionManager {
if cookieName == "" {
cookieName = "GoLangerSession"
}
if expires <= 0 {
expires = 3600 * 24
}
if sessionDir == "" {
sessionDir = "./tmp/" + "golangersession/"
}
os.MkdirAll(sessionDir, 0777)
var dTimerDuration time.Duration
if td, terr := time.ParseDuration(timerDuration); terr == nil {
dTimerDuration = td
} else {
dTimerDuration, _ = time.ParseDuration("24h")
}
s := &SessionManager{
CookieName: cookieName,
expires: expires,
sessionDir: sessionDir,
timerDuration: dTimerDuration,
}
time.AfterFunc(s.timerDuration, func() { s.GC() })
return s
}
示例8: init
func init() {
Environment = getEnv("_DEPLOY_ENV")
SignalfxAPIKey = getEnv("SIGNALFX_API_KEY")
data := getEnv("POLLING_CONFIG")
err := yaml.Unmarshal([]byte(data), &PollingConfigs)
if err != nil {
log.Fatalf("error: %v", err)
}
for i := range PollingConfigs {
fmt.Printf("%+v", PollingConfigs[i])
pollInterval, err := time.ParseDuration(PollingConfigs[i].PollIntervalRaw)
if err != nil {
log.Fatalf("Could not parse duration from poll_interval: %s", err)
}
PollingConfigs[i].PollInterval = pollInterval
// default to http for backwards compatibility
if PollingConfigs[i].RabbitMQProto == "" {
PollingConfigs[i].RabbitMQProto = "http"
}
var timeout time.Duration
if PollingConfigs[i].TimeoutRaw != "" {
timeout, err = time.ParseDuration(PollingConfigs[i].TimeoutRaw)
if err != nil {
log.Fatalf("Could not parse duration from timeout: %s", err)
}
} else {
// default to 60 seconds
timeout = time.Duration(60 * time.Second)
}
PollingConfigs[i].Timeout = timeout
}
}
示例9: decodeConfig
func decodeConfig(configBytes []byte) (*ProxyConfig, error) {
var config ProxyConfig
if err := json.Unmarshal(configBytes, &config); err != nil {
return nil, err
}
if config.StatsDelay != nil {
duration, err := time.ParseDuration(*config.StatsDelay)
config.StatsDelayDuration = &duration
if err != nil {
return nil, err
}
}
for _, f := range config.ForwardTo {
if f.Timeout != nil {
duration, err := time.ParseDuration(*f.Timeout)
f.TimeoutDuration = &duration
if err != nil {
return nil, err
}
}
}
for _, f := range config.ListenFrom {
if f.Timeout != nil {
duration, err := time.ParseDuration(*f.Timeout)
f.TimeoutDuration = &duration
if err != nil {
return nil, err
}
}
}
return &config, nil
}
示例10: toContainerControllerOptions
func (c ControllerOptions) toContainerControllerOptions() (options container.ControllerOptions, err error) {
options.ServicedEndpoint = c.ServicedEndpoint
options.Service.Autorestart = c.Autorestart
options.Service.InstanceID = c.InstanceID
options.Service.ID = c.ServiceID
options.Service.Command = c.Command
options.Mux.Port = c.MuxPort
options.Mux.Enabled = c.Mux
options.Mux.TLS = c.TLS
options.Mux.KeyPEMFile = c.KeyPEMFile
options.Mux.CertPEMFile = c.CertPEMFile
options.Logforwarder.Enabled = c.Logstash
options.Logforwarder.Path = c.LogstashBinary
options.Logforwarder.ConfigFile = c.LogstashConfig
options.Metric.Address = c.MetricForwarderPort
options.MetricForwarding = c.MetricForwardingEnabled
options.Metric.RemoteEndoint = "http://localhost:8444/api/metrics/store"
options.VirtualAddressSubnet = c.VirtualAddressSubnet
options.Logforwarder.SettleTime, err = time.ParseDuration(c.LogstashSettleTime)
if err != nil {
return options, err
}
options.Logforwarder.IdleFlushTime, err = time.ParseDuration(c.LogstashIdleFlushTime)
if err != nil {
return options, err
}
return options, nil
}
示例11: GetAccessToken
func GetAccessToken() (string, error) {
if cacheServer != nil {
tokenS, found := cacheServer.Get(key_access_token)
if found {
switch tokenS.(type) {
case string:
return tokenS.(string), nil
default:
return "", fmt.Errorf("access_token from cache is not type string.\n")
}
}
token, err := wapi.GetAcessToken()
if err != nil {
return "", fmt.Errorf("wapi GetAcessToken error. %s\n", err.Error())
}
expires_in, err := time.ParseDuration(strconv.Itoa(token.Expires_in) + "s")
if err != nil {
log.Panicf("format expires [%s] err:%s\n", token.Expires_in, err.Error())
log.Printf("use default expires_in %s", default_expires_in)
expires_in, err = time.ParseDuration(default_expires_in + "s")
if err != nil {
return "", fmt.Errorf("format default expires [%s] err:%s\n", token.Expires_in, err.Error())
}
}
cacheServer.Add(key_access_token, token.Access_token, expires_in)
return token.Access_token, nil
}
return "", fmt.Errorf("cacheServer is nil.\n")
}
示例12: parseDuration
func parseDuration(s string) (time.Duration, error) {
var interval time.Duration
if s[len(s)-1] == 'd' {
days, err := strconv.ParseInt(s[0:len(s)-1], 10, 64)
if err != nil {
return time.Nanosecond, err
}
interval, err = time.ParseDuration(strconv.FormatInt(days*24, 10) + "h")
if err != nil {
return time.Nanosecond, err
}
} else if s[len(s)-1] == 'h' ||
s[len(s)-1] == 'm' ||
s[len(s)-1] == 's' {
return time.ParseDuration(s)
} else {
seconds, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return time.Nanosecond, err
}
interval, err = time.ParseDuration(strconv.FormatInt(seconds, 10) + "s")
if err != nil {
return time.Nanosecond, err
}
}
return interval, nil
}
示例13: Kick
func (g *game) Kick() bool {
if g.State == _WAITING_FOR_OPPONENT || g.State == _DEACTIVATED {
return false
}
ret := false
if g.State == _GAME_IN_PROGRESS {
dur, _ := time.ParseDuration(strconv.Itoa(turnLength) + _TIME_UNIT)
if now().After(g.TurnStart.Add(dur)) {
g.State = _WAITING_FOR_REMATCH
ret = true
for i := 0; i < 2; i++ {
if g.CurrentChoices[i] == `` {
g.CurrentChoices[i] = options[rand.Intn(len(options))]
}
}
g.PastChoices = append(g.PastChoices, g.CurrentChoices[0], g.CurrentChoices[1])
if len(g.PastChoices) >= _DOUBLE_MAX_TURNS {
g.State = _DEACTIVATED
} else {
g.State = _WAITING_FOR_REMATCH
}
}
}
if g.State == _WAITING_FOR_REMATCH {
dur, _ := time.ParseDuration(strconv.Itoa(turnLength+_REMATCH_TIME_LIMIT) + _TIME_UNIT)
if now().After(g.TurnStart.Add(dur)) {
g.State = _DEACTIVATED
ret = true
}
}
return ret
}
示例14: FixupCheckType
func FixupCheckType(raw interface{}) error {
// Handle decoding of time durations
rawMap, ok := raw.(map[string]interface{})
if !ok {
return nil
}
if ttl, ok := rawMap["ttl"]; ok {
ttlS, ok := ttl.(string)
if ok {
if dur, err := time.ParseDuration(ttlS); err != nil {
return err
} else {
rawMap["ttl"] = dur
}
}
}
if interval, ok := rawMap["interval"]; ok {
intervalS, ok := interval.(string)
if ok {
if dur, err := time.ParseDuration(intervalS); err != nil {
return err
} else {
rawMap["interval"] = dur
}
}
}
return nil
}
示例15: New
func New(cookieName string, expires int, timerDuration string) *SessionManager {
if cookieName == "" {
cookieName = "GoLangerSession"
}
if expires <= 0 {
expires = 3600 * 24
}
var dTimerDuration time.Duration
if td, terr := time.ParseDuration(timerDuration); terr == nil {
dTimerDuration = td
} else {
dTimerDuration, _ = time.ParseDuration("24h")
}
s := &SessionManager{
CookieName: cookieName,
sessions: map[string][2]map[string]interface{}{},
expires: expires,
timerDuration: dTimerDuration,
}
time.AfterFunc(s.timerDuration, func() { s.GC() })
return s
}