ThinkSSL🔒 一键申购 5分钟快速签发 30天无理由退款 购买更放心 广告
### Session 为方便应用实现,dotweb内置实现了Session机制,目前支持Runtime与Redis两种存储模式 用户也可通过实现SessionStore接口实现自定义Session存储 * 除Session外,也可以使用dotweb的jwt中间件来实现用户身份状态维护 1、开启Session支持 ~~~ //设置Session开关 app.HttpServer.SetEnabledSession(true) ~~~ 如果需要使用Session,需要代码显示设置,默认情况下Session是关闭状态 2、设置Session存储模式 ~~~ //runtime mode app.HttpServer.SetSessionConfig(session.NewDefaultRuntimeConfig()) //redis mode app.HttpServer.SetSessionConfig(session.NewDefaultRedisConfig("redis url")) ~~~ 通过SetSessionConfig设置存储模式 3、使用 ~~~ func (ctx dotweb.Context) error{ err := ctx.Session().Set("username", user) if err != nil { ctx.WriteString("session set error => ", err, "\r\n") } c := ctx.Session().Get("username") if c != nil { userRead = c.(UserInfo) } else { ctx.WriteString("session read failed, get nil", "\r\n") } ctx.WriteString("userinfo", userRead) return nil } ~~~ 在handler内,通过Context.Session()获取当前请求的Session对象,然后可以通过Session提供的接口进行Session操作 ~~~ Set(key, value interface{}) error Get(key interface{}) interface{} GetString(key interface{}) string GetInt(key interface{}) int GetInt64(key interface{}) int64 Remove(key interface{}) error Clear() error SessionID() string Count() int ~~~