Skip to content

Conversation

ReneWerner87
Copy link
Member

@ReneWerner87 ReneWerner87 commented Jul 30, 2025

Summary

  • collect DisableStartupMessage and EnablePrintRoutes when migrating config
  • remove those fields from fiber.Config and add them to Listen calls
  • test migrating listener settings across multiple files and when ListenConfig already in use

Testing

  • go test ./...
  • go run github.com/golangci/golangci-lint/cmd/[email protected] run ./... (fails: can't load config because go1.23 is lower than target 1.24)

https://chatgpt.com/codex/tasks/task_e_6888ca5c6558832686a65efdaf1d37de

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of configuration fields during migration, ensuring DisableStartupMessage and EnablePrintRoutes are correctly moved to the listener configuration.
  • Tests
    • Enhanced and expanded tests to cover additional migration scenarios, including cases with existing listener configurations.

Copy link

coderabbitai bot commented Jul 30, 2025

Walkthrough

The migration logic in MigrateConfigListenerFields was extended to handle two additional configuration fields, moving them from the app configuration to the listen call. Corresponding tests were refactored and expanded to verify these changes, including scenarios with and without existing fiber.ListenConfig usage.

Changes

Cohort / File(s) Change Summary
Migration Logic Update
cmd/internal/migrations/v3/common.go
Enhanced the migration to move DisableStartupMessage and EnablePrintRoutes from app config to the .Listen call, handling both cases with and without existing fiber.ListenConfig arguments, and added error handling.
Test Refactor and Expansion
cmd/internal/migrations/v3/common_test.go
Refactored existing tests to split app initialization and listen call into separate files; added a new test to cover migration when .Listen already uses a fiber.ListenConfig argument; verified correct migration and log output.

Sequence Diagram(s)

sequenceDiagram
    participant AppConfig as App Config
    participant Migration as Migration Logic
    participant ListenCall as .Listen Call

    AppConfig->>Migration: Contains DisableStartupMessage, EnablePrintRoutes
    Migration->>AppConfig: Removes DisableStartupMessage, EnablePrintRoutes
    Migration->>ListenCall: Adds fields to fiber.ListenConfig (creates or extends)
    ListenCall->>Migration: Confirm fields present
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Suggested labels

🧹 Updates

Poem

A bunny hopped through lines of code,
Moving configs down the migration road.
From app creation, fields now fly,
To Listen calls, they wave goodbye.
With tests in tow, the change is clear—
The code is neat, the path sincere!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/2025-07-30-06-41-09

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 generate unit tests to generate unit tests for 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 or @coderabbitai title 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.

Summary of Changes

Hello @ReneWerner87, 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 an update to the v3 migration script, specifically addressing the relocation of certain configuration fields related to application listening behavior. The primary goal is to ensure that DisableStartupMessage and EnablePrintRoutes are correctly migrated from the general fiber.Config to the more specific fiber.ListenConfig associated with app.Listen calls, maintaining application functionality during the upgrade process.

Highlights

  • Configuration Field Migration: Implemented a migration strategy to move DisableStartupMessage and EnablePrintRoutes fields from the main fiber.Config struct to the fiber.ListenConfig used in app.Listen calls. This ensures that these settings are applied directly to the listener.
  • Dynamic Listener Configuration: The migration now intelligently injects the collected DisableStartupMessage and EnablePrintRoutes values into app.Listen calls. If a fiber.ListenConfig is not already present, one is created; otherwise, the existing fiber.ListenConfig is extended with these fields.
  • Enhanced Migration Testing: Added comprehensive tests to validate the new migration logic, covering scenarios where configuration fields are spread across multiple files and when fiber.ListenConfig is already explicitly used in app.Listen calls.
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 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 or fill out our survey 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 configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

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 updates the v3 migration script to handle moving DisableStartupMessage and EnablePrintRoutes from fiber.Config to fiber.ListenConfig. The implementation correctly handles finding these settings and injecting them into app.Listen calls, including cases where ListenConfig is already present. The new tests cover these scenarios well.

My review focuses on improving the robustness of the regular expression-based code modifications by adding bounds checks to prevent panics and by making one of the regexes more specific to avoid incorrect matches.

Comment on lines +412 to +413
sub := reWithCfg.FindStringSubmatch(s)
addr := sub[1]
Copy link
Contributor

Choose a reason for hiding this comment

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

high

Accessing slice elements from FindStringSubmatch without checking the slice length can lead to a panic if the regex matches but fails to capture the expected groups. It's safer to check the length of sub before accessing its elements.

sub := reWithCfg.FindStringSubmatch(s)
if len(sub) < 3 {
	return s
}
addr := sub[1]

return s
}

addr := rePlain.FindStringSubmatch(s)[1]
Copy link
Contributor

Choose a reason for hiding this comment

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

high

It's important to check the length of the submatch slice before accessing elements to prevent a potential panic. This is especially true after removing the guard clause that was previously on lines 435-437.

