Golang : How to feed or take banana with Gorilla Web Toolkit Session package
From previous tutorial on context package, we learn that in order to pass data to other handlers outside the lifetime of the http.Request, we need to use Gorilla's session package.
The following code example demonstrate how to pass variables from one handler to another handler with the session package.
NOTE : In order to use the session package correctly, you need to first initialize session's Options
at the init()
function and also remember to process your session data FIRST before writing anything to the client(web browser).
Here you go!
package main
import (
"fmt"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
"net/http"
)
var encryptionkey = "something-very-secret"
var store = sessions.NewCookieStore([]byte(encryptionkey))
func init() {
store.Options = &sessions.Options{
// change domain to match your machine. Can be localhost
Domain: "example.com",
Path: "/",
MaxAge: 3600 * 3, // 3 hours
HttpOnly: true,
}
}
func SetSessionHandler(w http.ResponseWriter, r *http.Request) {
// IMPORTANT! Do not writer anything to client first
// otherwise, your session data will be blank.
//w.Write([]byte(fmt.Sprintf("Setting session...")))
session, _ := store.Get(r, "your-session-name")
// set some session values.
session.Values["banana"] = "yes"
session.Values[108] = 801
session.Values["username"] = "extract from twitter"
// Save
err := session.Save(r, w)
if err != nil {
fmt.Println("Session not saved!", err)
w.Write([]byte(fmt.Sprintln("Setting not saved! ", err)))
}
// ONLY write to client after session is read.
w.Write([]byte(fmt.Sprintf("Setting session...")))
}
func GetSessionHandler(w http.ResponseWriter, r *http.Request) {
// IMPORTANT! Do not writer anything to client first
// otherwise, your session data will be blank.
//w.Write([]byte(fmt.Sprintf("Getting session...")))
// reading session values - without adding it to registry
session, err := store.New(r, "your-session-name")
if err != nil {
fmt.Println("Unable to retrieve session!", err)
w.Write([]byte(fmt.Sprintln("Unable to retrieve session! ", err)))
}
fmt.Println("Session name is : ", session.Name())
fmt.Println("Session values from SetSessionHandler...")
for k, v := range session.Values {
fmt.Printf("Key : [%v] Values : [%v]\n", k, v)
}
// ONLY write to client after session is read.
w.Write([]byte(fmt.Sprintf("Getting session...")))
}
func main() {
mx := mux.NewRouter()
mx.HandleFunc("/", SetSessionHandler)
mx.HandleFunc("/get", GetSessionHandler)
http.ListenAndServe(":8080", mx)
}
References :
http://www.gorillatoolkit.org/pkg/sessions#Options
See also : Golang : How to use Gorilla webtoolkit context package properly
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.6k Python : Find out the variable type and determine the type with simple test
+9.4k Golang : Find correlation coefficient example
+8.8k Golang : How to find out similarity between two strings with Jaro-Winkler Distance?
+5k Javascript : Change page title to get viewer attention
+24.1k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+12.8k Golang : How to calculate the distance between two coordinates using Haversine formula
+30.4k Golang : Download file example
+9.9k Golang : Compare files modify date example
+9.7k CodeIgniter : Load different view for mobile devices
+9.2k Golang : Get all countries currencies code in JSON format
+13.8k Javascript : Prompt confirmation before exit
+16.7k Golang : Get number of CPU cores