0

I'm using fasthttp to make an HTTP server in Go. When the user visits a certain route, say /foo I want to start a very long running task (think 10m+), but respond to the request immediately. This long running task should continue running in the background until it exits even if the function returns or the user terminates the connection.

What is the best way to do that in Go?

As far as I can tell Goroutines are probably not the right thing because they're meant for short running async code, or am I wrong about that?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
kognise
  • 612
  • 1
  • 8
  • 23
  • @mh-cbon If the user closes the tab before the task is finished what will happen? I understand the concept of goroutines (I hope). Also, link is broken – kognise Mar 11 '19 at 04:57
  • 1
    When you start a goroutine, it continues until the goroutine function returns, no matter how long it takes (assuming the process doesn't exit for some reason). The section in the Tour of Go about goroutines is here: https://tour.golang.org/concurrency/1 – Andy Schweig Mar 11 '19 at 05:16
  • 1
    `If the user closes the tab before the task is finished what will happen?` for as long you start the job in background (goroutine) and respond immediately, nothing. if you were to stop the process when the tab close (ie tcp conn as mentionned in the answer) that would not be a non blocking process anymore, and in http specifically that would we be long polling technique, which is different from what you described. –  Mar 11 '19 at 06:05
  • 1
    Goroutines are perfect for this. The only question is how to handle the HTTP request while the task happens in the background. There are many ways to do this. – Jonathan Hall Mar 11 '19 at 07:47
  • Your HTTP server itself is running in a goroutine and likely running as long as your process is. Goroutines run as long as they need to, I'm not sure where you go the impression they were "meant for short running async code". – Adrian Mar 11 '19 at 14:30

1 Answers1

2

No: a goroutine can last as long as you want (and the main program): you only need to know, as mentioned here, when to terminate said goroutine.

In your case, you would have to detect your connection has been terminated by the user, as in "Close the goroutine reading from a TCP connection without closing connection".

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250