请求事务(TransactionScope)

    main.go

    1. package main
    2. import (
    3. "github.com/kataras/iris"
    4. "github.com/kataras/iris/context"
    5. )
    6. func main() {
    7. app := iris.New()
    8. //子域可以与所有可用的路由器一起使用,就像其他功能一样。
    9. app.Get("/", func(ctx context.Context) {
    10. ctx.BeginTransaction(func(t *context.Transaction) {
    11. // t.SetScope(context.RequestTransactionScope)
    12. //在此处创建新的自定义错误类型,以跟踪状态代码和错误消息
    13. err := context.NewTransactionErrResult()
    14. //如果我们想要回滚这个函数clojure中的任何错误,我们应该使用t.Context。
    15. t.Context().Text("Blablabla this should not be sent to the client because we will fill the err with a message and status")
    16. //在这里虚拟化一个虚假的错误,为了测试这个例子
    17. fail := true
    18. if fail {
    19. err.StatusCode = iris.StatusInternalServerError
    20. //注意:如果为空原因则会触发默认或自定义http错误(如ctx.FireStatusCode)
    21. err.Reason = "Error: Virtual failure!!"
    22. //选择步骤:
    23. //但是如果我们想要在事务失败时将错误消息回发给客户端,这很有用
    24. //如果原因为空,那么交易成功完成,
    25. //header和Cookie,状态代码以及此事务中的所有内容
    26. }
    27. })
    28. ctx.BeginTransaction(func(t *context.Transaction) {
    29. t.Context().HTML("<h1>This will sent at all cases because it lives on different transaction and it doesn't fails</h1>")
    30. // *如果我们没有任何'throw error'逻辑,则不需要scope.Complete()
    31. })
    32. // OPTIONALLY,取决于用法:
    33. //无论如何,在上下文的事务中发生的情景都会发送给客户端
    34. ctx.HTML("<h1>Let's add a second html message to the response, " +
    35. "if the transaction was failed and it was request scoped then this message would " +
    36. "not been shown. But it has a transient scope(default) so, it is visible as expected!</h1>")
    37. })
    38. app.Run(iris.Addr(":8080"))
    • 尝试修改一下fail变量值,当与到错误,则会不显示里面的内容,也就是说回滚了