1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| import ( "fmt" "net/http"
"github.com/gorilla/sessions" )
var ( key = []byte("secret-key") store = sessions.NewCookieStore(key) )
func main() { http.HandleFunc("/secret", secret) http.HandleFunc("/login", login) http.HandleFunc("/logout", logout) http.ListenAndServe(":8080", nil) }
func secret(w http.ResponseWriter, r *http.Request) { session, _ := store.Get(r, "session-name") if auth, ok := session.Values["authenticated"].(bool); !ok || !auth { http.Error(w, "禁止访问", http.StatusForbidden) return } fmt.Fprintln(w, "允许访问") }
func login(w http.ResponseWriter, r *http.Request) { session, _ := store.Get(r, "session-name") session.Values["authenticated"] = true session.Save(r, w) }
func logout(w http.ResponseWriter, r *http.Request) { session, _ := store.Get(r, "session-name") session.Values["authenticated"] = false session.Save(r, w) }
|