Golang-session管理

本文将演示如何通过包 gorilla/sessions 做session管理,session是服务端存储用户数据的形式,浏览器的每次请求,都会将存储用户信息的cookie发送给服务端。由于http协议是无状态的,所以通过cookie session 记录用户的登录状态是一种再常见不过的方式。

本文将通过一个实例演示三个页面来模拟 登录认证,授权访问,注销登录的三个过程。用户首先会访问/login,服务端通过session记录用户登录状态,并将cookie信息返回给用户,下一次用户携带cookie访问/secret页面,服务器查看session发现该用户已经登录所以才能够正常访问。如果用户想退出登录,则访问/logout页面即可。

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)
}

效果展示

1. 首次未登录访问/secret 2. 访问/login进行登录
3. 再次访问/secret 4. 访问/logout注销登录

猜你喜欢

转载自blog.csdn.net/mryang125/article/details/114647187