Skip to content

🔥 feat: Add Session Access via Go Context#3339

Closed
JIeJaitt wants to merge 16 commits intogofiber:mainfrom
JIeJaitt:JIeJaitt-jiejaitt-feature/add-sessionMD-userContext-support
Closed

🔥 feat: Add Session Access via Go Context#3339
JIeJaitt wants to merge 16 commits intogofiber:mainfrom
JIeJaitt:JIeJaitt-jiejaitt-feature/add-sessionMD-userContext-support

Conversation

@JIeJaitt
Copy link
Contributor

@JIeJaitt JIeJaitt commented Mar 6, 2025

In order to maintain the consistency of the fiber middleware, this pr is proposed to add the corresponding function mentioned in #3212 to the session middleware.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 6, 2025

Walkthrough

The changes focus on refining session management in the middleware. A new context key (middlewareContextKey) is introduced to store middleware instances instead of sessions. The FromContext function is modified to handle a generic type and log errors for unsupported contexts. Additionally, session retrieval is consolidated by removing the old FromGoContext function and introducing the GetAndSetInContext method in the store. Test files are updated to reflect these changes and to add comprehensive test cases for session creation, persistence, modification, and error handling.

Changes

File(s) Change Summary
middleware/session/middleware.go
middleware/session/middleware_test.go
- Added context import.
- Replaced the old context key with middlewareContextKey in functions NewWithStore and initialize.
- Modified FromContext to accept a generic type and log errors for unsupported contexts.
- Added test function Test_Session_Context to test session management.
middleware/session/session.go
middleware/session/store.go
- Removed unexported contextKey type and sessionContextKey constant.
- Deleted FromGoContext and consolidated session retrieval by introducing the GetAndSetInContext method in the store.
- Enhanced error handling in the Get method by capturing and immediately returning errors.
middleware/session/session_test.go - Added new tests for the GetAndSetInContext method covering:
• Session creation and context storage.
• Session retrieval with persistent data and modification.
• Error scenarios using a mock storage implementation (mockGetErrorStorage).

Sequence Diagram(s)

sequenceDiagram
    participant C as Client/Request
    participant M as Middleware
    participant S as Session Store

    C->>M: Incoming request
    M->>S: Call GetAndSetInContext(c)
    S->>S: Execute Get() with error handling
    alt Session retrieved
      S-->>M: Return session
    else Error occurred
      S-->>M: Return error
      M->>M: Log error
    end
    M->>C: Proceed with updated context
Loading

Poem

I'm a jolly rabbit on a coding spree,
Hopping through sessions so gracefully.
Contexts now sparkle with keys brand new,
Errors logged, and flows are smooth too!
With whiskers twitching in lines of delight,
Our sleek session code takes flight!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Free

📥 Commits

Reviewing files that changed from the base of the PR and between e8b9fd6 and 21b5cf5.

📒 Files selected for processing (1)
  • middleware/session/middleware_test.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • middleware/session/middleware_test.go

Note

🎁 Summarized by CodeRabbit Free

Your organization has reached its limit of developer seats under the Pro Plan. For new users, CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please add seats to your subscription by visiting https://app.coderabbit.ai/login.If you believe this is a mistake and have available seats, please assign one to the pull request author through the subscription management page using the link above.

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@JIeJaitt JIeJaitt marked this pull request as ready for review March 6, 2025 07:03
@JIeJaitt JIeJaitt requested a review from a team as a code owner March 6, 2025 07:03
@JIeJaitt JIeJaitt requested review from ReneWerner87, efectn, gaby and sixcolors and removed request for a team March 6, 2025 07:03
@codecov
Copy link

codecov bot commented Mar 6, 2025

Codecov Report

Attention: Patch coverage is 93.33333% with 2 lines in your changes missing coverage. Please review.

Project coverage is 83.65%. Comparing base (395c8fa) to head (d19b4f2).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
middleware/session/middleware.go 88.88% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3339      +/-   ##
==========================================
+ Coverage   83.61%   83.65%   +0.04%     
==========================================
  Files         118      118              
  Lines       11727    11750      +23     
==========================================
+ Hits         9806     9830      +24     
  Misses       1491     1491              
