alexedwards / scs

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

constant panicing with chi v5 and pgxpool #148

Closed c-nv-s closed 1 year ago

c-nv-s commented 1 year ago

basic edited version of pgxpool example with chi v5 is constantly panicing:

package main

import (
    "context"
    "io"
    "log"
    "net/http"
    "time"

    "github.com/alexedwards/scs/pgxstore"
    "github.com/alexedwards/scs/v2"
    "github.com/go-chi/chi/middleware"
    chi "github.com/go-chi/chi/v5"
    "github.com/jackc/pgx/v4/pgxpool"
)

var sessionManager *scs.SessionManager

func main() {

    pool, err := pgxpool.Connect(context.Background(), "postgres://username:password@host/dbname")
    if err != nil {
        log.Fatal(err)
    }
    defer pool.Close()

    sessionManager := scs.New()
    sessionManager.Store = pgxstore.New(pool)
    sessionManager.Lifetime = 3 * time.Hour

    router := chi.NewRouter()
    router.Use(middleware.RequestID)
    router.Use(middleware.RealIP)
    router.Use(middleware.Logger)
    router.Use(middleware.Recoverer)
    router.Use(sessionManager.LoadAndSave) // THIS MUST BE USED LAST OTHERWISE WILL PANIC???
    router.Get("/put", putHandler)
    router.Get("/get", getHandler)
    http.ListenAndServe(":3000", router)

}

func putHandler(w http.ResponseWriter, r *http.Request) {
    sessionManager.Put(r.Context(), "message", "Hello from a session!")
}

func getHandler(w http.ResponseWriter, r *http.Request) {
    msg := sessionManager.GetString(r.Context(), "message")
    io.WriteString(w, msg)
}
alexedwards commented 1 year ago

Hi,

The problem is this line in your code:

sessionManager := scs.New()

By using := you are creating and assigning to a sessionManager variable scoped to the main() function, not your sessionManager global variable.

Please try changing it to the following instead:

sessionManager = scs.New()