alexedwards / scs

HTTP Session Management for Go
MIT License
2.05k stars 165 forks source link

Add example using gin #164

Closed fadhilaf closed 1 year ago

fadhilaf commented 1 year ago

I've been doing some trial and error, maybe it would be good if i put this

package main

import (
    "net/http"
    "time"

    "github.com/gin-gonic/gin"

    "github.com/alexedwards/scs/v2"
)

var sessionManager *scs.SessionManager

func main() {
    // Initialize a new session manager and configure the session lifetime.
    sessionManager = scs.New()
    sessionManager.Lifetime = 24 * time.Hour

    router := gin.Default()

    router.GET("/put", putHandler)
    router.GET("/get", getHandler)

    // Wrap your handlers with the LoadAndSave() middleware.
    http.ListenAndServe(":4000", sessionManager.LoadAndSave(router))
}

func putHandler(c *gin.Context) {
    // Store a new key and value in the session data.
    sessionManager.Put(c.Request.Context(), "message", "Hello from a session!")
}

func getHandler(c *gin.Context) {
    // Use the GetString helper to retrieve the string value associated with a
    // key. The zero value is returned if the key does not exist.
    msg := sessionManager.GetString(c.Request.Context(), "message")
    c.String(http.StatusOK, msg)
}