Search code examples
gochainingmux

Gorilla mux, count all incoming requets


I have a server using gorilla mux. Now I have two handlers like this:

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

Now I would like to create a generic method (logHandler) which counts the requests. Now I have something like this:

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

I can get all my necessary information from the request (r) in the logHandler function, but what do I need to return? How do I get this to work?


Solution

  • This should work.

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

    and just a heads up, I am not sure if count variable is thread safe or not. if not you might want to use channels to send out a signal to increment the counter

    I have Updated the answer to avoid race conditions. using atomic as mentioned in the comments.