How to create custom timeout handler based on request path?

I want to write a custom timeout handler based on different request path but i couldn’t write any. So my question is: Is it possible to write this type of timeout handler? If it is, please write a simple example.

For HTTP? Are you the client or the server? What are you waiting for that you want to time out? Details.

I’m not 100% sure what you are looking for, but I think you are looking for a way to do something like parse the path (or something similar) and use that to set a timeout. If so, you can do it with something like this:

package main

import (
	"fmt"
	"net/http"
	"path"
	"strconv"
	"time"
)

func main() {
	m := http.NewServeMux()
	m.Handle("/", timeoutHandler(http.HandlerFunc(slowHandler)))
	http.ListenAndServe(":8080", m)
}

func timeoutHandler(h http.Handler) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var timeoutHandler http.Handler
		msg := "Your request has timed out."
		p := path.Clean("/" + r.URL.Path)
		// if your path has more than an integer in it you will
		// need to parse it differently
		timeout, err := strconv.Atoi(p[1:])
		if err != nil {
			// use the default timeout of 5s
			timeoutHandler = http.TimeoutHandler(h, 5*time.Second, msg)
		} else {
			fmt.Printf("Using custom timeout of %d seconds\n", timeout)
			timeoutHandler = http.TimeoutHandler(h, time.Duration(timeout)*time.Second, msg)
		}
		timeoutHandler.ServeHTTP(w, r)
	}
}

func slowHandler(w http.ResponseWriter, r *http.Request) {
	time.Sleep(2 * time.Second)
	fmt.Fprintf(w, "Done doing slow work!")
}

https://play.golang.org/p/Epl1Lsm5UV

Most of that code is parsing the path and you could use a library like gorilla/mux to do that for you if you wanted, but that should get the idea across of how this can be achieved. The one caveat is that your parsing the path code happens before the timeout so keep that in mind if you need exact timeout durations.

1 Like

server

I think your answer helps me a lot. Thank you.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.