sub := rePlain.FindStringSubmatch(s)
if len(sub) < 2 {
	return s
}
addr := sub[1]

return fmt.Sprintf(".Listen(%s, fiber.ListenConfig{%s})", addr, cfg)
})

rePlain := regexp.MustCompile(`\.Listen\(([^,\n)]+)\)`)
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This regular expression can be made more specific to only match .Listen calls with a single argument. By ensuring no other arguments follow the address (\s*\)), you can then remove the strings.Contains check on lines 435-437, which makes the migration logic more robust.

rePlain := regexp.MustCompile(`\.Listen\(([^,\n)]+)\s*\)`)

Comment on lines +435 to +437
if strings.Contains(s, "fiber.ListenConfig") {
return s
}
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

Following the suggested change to the regular expression on line 433, this check is no longer necessary and can be removed.

Copy link

@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: 0

🧹 Nitpick comments (1)
cmd/internal/migrations/v3/common.go (1)

405-454: Consider edge cases in regex patterns for Listen call matching.

The regex patterns for matching .Listen calls may not handle all edge cases properly:

  1. The pattern \.Listen\(([^,\n)]+)\) could match non-Fiber Listen methods
  2. Whitespace and comment handling could be improved
  3. Multi-line Listen calls might not be handled correctly

Consider making the regex patterns more robust:

-reWithCfg := regexp.MustCompile(`\.Listen\(([^,]+),\s*fiber.ListenConfig\{([^}]*)\}\)`)
+reWithCfg := regexp.MustCompile(`\.Listen\s*\(\s*([^,]+),\s*fiber\.ListenConfig\s*\{\s*([^}]*)\s*\}\s*\)`)

-rePlain := regexp.MustCompile(`\.Listen\(([^,\n)]+)\)`)
+rePlain := regexp.MustCompile(`\.Listen\s*\(\s*([^,\n)]+)\s*\)`)

Also consider adding validation to ensure we're only matching Fiber app Listen calls by checking for common patterns like app.Listen or similar variable names.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a5e7ef7 and e36b3c3.

