Run function after quit
tutunci opened this issue · comments
Hi,
I'm trying to find a way to run a function after sending result.
Let's suppose that I've to send the 200 OK quite fast but than continue processing data and doing insert on a slow service.
I've added my AddPost at the end of the list but:
if I set function without the quit (and it's in the previous one) function is never run
if I set function as quit it runs but output is at the end of all.
Can you please suggest a solution
Thanks
Maurizio
I don't understand the following:
if I set function without the quit (and it's in the previous one) function is never run
if I set function as quit it runs but output is at the end of all.
Could you rephrase that?
Sure,
let me try to give more details.
I've done some tests to the authentication example.
I've added to the main.go
service.AddPost(responseWriter)
// my custom function
service.AddPost(doSomethingMore)
than on middleware.go
func doSomethingMore(c siesta.Context, w http.ResponseWriter, r *http.Request,
quit func()) {
time.Sleep(5000 * time.Millisecond)
log.Printf("This is run after responseWrite")
quit()
}
With this solution I've the output but the response is sent after it (so it waits for 5 seconds)
Than I've tried to change my function putting the quit() back into the responseWriter
function
and removing from the doSomethingMore
func doSomethingMore(c siesta.Context, w http.ResponseWriter, r *http.Request) {
time.Sleep(5000 * time.Millisecond)
log.Printf("This is run after responseWrite")
}
In this case my doSomethingMore
is never run
So is there a way to have the output sent into responseWriter
without waiting that doSomethingMore
complete its job?
Appreciate your help.
Thanks
Maurizio
If responseWriter
always calls quit()
, doSomethingMore
will never run. That's probably not what you want.
So is there a way to have the output sent into
responseWriter
without waiting thatdoSomethingMore
complete its job?
The purpose of responseWriter
is to send a JSON payload back to the client. If you need doSomethingMore
to always run after a response is sent, then there's no need to use quit()
at all in either function.
Hi Preetam,
thanks for your feedback.
I've just tested as you suggested, removing quit() from all functions.
Unfortunately result is still not what I'd like to have.
Now the doSomethingMore
function is run but the output of the client is sent only after its execution.
As you can see into my trivial example I've put a Sleep of 5 seconds, the output to the client is sent after 5 seconds.
My best expectation would be that output is immediately sent and doSomethingMore
will do its job without having client to wait for.
Did you think it can be done?
Thanks
Maurizio
I still don't completely understand what you're trying to do, but it sounds like doSomethingMore
should not be in the chain at all. Why not start another goroutine to run doSomethingMore
?
Good idea, I'll try with this.
Thanks for your help
Maurizio