123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- package base
- import (
- "fmt"
- "github.com/druidcaesa/gotool"
- "sync"
- "ulink-admin/frame"
- "ulink-admin/frame/third_plugins/http"
- "xorm.io/xorm"
- )
- var sessionMap sync.Map
- var userMap sync.Map
- const (
- ADMIN = "admin"
- MEMBER = "member"
- )
- type UserInfo struct {
- Id int64
- Name string
- IsAdmin bool
- ComponyId int64
- UserType string
- }
- func GetCurUser() *UserInfo {
- routineId := http.GetRoutineId()
- txv, ok := userMap.Load(routineId)
- if ok {
- return txv.(interface{}).(*UserInfo)
- } else {
- return nil
- }
- }
- func SetCurUser(user *UserInfo) {
- routineId := http.GetRoutineId()
- userMap.Store(routineId, user)
- }
- type SessionPlus struct {
- Session *xorm.Session
- IsTx bool
- Level int
- Id uint64
- }
- func GetSession() *SessionPlus {
-
- var sessionPlus *SessionPlus
-
- routineId := http.GetRoutineId()
- txv, ok := sessionMap.Load(routineId)
- fmt.Printf("routineId:%d\n", routineId)
-
-
- if ok {
- sessionPlus = txv.(interface{}).(*SessionPlus)
-
- } else {
- sessionPlus = &SessionPlus{Session: SqlDB.NewSession(), IsTx: false, Id: routineId}
- sessionMap.Store(routineId, sessionPlus)
- }
- return sessionPlus
- }
- func Transaction(f func(session *xorm.Session)) {
- var err error
- sessionPlus := GetSession()
- if sessionPlus.IsTx == false {
- if err = sessionPlus.Session.Begin(); err != nil {
- gotool.Logs.ErrorLog().Println("session begin failed, err msg: %s", err.Error())
- frame.Throw(frame.BUSINESS_CODE, "session begin failed")
- } else {
- sessionPlus.IsTx = true
- sessionPlus.Level = 1
- }
- } else {
- sessionPlus.Level = sessionPlus.Level + 1
- }
- defer func() {
-
-
- if sessionPlus.Level <= 1 && sessionPlus.IsTx {
- if r := recover(); r != nil {
- gotool.Logs.ErrorLog().Println("异常%v", r)
- if err := sessionPlus.Session.Rollback(); err != nil {
- gotool.Logs.ErrorLog().Println("session rollback failed, err msg: %s", err.Error())
- }
- sessionPlus.IsTx = false
- sessionPlus.Session.Close()
-
- frame.Throw(frame.SQL_CODE, fmt.Sprintf("数据库错误%v", r))
- } else if err = sessionPlus.Session.Commit(); err != nil {
- gotool.Logs.ErrorLog().Println("session commit failed, err msg: %s", err.Error())
- }
- sessionPlus.IsTx = false
- sessionPlus.Session.Close()
-
- }
- if sessionPlus.Level > 1 && sessionPlus.IsTx {
- sessionPlus.Level = sessionPlus.Level - 1
- if r := recover(); r != nil {
- frame.Throw(100, "镶嵌事务错误")
- }
- }
- }()
- f(sessionPlus.Session)
- }
- func Clean() {
- sessionMap.Delete(http.GetRoutineId())
- userMap.Delete(http.GetRoutineId())
- }
|