Search code examples
gomiddlewaregorilla

How to use gorilla mux with http.TimeoutHandler


In an HTTP server written in go, I use gorilla/mux for routing,
I want to use http.TimeoutHandler (and/or other "middleware") but I can't understand where I can fit them.

To make it clear:

  1. I create a new Router by gorillaMux := mux.NewRouter()
  2. add my routes by calls like gorillaMux.HandleFunc("/", rootHandler)
  3. I create the server by server := &http.Server{Addr:":1234"} and server.ListenAndServe()

Where can I insert the http.TimeoutHandler or any other middleware for that matter?


Solution

  • Here is how you can do this:

    package main
    
    import (
        "fmt"
        "github.com/gorilla/mux"
        "net/http"
        "time"
    )
    
    func rootHandler(w http.ResponseWriter, r *http.Request) {
        time.Sleep(5 * time.Second)
        fmt.Fprintf(w, "Hello!")
    }
    
    func main() {
        mux := mux.NewRouter()
        mux.HandleFunc("/", rootHandler)
    
        muxWithMiddlewares := http.TimeoutHandler(mux, time.Second*3, "Timeout!")
    
        http.ListenAndServe(":8080", muxWithMiddlewares)
    }
    

    If you have more than one HTTP handler, you can stack them up:

    // this is quite synthetic and ugly example, but it illustrates how Handlers works
    muxWithMiddlewares := http.StripPrefix("/api", http.TimeoutHandler(mux, time.Second*3, "Timeout!"))