取消Http处理程序请求

I have handlers that respond to https requests. In the handlers I call a function F1() which does some application logic and connects to a mysql db and does a query. I want to know how I can use the golang context package to cancel the Db query if the client cancels the request. Do I need to pass the ctx to F1()? Also the code I have now will take 4 seconds even if F1() returns in less then 4. How can I return as soon as F1() returns?

func handler(w http.ResponseWriter, r *http.Request) {

  ctx:= r.context()

  F1()


 select {

     case <-ctx.Done():

     case <- time.After( 4*time.Second):

   }


   w.WriteHeader(http.statusOk)
  return 

 }

To begin, I highly recommend taking a look at the Context blog post to familiarize yourself with contexts, in addition to reading over the context documentation itself.

To address your specific questions:

How can you cancel the database query if the user cancels their quest?

To make this work, there are a few things you want to check:

  1. Ensure that your database driver (if you are using database/sql) supports context cancellation.
  2. Ensure you are using the Context variants of all available methods (e.g. db.QueryContext instead of db.Query).
  3. Ensure that you are passing the context (or a derivative of the context) through the stack from your HTTP request through to the database calls.

Do I need to pass the ctx to F1()?

Per #3 above, yes: you will need to pass the context through all intermediate calls to "connect" the database call with the request context.

How can I return as soon as F1() returns?

The code that you have in your question calls F1 in series, rather than concurrently, with your cancellation/timeout select.

If you want to apply a specific deadline to your database call, use context.WithTimeout to limit how long it can take. Otherwise, you do not need to do anything special: just call F1 with your context, and the rest will happen for you, no select is needed.