gsession_session.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. // Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gsession
  7. import (
  8. "errors"
  9. "github.com/gogf/gf/internal/intlog"
  10. "time"
  11. "github.com/gogf/gf/container/gmap"
  12. "github.com/gogf/gf/container/gvar"
  13. "github.com/gogf/gf/os/gtime"
  14. "github.com/gogf/gf/util/gconv"
  15. )
  16. // Session struct for storing single session data,
  17. // which is bound to a single request.
  18. type Session struct {
  19. id string // Session id.
  20. data *gmap.StrAnyMap // Session data.
  21. dirty bool // Used to mark session is modified.
  22. start bool // Used to mark session is started.
  23. manager *Manager // Parent manager.
  24. // idFunc is a callback function used for creating custom session id.
  25. // This is called if session id is empty ever when session starts.
  26. idFunc func(ttl time.Duration) (id string)
  27. }
  28. // init does the lazy initialization for session.
  29. // It here initializes real session if necessary.
  30. func (s *Session) init() {
  31. if s.start {
  32. return
  33. }
  34. if s.id != "" {
  35. var err error
  36. // Retrieve memory session data from manager.
  37. if r, _ := s.manager.sessionData.Get(s.id); r != nil {
  38. s.data = r.(*gmap.StrAnyMap)
  39. intlog.Print("session init data:", s.data)
  40. }
  41. // Retrieve stored session data from storage.
  42. if s.manager.storage != nil {
  43. if s.data, err = s.manager.storage.GetSession(s.id, s.manager.ttl, s.data); err != nil {
  44. intlog.Errorf("session restoring failed for id '%s': %v", s.id, err)
  45. }
  46. }
  47. }
  48. // Use custom session id creating function.
  49. if s.id == "" && s.idFunc != nil {
  50. s.id = s.idFunc(s.manager.ttl)
  51. }
  52. // Use default session id creating function of storage.
  53. if s.id == "" {
  54. s.id = s.manager.storage.New(s.manager.ttl)
  55. }
  56. // Use default session id creating function.
  57. if s.id == "" {
  58. s.id = NewSessionId()
  59. }
  60. if s.data == nil {
  61. s.data = gmap.NewStrAnyMap(true)
  62. }
  63. s.start = true
  64. }
  65. // Close closes current session and updates its ttl in the session manager.
  66. // If this session is dirty, it also exports it to storage.
  67. //
  68. // NOTE that this function must be called ever after a session request done.
  69. func (s *Session) Close() {
  70. if s.start && s.id != "" {
  71. size := s.data.Size()
  72. if s.manager.storage != nil {
  73. if s.dirty {
  74. if err := s.manager.storage.SetSession(s.id, s.data, s.manager.ttl); err != nil {
  75. panic(err)
  76. }
  77. } else if size > 0 {
  78. if err := s.manager.storage.UpdateTTL(s.id, s.manager.ttl); err != nil {
  79. panic(err)
  80. }
  81. }
  82. }
  83. if s.dirty || size > 0 {
  84. s.manager.UpdateSessionTTL(s.id, s.data)
  85. }
  86. }
  87. }
  88. // Set sets key-value pair to this session.
  89. func (s *Session) Set(key string, value interface{}) error {
  90. s.init()
  91. if err := s.manager.storage.Set(s.id, key, value, s.manager.ttl); err != nil {
  92. if err == ErrorDisabled {
  93. s.data.Set(key, value)
  94. } else {
  95. return err
  96. }
  97. }
  98. s.dirty = true
  99. return nil
  100. }
  101. // Sets batch sets the session using map.
  102. // Deprecated, use SetMap instead.
  103. func (s *Session) Sets(data map[string]interface{}) error {
  104. return s.SetMap(data)
  105. }
  106. // SetMap batch sets the session using map.
  107. func (s *Session) SetMap(data map[string]interface{}) error {
  108. s.init()
  109. if err := s.manager.storage.SetMap(s.id, data, s.manager.ttl); err != nil {
  110. if err == ErrorDisabled {
  111. s.data.Sets(data)
  112. } else {
  113. return err
  114. }
  115. }
  116. s.dirty = true
  117. return nil
  118. }
  119. // Remove removes key along with its value from this session.
  120. func (s *Session) Remove(keys ...string) error {
  121. if s.id == "" {
  122. return nil
  123. }
  124. s.init()
  125. for _, key := range keys {
  126. if err := s.manager.storage.Remove(s.id, key); err != nil {
  127. if err == ErrorDisabled {
  128. s.data.Remove(key)
  129. } else {
  130. return err
  131. }
  132. }
  133. }
  134. s.dirty = true
  135. return nil
  136. }
  137. // Clear is alias of RemoveAll.
  138. func (s *Session) Clear() error {
  139. return s.RemoveAll()
  140. }
  141. // RemoveAll deletes all key-value pairs from this session.
  142. func (s *Session) RemoveAll() error {
  143. if s.id == "" {
  144. return nil
  145. }
  146. s.init()
  147. if err := s.manager.storage.RemoveAll(s.id); err != nil {
  148. if err == ErrorDisabled {
  149. s.data.Clear()
  150. } else {
  151. return err
  152. }
  153. }
  154. s.dirty = true
  155. return nil
  156. }
  157. // Id returns the session id for this session.
  158. // It create and returns a new session id if the session id is not passed in initialization.
  159. func (s *Session) Id() string {
  160. s.init()
  161. return s.id
  162. }
  163. // SetId sets custom session before session starts.
  164. // It returns error if it is called after session starts.
  165. func (s *Session) SetId(id string) error {
  166. if s.start {
  167. return errors.New("session already started")
  168. }
  169. s.id = id
  170. return nil
  171. }
  172. // SetIdFunc sets custom session id creating function before session starts.
  173. // It returns error if it is called after session starts.
  174. func (s *Session) SetIdFunc(f func(ttl time.Duration) string) error {
  175. if s.start {
  176. return errors.New("session already started")
  177. }
  178. s.idFunc = f
  179. return nil
  180. }
  181. // Map returns all data as map.
  182. // Note that it's using value copy internally for concurrent-safe purpose.
  183. func (s *Session) Map() map[string]interface{} {
  184. if s.id != "" {
  185. s.init()
  186. if data := s.manager.storage.GetMap(s.id); data != nil {
  187. return data
  188. }
  189. return s.data.Map()
  190. }
  191. return nil
  192. }
  193. // Size returns the size of the session.
  194. func (s *Session) Size() int {
  195. if s.id != "" {
  196. s.init()
  197. if size := s.manager.storage.GetSize(s.id); size >= 0 {
  198. return size
  199. }
  200. return s.data.Size()
  201. }
  202. return 0
  203. }
  204. // Contains checks whether key exist in the session.
  205. func (s *Session) Contains(key string) bool {
  206. s.init()
  207. return s.Get(key) != nil
  208. }
  209. // IsDirty checks whether there's any data changes in the session.
  210. func (s *Session) IsDirty() bool {
  211. return s.dirty
  212. }
  213. // Get retrieves session value with given key.
  214. // It returns <def> if the key does not exist in the session if <def> is given,
  215. // or else it return nil.
  216. func (s *Session) Get(key string, def ...interface{}) interface{} {
  217. if s.id == "" {
  218. return nil
  219. }
  220. s.init()
  221. if v := s.manager.storage.Get(s.id, key); v != nil {
  222. return v
  223. }
  224. if v := s.data.Get(key); v != nil {
  225. return v
  226. }
  227. if len(def) > 0 {
  228. return def[0]
  229. }
  230. return nil
  231. }
  232. func (s *Session) GetVar(key string, def ...interface{}) *gvar.Var {
  233. return gvar.New(s.Get(key, def...), true)
  234. }
  235. func (s *Session) GetString(key string, def ...interface{}) string {
  236. return gconv.String(s.Get(key, def...))
  237. }
  238. func (s *Session) GetBool(key string, def ...interface{}) bool {
  239. return gconv.Bool(s.Get(key, def...))
  240. }
  241. func (s *Session) GetInt(key string, def ...interface{}) int {
  242. return gconv.Int(s.Get(key, def...))
  243. }
  244. func (s *Session) GetInt8(key string, def ...interface{}) int8 {
  245. return gconv.Int8(s.Get(key, def...))
  246. }
  247. func (s *Session) GetInt16(key string, def ...interface{}) int16 {
  248. return gconv.Int16(s.Get(key, def...))
  249. }
  250. func (s *Session) GetInt32(key string, def ...interface{}) int32 {
  251. return gconv.Int32(s.Get(key, def...))
  252. }
  253. func (s *Session) GetInt64(key string, def ...interface{}) int64 {
  254. return gconv.Int64(s.Get(key, def...))
  255. }
  256. func (s *Session) GetUint(key string, def ...interface{}) uint {
  257. return gconv.Uint(s.Get(key, def...))
  258. }
  259. func (s *Session) GetUint8(key string, def ...interface{}) uint8 {
  260. return gconv.Uint8(s.Get(key, def...))
  261. }
  262. func (s *Session) GetUint16(key string, def ...interface{}) uint16 {
  263. return gconv.Uint16(s.Get(key, def...))
  264. }
  265. func (s *Session) GetUint32(key string, def ...interface{}) uint32 {
  266. return gconv.Uint32(s.Get(key, def...))
  267. }
  268. func (s *Session) GetUint64(key string, def ...interface{}) uint64 {
  269. return gconv.Uint64(s.Get(key, def...))
  270. }
  271. func (s *Session) GetFloat32(key string, def ...interface{}) float32 {
  272. return gconv.Float32(s.Get(key, def...))
  273. }
  274. func (s *Session) GetFloat64(key string, def ...interface{}) float64 {
  275. return gconv.Float64(s.Get(key, def...))
  276. }
  277. func (s *Session) GetBytes(key string, def ...interface{}) []byte {
  278. return gconv.Bytes(s.Get(key, def...))
  279. }
  280. func (s *Session) GetInts(key string, def ...interface{}) []int {
  281. return gconv.Ints(s.Get(key, def...))
  282. }
  283. func (s *Session) GetFloats(key string, def ...interface{}) []float64 {
  284. return gconv.Floats(s.Get(key, def...))
  285. }
  286. func (s *Session) GetStrings(key string, def ...interface{}) []string {
  287. return gconv.Strings(s.Get(key, def...))
  288. }
  289. func (s *Session) GetInterfaces(key string, def ...interface{}) []interface{} {
  290. return gconv.Interfaces(s.Get(key, def...))
  291. }
  292. func (s *Session) GetTime(key string, format ...string) time.Time {
  293. return gconv.Time(s.Get(key), format...)
  294. }
  295. func (s *Session) GetGTime(key string, format ...string) *gtime.Time {
  296. return gconv.GTime(s.Get(key), format...)
  297. }
  298. func (s *Session) GetDuration(key string, def ...interface{}) time.Duration {
  299. return gconv.Duration(s.Get(key, def...))
  300. }
  301. func (s *Session) GetMap(key string, tags ...string) map[string]interface{} {
  302. return gconv.Map(s.Get(key), tags...)
  303. }
  304. func (s *Session) GetMapDeep(key string, tags ...string) map[string]interface{} {
  305. return gconv.MapDeep(s.Get(key), tags...)
  306. }
  307. func (s *Session) GetMaps(key string, tags ...string) []map[string]interface{} {
  308. return gconv.Maps(s.Get(key), tags...)
  309. }
  310. func (s *Session) GetMapsDeep(key string, tags ...string) []map[string]interface{} {
  311. return gconv.MapsDeep(s.Get(key), tags...)
  312. }
  313. func (s *Session) GetStruct(key string, pointer interface{}, mapping ...map[string]string) error {
  314. return gconv.Struct(s.Get(key), pointer, mapping...)
  315. }
  316. // Deprecated, use GetStruct instead.
  317. func (s *Session) GetStructDeep(key string, pointer interface{}, mapping ...map[string]string) error {
  318. return gconv.StructDeep(s.Get(key), pointer, mapping...)
  319. }
  320. func (s *Session) GetStructs(key string, pointer interface{}, mapping ...map[string]string) error {
  321. return gconv.Structs(s.Get(key), pointer, mapping...)
  322. }
  323. // Deprecated, use GetStructs instead.
  324. func (s *Session) GetStructsDeep(key string, pointer interface{}, mapping ...map[string]string) error {
  325. return gconv.StructsDeep(s.Get(key), pointer, mapping...)
  326. }