Golang-session management

This article will demonstrate how to gorilla/sessionsdo . 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 /secretthe 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 /logoutthe 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

Guess you like

Origin blog.csdn.net/mryang125/article/details/114647187