Skip to content

✨ feat: Add support for Keys() in session middleware#3517

Merged
ReneWerner87 merged 3 commits intomainfrom
session-mw-keys
Jun 13, 2025
Merged

✨ feat: Add support for Keys() in session middleware#3517
ReneWerner87 merged 3 commits intomainfrom
session-mw-keys

Conversation

@sixcolors
Copy link
Member

Enhance the session middleware by introducing a method to retrieve all keys in the current session. Update documentation to reflect these changes and key any type.

Copilot AI review requested due to automatic review settings June 12, 2025 20:09
@sixcolors sixcolors requested a review from a team as a code owner June 12, 2025 20:09
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR updates the session middleware to support keys of any type by updating method signatures and documentation, and it adds a new Keys method to the middleware.

  • Updated documentation in session.go to reflect a return type of []any for Keys.
  • Added a new Keys method in middleware.go that safely retrieves all session keys.
  • Modified docs/middleware/session.md to update method signatures for Set, Get, Delete, and Keys.

Reviewed Changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

File Description
middleware/session/session.go Updated documentation for the Keys method to return []any.
middleware/session/middleware.go Added a new Keys method that returns session keys.
docs/middleware/session.md Updated method signatures to use key type any and added Keys.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @sixcolors, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a new Keys() method to the session middleware and session objects, providing a way to list all keys within a session. It also includes significant updates to the documentation to accurately reflect the supported any type for session keys and document the new and existing methods.

Highlights

  • New Feature: Added a Keys() method to both the Middleware and Session objects, allowing users to retrieve a slice of all keys currently stored in the session.
  • Documentation Update: Updated the documentation (docs/middleware/session.md) to reflect the newly added Keys() method and to clarify that session keys for Set, Get, and Delete methods can be of any type, not just string. Also added documentation for the Session.Delete method which was previously missing.
  • Type Clarification: Updated the documentation comment for the Session.Keys() method in the code to explicitly state that it returns []any, aligning with the documentation changes.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configureGemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@codecov
Copy link

codecov bot commented Jun 12, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.85%. Comparing base (b29171c) to head (88fa905).
Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3517      +/-   ##
==========================================
- Coverage   83.91%   83.85%   -0.06%     
==========================================
  Files         120      120              
  Lines       12281    12286       +5     
==========================================
- Hits        10305    10302       -3     
- Misses       1553     1559       +6     
- Partials      423      425       +2     
Flag Coverage Δ
unittests 83.85% <100.00%> (-0.06%) ⬇️

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.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 12, 2025

