Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@ReneWerner87
Copy link
Member

@ReneWerner87 ReneWerner87 commented Aug 4, 2025

Summary

  • migrate healthcheck middleware config and usage to Fiber v3 handler-based probes
  • add tests for healthcheck migration

Testing

  • go test ./...

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

Summary by CodeRabbit

  • New Features
    • Improved migration of healthcheck middleware configuration to support the latest API, automatically updating route registrations and configuration fields.
  • Bug Fixes
    • Ensured correct handling and adaptation of liveness and readiness probes and endpoints during migration.
  • Tests
    • Added and expanded tests to verify correct migration behavior for various healthcheck configuration scenarios, including default, liveness-only, readiness-only, and standalone configurations.

@coderabbitai
Copy link

coderabbitai bot commented Aug 4, 2025

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.

Caution

Review failed

The pull request is closed.

Walkthrough

This update rewrites the migration logic for Fiber healthcheck middleware, converting old middleware usage patterns into explicit route registrations compatible with Fiber v3. The migration now parses and adapts configuration structures, separates liveness and readiness probes, and updates all relevant configuration fields. Corresponding tests are expanded to cover diverse migration scenarios.

Changes

Cohort / File(s) Change Summary
Healthcheck Migration Logic
cmd/internal/migrations/v3/common.go
Overhauled the MigrateHealthcheckConfig function to transform old middleware usage (app.Use(healthcheck.New(...))) into explicit app.Get(...) route registrations, parsing and adapting config structures, and updating/removing old config fields. Added helper functions skipCommaSuffix and removeConfigField to assist with config string manipulation and parsing complex nested structures.
Healthcheck Migration Tests
cmd/internal/migrations/v3/common_test.go
Expanded and added tests for the migration function, covering default, liveness-only, readiness-only, and standalone config scenarios. Tests verify correct transformation of middleware usage, config adaptation, field removal, and logging of migration actions.

Sequence Diagram(s)

sequenceDiagram
    participant Dev as Developer Codebase
    participant Migrator as MigrateHealthcheckConfig
    participant Parser as Config Parser

    Dev->>Migrator: Call migration on Fiber v2 healthcheck usage
    Migrator->>Parser: Parse for app.Use(healthcheck.New(...))
    Parser-->>Migrator: Extract config, endpoints, probes
    Migrator->>Dev: Replace with app.Get(livenessEndpoint, ...)\napp.Get(readinessEndpoint, ...)
    Migrator->>Dev: Update config fields (rename/remove as needed)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • feat: migrate healthcheck middlewareΒ #154: Introduces the same helper function removeConfigField and rewrites MigrateHealthcheckConfig to migrate Fiber healthcheck middleware usage from v2 to v3, including extensive test coverage updates; changes overlap significantly at the code level.

Poem

A bunny hopped through code so bright,
Transforming healthchecks left and right.
From middleware old to routes anew,
Liveness and readiness shining through.
With clever tests and configs trimmed,
This migration’s magic is now well-primed!
πŸ‡βœ¨

Note

⚑️ Unit Test Generation is now available in beta!

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


πŸ“œ 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 b061c64 and 55750a9.

πŸ“’ Files selected for processing (1)
  • cmd/internal/migrations/v3/common.go (2 hunks)
✨ 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-08-04-14-41-15

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.
  • 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.

Support

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

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!

I've implemented a migration for the healthcheck middleware to align with the new handler-based API in Fiber v3. This change updates how healthcheck probes are registered, moving from a single app.Use middleware to explicit app.Get calls for liveness and readiness endpoints, and adapts the associated configuration.

Highlights

  • Healthcheck Middleware Migration: The primary change involves migrating the healthcheck middleware usage from app.Use(healthcheck.New(...)) to separate app.Get registrations for liveness and readiness endpoints, reflecting Fiber v3's handler-based approach.
  • Configuration Adaptation: The migration logic now intelligently parses and adapts the healthcheck.Config structure. It renames LivenessProbe to Probe and extracts LivenessEndpoint and ReadinessEndpoint values for use in the app.Get calls, ensuring compatibility with the new API.
  • Comprehensive Test Coverage: I've added new test cases to validate the migration logic across various scenarios, including default healthcheck configurations and cases where only liveness or readiness probes are explicitly defined, ensuring robustness.
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 migrates the healthcheck middleware to the new Fiber v3 handler-based API. The changes primarily involve a complex migration script in cmd/internal/migrations/v3/common.go that uses regular expressions to transform the old app.Use(healthcheck.New(...)) calls into new app.Get(...) registrations for liveness and readiness probes. While the approach is clever, I've identified several critical issues with the regular expressions used, which are not robust enough to handle common Go code formatting like multi-line functions. This could cause the migration to fail for many users. I've provided specific feedback on these regexes. Additionally, I've suggested enhancing the new test cases to cover these edge scenarios to ensure the migration script is more reliable.

