Skip to content

Instantly share code, notes, and snippets.

@calogxro
Last active November 23, 2021 00:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calogxro/685e54201a3d4ad53983d1b13e770c58 to your computer and use it in GitHub Desktop.
Save calogxro/685e54201a3d4ad53983d1b13e770c58 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
)
// Note: Don't store your key in your source code. Pass it via an
// environmental variable, or flag (or both), and don't accidentally commit it
// alongside your code. Ensure your key is sufficiently random - i.e. use Go's
// crypto/rand or securecookie.GenerateRandomKey(32) and persist the result.
var (
// key must be 16, 24 or 32 bytes long (AES-128, AES-192 or AES-256)
key = "super-secret-key" // os.Getenv("SESSION_KEY")
store = sessions.NewCookieStore([]byte(key))
)
var nextID = 1
func main() {
r := mux.NewRouter()
r.HandleFunc("/", home)
r.Use(sessionMiddleware)
http.ListenAndServe(":8080", r)
}
func sessionMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Do stuff here
session, _ := store.Get(r, "cookie-name")
// Check if user is authenticated
if _, auth := session.Values["userID"].(int); !auth {
// Set user as authenticated
session.Values["userID"] = nextID
// Save it before we write to the response/return from the handler.
err := session.Save(r, w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
nextID++
}
fmt.Fprintln(w, )
// Call the next handler,
// which can be another middleware in the chain, or the final handler.
next.ServeHTTP(w, r)
})
}
func getUserID(r *http.Request) interface{} {
session, _ := store.Get(r, "cookie-name")
return session.Values["userID"]
}
func home(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "userID: ", getUserID(r))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment