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!"))