我正在使用以下代码运行服务器:
// 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 handler包装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)
}
}
}没有错误。对这种行为有什么建议吗?如何让它工作?
发布于 2014-11-19 17:20:29
我不确定这段代码有什么问题,但似乎不是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)
}
}希望这能帮助到别人。
https://stackoverflow.com/questions/27010867
复制相似问题