duanou1904 2019-08-26 00:24
浏览 152

取消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 

 }
  • 写回答

1条回答 默认 最新

  • dongmei8071 2019-08-26 00:40
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line