I want to know if how can I count the number of request based on the moving window in golang after 60s?
You could use some middleware:
import (
"sync/atomic"
"net/http"
)
type counter int32
func (c *counter) increment() int32 {
return atomic.AddInt32((*int32)(c), 1)
}
func (c *counter) decrement() int32 {
return atomic.AddInt32((*int32)(c), -1)
}
func (c *count32) get() int32 {
return atomic.LoadInt32((*int32)(c))
}
var c counter
func Last60SecondsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c.increment()
next.ServeHTTP(w, r)
time.AfterFunc(time.Minute, func() {
c.decrement()
})
})
}
And then to get the value, you can just call c.get()