Session Management in Go

Session management in Go is not built into the language or the standard package for web applications. However, there are libraries that simplify this task, such as gorilla/sessions. In this article, we will see how to implement basic session management using this library.

Installing the Library

First, you need to install the gorilla/sessions package:

go get github.com/gorilla/sessions

Creating the Session Handler

The following example shows how to configure and use a session:

package main

import (
    "fmt"
    "net/http"
    "github.com/gorilla/sessions"
)

var store = sessions.NewCookieStore([]byte("super-secret-key"))

func loginHandler(w http.ResponseWriter, r *http.Request) {
    session, _ := store.Get(r, "session-name")
    session.Values["authenticated"] = true
    session.Save(r, w)
    fmt.Fprintln(w, "Logged in")
}

func logoutHandler(w http.ResponseWriter, r *http.Request) {
    session, _ := store.Get(r, "session-name")
    session.Values["authenticated"] = false
    session.Save(r, w)
    fmt.Fprintln(w, "Logged out")
}

func protectedHandler(w http.ResponseWriter, r *http.Request) {
    session, _ := store.Get(r, "session-name")
    if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
        http.Error(w, "Forbidden", http.StatusForbidden)
        return
    }
    fmt.Fprintln(w, "This is a protected area")
}

func main() {
    http.HandleFunc("/login", loginHandler)
    http.HandleFunc("/logout", logoutHandler)
    http.HandleFunc("/protected", protectedHandler)
    http.ListenAndServe(":8080", nil)
}

Code Explanation

  • store: initialized with a secret key, used to sign the cookies.
  • loginHandler: sets the authenticated value to true.
  • logoutHandler: sets the authenticated value to false.
  • protectedHandler: checks if the user is authenticated.

Security Considerations

It is important to use a strong and unique secret key. In production, consider using alternative session stores, such as Redis or a database, for greater scalability and security.

Back to top