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

标签 http go servemux

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

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

相关文章:

http - 不直接导致数据操作但触发操作的 RESTful HTTP 请求是否应该具有 GET、PUT 或 POST 操作?

http - GOLANG,HTTP 有 "use of closed network connection"错误

go - MVC 模式是否实现了 Web 框架的常见任务?

sockets - 如何处理 go 中的粘性 tcp 数据包?

angularjs - 如果 URL 与 Go 中的任何模式都不匹配,如何提供文件?

c++ - poco 1.10.1中发送HTTPRequest超时

java - 为什么 Java 编码的 HTTP GET 提供的网页与看似相同的 Firefox GET 请求不同?

java - 对 Java POST 调用的 HTTP 错误请求响应

regex - 去正则表达式 : how I can replace named groups by concrete values in source pattern?