HTTP請求限速中間件:Tollbooth

nwbg 9年前發布 | 15K 次閱讀 Tollbooth

Tollbooth 是一個用 Go 語言編寫的用來限制 HTTP 訪問速度的中間件,可用來限制每個 HTTP 請求的傳輸速率。例如你可以不限制 / 的訪問速率,但是可以針對 /login 限制每個 IP 每秒最多 POST 多少個請求。

Features

  1. Rate-limit by request's remote IP, path, methods, custom headers, & basic auth usernames.

    limiter := tollbooth.NewLimiter(1, time.Second)
    
    // Limit only GET and POST requests.
    limiter.Methods = []string{"GET", "POST"}
    
    // Limit request headers containing certain values.
    // Typically, you prefetched these values from the database.
    limiter.Headers = make(map[string][]string)
    limiter.Headers["X-Access-Token"] = []string{"abc123", "xyz098"}
    
    // Limit based on basic auth usernames.
    // Typically, you prefetched these values from the database.
    limiter.BasicAuthUsers = []string{"bob", "joe", "didip"}
  2. Each request handler can be rate-limited individually.

  3. Compose your own middleware by usingLimitByKeys().

  4. Tollbooth does not require external storage since it uses an algorithm called Token Bucket (Go library: ratelimit).


Go 程序中使用的方法:

package main

import (
    "github.com/didip/tollbooth"
    "net/http"
    "time"
)

func HelloHandler(w http.ResponseWriter, req *http.Request) {
    w.Write([]byte("Hello, World!"))
}

func main() {
    // You can create a generic limiter for all your handlers
    // or one for each handler. Your choice.
    // This limiter basically says: allow at most 1 request per 1 second.
    limiter := tollbooth.NewLimiter(1, time.Second)

    // This is an example on how to limit only GET and POST requests.
    limiter.Methods = []string{"GET", "POST"}

    // You can also limit by specific request headers, containing certain values.
    // Typically, you prefetched these values from the database.
    limiter.Headers = make(map[string][]string)
    limiter.Headers["X-Access-Token"] = []string{"abc123", "xyz098"}

    // And finally, you can limit access based on basic auth usernames.
    // Typically, you prefetched these values from the database as well.
    limiter.BasicAuthUsers = []string{"bob", "joe", "didip"}

    // Example on how to wrap your request handler.
    http.Handle("/", tollbooth.LimitFuncHandler(limiter, HelloHandler))
    http.ListenAndServe(":12345", nil)

項目主頁:http://www.baiduhome.net/lib/view/home/1432357728755

 本文由用戶 nwbg 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!