Comment on lines 610 to 613
reRP := regexp.MustCompile(`(?m)\s*ReadinessProbe:\s*[^,\n}]+,?`)
bodyL = reRP.ReplaceAllString(bodyL, "")
reLP := regexp.MustCompile(`LivenessProbe:\s*([^,\n}]+)`) // rename to Probe
bodyL = reLP.ReplaceAllString(bodyL, "Probe: $1")
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

The regular expressions used to parse LivenessProbe and ReadinessProbe do not handle multi-line function literals. The character class [^,\n}]+ disallows newlines, which will cause the migration to fail for commonly formatted Go code, such as:

LivenessProbe: func(c fiber.Ctx) bool {
    return true
},

This is a critical issue as it will prevent the migration script from running successfully on many projects. This issue affects all regular expressions that parse probes in this function (e.g., lines 610, 612, 620, 622, 646).

Reliably parsing Go code with regex is difficult. A more robust solution might involve using the Go AST parser. Given the context of a migration script, a "best-effort" but more resilient regex would be an improvement.


// Adapt remaining config structures outside of app.Use replacements
content = strings.ReplaceAll(content, "LivenessProbe:", "Probe:")
re := regexp.MustCompile(`\s*ReadinessProbe:\s*[^,]+,?\n?`)
Copy link
Contributor

Choose a reason for hiding this comment

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

high

This regular expression for ReadinessProbe is not robust. It uses [^,]+, which will fail to match the full probe value if it contains a comma (e.g., a function call with multiple arguments). It's also unable to handle multi-line function literals. This can cause the migration to fail for some healthcheck.Config declarations outside of app.Use calls.

bodyL := body
reRP := regexp.MustCompile(`(?m)\s*ReadinessProbe:\s*[^,\n}]+,?`)
bodyL = reRP.ReplaceAllString(bodyL, "")
reLP := regexp.MustCompile(`LivenessProbe:\s*([^,\n}]+)`) // rename to Probe
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 is missing the (?m) multi-line flag and \s* prefix to handle leading whitespace. This is inconsistent with other regexes in this function (like on line 610) and may cause it to fail to match indented LivenessProbe fields. A similar issue exists for reRP2 on line 622.

Suggested change
reLP := regexp.MustCompile(`LivenessProbe:\s*([^,\n}]+)`) // rename to Probe
reLP := regexp.MustCompile(`(?m)\s*LivenessProbe:\s*([^,\n}]+)`) // rename to Probe

