作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我正在使用以下代码运行服务器:
// Assuming there is no import error
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
http.Error(w, "File not found", http.StatusNotFound)
})
n := negroni.Classic()
n.Use(negroni.HandlerFunc(bodmas.sum(4,5)))
n.UseHandler(mux)
n.Run(":4000" )
它工作得很好。
但是当我用另一个 http 处理程序
包装 bodmas.sum
时,我总是得到“找不到文件”。流不走这条路。
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
http.Error(w, "File not found", http.StatusNotFound)
})
n := negroni.Classic()
n.Use(negroni.HandlerFunc(wrapper.RateLimit(bodmas.sum(4,5),10)))
n.UseHandler(mux)
n.Run(":" + cfg.Server.Port)
}
wrapper.RateLimit
定义如下。这在单独测试时按预期工作:
func RateLimit(h resized.HandlerFunc, rate int) (resized.HandlerFunc) {
:
:
// logic here
rl, _ := ratelimit.NewRateLimiter(rate)
return func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc){
if rl.Limit(){
http.Error(w, "Gateway Timeout", http.StatusGatewayTimeout )
} else {
next(w, r)
}
}
}
没有错误。关于这种行为有什么建议吗?如何让它发挥作用?
最佳答案
我不确定这段代码有什么问题,但它似乎不是 negorni
方式。如果我们用另一个 http.Handlerfunc
包装它的处理程序,negroni
的行为可能不会像预期的那样。所以,我修改了我的代码并让 middleware
完成了工作。
我当前的代码如下所示:
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
http.Error(w, "File not found", http.StatusNotFound)
})
n := negroni.Classic()
n.Use(wrapper.Ratelimit(10))
n.Use(negroni.HandlerFunc(bodmas.sum(4,5)))
n.UseHandler(mux)
n.Run(":4000")
}
wrapper.go
有:
type RatelimitStruct struct {
rate int
}
// A struct that has a ServeHTTP method
func Ratelimit(rate int) *RatelimitStruct{
return &RatelimitStruct{rate}
}
func (r *RatelimitStruct) ServeHTTP(w http.ResponseWriter, req *http.Request, next http.HandlerFunc){
rl, _ := ratelimit.NewRateLimiter(r.rate)
if rl.Limit(){
http.Error(w, "Gateway Timeout", http.StatusGatewayTimeout )
}
else {
next(w, req)
}
}
希望对大家有帮助。
关于http - Golang negroni 和 http.NewServeMux() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27010867/
这是我的代码。我想将 mux1 作为子路由器放入 mux.Handle 中。接下来,我运行代码。我可以访问路径/index 但我无法访问路径/index/sub1。不知道为什么我可以访问/index但
我正在使用以下代码运行服务器: // Assuming there is no import error mux := http.NewServeMux() mux.HandleFunc("/
我收到一条错误消息:不能在 mx.HandleFunc 的参数中使用 websocket.Handler(handler)(类型 websocket.Handler)作为类型 func(http.Re
我是一名优秀的程序员,十分优秀!