首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Golang negroni和http.NewServeMux()问题

Golang negroni和http.NewServeMux()问题
EN

Stack Overflow用户
提问于 2014-11-19 15:02:05
回答 1查看 1.3K关注 0票数 1

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

代码语言:javascript
复制
// 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时,我总是得到“找不到文件”的消息。该流不会去往此路由。

代码语言:javascript
复制
  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定义如下。单独测试时,它的工作方式与预期相同:

代码语言:javascript
复制
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)
         }
    }
}

没有错误。对这种行为有什么建议吗?如何让它工作?

EN

回答 1

Stack Overflow用户

发布于 2014-11-19 17:20:29

我不确定这段代码有什么问题,但似乎不是negorni的方式。如果我们用另一个http.Handlerfunc包装它的处理程序,negroni可能不会像预期的那样工作。所以,我修改了我的代码,让middleware完成了这项工作。

我当前的代码如下所示:

代码语言:javascript
复制
         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具有:

代码语言:javascript
复制
    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)
    } 
}

希望这能帮助到别人。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27010867

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档