Comment on lines 739 to 752
file := writeTempFile(t, dir, `package main
import "github.com/gofiber/fiber/v2/middleware/healthcheck"
var _ = healthcheck.New(healthcheck.Config{
LivenessProbe: func(c fiber.Ctx) bool { return true },
LivenessEndpoint: "/live",
ReadinessProbe: func(c fiber.Ctx) bool { return true },
ReadinessEndpoint: "/ready",
})`)
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/healthcheck"
)
func main() {
app := fiber.New()
app.Use(healthcheck.New(healthcheck.Config{
LivenessProbe: func(c fiber.Ctx) bool { return true },
LivenessEndpoint: "/live",
ReadinessProbe: func(c fiber.Ctx) bool { return true },
ReadinessEndpoint: "/ready",
}))
}`)
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The test cases for the healthcheck migration are a good start, but they don't cover some important edge cases that could cause the migration to fail. It would be beneficial to add test cases for:

  • Probes defined as multi-line functions.
  • healthcheck.Config structs with varied indentation.

This would help validate the robustness of the migration script against common code formatting styles and catch issues like the ones I've pointed out in common.go.

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)

566-660: Review the complex migration logic for maintainability and robustness.

The MigrateHealthcheckConfig function implements comprehensive migration logic but has several areas that could benefit from improvement:

  1. Complex regex patterns: The nested regex operations (lines 576-642) are quite complex and could be brittle to changes in code formatting.

  2. Redundant string operations: The makeCall helper function (lines 629-637) performs redundant trimming operations that could be simplified.

  3. Deep nesting: The configuration parsing logic has significant nesting depth, making it harder to follow and test.

Consider extracting helper functions to improve readability:

+// extractEndpoints extracts custom liveness and readiness endpoints from config body
+func extractEndpoints(body string) (liveness, readiness string) {
+	liveness = "healthcheck.LivenessEndpoint"
+	readiness = "healthcheck.ReadinessEndpoint"
+	
+	if m := regexp.MustCompile(`(?m)\s*LivenessEndpoint:\s*([^,\n}]+),?`).FindStringSubmatch(body); len(m) > 1 {
+		liveness = strings.TrimSpace(m[1])
+	}
+	if m := regexp.MustCompile(`(?m)\s*ReadinessEndpoint:\s*([^,\n}]+),?`).FindStringSubmatch(body); len(m) > 1 {
+		readiness = strings.TrimSpace(m[1])
+	}
+	return
+}
+
+// buildProbeConfig creates separate liveness/readiness configs
+func buildProbeConfig(body, probeType string) string {
+	// Implementation for config separation logic
+}

This would make the main function more readable and easier to test individual components.

πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 944e763 and d1c03a3.

πŸ“’ 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 (7)
πŸ““ 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/recipes#0
File: :0-0
Timestamp: 2024-11-26T20:05:15.793Z
Learning: For future contributions to the `gofiber/recipes` repository, ensure that the tasks outlined in `.github/CONTRIBUTING.md` are incorporated, including creating a new directory without a "fiber" prefix, adding a `README.md` with Docusaurus metadata, and updating the overview by running `make generate`.
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.
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: gaby
PR: gofiber/fiber#3193
File: middleware/adaptor/adaptor.go:111-111
Timestamp: 2024-11-10T23:44:13.704Z
Learning: In the `middleware/adaptor/adaptor.go` file of the Fiber framework, when updating context handling, replacing `c.Context()` with `c.RequestCtx()` is appropriate to access the `fasthttp.RequestCtx`.
πŸ“š Learning: in the fiber framework, breaking changes are acceptable when moving from version 2 to version 3, inc...
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`.

Applied to files:

  • cmd/internal/migrations/v3/common.go
  • cmd/internal/migrations/v3/common_test.go
πŸ“š Learning: in the `middleware/adaptor/adaptor.go` file of the fiber framework, when updating context handling, ...
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/adaptor/adaptor.go:111-111
Timestamp: 2024-11-10T23:44:13.704Z
Learning: In the `middleware/adaptor/adaptor.go` file of the Fiber framework, when updating context handling, replacing `c.Context()` with `c.RequestCtx()` is appropriate to access the `fasthttp.RequestCtx`.

Applied to files:

  • cmd/internal/migrations/v3/common.go
πŸ“š Learning: parallel tests for `session.save` already exist in the `middleware/session/session_test.go` file, sp...
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.

Applied to files:

  • cmd/internal/migrations/v3/common_test.go
