This article will demonstrate how to gorilla/sessions
do . Session is the form in which the server stores user data. Every time the browser makes a request, it will send a cookie storing user information to the server. Since the http protocol is stateless, it is a very common way to record the user's login status through the cookie session.
This article will use an example to demonstrate three pages to simulate the three processes of login authentication, authorized access, and logout. The user will visit first /login
, and the server records the user's login status through the session, and returns the cookie information to the user. The next time the user visits /secret
the page with the cookie, the server checks the session and finds that the user has logged in, so it can access normally. If the user wants to log out, just visit /logout
the page.
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)
}
Show results
1. Access /secret without logging in for the first time | 2. Visit /login to log in |
---|---|
3. Visit /secret again | 4. Visit /logout to log out and log in |
---|---|