Documentation ¶
Overview ¶
Package limit provides a simple rate limiter for concurrent access.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
Functions ¶
This section is empty.
Types ¶
type Limit ¶
type Limit struct {
// contains filtered or unexported fields
}
Limit defines the limiter.
Example ¶
package main import ( "fmt" "net/http" "net/http/httptest" "time" "github.com/pmorjan/limit" "github.com/tomasen/realip" ) func main() { // middleware function limitRequests := func(next http.Handler) http.Handler { userLimit, _ := limit.New(1, 3) // 1 request per second, burst 3 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ip := realip.FromRequest(r) if !userLimit.Allowed(ip) { http.Error(w, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests) return } next.ServeHTTP(w, r) }) } handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello world")) }) srv := httptest.NewServer(limitRequests(handler)) defer srv.Close() // 4 requests for i := 0; i < 4; i++ { res, _ := http.Get(srv.URL) fmt.Println(res.Status) } // next request after 1 sec delay time.Sleep(time.Second) res, _ := http.Get(srv.URL) fmt.Println(res.Status) }
Output: 200 OK 200 OK 200 OK 429 Too Many Requests 200 OK
Click to show internal directories.
Click to hide internal directories.