πŸ“š Learning: in go test files, prefer using the `require` methods from the `testify` package for assertions inste...
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`.

Applied to files:

  • cmd/internal/migrations/v3/common_test.go
πŸ“š 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.

Applied to files:

  • cmd/internal/migrations/v3/common_test.go
πŸ“š 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.

Applied to files:

  • cmd/internal/migrations/v3/common_test.go
🧬 Code Graph Analysis (1)
cmd/internal/migrations/v3/common.go (1)
cmd/internal/helpers.go (1)
  • ChangeFileContent (36-68)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Build (1.24.x, macos-13)
  • GitHub Check: Build (1.24.x, windows-latest)
πŸ”‡ Additional comments (4)
cmd/internal/migrations/v3/common_test.go (4)

732-768: LGTM - Comprehensive test coverage for full configuration scenario.

The original test effectively validates the migration of healthcheck middleware with both liveness and readiness probes configured. The assertions properly verify:

  • Conversion from app.Use() to explicit app.Get() calls
  • Correct endpoint handling
  • Removal of deprecated config fields
  • Proper probe function transformation

770-796: LGTM - Essential test for default configuration handling.

This test covers a critical edge case where users employ the simplest healthcheck setup without explicit configuration. The test properly validates:

  • Usage of default constants for endpoints
  • Proper transformation from middleware to route handlers
  • Generation of both liveness and readiness routes even with minimal input

798-829: LGTM - Important test for partial configuration scenarios.

This test validates the migration behavior when users configure only the liveness probe, ensuring:

  • Custom liveness configuration is preserved
  • Readiness defaults are properly applied
  • Both route registrations are generated
  • Deprecated fields are correctly removed

This covers an important real-world usage pattern where users might only need liveness checks.


831-862: LGTM - Completes comprehensive test coverage for all configuration scenarios.

This test validates the symmetric case where only readiness is configured, ensuring:

  • Custom readiness configuration is preserved
  • Liveness defaults are properly applied
  • Both route registrations are generated
  • Deprecated fields are correctly removed

Together with the other new tests, this provides complete coverage of all healthcheck migration scenarios: default, liveness-only, readiness-only, and full configuration.

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

♻️ Duplicate comments (2)
cmd/internal/migrations/v3/common.go (1)

629-714: Consider improving regex robustness for complex Go code patterns.

The migration logic is comprehensive but may fail on certain Go code patterns, particularly multi-line function literals. The current regex patterns have limitations when handling:

  1. Multi-line function literals: The regex patterns don't account for newlines within function bodies
  2. Complex nested structures: Deeply nested configurations may not parse correctly
  3. Comments within configurations: Inline comments could break the parsing

Consider using Go's AST parser for more robust code analysis:

import (
    "go/ast"
    "go/parser"
    "go/token"
)

func parseHealthcheckConfig(src string) (*ast.File, error) {
    fset := token.NewFileSet()
    return parser.ParseFile(fset, "", src, parser.ParseComments)
}

Alternatively, improve the regex patterns to handle multi-line scenarios:

-		reUse := regexp.MustCompile(`(?m)^(\s*)(\w+)\.Use\(\s*healthcheck\.New\((?s:(.*))\)\s*\)`)
+		reUse := regexp.MustCompile(`(?ms)^(\s*)(\w+)\.Use\(\s*healthcheck\.New\((.*?)\)\s*\)`)

The (?ms) flags enable multi-line mode and make . match newlines, which should better handle function literals that span multiple lines.

Generate a verification script to test the migration with multi-line function literals:

#!/bin/bash
# Test migration with multi-line function literals

echo 'Testing healthcheck migration with complex patterns...'

# Create test files with various patterns
cat > test_multiline.go << 'EOF'
package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/healthcheck"
)

func main() {
    app := fiber.New()
    app.Use(healthcheck.New(healthcheck.Config{
        LivenessProbe: func(c fiber.Ctx) bool {
            // Complex multi-line function
            if c.Method() == "GET" {
                return true
            }
            return false
        },
        ReadinessProbe: func(c fiber.Ctx) bool {
            return checkDB() &&
                   checkCache()
        },
    }))
}
EOF

# Test the current implementation
echo "Original file:"
cat test_multiline.go
cmd/internal/migrations/v3/common_test.go (1)

864-900: Good coverage for standalone configuration objects.

This test validates migration of healthcheck.Config variables outside of middleware registration, which is important for comprehensive migration coverage. The test includes multi-line function literals, though it primarily validates field cleanup rather than complex parsing scenarios.

The test cases don't fully address the multi-line function literal parsing robustness mentioned in past reviews. Consider adding specific assertions to verify that complex function bodies are preserved correctly during migration.

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

22-83: Address control flow complexity and consider refactoring.

The function has high cyclomatic complexity with nested control flow exceeding 5 levels (flagged by static analysis). While the parsing logic is comprehensive, consider refactoring to improve maintainability:

+// parseFieldValue extracts the value of a field from a struct literal
+func parseFieldValue(src string, start int) (end int) {
+	depth := 0
+	inString := false
+	for i := start; i < len(src); i++ {
+		ch := src[i]
+		if inString {
+			if ch == '\\' && i+1 < len(src) {
+				i++
+				continue
+			}
+			if ch == '"' {
+				inString = false
+			}
+		} else {
+			switch ch {
+			case '"':
+				inString = true
+			case '(', '{', '[':
+				depth++
+			case ')', '}', ']':
+				if depth > 0 {
+					depth--
+				}
+			case ',', '\n':
+				if depth == 0 {
+					return i
+				}
+			}
+		}
+	}
+	return len(src)
+}
+
 func removeConfigField(src, field string) string {
 	re := regexp.MustCompile(`(?m)^\s*` + field + `:\s*`)
 	for {
 		loc := re.FindStringIndex(src)
 		if loc == nil {
 			break
 		}
 		start := loc[0]
-		i := loc[1]
-		depth := 0
-		inString := false
-		for i < len(src) {
-			ch := src[i]
-			if inString {
-				if ch == '\\' && i+1 < len(src) {
-					i += 2
-					continue
-				}
-				if ch == '"' {
-					inString = false
-				}
-			} else {
-				switch ch {
-				case '"':
-					inString = true
-				case '(', '{', '[':
-					depth++
-				case ')', '}', ']':
-					if depth > 0 {
-						depth--
-					}
-				case ',':
-					if depth == 0 {
-						i++
-						for i < len(src) && (src[i] == ' ' || src[i] == '\t') {
-							i++
-						}
-						if i < len(src) && src[i] == '\n' {
-							i++
-						}
-						src = src[:start] + src[i:]
-						goto nextField
-					}
-				case '\n':
-					if depth == 0 {
-						i++
-						src = src[:start] + src[i:]
-						goto nextField
-					}
-				}
-			}
-			i++
-		}
-		src = src[:start]
-	nextField:
+		end := parseFieldValue(src, loc[1])
+		// Skip trailing whitespace and newlines
+		for end < len(src) && (src[end] == ' ' || src[end] == '\t') {
+			end++
+		}
+		if end < len(src) && src[end] == '\n' {
+			end++
+		}
+		src = src[:start] + src[end:]
 	}
 	return src
 }

This refactoring extracts the parsing logic into a separate function, eliminates goto statements, and reduces nesting complexity.

cmd/internal/migrations/v3/common_test.go (1)

732-768: Comprehensive test coverage for the main migration scenario.

The test properly validates the core healthcheck migration functionality, including middleware-to-route transformation and field cleanup. The assertions correctly verify both the positive changes (new app.Get() calls, Probe fields) and negative checks (removal of old patterns).

Consider adding test cases for edge cases mentioned in past reviews:

func Test_MigrateHealthcheckConfig_MultilineFunction(t *testing.T) {
    // Test with multi-line function literals
    file := writeTempFile(t, dir, `package main
