我正在使用以下代码运行服务器:
// 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" )
完美无缺。
但是当我用另一个bodmas.sum
包裹http handler
时,我总是得到"找不到文件。"流程不会走这条路。
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)
}
}
}
没有错误。 有关此行为的任何建议吗? 如何使它工作?
答案 0 :(得分:2)
我不确定此代码的问题是什么,但似乎不是negorni
方式。如果我们用另一个negroni
包装其处理程序,http.Handlerfunc
可能不会按预期运行。所以,我修改了我的代码并完成了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)
}
}
希望它有所帮助。