Gorilla Sessions
[!IMPORTANT]
The latest version of this repository requires go 1.23 because of the new partitioned attribute. The last version that is compatible with older versions of go is v1.3.0.
![sourcegraph](https://sourcegraph.com/github.com/gorilla/sessions/-/badge.svg)
![Gorilla Logo](https://github.com/gorilla/.github/assets/53367916/d92caabf-98e0-473e-bfbf-ab554ba435e5)
gorilla/sessions provides cookie and filesystem sessions and infrastructure for
custom session backends.
The key features are:
- Simple API: use it as an easy way to set signed (and optionally
encrypted) cookies.
- Built-in backends to store sessions in cookies or the filesystem.
- Flash messages: session values that last until read.
- Convenient way to switch session persistency (aka "remember me") and set
other attributes.
- Mechanism to rotate authentication and encryption keys.
- Multiple sessions per request, even using different backends.
- Interfaces and infrastructure for custom session backends: sessions from
different stores can be retrieved and batch-saved using a common API.
Let's start with an example that shows the sessions API in a nutshell:
import (
"net/http"
"github.com/gorilla/sessions"
)
var store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY")))
func MyHandler(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "session-name")
session.Values["foo"] = "bar"
session.Values[42] = 43
err := session.Save(r, w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
First we initialize a session store calling NewCookieStore()
and passing a
secret key used to authenticate the session. Inside the handler, we call
store.Get()
to retrieve an existing session or create a new one. Then we set
some session values in session.Values, which is a map[interface{}]interface{}
.
And finally we call session.Save()
to save the session in the response.
More examples are available at package documentation.
Store Implementations
Other implementations of the sessions.Store
interface:
License
BSD licensed. See the LICENSE file for details.