Scenario:
User submits something, I want to give an instantaneous response "ok received", so that the user can go on his way. Meanwhile, I need to spend 2-3 seconds to perform some computation on the new submission (e.g., generate thumbnails, add indices, inform admins). Users don't need to wait for the result, but I want the computation done asap.
My current solution is to launch a goroutine for heavy stuffs before returning response. I don't know whether this is the best practise. In my opinion, this is wasteful, because it should be cheaper to continue on the same thread instead of launching a new one. It also appears that when I perform gin.JSON(...), the result is sent already? even if there are more lines down the road?
Is it possible to first return the response and then continue in the same thread? Does gin support this already?
I would say a goroutine is the easiest way to do this. They are massively optimized and the overhead is tiny.
If you're worried about goroutine startup overhead, you could super easily implement a small job/worker pattern within your app and dispatch jobs through channels. This is still one of the best inspiration texts when it comes to workers (with examples) http://marcio.io/2015/07/handling-1-million-requests-per-minute-with-golang/
Alternatively, you could try manually closing the writer, that should close the connection.
@mingyuguo, I agree with @nazwa.
Either call a goroutine or use channels (careful with buffer lenght).
If you keep working on the same thread, middlewares who use c.Next() should also use IsAborted(). Not many do that, so some panic can emerge from that (using an aborted context).
Most helpful comment
@mingyuguo, I agree with @nazwa.
Either call a goroutine or use channels (careful with buffer lenght).
If you keep working on the same thread, middlewares who use
c.Next()should also useIsAborted(). Not many do that, so some panic can emerge from that (using an aborted context).