安装gorilla/sessions
go get -u github.com/gorilla/sessions
命令行运行以上命令。
创建存储
key = []byte("super-secret-key")
store = sessions.NewCookieStore(key)
以上代码创建了Cookie存储对象。该存储对象用于网络请求中的身份识别和信息存储。
会话处理
func login(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "cookie-name")
session.Values["authenticated"] = true
session.Save(r, w)
}
func logout(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "cookie-name")
session.Values["authenticated"] = false
session.Save(r, w)
}
func secret(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "cookie-name")
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
fmt.Fprintln(w, "The cake is a lie!")
}
以上代码包含了身份识别、信息存储和信息判断功能。
完整源码
package main
import (
"fmt"
"net/http"
"github.com/gorilla/sessions"
)
var (
key = []byte("super-secret-key")
store = sessions.NewCookieStore(key)
)
func login(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "cookie-name")
session.Values["authenticated"] = true
session.Save(r, w)
}
func logout(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "cookie-name")
session.Values["authenticated"] = false
session.Save(r, w)
}
func secret(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "cookie-name")
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
fmt.Fprintln(w, "The cake is a lie!")
}
func main() {
http.HandleFunc("/login", login)
http.HandleFunc("/logout", logout)
http.HandleFunc("/secret", secret)
http.ListenAndServe(":8090", nil)
}