【问题标题】:Gorilla mux, count all incoming requetsGorilla mux,计算所有传入请求
【发布时间】:2018-04-13 11:44:38
【问题描述】:

我有一个使用 gorilla mux 的服务器。现在我有两个这样的处理程序:

api.HandleFunc("/foo", logHandler(mypackage.fooHandler)).Methods("GET")
api.HandleFunc("/bar", logHandler(mypackage.barHandler)).Methods("GET")

现在我想创建一个计算请求的通用方法 (logHandler)。现在我有这样的东西:

func logHandler(fn http.HandlerFunc) http.HandlerFunc {
  return func(w http.ResponseWriter, r *http.Request) {
    // what to do here???
  }
}

我可以从 logHandler 函数中的请求 (r) 中获取所有必要的信息,但是我需要返回什么?我如何让它发挥作用?

【问题讨论】:

  • 不需要返回任何东西,因为http.HandlerFunc 被定义为没有返回参数,只要确保在返回的http.HandlerFunc 中调用传入的处理函数fn。例如。 fn(w, r)play.golang.org/p/ugqZp1vBz5B
  • 只计算你的请求。
  • 考虑使用r.Use()安装中间件。
  • 以防万一您想使用 prometheus:violetear.org/post/prometheus

标签: go chaining mux


【解决方案1】:

这应该可行。

var count = 0
func logHandler(fn http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        atomic.AddInt32(&count, 1)
        log.Println(count)
        fn(w, r)
    }
}

只是提醒一下,我不确定count 变量是否是线程安全的。如果不是,您可能想使用channels 发送信号以增加计数器

我已更新答案以避免出现竞争条件。使用 cmets 中提到的 atomic。

【讨论】:

  • 是的,这与其他处理程序竞争。使用互斥锁来保护计数,或者类似于atomic.AddInt32(&count, 1) 的东西。
猜你喜欢
  • 2015-04-07
  • 2015-04-02
  • 2017-06-14
  • 2020-06-14
  • 1970-01-01
  • 2018-03-13
  • 2014-12-22
  • 2017-06-19
  • 2018-02-08
相关资源
最近更新 更多