📒 Files selected for processing (2)
  • cmd/internal/migrations/v3/common.go (1 hunks)
  • cmd/internal/migrations/v3/common_test.go (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ReneWerner87
PR: gofiber/fiber#3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the `Test` method in `app.go`.
Learnt from: ReneWerner87
PR: gofiber/contrib#0
File: :0-0
Timestamp: 2024-07-03T11:59:00.303Z
Learning: The i18n functionality in the gofiber/contrib repository is being refactored from middleware to a global container to improve robustness and performance. The global container will be initialized once before setting up routes and will manage the i18n bundle and localizer map.
Learnt from: ReneWerner87
PR: gofiber/contrib#0
File: :0-0
Timestamp: 2024-10-16T10:04:06.328Z
Learning: The i18n functionality in the gofiber/contrib repository is being refactored from middleware to a global container to improve robustness and performance. The global container will be initialized once before setting up routes and will manage the i18n bundle and localizer map.
cmd/internal/migrations/v3/common_test.go (11)

Learnt from: ReneWerner87
PR: gofiber/fiber#3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the Test method in app.go.

Learnt from: efectn
PR: gofiber/fiber#3162
File: hooks_test.go:228-228
Timestamp: 2024-12-13T08:14:22.851Z
Learning: In Go test files, prefer using the require methods from the testify package for assertions instead of manual comparisons and calls to t.Fatal or t.Fatalf.

Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/datasources/database/db_mock.go:13-19
Timestamp: 2024-11-23T19:50:06.387Z
Learning: In test code within clean-code/app/datasources/database/db_mock.go, adding safety checks like context validation, safe type assertions, and extra documentation is not necessary.

Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/server/server.go:14-16
Timestamp: 2024-11-23T19:50:41.765Z
Learning: In the clean-code example at clean-code/app/server/server.go using the Go Fiber framework, it's acceptable to omit production-level features like context usage and graceful shutdown handling to keep the example simple.

Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-02T23:03:31.727Z
Learning: Unit tests in this project use testify require.

Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests in this project use testify require.

Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/main.go:0-0
Timestamp: 2024-11-23T19:35:36.767Z
Learning: In the Go clean-code example (clean-code/app/main.go) in the gofiber/recipes repository, it's acceptable to omit graceful shutdown handling, as the example code prioritizes simplicity over production-level practices.

Learnt from: sixcolors
PR: gofiber/fiber#3051
File: middleware/session/session.go:215-216
Timestamp: 2024-06-30T00:38:06.580Z
Learning: Parallel tests for Session.Save already exist in the middleware/session/session_test.go file, specifically in the Test_Session_Save and Test_Session_Save_Expiration functions.

Learnt from: sixcolors
PR: gofiber/fiber#3051
File: middleware/session/session.go:215-216
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Parallel tests for Session.Save already exist in the middleware/session/session_test.go file, specifically in the Test_Session_Save and Test_Session_Save_Expiration functions.

Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The project uses the testify/assert package for assertions in unit tests.

Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.

🧬 Code Graph Analysis (1)
cmd/internal/migrations/v3/common.go (1)
cmd/internal/helpers.go (1)
  • ChangeFileContent (36-68)
🔇 Additional comments (5)
cmd/internal/migrations/v3/common.go (3)

416-430: LGTM! Comma handling logic is well implemented.

The logic for handling comma placement in both existing and new ListenConfig structs is correct:

  • Checks for existing fields to avoid duplicates
  • Properly handles comma placement
  • Removes trailing commas appropriately

Minor suggestion: Consider extracting the comma handling logic into a helper function to reduce duplication:

func appendConfigField(cfg, fieldName, fieldValue string) string {
    if len(cfg) > 0 && !strings.HasSuffix(cfg, ",") {
        cfg += ","
    }
    return cfg + " " + fieldName + ": " + fieldValue + ","
}

Also applies to: 441-448


401-403: LGTM! Error handling is well implemented.

The error handling approach is solid:

  • Both transformation steps have appropriate error handling
  • Error messages provide clear context about which step failed
  • Success message is printed only after both transformations complete successfully

Also applies to: 455-461


367-400: Address potential race condition with package-level variables.

The use of package-level variables disableStartup and enablePrint to pass state between the two ChangeFileContent calls creates a race condition risk if multiple migrations run concurrently.

Consider refactoring to avoid shared state:

func MigrateConfigListenerFields(cmd *cobra.Command, cwd string, _, _ *semver.Version) error {
-	var disableStartup string
-	var enablePrint string
+	type extractedFields struct {
+		disableStartup string
+		enablePrint    string
+	}
+	
+	var extracted extractedFields

	err := internal.ChangeFileContent(cwd, func(content string) string {
		replacer := strings.NewReplacer(
			"Prefork:", "EnablePrefork:",
			"Network:", "ListenerNetwork:",
		)
		content = replacer.Replace(content)

		reStartup := regexp.MustCompile(`(?m)^\s*DisableStartupMessage:\s*([^,]+),?\n`)
		content = reStartup.ReplaceAllStringFunc(content, func(s string) string {
-			if disableStartup == "" {
+			if extracted.disableStartup == "" {
				sub := reStartup.FindStringSubmatch(s)
				if len(sub) > 1 {
-					disableStartup = strings.TrimSpace(sub[1])
+					extracted.disableStartup = strings.TrimSpace(sub[1])
				}
			}
			return ""
		})

		rePrint := regexp.MustCompile(`(?m)^\s*EnablePrintRoutes:\s*([^,]+),?\n`)
		content = rePrint.ReplaceAllStringFunc(content, func(s string) string {
-			if enablePrint == "" {
+			if extracted.enablePrint == "" {
				sub := rePrint.FindStringSubmatch(s)
				if len(sub) > 1 {
-					enablePrint = strings.TrimSpace(sub[1])
+					extracted.enablePrint = strings.TrimSpace(sub[1])
				}
			}
			return ""
		})

		return content
	})

Then update the second transformation to use extracted.disableStartup and extracted.enablePrint.

⛔ Skipped due to learnings
Learnt from: sixcolors
PR: gofiber/fiber#3625
File: middleware/session/config.go:57-58
Timestamp: 2025-07-27T17:28:53.403Z
Learning: In the session middleware `Config` struct, the `Extractor` field uses function closures (like `FromCookie(key)`), making it impossible to introspect extractor parameters at runtime for validation purposes without complex reflection techniques.
cmd/internal/migrations/v3/common_test.go (2)

475-515: Excellent test refactoring! The separation of concerns improves realism.

The refactoring to split the test into separate app.go and main.go files is a great improvement:

  • Better simulates real-world project structure where app configuration and Listen calls are often in different files
  • Comprehensive assertions verify both the removal of fields from app config and their addition to the Listen call
  • Proper use of testify assertions as per project standards

The test thoroughly validates the migration behavior and covers the primary use case effectively.


517-555: Excellent addition! This test covers a critical edge case.

The new test function provides essential coverage for the scenario where app.Listen already uses a fiber.ListenConfig parameter:

  • Tests the merging behavior to ensure existing fields (EnablePrefork) are preserved
  • Verifies that extracted fields (DisableStartupMessage, EnablePrintRoutes) are properly added
  • Maintains consistent test structure and proper assertions
  • Uses realistic file separation like the main test

This test case is crucial for ensuring the migration doesn't break existing ListenConfig usage and properly merges the configuration fields.

@ReneWerner87 ReneWerner87 merged commit c1f78dc into master Jul 30, 2025
13 checks passed
@ReneWerner87 ReneWerner87 deleted the codex/2025-07-30-06-41-09 branch July 30, 2025 06:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant