douhai5835 2015-08-15 09:02
浏览 7

在Go中使用交易

When a user registers, my app does two things - it adds the user to the database and it sends a verification email:

...
err := collection("users").Insert(&u);
if err != nil {
    WriteServerError(w, err)
    return
}

if err = sendVerificationEmail(&u); err != nil {
    WriteServerError(w, err)
}
...

I wouldn't want to add the user to the database if the email does not get sent nor would I want to send the email if the user didn't get added to the database (the latter is of course taken care of with the code blocks in this order).

Assuming Go supports transactions, is it worth bothering with for something like this? If so then could someone give me some pointers as to how I would convert this code above?

I could use nested statements but this could get very ugly.

  • 写回答

4条回答 默认 最新

  • dongxian0320 2015-08-15 09:19
    关注

    There is no "transaction" in Go. The better you can do is to take the steps in the right order:

    1. Insert the user in the database
    2. If the insertion failed, return
    3. Send the email
    4. If the email failed, remove the user

    That said, generally speaking, there is no need to go to step 4. The common approach to this problem is to have a "I didn't get the verification email, please send another." button somewhere along your registration/login pages. You can't even be sure that your email arrived even if you sent it correctly: it could be filtered by the anti-spam, deleted by a missclick, etc.

    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号