会话

嗨,我是 Philipp!
我想告诉你,我的平台 Go Web 示例课程 刚刚发布。享受关于 Go 中 Web 开发的易于理解的视频课程。一定要查看我为早期支持者提供的特别优惠。
我们将在那里见面!:)
了解更多

会话

此示例将展示如何使用 Go 中流行的 gorilla/sessions 包在会话 cookie 中存储数据。

Cookie 是存储在用户浏览器中的少量数据,并在每次请求时发送到我们的服务器。在其中,我们可以存储例如用户是否登录到我们的网站,并找出他实际上是谁(在我们的系统中)。

在此示例中,我们只允许经过身份验证的用户查看 /secret 页面上的秘密消息。要访问它,他们首先需要访问 /login 以获取有效的会话 cookie,这将使他登录。此外,他可以访问 /logout 以撤销对我们的秘密消息的访问权限。

// sessions.go
package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/sessions"
)

var (
    // key must be 16, 24 or 32 bytes long (AES-128, AES-192 or AES-256)
    key = []byte("super-secret-key")
    store = sessions.NewCookieStore(key)
)

func secret(w http.ResponseWriter, r *http.Request) {
    session, _ := store.Get(r, "cookie-name")

    // Check if user is authenticated
    if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
        http.Error(w, "Forbidden", http.StatusForbidden)
        return
    }

    // Print secret message
    fmt.Fprintln(w, "The cake is a lie!")
}

func login(w http.ResponseWriter, r *http.Request) {
    session, _ := store.Get(r, "cookie-name")

    // Authentication goes here
    // ...

    // Set user as authenticated
    session.Values["authenticated"] = true
    session.Save(r, w)
}

func logout(w http.ResponseWriter, r *http.Request) {
    session, _ := store.Get(r, "cookie-name")

    // Revoke users authentication
    session.Values["authenticated"] = false
    session.Save(r, w)
}

func main() {
    http.HandleFunc("/secret", secret)
    http.HandleFunc("/login", login)
    http.HandleFunc("/logout", logout)

    http.ListenAndServe(":8080", nil)
}
$ go run sessions.go

$ curl -s http://localhost:8080/secret
Forbidden

$ curl -s -I http://localhost:8080/login
Set-Cookie: cookie-name=MTQ4NzE5Mz...

$ curl -s --cookie "cookie-name=MTQ4NzE5Mz..." http://localhost:8080/secret
The cake is a lie!