Calling a goroutine from an http.HandlerFunc - Is it safe / idiomatic?

Can a HTTP request handler be used to fire off a long running task simply by using a goroutine?

I’d like to be able to return a response immediately while another function continues to run for a few seconds:

func startJob(w http.ResponseWriter, r *http.Request)  {
	go longRunning("Do this job")

	dump, _ := httputil.DumpRequest(r, true)
	fmt.Fprintf(w, dump)

func longRunning(msg string)  {
	time.Sleep(5 * time.Second)


However, it might be better to send your long running jobs into a queue so you can control how many of those jobs are running. This will give you a way to limit the resources used by long running jobs allowing you to keep your server responsive.


nathankerr thanks for the clarification and for taking the time to suggest queuing.

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