1

我正在运行具有以下代码的服务器:

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

没有错误。关于这种行为的任何建议?如何使它工作?

4

1 回答 1

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)
    } 
}

希望它可以帮助某人。

于 2014-11-19T09:20:29.447 回答