session.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package router
  2. import (
  3. "app.yhyue.com/moapp/jybase/redis"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "github.com/gogf/gf/v2/frame/g"
  8. "github.com/gogf/gf/v2/net/ghttp"
  9. "net/url"
  10. )
  11. const (
  12. JY_SESSIONNAME = "SESSIONID"
  13. )
  14. // JySession 剑鱼程序SESSION获取
  15. type JySession struct {
  16. UserId string // 上下文用户信息
  17. EntId int64 // 当前企业id
  18. Data g.Map // 当前Session管理对象
  19. }
  20. // GetJySession 获取剑鱼程序session内容
  21. func GetJySession(ctx context.Context) (jSession *JySession) {
  22. jSession = &JySession{}
  23. value := ctx.Value(JY_SESSIONNAME)
  24. if value == nil {
  25. return
  26. }
  27. if localCtx, ok := value.(*JySession); ok {
  28. jSession = localCtx
  29. }
  30. return
  31. }
  32. // InitJySessionContext 获取用户session
  33. func InitJySessionContext(r *ghttp.Request) (jSession *JySession, err error) {
  34. jSession = &JySession{}
  35. cookie, err := r.Request.Cookie(JY_SESSIONNAME)
  36. if err != nil {
  37. return
  38. }
  39. if cookie.Value == "" {
  40. err = fmt.Errorf("cookie 内容为空")
  41. return
  42. }
  43. findKey, _ := url.QueryUnescape(cookie.Value)
  44. bs, err := redis.GetBytes("session", findKey)
  45. if err != nil {
  46. return
  47. }
  48. var data map[string]interface{}
  49. err = json.Unmarshal(*bs, &data)
  50. jSession.UserId, _ = data["userId"].(string)
  51. jSession.EntId, _ = data["ent_id"].(int64)
  52. jSession.Data = data
  53. return
  54. }