In this blog, we will learn about Golang Gorilla Sessions NewCookieStore.
HTTP (Hypertext Transfer Protocol) being a stateless protocol does not store any kind of information about the previous requests and the user on the server. Every time a client requests a web page from the server, a new connection is started. But we can make our server stateful by using sessions.
When the server uses session, client sends the session ID to the server and the server then authenticates the ID and shows the web page according to the user.
Read Golang Template, Serve Static Files in Golang.
Here is a simple example of Golang Gorilla Session NewCookieStore.
Golang Session Cookie
var cookie *sessions.CookieStore
This creates a cookie variable to store sessions using secure cookies.
The init function which runs before the main function, a new cookie is created using the string provided in the parameter of the sessions.NewCookieStore()
function.
Golang Session Authentication
The
/login
is used for the creation of the session. The
/
URL i.e the Home Page uses the session and authenticates it. If the session ID and Key match the successful message page.
/logout
path as the name suggests logs out from the current session. This leads to the deletion of session IDs and keys.
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/sessions"
)
var cookie *sessions.CookieStore
func init() {
cookie = sessions.NewCookieStore([]byte("Golang-Blogs"))
}
func home(w http.ResponseWriter, r *http.Request) {
session, _ := cookie.Get(r, "Golang-session")
var authenticated interface{} = session.Values["authenticated"]
if authenticated != nil {
isAuthenticated := session.Values["authenticated"].(bool)
if !isAuthenticated {
http.Error(w, "UnAuthorized to Access this Page.", http.StatusForbidden)
return
}
fmt.Fprintf(w, "Authenticated User's Home Page")
}
}
func login(w http.ResponseWriter, r *http.Request) {
session, _ := cookie.Get(r, "Golang-session")
session.Values["authenticated"] = true
session.Save(r, w)
fmt.Fprintf(w, "Successfully Logged In")
}
func logout(w http.ResponseWriter, r *http.Request) {
session, _ := cookie.Get(r, "Golang-session")
session.Values["authenticated"] = false
session.Save(r, w)
fmt.Fprintf(w, "Successfully Logged Out")
}
func main() {
http.HandleFunc("/", home)
http.HandleFunc("/login", login)
http.HandleFunc("/logout", logout)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("Error Starting the HTTP Server : ", err)
return
}
}
Run http-session.go
using the go run
command.
Golang Gorilla Sessions in Chrome Developer Tool
We can use the Chrome Developer tool to see our Golang session that is being created.
Learn More about Golang Gorilla Sessions NewCookieStore from the Golang Official Web Page – Golang.org