"""

Walkthrough

The session middleware documentation and code were updated to generalize key parameter types from string to any for Set, Get, and Delete methods in both Middleware and Session. New Keys() and Delete(key any) methods were added, and documentation was revised to reflect these changes. Additionally, new test routes for setting and retrieving multiple keys were added to the middleware test suite.

Changes

File(s) Change Summary
docs/middleware/session.md Updated method signatures and documentation to use any for keys; added Keys() and Delete() methods; removed Keys() []string.
middleware/session/middleware.go Added Keys() []any method to Middleware with documentation and usage instructions.
middleware/session/session.go Updated comment for Session.Keys() to indicate return type is []any instead of []string.
middleware/session/middleware_test.go Added POST and GET /keys route handlers and tests to set multiple session keys and retrieve all keys.

Poem

In the warren of sessions, keys now roam free,
Not just strings, but any type—what glee!
With new ways to fetch and delete,
Middleware and Session are now more complete.
🗝️ Hop along, dear coder, and see—
Flexibility blooms in this API tree!

Suggested labels

SessionMW, v3

Suggested reviewers

  • gaby
  • efectn

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 36e455b and 88fa905.

📒 Files selected for processing (1)
  • middleware/session/middleware_test.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • middleware/session/middleware_test.go
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Compare
  • GitHub Check: unit (1.24.x, windows-latest)
  • GitHub Check: unit (1.24.x, macos-latest)
  • GitHub Check: unit (1.24.x, macos-13)
  • GitHub Check: unit (1.24.x, ubuntu-latest)
  • GitHub Check: lint
  • GitHub Check: repeated
  • GitHub Check: Analyse
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a Keys() method to the session middleware and updates documentation to reflect that session keys are of type any. A suggestion for code improvement is to add a nil check in the new Middleware.Keys() method for increased robustness.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b29171c and ea8f831.

📒 Files selected for processing (3)
  • docs/middleware/session.md (2 hunks)
  • middleware/session/middleware.go (1 hunks)
  • middleware/session/session.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
middleware/session/middleware.go (1)
middleware/session/session.go (1)
  • Session (16-24)
🪛 GitHub Check: codecov/patch
middleware/session/middleware.go

[warning] 243-247: middleware/session/middleware.go#L243-L247
Added lines #L243 - L247 were not covered by tests

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: repeated
  • GitHub Check: Compare
🔇 Additional comments (2)
middleware/session/session.go (1)

328-334: Docstring now matches the implementation – LGTM
The return type change to []any is reflected in both code and comment, ensuring consistency. No further action required.

docs/middleware/session.md (1)

196-201: Documentation correctly mirrors the updated API
Method signatures show the new any key type and the added Keys() helper, keeping docs in sync with code.

Comment on lines +235 to +248
// Keys returns all keys in the current session.
//
// Returns:
// - []any: A slice of all keys in the session.
//
// Usage:
//
// keys := m.Keys()
func (m *Middleware) Keys() []any {
m.mu.RLock()
defer m.mu.RUnlock()

return m.Session.Keys()
}
Copy link
Contributor

@coderabbitai coderabbitai bot Jun 12, 2025

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Add nil-safety & tests for the new Keys() helper

m.Session is dereferenced without a check. Once releaseMiddleware has run, this pointer is explicitly set to nil; calling Keys() on such an instance will panic. A small guard avoids foot-guns and clarifies behaviour:

func (m *Middleware) Keys() []any {
-	m.mu.RLock()
-	defer m.mu.RUnlock()
-
-	return m.Session.Keys()
+	m.mu.RLock()
+	sess := m.Session
+	m.mu.RUnlock()
+
+	if sess == nil {
+		return nil
+	}
+	return sess.Keys()
}

Codecov also flags these lines as untested. Please add a unit test that:

  1. Asserts the happy path returns the expected slice.
  2. Asserts a nil-session returns nil (or an empty slice, whichever you decide).

These two changes will harden the API and keep CI green.


To confirm whether m.Session can be nil after releaseMiddleware and ensure the guard is needed, let’s locate the Middleware struct, any releaseMiddleware calls, and assignments of Session to nil:


🏁 Script executed:

#!/bin/bash
set -e

echo "1) Middleware struct definition (show Session field):"
rg -n "type Middleware" -A3 middleware/session/middleware.go

echo
echo "2) References to releaseMiddleware in the repo:"
rg -n "releaseMiddleware" .

echo
echo "3) Any assignments of Session to nil in the repo:"
rg -n "Session = nil" .

Length of output: 931


Add nil-safety & tests for the new Keys() helper

Once releaseMiddleware runs it sets m.Session = nil (see middleware/session/middleware.go line 160), so calling m.Session.Keys() without a guard will panic. Please update Keys() and add unit tests:

• File: middleware/session/middleware.go (around lines 235–248)

func (m *Middleware) Keys() []any {
-	m.mu.RLock()
-	defer m.mu.RUnlock()
-
-	return m.Session.Keys()
+	m.mu.RLock()
+	sess := m.Session
+	m.mu.RUnlock()
+
+	if sess == nil {
+		return nil
+	}
+	return sess.Keys()
}

• Add tests for:

  1. Happy path – returns the expected slice of keys
  2. Nil session – returns nil (or an empty slice, based on your API decision)

These changes prevent a nil‐dereference panic and satisfy Codecov’s coverage requirements.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Keys returns all keys in the current session.
//
// Returns:
// - []any: A slice of all keys in the session.
//
// Usage:
//
// keys := m.Keys()
func (m *Middleware) Keys() []any {
m.mu.RLock()
defer m.mu.RUnlock()
return m.Session.Keys()
}
// Keys returns all keys in the current session.
//
// Returns:
// - []any: A slice of all keys in the session.
//
// Usage:
//
// keys := m.Keys()
func (m *Middleware) Keys() []any {
m.mu.RLock()
sess := m.Session
m.mu.RUnlock()
if sess == nil {
return nil
}
return sess.Keys()
}
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 243-247: middleware/session/middleware.go#L243-L247
Added lines #L243 - L247 were not covered by tests

🤖 Prompt for AI Agents
In middleware/session/middleware.go around lines 235 to 248, the Keys() method
calls m.Session.Keys() without checking if m.Session is nil, which can cause a
panic after releaseMiddleware sets m.Session to nil. Update the Keys() method to
first check if m.Session is nil and return nil (or an empty slice) if so,
otherwise return m.Session.Keys(). Additionally, add unit tests covering both
the happy path (where m.Session is non-nil and returns expected keys) and the
nil session case (where Keys() returns nil or an empty slice) to prevent nil
dereference panics and improve test coverage.

Copy link
Member Author

Choose a reason for hiding this comment

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

middleware Keys method calls Session method Keys which does this check.

Copy link
Contributor

Choose a reason for hiding this comment

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

@sixcolors Thanks for pointing that out! 🙌
I double-checked Session.Keys() in middleware/session/session.go; it already guards against a nil map / empty session and returns nil (effectively preventing a panic). Because m.Session itself is only set to nil inside releaseMiddleware—which happens after the handler finishes—the existing flow is safe during normal request handling.

Given that:
m.Keys() can only be invoked while the handler is still active (before releaseMiddleware resets the object), and
• the downstream call is already nil-safe,

an extra guard inside Middleware.Keys() would indeed be redundant. Likewise, unit coverage for Session.Keys() already exercises the nil-session case, so no additional test is necessary for the wrapper.

I’ll mark the earlier suggestion as resolved. Let me know if you’d like any further changes! 🐇

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: 3

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

3-6: Keep import list alphabetically ordered and add missing package sort if you decide to sort keys

fmt was appended in front of strings, breaking the previously-alphabetised import block.
If you adopt the suggestion below to sort the keys you will also need sort. Consider:

-import (
-    "fmt"
-    "strings"
+import (
+    "fmt"
+    "sort"
+    "strings"
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ea8f831 and 36e455b.

📒 Files selected for processing (1)
  • middleware/session/middleware_test.go (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: unit (1.24.x, macos-latest)
  • GitHub Check: lint
  • GitHub Check: unit (1.24.x, macos-13)
  • GitHub Check: unit (1.24.x, windows-latest)
  • GitHub Check: Analyse
  • GitHub Check: unit (1.24.x, ubuntu-latest)
  • GitHub Check: Compare
  • GitHub Check: repeated

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50.

Benchmark suite Current: 88fa905 Previous: b29171c Ratio
Benchmark_Fiberlog_SetLevel_Parallel/Test_case_1_Parallel 11.54 ns/op 0 B/op 0 allocs/op 6.843 ns/op 0 B/op 0 allocs/op 1.69
Benchmark_Fiberlog_SetLevel_Parallel/Test_case_1_Parallel - ns/op 11.54 ns/op 6.843 ns/op 1.69
Benchmark_Fiberlog_SetLevel_Parallel/Test_case_2_Parallel 11.53 ns/op 0 B/op 0 allocs/op 6.864 ns/op 0 B/op 0 allocs/op 1.68
Benchmark_Fiberlog_SetLevel_Parallel/Test_case_2_Parallel - ns/op 11.53 ns/op 6.864 ns/op 1.68
Benchmark_Fiberlog_SetLevel_Parallel/Test_case_3_Parallel 11.55 ns/op 0 B/op 0 allocs/op 6.896 ns/op 0 B/op 0 allocs/op 1.67
Benchmark_Fiberlog_SetLevel_Parallel/Test_case_3_Parallel - ns/op 11.55 ns/op 6.896 ns/op 1.67
Benchmark_Fiberlog_SetLevel_Parallel/Test_case_4_Parallel 11.53 ns/op 0 B/op 0 allocs/op 6.867 ns/op 0 B/op 0 allocs/op 1.68
Benchmark_Fiberlog_SetLevel_Parallel/Test_case_4_Parallel - ns/op 11.53 ns/op 6.867 ns/op 1.68
Benchmark_Fiberlog_SetLevel_Parallel/Test_case_5_Parallel 11.53 ns/op 0 B/op 0 allocs/op 6.843 ns/op 0 B/op 0 allocs/op 1.68
Benchmark_Fiberlog_SetLevel_Parallel/Test_case_5_Parallel - ns/op 11.53 ns/op 6.843 ns/op 1.68

This comment was automatically generated by workflow using github-action-benchmark.

@gaby gaby added this to v3 Jun 13, 2025
@gaby gaby moved this to In Progress in v3 Jun 13, 2025
@gaby gaby added this to the v3 milestone Jun 13, 2025
@gaby gaby changed the title ✨ feat: Update session middleware add Keys method and update docs to match key type any ✨ feat: Add support for Keys() in session middleware Jun 13, 2025
@ReneWerner87 ReneWerner87 merged commit 670fbd5 into main Jun 13, 2025
13 of 14 checks passed
@github-project-automation github-project-automation bot moved this from In Progress to Done in v3 Jun 13, 2025
@gaby gaby deleted the session-mw-keys branch June 13, 2025 11:15
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