Go Session Handling on Heroku
Last updated May 30, 2024
Table of Contents
HTTP is a stateless protocol, but for most applications, it’s necessary to preserve certain information, such as login state or the contents of a shopping cart, across requests.
Sessions are the solution, and the information can either be stored in encrypted HTTP cookies on the client side, or in some sort of storage on the server side (with an HTTP cookie holding only the session ID so the server can identify the client).
Both approaches have their advantages and disadvantages. This article shows how to reliably handle cookie-based sessions in Go applications on Heroku using Gorilla, a popular web toolkit for Go, session package.
The need for sessions
Because of the stateless nature of dynos and the need to scale horizontally, file based session storage cannot be used. If sessions are stored on each dyno’s file system, the next request from a user (who in this example is assumed to have previously been logged in, so the request would contain a session cookie) could end up on a different dyno, where the session information does not exist.
A common solution in the past has been the concept of “sticky sessions” where the load balancer makes sure to always send users to the same backend server. This approach is problematic for various reasons as it negatively affects scalability and durability (for example, in the event of a backend server outage).
Application setup
Start by getting a copy of the sample application:
$ go get -u github.com/heroku-examples/go-sessions-demo
$ cd $GOPATH/src/github.com/heroku-examples/go-sessions-demo
Next, lets set up the application on Heroku:
$ heroku create
$ heroku config:set SESSION_AUTHENTICATION_KEY="<string of any length>"
$ heroku config:set SESSION_ENCRYPTION_KEY="<string of 16, 24 or 32 bytes length>"
$ git push heroku master
You can also click on the button in the GitHub repo to have it automatically create and configure the application for you instead of doing it from the command line.
Exploring the demo application
The application contains a single command, which is in the Procfile as the web process.
The main
function is our entry point into the web process. First, we determine our encryption key and error out if we can’t. The encryption key is used to encrypt the cookie before it’s sent to the web browser.
Next, we create a new cookie store and assign it to the global variable, sessionStore
. sessionStore
is defined as a global variable of type sessions.Store
, which is a Go interface that all Gorilla storage backends need to support.
Next, we register our handlers with the default mux and start up the http server to handle the requests.
func main() {
ek, err := determineEncryptionKey()
if err != nil {
log.Fatal(err)
}
port := os.Getenv("PORT")
if port == "" {
log.WithField("PORT", port).Fatal("$PORT must be set")
}
sessionStore = sessions.NewCookieStore(
[]byte(os.Getenv("SESSION_AUTHENTICATION_KEY")),
ek,
)
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("./public"))))
http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Not Found", http.StatusNotFound)
})
http.HandleFunc("/login", login)
http.HandleFunc("/logout", logout)
http.HandleFunc("/", home)
log.Println(http.ListenAndServe(":"+port, nil))
}```
### Handlers
The `home` handler first attempts to get an existing session from the `sessionStore`. If none exists a zero value session is returned instead. The app then attempts to get the username from the session. If the username isn't found or the contents of the string are empty then we redirect to the `/public/login.html` page, which is served via the use of [`http.FileServer`](https://golang.org/pkg/net/http/#FileServer) in `main`. Otherwise we continue and welcome the user with a `Hello <username>` message and the option to logout.
```go
func home(w http.ResponseWriter, r *http.Request) {
session, err := sessionStore.Get(r, SessionName)
if err != nil {
handleSessionError(w, err)
return
}
username, found := session.Values["username"]
if !found || username == "" {
http.Redirect(w, r, "/public/login.html", http.StatusSeeOther)
log.WithField("username", username).Info("Username is empty/notfound, redirecting")
return
}
w.Header().Add("Content-Type", "text/html")
fmt.Fprintf(w, "<html><body>Hello %s<br/><a href='/logout'>Logout</a></body></html>", username)
}
The login
handler extracts the username and password from the login form and if the values are equal to our hard coded values then the username is stored in the session, the session is saved and the user is redirected to /
(home
handler).
func login(w http.ResponseWriter, r *http.Request) {
username := r.FormValue("username")
password := r.FormValue("password")
log.WithFields(logrus.Fields{"username": username, "password": password}).Info("Received login request.")
// Normally, these would probably be looked up in a DB or environment
if username == "foo" && password == "secret" {
session, err := sessionStore.Get(r, SessionName)
if err != nil {
handleSessionError(w, err)
return
}
session.Values["username"] = username
if err := session.Save(r, w); err != nil {
handleSessionError(w, err)
return
}
log.WithField("username", username).Info("completed login & session.Save")
}
http.Redirect(w, r, "/", 303)
}
The logout
handler gets the session, sets the username to an empty string, saves the session and redirects the user to /
(home
handler).
func logout(w http.ResponseWriter, r *http.Request) {
session, err := sessionStore.Get(r, SessionName)
if err != nil {
handleSessionError(w, err)
return
}
session.Values["username"] = ""
if err := session.Save(r, w); err != nil {
handleSessionError(w, err)
return
}
log.Info("completed logout & session.Save")
http.Redirect(w, r, "/", 302)
}
Session storage options
The example application shows that session information can be stored in encrypted, client-side cookies. Sessions can also be stored in other data stores such as Memcache, Redis, or relational databases like PostgreSQL.
Gorilla’s sessions package provides an interface for storage backends, so switching to other backends is easy. For instance if you wanted to use Redis as a backend you would do something like:
import redisStore "gopkg.in/boj/redistore.v1"
...
func main() {
...
sessionStore = redisStore.NewRediStore(5, "tcp", ":6379", "redis-password",
[]byte(os.Getenv("SESSION_AUTHENTICATION_KEY")),
ek,
)
...
}