Created
June 10, 2019 09:40
-
-
Save leafsummer/73717fbc672c177b28367a81c6a179eb to your computer and use it in GitHub Desktop.
[timeoutset with golang]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"sync" | |
"time" | |
) | |
type TimeoutSet struct { | |
sync.RWMutex | |
time map[string]time.Time | |
timeout time.Duration | |
} | |
func NewTimeoutSet(timeout time.Duration) *TimeoutSet { | |
ts := &TimeoutSet{time: make(map[string]time.Time), | |
timeout: timeout, | |
} | |
return ts | |
} | |
func (ts *TimeoutSet) add(key string) { | |
now := time.Now() | |
ts.Lock() | |
ts.time[key] = now | |
ts.Unlock() | |
} | |
func (ts *TimeoutSet) has(key string) bool { | |
ts.RLock() | |
t, ok := ts.time[key] | |
ts.RUnlock() | |
if !ok { | |
return false | |
} | |
if time.Now().Sub(t) > ts.timeout { | |
ts.del(key) | |
return false | |
} | |
return true | |
} | |
func (ts *TimeoutSet) del(key string) { | |
ts.Lock() | |
delete(ts.time, key) | |
ts.Unlock() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment