Deep-dive on the Next Gen Platform. Join the Webinar!

Skip Navigation
Show nav
Dev Center
  • Get Started
  • Documentation
  • Changelog
  • Search
  • Get Started
    • Node.js
    • Ruby on Rails
    • Ruby
    • Python
    • Java
    • PHP
    • Go
    • Scala
    • Clojure
    • .NET
  • Documentation
  • Changelog
  • More
    Additional Resources
    • Home
    • Elements
    • Products
    • Pricing
    • Careers
    • Help
    • Status
    • Events
    • Podcasts
    • Compliance Center
    Heroku Blog

    Heroku Blog

    Find out what's new with Heroku on our blog.

    Visit Blog
  • Log inorSign up
Hide categories

Categories

  • Heroku Architecture
    • Compute (Dynos)
      • Dyno Management
      • Dyno Concepts
      • Dyno Behavior
      • Dyno Reference
      • Dyno Troubleshooting
    • Stacks (operating system images)
    • Networking & DNS
    • Platform Policies
    • Platform Principles
  • Developer Tools
    • Command Line
    • Heroku VS Code Extension
  • Deployment
    • Deploying with Git
    • Deploying with Docker
    • Deployment Integrations
  • Continuous Delivery & Integration (Heroku Flow)
    • Continuous Integration
  • Language Support
    • Node.js
      • Working with Node.js
      • Troubleshooting Node.js Apps
      • Node.js Behavior in Heroku
    • Ruby
      • Rails Support
      • Working with Bundler
      • Working with Ruby
      • Ruby Behavior in Heroku
      • Troubleshooting Ruby Apps
    • Python
      • Working with Python
      • Background Jobs in Python
      • Python Behavior in Heroku
      • Working with Django
    • Java
      • Java Behavior in Heroku
      • Working with Java
      • Working with Maven
      • Working with Spring Boot
      • Troubleshooting Java Apps
    • PHP
      • PHP Behavior in Heroku
      • Working with PHP
    • Go
      • Go Dependency Management
    • Scala
    • Clojure
    • .NET
      • Working with .NET
  • Databases & Data Management
    • Heroku Postgres
      • Postgres Basics
      • Postgres Getting Started
      • Postgres Performance
      • Postgres Data Transfer & Preservation
      • Postgres Availability
      • Postgres Special Topics
      • Migrating to Heroku Postgres
    • Heroku Key-Value Store
    • Apache Kafka on Heroku
    • Other Data Stores
  • AI
    • Working with AI
  • Monitoring & Metrics
    • Logging
  • App Performance
  • Add-ons
    • All Add-ons
  • Collaboration
  • Security
    • App Security
    • Identities & Authentication
      • Single Sign-on (SSO)
    • Private Spaces
      • Infrastructure Networking
    • Compliance
  • Heroku Enterprise
    • Enterprise Accounts
    • Enterprise Teams
    • Heroku Connect (Salesforce sync)
      • Heroku Connect Administration
      • Heroku Connect Reference
      • Heroku Connect Troubleshooting
  • Patterns & Best Practices
  • Extending Heroku
    • Platform API
    • App Webhooks
    • Heroku Labs
    • Building Add-ons
      • Add-on Development Tasks
      • Add-on APIs
      • Add-on Guidelines & Requirements
    • Building CLI Plugins
    • Developing Buildpacks
    • Dev Center
  • Accounts & Billing
  • Troubleshooting & Support
  • Integrating with Salesforce
  • Language Support
  • Go
  • Go Session Handling on Heroku

Go Session Handling on Heroku

English — 日本語に切り替える

Last updated May 30, 2024

Table of Contents

  • The need for sessions
  • Application setup
  • Exploring the demo application
  • Session storage options

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,
    )
    ...
  }

Keep reading

  • Go

Feedback

Log in to submit feedback.

Using WebSockets on Heroku with Go Heroku Go Support

Information & Support

  • Getting Started
  • Documentation
  • Changelog
  • Compliance Center
  • Training & Education
  • Blog
  • Support Channels
  • Status

Language Reference

  • Node.js
  • Ruby
  • Java
  • PHP
  • Python
  • Go
  • Scala
  • Clojure
  • .NET

Other Resources

  • Careers
  • Elements
  • Products
  • Pricing
  • RSS
    • Dev Center Articles
    • Dev Center Changelog
    • Heroku Blog
    • Heroku News Blog
    • Heroku Engineering Blog
  • Twitter
    • Dev Center Articles
    • Dev Center Changelog
    • Heroku
    • Heroku Status
  • Github
  • LinkedIn
  • © 2025 Salesforce, Inc. All rights reserved. Various trademarks held by their respective owners. Salesforce Tower, 415 Mission Street, 3rd Floor, San Francisco, CA 94105, United States
  • heroku.com
  • Legal
  • Terms of Service
  • Privacy Information
  • Responsible Disclosure
  • Trust
  • Contact
  • Cookie Preferences
  • Your Privacy Choices