Memory Storage

Memory storage is relatively simple and efficient, but it does not persistently store Session data, so the Session data will be lost after the application restarts. It can be used in specific business scenarios. The memory storage of gsession is implemented using the StorageMemory object.

Example Usage

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. "github.com/gogf/gf/v2/os/gsession"
  6. "github.com/gogf/gf/v2/os/gtime"
  7. "time"
  8. )
  9. func main() {
  10. s := g.Server()
  11. s.SetSessionMaxAge(time.Minute)
  12. s.SetSessionStorage(gsession.NewStorageMemory())
  13. s.Group("/", func(group *ghttp.RouterGroup) {
  14. group.ALL("/set", func(r *ghttp.Request) {
  15. r.Session.MustSet("time", gtime.Timestamp())
  16. r.Response.Write("ok")
  17. })
  18. group.ALL("/get", func(r *ghttp.Request) {
  19. r.Response.Write(r.Session.Data())
  20. })
  21. group.ALL("/del", func(r *ghttp.Request) {
  22. _ = r.Session.RemoveAll()
  23. r.Response.Write("ok")
  24. })
  25. })
  26. s.SetPort(8199)
  27. s.Run()
  28. }

In this example, to conveniently observe expiration, we set the Session expiration time to 1 minute. After executing,

  1. First, visit http://127.0.0.1:8199/set to set a Session variable;
  2. Then, visit http://127.0.0.1:8199/get to see that the Session variable has been set and successfully retrieved;
  3. Next, we stop the program and restart it. Visit http://127.0.0.1:8199/get again to see that the Session variable is gone;