session.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. /*
  2. * Public Domain Software
  3. *
  4. * I (Matthias Ladkau) am the author of the source code in this file.
  5. * I have placed the source code in this file in the public domain.
  6. *
  7. * For further information see: http://creativecommons.org/publicdomain/zero/1.0/
  8. */
  9. /*
  10. Package user contains user session management for webservers. Sessions are
  11. identified via session cookies and stored in memory on the server side.
  12. */
  13. package user
  14. import "fmt"
  15. /*
  16. Session models a user session object.
  17. */
  18. type Session interface {
  19. /*
  20. Id returns the session id.
  21. */
  22. ID() string
  23. /*
  24. User returns the user of the session.
  25. */
  26. User() string
  27. /*
  28. GetAll returns all known session values.
  29. */
  30. GetAll() map[string]interface{}
  31. /*
  32. Get returns a session.
  33. */
  34. Get(key string) (interface{}, bool)
  35. /*
  36. Set sets a session value. A nil value deletes a value
  37. from the session.
  38. */
  39. Set(key string, value interface{})
  40. /*
  41. String returns a string representation of the session.
  42. */
  43. String() string
  44. }
  45. /*
  46. NewDefaultSession creates a new default session object.
  47. */
  48. func NewDefaultSession(id string, user string) Session {
  49. return &DefaultSession{id, user, make(map[string]interface{})}
  50. }
  51. /*
  52. DefaultSession is the default manager for web sessions.
  53. */
  54. type DefaultSession struct {
  55. id string
  56. user string
  57. values map[string]interface{}
  58. }
  59. /*
  60. ID returns the session id.
  61. */
  62. func (ds *DefaultSession) ID() string {
  63. return ds.id
  64. }
  65. /*
  66. User returns the user of the session.
  67. */
  68. func (ds *DefaultSession) User() string {
  69. return ds.user
  70. }
  71. /*
  72. GetAll returns all known session values.
  73. */
  74. func (ds *DefaultSession) GetAll() map[string]interface{} {
  75. return ds.values
  76. }
  77. /*
  78. Get returns a session.
  79. */
  80. func (ds *DefaultSession) Get(key string) (interface{}, bool) {
  81. ret, ok := ds.values[key]
  82. return ret, ok
  83. }
  84. /*
  85. Set sets a session value. A nil value deletes a value
  86. from the session.
  87. */
  88. func (ds *DefaultSession) Set(key string, value interface{}) {
  89. ds.values[key] = value
  90. }
  91. /*
  92. String returns a string representation of the session.
  93. */
  94. func (ds *DefaultSession) String() string {
  95. return fmt.Sprint("Session: ", ds.id, " (User:", ds.user, " Values:", ds.values, ")")
  96. }