import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/healthcheck"
)
func main() {
    app := fiber.New()
    app.Use(healthcheck.New(healthcheck.Config{
        LivenessProbe: func(c fiber.Ctx) bool {
            if c.Method() == "GET" {
                return true
            }
            return false
        },
    }))
}`)
    // ... test implementation
}
πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between d1c03a3 and b061c64.

πŸ“’ Files selected for processing (2)
  • cmd/internal/migrations/v3/common.go (2 hunks)
  • cmd/internal/migrations/v3/common_test.go (1 hunks)
🧰 Additional context used
🧠 Learnings (14)
πŸ““ 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/recipes#0
File: :0-0
Timestamp: 2024-11-26T20:05:15.793Z
Learning: For future contributions to the `gofiber/recipes` repository, ensure that the tasks outlined in `.github/CONTRIBUTING.md` are incorporated, including creating a new directory without a "fiber" prefix, adding a `README.md` with Docusaurus metadata, and updating the overview by running `make generate`.
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.
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: gaby
PR: gofiber/fiber#3193
File: middleware/adaptor/adaptor.go:111-111
Timestamp: 2024-11-10T23:44:13.704Z
Learning: In the `middleware/adaptor/adaptor.go` file of the Fiber framework, when updating context handling, replacing `c.Context()` with `c.RequestCtx()` is appropriate to access the `fasthttp.RequestCtx`.
πŸ“š Learning: in the fiber framework, breaking changes are acceptable when moving from version 2 to version 3, inc...
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`.

Applied to files:

  • cmd/internal/migrations/v3/common.go
  • cmd/internal/migrations/v3/common_test.go
πŸ“š Learning: in the go unit tests in `ctx_test.go`, it is acceptable to use invalid cidr notation such as `"0.0.0...
Learnt from: gaby
PR: gofiber/fiber#3170
File: ctx_test.go:1721-1724
Timestamp: 2024-10-16T12:12:30.506Z
Learning: In the Go unit tests in `ctx_test.go`, it is acceptable to use invalid CIDR notation such as `"0.0.0.1/31junk"` for testing purposes.

Applied to files:

  • cmd/internal/migrations/v3/common.go
πŸ“š Learning: in the `clean-code/app/server/server.go` file, the team prefers to maintain a simple health check en...
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/server/server.go:18-20
Timestamp: 2024-11-23T19:51:05.812Z
Learning: In the `clean-code/app/server/server.go` file, the team prefers to maintain a simple health check endpoint without additional system status information.

Applied to files:

  • cmd/internal/migrations/v3/common.go
  • cmd/internal/migrations/v3/common_test.go
πŸ“š Learning: in 'clean-code/app/server/handlers/books.go', validation is out of scope and should not be suggested...
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/server/handlers/books.go:28-43
Timestamp: 2024-11-23T19:54:01.389Z
Learning: In 'clean-code/app/server/handlers/books.go', validation is out of scope and should not be suggested.

Applied to files:

  • cmd/internal/migrations/v3/common.go
πŸ“š Learning: in the session middleware `config` struct, the `extractor` field uses function closures (like `fromc...
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.

