使用应用程序时,请先将其打开,进行一些更改,然后再将其关闭。这很像一个 Session。电脑知道你是谁。它知道何时启动应用程序以及何时终止。但是在 Internet 上存在一个问题:Web服务器不知道你是谁或做什么,因为HTTP地址无法保持状态。
Session 变量通过存储要在多个页面上使用的用户信息(例如用户名,喜欢的颜色等)来解决此问题。 默认情况下, session 变量将持续到用户关闭浏览器为止。
所以, Session 变量保存有关一个用户的信息,并且可用于一个应用程序中的所有页面。
> **提示**: 如果你需要永久存储,则可能需要将数据存储在[数据库](https://github.com/kataras/iris/wiki/Sessions-database) 中。
* * * * *
Iris 拥有自己的 session 实现, sessions 管理器位于 [iris/sessions](https://github.com/kataras/iris/tree/master/sessions) 包。需要导入此软件包才能使用 HTTP Sessions。
一个 session 通过 `New` 包级函数创建的 `Sessions`对象的 `Start` 函数启动 。该函数将返回一个 `Session`。
Session 变量是使用 `Session.Set` 方法设置 ,并通过 `Session.Get`及其相关方法进行检索。要删除单个变量, 请使用 `Session.Delete`方法。 要删除整个Session 并使它们无效,请使用`Session.Destroy` 方法。
查看所有方法
sessions 管理器是使用 `New` 包级函数创建的。
```
import "github.com/kataras/iris/v12/sessions"
sess := sessions.New(sessions.Config{Cookie: "cookieName", ...})
```
`设置` 看起来是这样的。
```
SessionIDGenerator func(iris.Context) string
// 默认为 "irissessionid".
Cookie string
CookieSecureTLS bool
// 默认为 false.
AllowReclaim bool
// 默认为 nil.
Encode func(cookieName string, value interface{}) (string, error)
// 默认为 nil.
Decode func(cookieName string, cookieValue string, v interface{}) error
// 默认为 nil.
Encoding Encoding
// 默认为 不确定的/无限的生命周期(0).
Expires time.Duration
// 默认为 false.
DisableSubdomainPersistence bool
```
返回值,是一个 `Sessions` 指针, 由以下函数导出。
```
Start(ctx iris.Context,
cookieOptions ...iris.CookieOption) *Session
Handler(cookieOptions ...iris.CookieOption) iris.Handler
Destroy()
DestroyAll()
DestroyByID(sessID string)
OnDestroy(callback func(sid string))
ShiftExpiration(ctx iris.Context,
cookieOptions ...iris.CookieOption) error
UpdateExpiration(ctx iris.Context, expires time.Duration,
cookieOptions ...iris.CookieOption) error
UseDatabase(db Database)
```
`CookieOption` 仅仅是一个允许去自定义 cookie 的属性的 `func(*http.Cookie)` 函数。
`Start` 方法返回一个 `Session` 指针值,它为每个 session 导出自己的方法。
```
func (ctx iris.Context) {
session := sess.Start(ctx)
.ID() string
.IsNew() bool
.Set(key string, value interface{})
.SetImmutable(key string, value interface{})
.GetAll() map[string]interface{}
.Len() int
.Delete(key string) bool
.Clear()
.Get(key string) interface{}
.GetString(key string) string
.GetStringDefault(key string, defaultValue string) string
.GetInt(key string) (int, error)
.GetIntDefault(key string, defaultValue int) int
.Increment(key string, n int) (newValue int)
.Decrement(key string, n int) (newValue int)
.GetInt64(key string) (int64, error)
.GetInt64Default(key string, defaultValue int64) int64
.GetFloat32(key string) (float32, error)
.GetFloat32Default(key string, defaultValue float32) float32
.GetFloat64(key string) (float64, error)
.GetFloat64Default(key string, defaultValue float64) float64
.GetBoolean(key string) (bool, error)
.GetBooleanDefault(key string, defaultValue bool) bool
.SetFlash(key string, value interface{})
.HasFlash() bool
.GetFlashes() map[string]interface{}
.PeekFlash(key string) interface{}
.GetFlash(key string) interface{}
.GetFlashString(key string) string
.GetFlashStringDefault(key string, defaultValue string) string
.DeleteFlash(key string)
.ClearFlashes()
.Destroy()
}
```
## [示例](https://github.com/kataras/iris/wiki/Sessions#example)
在此示例中,我们仅仅允许经过身份认证的用户通过 /secret 路由查看年龄的秘密消息。要访问这个路由, 首先要去访问 /login 路由来获取一个有效的 session cookie,用来让他登陆(原文是:hich logs him in 可能是拼写错误)。 除之之外,他可以访问 /logout 路由去移除它访问我们秘密消息的权限。
```
// sessions.go
package main
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/sessions"
)
var (
cookieNameForSessionID = "mycookiesessionnameid"
sess = sessions.New(sessions.Config{Cookie: cookieNameForSessionID})
)
func secret(ctx iris.Context) {
// 检查是否用户已经认证过
if auth, _ := sess.Start(ctx).GetBoolean("authenticated"); !auth {
ctx.StatusCode(iris.StatusForbidden)
return
}
// 打印私密消息
ctx.WriteString("The cake is a lie!")
}
func login(ctx iris.Context) {
session := sess.Start(ctx)
// 在这里验证身份
// ...
// 设置一个认证过的用户
session.Set("authenticated", true)
}
func logout(ctx iris.Context) {
session := sess.Start(ctx)
// 移除一个认证用户
session.Set("authenticated", false)
// 或者移除变量:
session.Delete("authenticated")
// 或者摧毁 session:
session.Destroy()
}
func main() {
app := iris.New()
app.Get("/secret", secret)
app.Get("/login", login)
app.Get("/logout", logout)
app.Run(iris.Addr(":8080"))
}
```
```
$ go run sessions.go
$ curl -s http://localhost:8080/secret
Forbidden
$ curl -s -I http://localhost:8080/login
Set-Cookie: mysessionid=MTQ4NzE5Mz...
$ curl -s --cookie "mysessionid=MTQ4NzE5Mz..." http://localhost:8080/secret
蛋糕是谎言!
```
## [中间件](https://github.com/kataras/iris/wiki/Sessions#midddleware)
当你想在相同的请求处理程序和生命周期(处理程序和中间件链)中使用 `Session` 时, 可以选择将其注册为中间件并使用包级的 `sessions.Get` 方法检索存储到 Context 的 Session 。
`Sessions` 结构值包含 `Handler`方法,该方法可用于返回 `iris.Handler` 以注册为中间件。
```
import "github.com/kataras/iris/v12/sessions"
sess := sessions.New(sessions.Config{...})
app := iris.New()
app.Use(sess.Handler())
app.Get("/path", func(ctx iris.Context){
session := sessions.Get(ctx)
// [使 session...]
})
```
另外,如果 sessions 管理的 `Config.AllowReclaim` 是 `true` , 那么你仍可以在同一请求生命周期中多次调用 `sess.Start` 的同时,不需要将其注册为中间件。
导航到 <https://github.com/kataras/iris/tree/master/_examples/sessions> 以获得有关 sessions 子包的更多示例。
请继续阅读 [闪存消息](https://github.com/kataras/iris/wiki/Sessions-flash-messages) 章节。