session.go 1.2 KB

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