【问题标题】:Golang negroni and http.NewServeMux() issueGolang negroni 和 http.NewServeMux() 问题
【发布时间】:2015-01-16 14:50:30
【问题描述】:

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

// 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 时,我总是得到“找不到文件”。流不去这条路线。

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

没有错误。 关于这种行为的任何建议? 如何让它发挥作用?

【问题讨论】:

    标签: http go servemux


    【解决方案1】:

    我不确定这段代码有什么问题,但它似乎不是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)
        } 
    }
    

    希望对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-05
      • 2020-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多