| |
1、创建一个session存储,这里使用gorilla/sessions包。
2、在登录时设置session标记用户已认证。
3、在受保护页面获取session,检查session的authenticated标记,确认用户已认证。
4、如果未认证则返回403错误。
package main
import (
"github.com/gorilla/sessions"
"net/http"
"time"
)
var (
// 使用gorilla/sessions存储session
store = sessions.NewCookieStore([]byte("secret-key"))
)
func login(w http.ResponseWriter, r *http.Request) {
// 用户登录逻辑
session, _ := store.Get(r, "session-name")
// 设置session
session.Values["authenticated"] = true //设置bool类型的值
session.Values["foo"] = "bar" //设置字符串类型的值
session.Values[42] = 43 //设置数字类型的值
session.Save(r, w)
}
func protectedPage(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "session-name")
// 检查session
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
// 执行正常逻辑
w.Write([]byte("Protected Page"))
}
func main() {
http.HandleFunc("/login", login)
http.HandleFunc("/protected", protectedPage)
http.ListenAndServe(":8080", nil)
}