Thanks for answering my question. Another question is will ctx become invalidated once handleRequest finishes? In fakeUpFunc, I called a method in remote server, and I tried logging the request in remote server, I never saw any request got logged. So I wonder if it is the case that ctx is invalidated once handleRequest is out of scope, so that invalidate fakeUpFunc too.
If so, what is the best practice to asynchronously call fakeUpFunc without blocking handleRequest? Thanks Jieru On Tue, May 24, 2016 at 9:38 PM, Ian Lance Taylor <i...@golang.org> wrote: > On Tue, May 24, 2016 at 9:23 PM, Shirley Shi <crony...@gmail.com> wrote: > > > > I have a function looks like > > > > func handleRequest(w http.ResponseWriter, r *http.Request) error { > > ctx, cancel := context.WithTimeout(corplogin.Context(r), *timeout) > > defer cancel() > > > > go fakeUpFunc(ctx); > > } > > > > fakeUpFunc depends on ctx. > > > > My question is after the handleRequest finishes, will fakeUpFunc be > > executed? > > > > I did some experimentation, with "defer cancel()" in place, fakeUpFunc > > wasn't executed. After I deleted "defer cancel()", fakeUpFunc got > executed. > > So I guess when handleRequest finishes, cancel() will be executed which > > invalidates the ctx. > > > > Is deleting "defer cancel()" a good practice if I want fakeUpFunc to be > > executed? > > Yes. The cancel function returned by context.WithTimeout cancels all > operations using the context. The defer suggested in the docs is only > usable if all operations using the context are synchronous. > > Ian > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.