session.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. "github.com/gogf/gf/v2/util/gconv"
  10. "net/url"
  11. )
  12. const (
  13. JY_SESSIONNAME = "SESSIONID"
  14. )
  15. // JySession 剑鱼程序SESSION获取
  16. type JySession struct {
  17. UserId string // 上下文用户信息
  18. EntId int64 // 当前企业id
  19. Phone string // 手机号
  20. Data g.Map // 当前Session管理对象
  21. }
  22. // GetJySession 获取剑鱼程序session内容
  23. func GetJySession(ctx context.Context) (jSession *JySession) {
  24. jSession = &JySession{}
  25. value := ctx.Value(JY_SESSIONNAME)
  26. if value == nil {
  27. return
  28. }
  29. if localCtx, ok := value.(*JySession); ok {
  30. jSession = localCtx
  31. }
  32. return
  33. }
  34. // InitJySessionContext 获取用户session
  35. func InitJySessionContext(r *ghttp.Request) (jSession *JySession, err error) {
  36. jSession = &JySession{}
  37. cookie, err := r.Request.Cookie(JY_SESSIONNAME)
  38. if err != nil {
  39. return
  40. }
  41. if cookie.Value == "" {
  42. err = fmt.Errorf("cookie 内容为空")
  43. return
  44. }
  45. findKey, _ := url.QueryUnescape(cookie.Value)
  46. bs, err := redis.GetBytes("session", findKey)
  47. if err != nil {
  48. return
  49. }
  50. var data map[string]interface{}
  51. err = json.Unmarshal(*bs, &data)
  52. jSession.Phone, _ = data["phone"].(string)
  53. jSession.UserId, _ = data["userId"].(string)
  54. jSession.EntId = gconv.Int64(data["entId"])
  55. jSession.Data = data
  56. return
  57. }