Applied to files:

  • cmd/internal/migrations/v3/common.go
πŸ“š Learning: in go test files, prefer using the `require` methods from the `testify` package for assertions inste...
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`.

Applied to files:

  • cmd/internal/migrations/v3/common_test.go
πŸ“š Learning: in test code within `clean-code/app/datasources/database/db_mock.go`, adding safety checks like cont...
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.

Applied to files:

  • cmd/internal/migrations/v3/common_test.go
πŸ“š Learning: in the `clean-code/app/datasources/database/memory_db.go`, the in-memory database implementation is ...
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/datasources/database/memory_db_test.go:0-0
Timestamp: 2024-11-25T19:36:45.661Z
Learning: In the `clean-code/app/datasources/database/memory_db.go`, the in-memory database implementation is not intended for production use. Therefore, adding extensive tests for concurrency and error handling in `memory_db_test.go` is unnecessary.

Applied to files:

  • cmd/internal/migrations/v3/common_test.go
πŸ“š Learning: in the gofiber `tableflip` recipe (`tableflip/main.go`), the implementation matches the upstream ref...
Learnt from: juls0730
PR: gofiber/recipes#2710
File: tableflip/main.go:61-62
Timestamp: 2024-12-01T01:15:48.126Z
Learning: In the GoFiber `tableflip` recipe (`tableflip/main.go`), the implementation matches the upstream reference implementation. Future code suggestions should consider maintaining this alignment to ensure consistency.

Applied to files:

  • cmd/internal/migrations/v3/common_test.go
πŸ“š 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-10-08T19:06:06.583Z
Learning: The project uses the testify/assert package for assertions in unit tests.

Applied to files:

  • cmd/internal/migrations/v3/common_test.go
πŸ“š 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-02T23:03:31.727Z
Learning: Unit tests in this project use testify require.

Applied to files:

  • cmd/internal/migrations/v3/common_test.go
πŸ“š Learning: in this codebase, `newconfiguration()` reads environment variables with defaults and cannot fail, so...
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/main.go:0-0
Timestamp: 2024-11-23T19:34:59.534Z
Learning: In this codebase, `NewConfiguration()` reads environment variables with defaults and cannot fail, so error handling for it is unnecessary.

Applied to files:

  • cmd/internal/migrations/v3/common_test.go
πŸ“š Learning: parallel tests for `session.save` already exist in the `middleware/session/session_test.go` file, sp...
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.

Applied to files:

  • cmd/internal/migrations/v3/common_test.go
🧬 Code Graph Analysis (1)
cmd/internal/migrations/v3/common.go (1)
cmd/internal/helpers.go (1)
  • ChangeFileContent (36-68)
πŸͺ› GitHub Check: lint
cmd/internal/migrations/v3/common.go

[failure] 63-63:
max-control-nesting: control flow nesting exceeds 5 (revive)


[failure] 60-60:
max-control-nesting: control flow nesting exceeds 5 (revive)

πŸͺ› GitHub Actions: golangci-lint
cmd/internal/migrations/v3/common.go

[error] 60-60: golangci-lint (revive): control flow nesting exceeds 5 (max-control-nesting)

πŸ”‡ Additional comments (3)
cmd/internal/migrations/v3/common_test.go (3)

770-796: Good coverage for default configuration scenario.

This test properly validates the migration behavior when no configuration is provided, ensuring that default endpoints are used correctly in the generated route registrations.


798-829: Excellent coverage for partial configuration scenarios.

This test validates the important case where only one probe type is configured, ensuring the migration correctly handles mixed default and custom endpoint configurations.


831-862: Comprehensive coverage for readiness-only configuration.

This test complements the liveness-only test, ensuring all partial configuration scenarios are properly handled by the migration.

@ReneWerner87 ReneWerner87 merged commit 5a01676 into master Aug 5, 2025
12 of 13 checks passed
@ReneWerner87 ReneWerner87 deleted the codex/2025-08-04-14-41-15 branch August 5, 2025 06:49
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.

2 participants