+ Partials      430      429       -1     
Flag Coverage Δ
unittests 83.65% <93.33%> (+0.04%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@JIeJaitt JIeJaitt marked this pull request as draft March 6, 2025 07:05
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
middleware/session/middleware_test.go (1)

457-502: Well-structured test for Go context integration.

The test verifies that sessions can be accessed from both Fiber context and Go context, confirming that the implementation works correctly. It properly tests the "happy path" where a session exists and can be retrieved.

However, consider adding test cases for edge conditions:

Add tests for:

  1. When the provided context is nil
  2. When the context doesn't contain a session

This would improve test coverage for the FromGoContext function.

+func Test_Session_GoContext_EdgeCases(t *testing.T) {
+	t.Parallel()
+	
+	// Test with nil context
+	sess := FromGoContext(nil)
+	require.Nil(t, sess, "Session should be nil with nil context")
+	
+	// Test with context that doesn't have a session
+	ctx := context.Background()
+	sess = FromGoContext(ctx)
+	require.Nil(t, sess, "Session should be nil when not in context")
+}
middleware/session/store_test.go (1)

229-279: Well-structured test for the new Go context session functionality.

This test properly validates the new functionality for accessing session data via Go context. It covers the main flow by:

  1. Getting a session directly from the store
  2. Setting data in the session
  3. Retrieving and validating the same session from Go context
  4. Verifying data consistency between contexts
  5. Testing end-to-end with a real HTTP request

Consider adding test cases for edge scenarios, such as:

  • Behavior when a session hasn't been initialized before calling FromGoContext
  • Error handling when session operations fail

For example:

t.Run("no session in context", func(t *testing.T) {
    app := fiber.New()
    c := app.AcquireCtx(&fasthttp.RequestCtx{})
    defer app.ReleaseCtx(c)
    
    // No session has been created yet
    goCtxSess := FromGoContext(c.Context())
    require.Nil(t, goCtxSess)
})
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a5c7b77 and 740d04f.

📒 Files selected for processing (5)
  • middleware/session/middleware.go (2 hunks)
  • middleware/session/middleware_test.go (2 hunks)
  • middleware/session/session.go (3 hunks)
  • middleware/session/store.go (2 hunks)
  • middleware/session/store_test.go (2 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
middleware/session/session.go

[warning] 529-530: middleware/session/session.go#L529-L530
Added lines #L529 - L530 were not covered by tests


[warning] 534-534: middleware/session/session.go#L534
Added line #L534 was not covered by tests

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: unit (1.24.x, windows-latest)
  • GitHub Check: Compare
  • GitHub Check: repeated
🔇 Additional comments (8)
middleware/session/middleware.go (2)

6-6: Context package import added correctly.

This import is needed for integrating Go's standard context capabilities with Fiber's session management.


94-97: Well-implemented session integration with Go context.

The implementation properly adds the session to Go's context using the standard context.WithValue pattern and then updates the Fiber context. This enables retrieving the session via Go's context package, which aligns with modern Go practices.

middleware/session/session.go (2)

5-5: Context package import added correctly.

This import is needed for the new FromGoContext function.


34-41: Well-designed context key implementation.

Using an unexported type for context keys is a best practice in Go as it prevents key collisions with other packages. The implementation follows the recommendations from the Go context package documentation.

middleware/session/store.go (2)

4-4: Context package import added correctly.

This import is needed for the enhanced Get method implementation.


104-113: Robust error handling and context integration.

The enhanced Get method now properly:

  1. Explicitly handles errors from getSession
  2. Sets the session in the Go context
  3. Updates the Fiber context with the Go context

This provides a consistent way to access sessions from both Fiber and Go contexts.

middleware/session/middleware_test.go (1)

4-5: Appropriate imports for testing.

The added imports for io and net/http/httptest are needed for reading response bodies and creating test HTTP requests.

middleware/session/store_test.go (1)

5-6: LGTM: New imports support the new test functionality.

The added imports (io and net/http/httptest) are appropriate for the new test function that requires reading response bodies and simulating HTTP requests.

@JIeJaitt
Copy link
Contributor Author

JIeJaitt commented Mar 6, 2025

This unit test I ran locally reported no errors and I didn't change it. Anything else to note here? @ReneWerner87 @gaby
image

image

@JIeJaitt JIeJaitt marked this pull request as ready for review March 6, 2025 07:20
@ReneWerner87 ReneWerner87 added this to the v3 milestone Mar 6, 2025
@ReneWerner87 ReneWerner87 added this to v3 Mar 6, 2025
@ReneWerner87
Copy link
Member

@sixcolors can you check this

@JIeJaitt
Copy link
Contributor Author

JIeJaitt commented Mar 6, 2025

@ReneWerner87 How can I avoid lint error , I used the following comment but it doesn't seem to have any effect, he still reports lint error:
image

@gaby gaby changed the title 🔥 Feature: Add Session Access via Go Context 🔥 feat: Add Session Access via Go Context Mar 6, 2025
@gaby gaby moved this to In Progress in v3 Mar 10, 2025
Copy link
Member

@gaby gaby left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One small comment, should we rename it? Also the documentation needs to be updated and the whats_new.md file.

Besides that it looks good to me.

@sixcolors
Copy link
Member

@sixcolors can you check this

Yes. Will do a full review this week.

Copy link
Member

@sixcolors sixcolors left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

session.Session and session.Middleware are distinct and have differing purposes. Storing them in the context with the same key is not correct.

See: https://github.com/gofiber/fiber/blob/main/docs/middleware/session.md#v2-to-v3

m.initialize(c, cfg)

// Add session to Go context
ctx := context.WithValue(c.Context(), middlewareContextKey, m)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand the benefit of retaining the references in both c.Context and c.Locals. Given that the UserContext used is always linked to the ctx.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I answered the question here: #3340 (comment)

@JIeJaitt
Copy link
Contributor Author

on.Session and session.Middleware are distinct and have differing purposes. Storing them in the context with the same key is not correct.

See: https://github.com/gofiber/fiber/blob/main/docs/middleware/session.md#v2-to-v3

At first I thought the same thing, but I think that since Middleware includes Session, why not get the Middleware when the user wants to use Session, and just fetch the Session from it?

So this pr only considers storing Middleware into Fiber.Ctx and context.Context, but not Session.

What do you think? @ReneWerner87 @gaby

@sixcolors
Copy link
Member

sixcolors commented Mar 17, 2025

on.Session and session.Middleware are distinct and have differing purposes. Storing them in the context with the same key is not correct.
See: https://github.com/gofiber/fiber/blob/main/docs/middleware/session.md#v2-to-v3

At first I thought the same thing, but I think that since Middleware includes Session, why not get the Middleware when the user wants to use Session, and just fetch the Session from it?

So this pr only considers storing Middleware into Fiber.Ctx and context.Context, but not Session.

What do you think? @ReneWerner87 @gaby

Session only exists in v3 for legacy use or for use without a context. Using Session methods is otherwise not recommended and Middleware methods would be preferred. See #2741

So I would reject the added GetAndSetInContext function.

@JIeJaitt
Copy link
Contributor Author

on.Session and session.Middleware are distinct and have differing purposes. Storing them in the context with the same key is not correct.
See: https://github.com/gofiber/fiber/blob/main/docs/middleware/session.md#v2-to-v3

At first I thought the same thing, but I think that since Middleware includes Session, why not get the Middleware when the user wants to use Session, and just fetch the Session from it?
So this pr only considers storing Middleware into Fiber.Ctx and context.Context, but not Session.
What do you think? @ReneWerner87 @gaby

Session only exists in v3 for legacy use or for use without a context. Using Session methods is otherwise not recommended and Middleware methods would be preferred. See #2741

So I would reject the added GetAndSetInContext function.

If that's the case, as I understand it Session is an already obsolete piece of code, and adding a new GetAndSetInContext function would encourage the use of an API that is no longer recommended.

If my understanding is correct I would remove the GetAndSetInContext function.

Copy link
Member

@sixcolors sixcolors left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your contribution! However, I do not support merging this change due to the reasons outlined in issue #3358.

Fiber is designed to be lightweight and high-performance, and modifying context.Context within middleware introduces unnecessary overhead.

If you need context.Context integration, you can implement a custom middleware to copy values into context.Context for your specific use case without affecting Fiber’s default behavior.

For more details, see: this comment.

I recommend closing this PR. Thanks again! 🚀

@JIeJaitt
Copy link
Contributor Author

Thanks for your contribution! However, I do not support merging this change due to the reasons outlined in issue #3358.

Fiber is designed to be lightweight and high-performance, and modifying context.Context within middleware introduces unnecessary overhead.

If you need context.Context integration, you can implement a custom middleware to copy values into context.Context for your specific use case without affecting Fiber’s default behavior.

For more details, see: this comment.

I recommend closing this PR. Thanks again! 🚀

thinks,I've already understood the whole working process and I will close this pr

@JIeJaitt JIeJaitt closed this Mar 19, 2025
@github-project-automation github-project-automation bot moved this from In Progress to Done in v3 Mar 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants