整合dxvgef/session实现Session

使用dxvgef/session包实现数据存储于Redis的Session功能:

  1. package main
  2.  
  3. import (
  4. "github.com/dxvgef/httpdispatcher"
  5. "net/http"
  6. "log"
  7. "github.com/dxvgef/sessions"
  8. "time"
  9. )
  10.  
  11. //session管理器实例
  12. var SessionManager *sessions.SessionManager
  13.  
  14. func main() {
  15. var err error
  16.  
  17. //获得一个调度器的实例化对象
  18. var dispatcher = httpdispatcher.New()
  19.  
  20. //设置参数并获得session管理器实例
  21. SessionManager, err = sessions.NewSessions(&sessions.Config{
  22. CookieName: "sessionid",
  23. HttpOnly: true,
  24. Path: "/",
  25. MaxAge: 120,
  26. IdleTime: time.Duration(20) * time.Minute,
  27. Secure: false,
  28. RedisAddr: "127.0.0.1:6379",
  29. RedisDB: 0,
  30. RedisPassword: "",
  31. RedisKeyPrefix: "sess",
  32. Key: "key",
  33. })
  34. if err != nil {
  35. log.Println(err.Error())
  36. return
  37. }
  38.  
  39. //在入口路由里传入session处理器
  40. router := dispatcher.Router.GROUP("", func(ctx *httpdispatcher.Context) error {
  41. //更新session空闲时间
  42. err := SessionManager.UpdateIdleTime(ctx.Request, ctx.ResponseWriter)
  43. if err != nil {
  44. return ctx.Event(err)
  45. }
  46. //继续执行下一个处理器
  47. return ctx.Next(true)
  48. })
  49. //在路由组中定义GET路由测试session读写
  50. router.GET("/", func(ctx *httpdispatcher.Context) error {
  51. //使用session
  52. session, err := SessionManager.UseSession(ctx.Request, ctx.ResponseWriter)
  53. if err != nil {
  54. return ctx.Event(err)
  55. }
  56.  
  57. //在session中写入数据
  58. if err := session.Set("test", "ok"); err != nil {
  59. return ctx.Event(err)
  60. }
  61.  
  62. //从session中读取数据
  63. if test, err := session.Get("test").String(); err != nil {
  64. return ctx.Event(err)
  65. } else {
  66. log.Println(test)
  67. }
  68.  
  69. return nil
  70. })
  71.  
  72. svr := &http.Server{
  73. Addr: ":8080",
  74. Handler: dispatcher,
  75. }
  76. if err := svr.ListenAndServe(); err != nil {
  77. log.Fatal(err.Error())
  78. }
  79. }