gpt4 book ai didi

http - Golang negroni 和 http.NewServeMux() 问题

转载 作者:IT王子 更新时间:2023-10-29 02:05:43 27 4
gpt4 key购买 nike

我正在使用以下代码运行服务器:

// 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com