Skip to content

Commit

Permalink
🔥 Feature: Add Session to Go Context in Middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
JIeJaitt committed Mar 6, 2025
1 parent e8f8e4d commit aa756da
Show file tree
Hide file tree
Showing 3 changed files with 1 addition and 59 deletions.
1 change: 1 addition & 0 deletions middleware/session/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ func (m *Middleware) initialize(c fiber.Ctx, cfg Config) {
m.ctx = c

c.Locals(middlewareContextKey, m)
c.SetContext(context.WithValue(c.Context(), sessionContextKey, session))
}

// saveSession handles session saving and error management after the response.
Expand Down
5 changes: 0 additions & 5 deletions middleware/session/store.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package session

import (
"context"
"encoding/gob"
"errors"
"fmt"
Expand Down Expand Up @@ -106,10 +105,6 @@ func (s *Store) Get(c fiber.Ctx) (*Session, error) {
return nil, err
}

// Add session to Go context
ctx := context.WithValue(c.Context(), sessionContextKey, sess)
c.SetContext(ctx)

return sess, nil
}

Expand Down
54 changes: 0 additions & 54 deletions middleware/session/store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ package session

import (
"fmt"
"io"
"net/http/httptest"
"testing"

"github.com/gofiber/fiber/v3"
Expand Down Expand Up @@ -225,55 +223,3 @@ func Test_Store_GetByID(t *testing.T) {
})
})
}

func Test_Store_Get_GoContext(t *testing.T) {
t.Parallel()
app := fiber.New()
store := NewStore()

app.Get("/direct-get", func(c fiber.Ctx) error {
// Get session directly from store (not using middleware)
sess, err := store.Get(c)
if err != nil {
return err
}
defer sess.Release()

// Set some data
sess.Set("name", "JIeJaitt")

// Now get session from Go context
goCtxSess := FromGoContext(c.Context())

// Verify the session exists in Go context
if goCtxSess == nil {
return c.Status(fiber.StatusInternalServerError).SendString("Session not found in Go context")
}

// Verify it's the same session
if goCtxSess.ID() != sess.ID() {
return c.Status(fiber.StatusInternalServerError).SendString("Session IDs don't match")
}

// Verify data is accessible from Go context session
if goCtxSess.Get("name") != "JIeJaitt" {
return c.Status(fiber.StatusInternalServerError).SendString("Wrong value in Go context session")
}

// Save session
if err := sess.Save(); err != nil {
return err
}

return c.SendString("success")
})

// Make request
resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/direct-get", nil))
require.NoError(t, err)
require.Equal(t, fiber.StatusOK, resp.StatusCode)

body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, "success", string(body))
}

0 comments on commit aa756da

Please sign in to comment.