Documentation ¶
Overview ¶
Package httpcap provides rate limiting for HTTP handlers and response writers.
Rate limiting can be applied to an http.Handler either on a per-request basis, or using a rate limiting group.
h = httpcap.Handler(h, rate) ... g := iocap.NewGroup(rate) h = httpcap.GroupHandler(h, g)
See the LimitByRequestIP method for a short-hand quick start.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GroupHandler ¶
GroupHandler is like Handler, but wraps an http.Handler with group rate limiting such that all requests share the same quota.
Example ¶
// Create a normal HTTP handler to serve data. h := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello world!")) })) // Wrap the handler with a rate limit group. All requests to this handler // will share the rate below. rate := iocap.Kbps(512) group := iocap.NewGroup(rate) h = GroupHandler(h, group) // Start a test server using the rate limited handler. ts := httptest.NewServer(h) defer ts.Close() // Make a request to the server. resp, err := http.Get(ts.URL) if err != nil { fmt.Println(err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return } fmt.Println(string(body))
Output: hello world!
func Handler ¶
Handler creates a new rate limited HTTP handler wrapper. The rate described by ro is used to rate limit each request independently.
Example ¶
// Create a normal HTTP handler to serve data. h := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello world!")) })) // Wrap the handler with a rate limit. rate := iocap.Kbps(512) h = Handler(h, rate) // Start a test server using the rate limited handler. ts := httptest.NewServer(h) defer ts.Close() // Make a request to the server. resp, err := http.Get(ts.URL) if err != nil { fmt.Println(err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return } fmt.Println(string(body))
Output: hello world!
func LimitByRequestIP ¶
LimitByRequestIP is a convenience wrapper to automatically limit inbound requests by the given rate, per client IP address. Just give it any old HTTP handler and a rate.
Example ¶
// Create a normal HTTP handler to serve data. h := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello world!")) })) // Rate limit requests to the handler per client IP. h = LimitByRequestIP(h, iocap.Kbps(512)) // Start the server. ts := httptest.NewServer(h) defer ts.Close() // Make a request to the server. resp, err := http.Get(ts.URL) if err != nil { fmt.Println(err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return } fmt.Println(string(body))
Output: hello world!
Types ¶
This section is empty.