Go语言Web : Sessions

如何传承会话数据

使用Iris你不需要任何第三方库

只允许验证过的用户在/secret页面查看信息,要实现这个功能,首先必须已经登录,以获取有效的会话cookie,

cookie记录用户已经登录;此外,用户可以访问/logout页面丢弃访问验证信息。

// sessions.go
package main

import (
    "gopkg.in/kataras/iris.v6"
    "gopkg.in/kataras/iris.v6/adaptors/httprouter"
    "gopkg.in/kataras/iris.v6/adaptors/sessions"
)

var (
    key = "my_sessionid"
)

func secret(ctx *iris.Context) {

    //检查用户是否已经验证
    if auth, _ := ctx.Session().GetBoolean("authenticated"); !auth {
        ctx.EmitError(iris.StatusForbidden)
        return
    }

    // 输出加密信息
    ctx.WriteString("The cake is a lie!")
}

func login(ctx *iris.Context) {
    session := ctx.Session()

    // 这里是验证
    // ...

    // 设置用户已经验证
    session.Set("authenticated", true)
}

func logout(ctx *iris.Context) {
    session := ctx.Session()

    // 丢弃验证信息
    session.Set("authenticated", false)
}

func main() {
    app := iris.New()
    app.Adapt(httprouter.New())

    sess := sessions.New(sessions.Config{Cookie: key})
    app.Adapt(sess)

    app.Get("/secret", secret)
    app.Get("/login", login)
    app.Get("/logout", logout)

    app.Listen(":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
The cake is a lie!

results matching ""

    No results matching ""