I am having some issues getting timeout to handle safely with github.com/julienschmidt/httprouter
I have tried setting the timeout when I initialize the http Server. This does timeout but I get no response back to the user at all.
HTTP := &http.Server{
Addr: ":" + port,
Handler: muxWithMiddlewares,
ReadTimeout: 1 * time.Second,
WriteTimeout: 1 * time.Second,
MaxHeaderBytes: 1 << 20,
}
HTTP.ListenAndServe()
I have also tried the technique suggested in the below stackoverflow link which explains how to get a timeout working with gorilla mux. This works the very first time a user calls the API, shows a timeout but subsequent requests still funciton as normal. Any help would be much appreciated.
How to use gorilla mux with http.TimeoutHandler
EDIT: Here is the code I tried first with the solution from the other stackoverflow article. As stated above it works for the first request and shows timeout but each request there after, the request can take however long it needs. Note I was mimicking a slow response by inputting time.Sleep(5*time.Second)
inside the handlerA
and handlerB
here. I would think timeouthandler
would run If any query takes longer than the time limit but that doesn't appear to be the way I have it configured at the moment in either of the solutions shown here.
router := httprouter.New()
router.GET("/xxx/", handlerA)
router.POST("/yyyy/", handlerB)
muxWithMiddlewares := http.TimeoutHandler(router, time.Second*1, "Timeout!")
err := http.ListenAndServe(":"+port, muxWithMiddlewares)