Skip to content

🐛 bug: Fix default value for MaxFunc in Limiter middleware#3871

Merged
ReneWerner87 merged 2 commits intomainfrom
update-middleware-limiter-config-and-add-regression-test
Nov 16, 2025
Merged

🐛 bug: Fix default value for MaxFunc in Limiter middleware#3871
ReneWerner87 merged 2 commits intomainfrom
update-middleware-limiter-config-and-add-regression-test

Conversation

@gaby
Copy link
Member

@gaby gaby commented Nov 16, 2025

Summary

  • This pull request enhances the robustness of the limiter middleware by ensuring that its MaxFunc is always properly initialized, even when the middleware is instantiated with default configurations. This change prevents potential runtime panics and improves the reliability of the rate-limiting mechanism, making it safer to use without explicit configuration.

Fixes #3867

Copilot AI review requested due to automatic review settings November 16, 2025 17:57
@gaby gaby requested a review from a team as a code owner November 16, 2025 17:57
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 16, 2025

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • .github/release-drafter.yml is excluded by !**/*.yml

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

The pull request extracts a defaultLimiterMax constant and integrates it into the limiter's default configuration. Additionally, a MaxFunc is added to ConfigDefault to enable dynamic max limit calculation. A test is added to verify the default configuration operates without panics.

Changes

Cohort / File(s) Change Summary
Limiter Configuration
middleware/limiter/config.go
Introduces defaultLimiterMax constant set to 5; updates ConfigDefault.Max to use the new constant; adds MaxFunc default that returns defaultLimiterMax for dynamic limit calculation
Limiter Tests
middleware/limiter/limiter_test.go
Adds TestLimiterDefaultConfigNoPanic test verifying that a Fiber app with limiter default configuration handles a GET request without panic and returns HTTP 200

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~5–10 minutes

  • Straightforward constant extraction and configuration updates with minimal logic changes
  • Single new test following established patterns
  • No complex interdependencies or control flow modifications

Possibly related PRs

Suggested reviewers

  • sixcolors
  • ReneWerner87
  • efectn

Poem

🐰 A constant bounds the limiter's reach,
MaxFunc brings dynamics to each,
No panic shall fall on requests so small,
The defaults align, no faults at all! 🎉

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Description check ❓ Inconclusive The PR description is minimal and lacks required sections from the template. It provides a summary and issue reference but omits details on changes introduced, type of change, and verification checklist. Add missing sections: 'Changes introduced' with details on benchmarks, documentation, and changelog; specify 'Type of change'; and complete the verification checklist from the template.
✅ Passed checks (2 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly references the fix for MaxFunc default value in Limiter middleware, which aligns with the main change introducing defaultLimiterMax constant and setting ConfigDefault.MaxFunc to use it.

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @gaby, 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 enhances the robustness of the limiter middleware by ensuring that its MaxFunc is always properly initialized, even when the middleware is instantiated with default configurations. This change prevents potential runtime panics and improves the reliability of the rate-limiting mechanism, making it safer to use without explicit configuration.

Highlights

  • Default MaxFunc: The ConfigDefault.MaxFunc for the limiter middleware is now set to a default closure. This closure returns the defaultLimiterMax value, preventing MaxFunc from being nil when limiter.New() is called without arguments.
  • New Constant: A new constant defaultLimiterMax with a value of 5 has been introduced to centralize the default maximum request limit.
  • Regression Test: A new test, TestLimiterDefaultConfigNoPanic, has been added to ensure that initializing the limiter middleware with default settings (limiter.New()) does not cause a panic.
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 by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

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 pull request 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 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. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

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 configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@gaby gaby changed the title Set limiter MaxFunc default 🐛 bug: Fix default value for MaxFunc in Limiter middleware Nov 16, 2025
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 correctly fixes a panic that occurs when limiter.New() is called without arguments. It achieves this by providing a default MaxFunc in ConfigDefault. The introduction of the defaultLimiterMax constant is a good improvement for maintainability. The added regression test TestLimiterDefaultConfigNoPanic effectively prevents this issue from recurring.

While reviewing the code, I noticed a potential pre-existing bug in the sliding window implementation (middleware/limiter/limiter_sliding.go). It appears to use cfg.Max for rate limit calculations instead of the value returned by cfg.MaxFunc. This can lead to incorrect behavior if a user provides a MaxFunc that returns a value different from cfg.Max. Since this is outside the scope of the current changes, I'm mentioning it here for awareness. It might be worth creating a separate issue to track and fix this.

Overall, the changes in this PR are correct and improve the robustness of the limiter middleware.

@codecov
Copy link

codecov bot commented Nov 16, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.64%. Comparing base (3bf25e8) to head (e764c68).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3871      +/-   ##
==========================================
- Coverage   91.69%   91.64%   -0.06%     
==========================================
  Files         115      115              
  Lines        9819     9848      +29     
==========================================
+ Hits         9004     9025      +21     
- Misses        516      523       +7     
- Partials      299      300       +1     
Flag Coverage Δ
unittests 91.64% <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.

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 fixes a nil pointer panic that occurred when calling limiter.New() without any configuration arguments. The fix sets a default MaxFunc in ConfigDefault that returns the default max value of 5.

  • Extracted the magic number 5 into a named constant defaultLimiterMax
  • Added a default MaxFunc to ConfigDefault that returns defaultLimiterMax
  • Added a regression test to ensure the middleware works without panicking when called with no configuration

Reviewed Changes

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

File Description
middleware/limiter/config.go Introduces defaultLimiterMax constant and sets a default MaxFunc in ConfigDefault to prevent nil pointer panics
middleware/limiter/limiter_test.go Adds regression test TestLimiterDefaultConfigNoPanic to verify the middleware can be instantiated and used without any configuration

Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines 77 to +85
// ConfigDefault is the default config
var ConfigDefault = Config{
Max: 5,
Max: defaultLimiterMax,
Expiration: 1 * time.Minute,
MaxFunc: func(_ fiber.Ctx) int {
return defaultLimiterMax
},

Choose a reason for hiding this comment

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

P1 Badge Retaining MaxFunc defaults ignores overrides

Setting ConfigDefault.MaxFunc to a concrete closure now means copies of ConfigDefault carry a non‑nil MaxFunc that always returns 5. A common pattern is cfg := limiter.ConfigDefault; cfg.Max = 100; app.Use(limiter.New(cfg)). After this change, configDefault will not replace the copied MaxFunc, so the middleware still enforces a limit of 5 despite cfg.Max being updated. Prior to this commit MaxFunc was nil, so the helper generated a closure reflecting the overridden Max. This regression silently discards user overrides of Max unless they also manually set MaxFunc.

Useful? React with 👍 / 👎.

Copy link
Member Author

Choose a reason for hiding this comment

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

If a user supplies a config, it's used in line 107: cfg := config[0]

@ReneWerner87 ReneWerner87 added this to v3 Nov 16, 2025
@ReneWerner87 ReneWerner87 added this to the v3 milestone Nov 16, 2025
@ReneWerner87 ReneWerner87 merged commit 5d91977 into main Nov 16, 2025
16 checks passed
@ReneWerner87 ReneWerner87 deleted the update-middleware-limiter-config-and-add-regression-test branch November 16, 2025 18:21
@github-project-automation github-project-automation bot moved this to Done in v3 Nov 16, 2025
@coldsmirk
Copy link

@gaby Are the changes incomplete?. In limiter_sliding.go, need to update the line remaining := cfg.Max - rate to remaining := maxRequests - rate, where maxRequests is retrieved from MaxFunc at the function's start.

@gaby
Copy link
Member Author

gaby commented Nov 17, 2025

@ilxqx I have another request coming, GitHub auto-closed the issue

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.

🐛 bug: Issues with limiter middleware

4 participants