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:
gorillaMux := mux.NewRouter()
gorillaMux.HandleFunc("/", rootHandler)
server := &http.Server{Addr:":1234"}
and server.ListenAndServe()
Where can I insert the http.TimeoutHandler
or any other middleware for that matter?
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!"))