context.go 940B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package utils
  2. import (
  3. "github.com/go-xorm/xorm"
  4. )
  5. // Context 上下文
  6. // 只限制在每次 Request 内
  7. type Context struct {
  8. DB *xorm.Session
  9. box map[string]interface{}
  10. }
  11. // NewContext 初始化上下文
  12. func NewContext(engine *xorm.Engine, opt map[string]interface{}) *Context {
  13. return &Context{
  14. DB: engine.NewSession(),
  15. box: opt,
  16. }
  17. }
  18. // Get 获取
  19. func (c *Context) Get(key string, def ...interface{}) interface{} {
  20. if c.box != nil {
  21. if opt, has := c.box[key]; has {
  22. return opt
  23. }
  24. }
  25. if len(def) > 0 {
  26. return def[0]
  27. }
  28. return nil
  29. }
  30. // Set 设置
  31. func (c *Context) Set(key string, val interface{}) {
  32. if c.box == nil {
  33. c.box = make(map[string]interface{})
  34. }
  35. c.box[key] = val
  36. }
  37. // Ready Request 级别初始化
  38. func (c *Context) Ready() error {
  39. // 开启事务
  40. if err := c.DB.Begin(); err != nil {
  41. return err
  42. }
  43. return nil
  44. }
  45. // Destroy 析构函数
  46. func (c *Context) Destroy() {
  47. c.DB.Close()
  48. }