Last active
March 19, 2020 04:36
-
-
Save clarkmcc/f239244b45f4b169877046f10779368a to your computer and use it in GitHub Desktop.
Throttler implements a leaky bucket request throttling algorithm where the duration between two requests is never less than the MinInterval
This file contains hidden or 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
type ThrottleEngine struct { | |
// The key to this map represents a unique user being throttled, such as | |
// an api key, or some user identification obtained from a header | |
MostRecentRequest map[string]time.Time | |
MinInterval time.Duration | |
M *sync.Mutex | |
} | |
type HttpHandlerFunc func(http.ResponseWriter, *http.Request) | |
// Throttler implements a leaky bucket request throttling algorithm where the | |
// duration between two requests is never less than the MinInterval | |
func Throttler(next HttpHandlerFunc, te *ThrottleEngine, header string) HttpHandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
k := r.Header.Get(header) | |
te.M.Lock() | |
defer te.M.Unlock() | |
if lr, ok := te.MostRecentRequest[k]; ok { | |
if time.Now().Sub(lr) < te.MinInterval { | |
<-time.NewTimer(lr.Add(te.MinInterval).Sub(time.Now())).C | |
} | |
} | |
te.MostRecentRequest[k] = time.Now() | |
next(w, r) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment