Tollbooth —— Go 语言的 HTTP 限速中间件

本文涉及的产品
Serverless 应用引擎 SAE,800核*时 1600GiB*时
注册配置 MSE Nacos/ZooKeeper,118元/月
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
简介:

Tollbooth 是一个用 Go 语言编写的用来限制 HTTP 访问速度的中间件,可用来限制每个 HTTP 请求的传输速率。例如你可以不限制 / 的访问速率,但是可以针对 /login 限制每个 IP 每秒最多 POST 多少个请求。

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.oschina.net]

相关文章
|
5天前
|
Go
Go 语言循环语句
在不少实际问题中有许多具有规律性的重复操作,因此在程序中就需要重复执行某些语句。
13 1
|
4天前
|
Go 开发者
探索Go语言的并发之美
在Go语言的世界里,"并发"不仅仅是一个特性,它是一种哲学。本文将带你领略Go语言中goroutine和channel的魔力,揭示如何通过Go的并发机制来构建高效、可靠的系统。我们将通过一个简单的示例,展示如何利用Go的并发特性来解决实际问题,让你的程序像Go一样,轻盈而强大。
|
5天前
|
JSON Go API
使用Go语言和Gin框架构建RESTful API:GET与POST请求示例
使用Go语言和Gin框架构建RESTful API:GET与POST请求示例
|
5天前
|
Go
go语言创建字典
go语言创建字典
|
6天前
|
NoSQL Go API
go语言操作Redis
go语言操作Redis
|
6天前
|
Unix Go
go语言获取当前时间戳
go语言获取当前时间戳
|
6天前
|
Go
go语言李mapstructure啥意思
go语言李mapstructure啥意思
|
5天前
|
Go
Go 语言接口
Go 语言提供了另外一种数据类型即接口,它把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口。 接口可以让我们将不同的类型绑定到一组公共的方法上,从而实现多态和灵活的设计。
|
6天前
|
存储 Go
go语言字符串变小写
go语言字符串变小写
|
6天前
|
Go
8-12|go语言之输入
8-12|go语言之输入

热门文章

最新文章

下一篇
无影云桌面