Golang : How to use Gorilla webtoolkit context package properly
Many new comers to Gorilla web toolkit are confused as why they cannot pass variables to another handler with the help of context package...as if it is not working as advertised. The assumption is that ... context works like a global variables within the source code page... but it is not meant to be.
If you read the manual carefully, it is clearly stated that - "context stores values shared during a request lifetime.". To pass values to another handlers(functions) OUTSIDE the request lifetime, you need the assistance of the session package.
This code example below will demonstrate how to use context package to pass data to another handler. Provided it is within the lifetime of the request (http.Request)
Here you go!
package main
import (
"fmt"
"github.com/gorilla/context"
"github.com/gorilla/mux"
"net/http"
)
type Key string
const GlobalRequestVariable Key = ""
func SetGlobalHandler(w http.ResponseWriter, r *http.Request) {
context.Set(r, GlobalRequestVariable, "test")
// will WORK because within request lifetime
get, ok := context.GetOk(r, GlobalRequestVariable)
w.Write([]byte(fmt.Sprintf("GetOK : [%v] and get what :[%v] ", ok, get)))
// global variable still accessible as long the request is still alive
// and everything is cleared because router from gorilla/mux will
// automatically call context.Clear(r)
// and cause GetGlobalHandler to fail
// WHEN you point the browser url to example.com:8080/get
// to make it work, you have to pass r down to inside SetGlobalHandler
// while the request is still alive to InternalGetGlobalHandler
InternalGetGlobalHandler(w, r)
}
func InternalGetGlobalHandler(w http.ResponseWriter, r *http.Request) {
// will WORK because still within request lifetime
get, ok := context.GetOk(r, GlobalRequestVariable)
w.Write([]byte(fmt.Sprintf("\nInternal GetOK : [%v] and get what :[%v] ", ok, get)))
}
func GetGlobalHandler(w http.ResponseWriter, r *http.Request) {
// will FAIL because NOT within request lifetime
get, ok := context.GetOk(r, GlobalRequestVariable)
w.Write([]byte(fmt.Sprintf("GetOK : [%v] and get what :[%v] ", ok, get)))
}
func main() {
mx := mux.NewRouter()
mx.HandleFunc("/", SetGlobalHandler)
mx.HandleFunc("/get", GetGlobalHandler)
http.ListenAndServe(":8080", mx)
}
Hope this helps and happy coding!
Reference :
See also : Golang : How to feed or take banana with Gorilla Web Toolkit Session package
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
+7k Golang : Gorrila mux.Vars() function example
+6.6k How to let Facebook Login button redirect to a particular URL ?
+12.7k Golang : Convert IPv4 address to packed 32-bit binary format
+6.6k Golang : Get expvar(export variables) to work with multiplexer
+19.8k Golang : Determine if directory is empty with os.File.Readdir() function
+16.1k Golang : Find out mime type from bytes in buffer
+19.5k Golang : Archive directory with tar and gzip
+7.6k Golang : Reverse a string with unicode
+22.5k Golang : Round float to precision example
+10.3k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+19.3k Golang : Get current URL example
+4.5k Golang : How to pass data between controllers with JSON Web Token