-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
🧹 chore: Handle nil map targets in Binder #3839
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
🧹 chore: Handle nil map targets in Binder #3839
Conversation
Summary of ChangesHello @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 binder by improving how it handles nil map targets. Previously, attempting to bind data to an uninitialized map might have led to silent failures or panics. The updated logic now ensures that such maps are either properly initialized on the fly or an explicit error is returned, making the binding process more reliable and easier to debug. Highlights
Using Gemini Code AssistThe 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
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 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
|
|
Note Other AI code review bot(s) detectedCodeRabbit 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. WalkthroughRefactors parseToMap to accept a reflect.Value target, adds validation and lazy map initialization, introduces exported ErrMapNilDestination for nil map destinations, and updates tests to call parseToMap with reflect.Value and cover the new error/path behaviors. Changes
Sequence Diagram(s)sequenceDiagram
participant Caller as parseIntoMap / tests
participant Reflect as reflect.Value target
participant parseToMap as parseToMap(target, data)
rect rgba(200,230,255,0.6)
Caller->>Reflect: reflect.ValueOf(dest)
Caller->>parseToMap: call with reflect.Value and data
end
alt target invalid / not a map or unexported
parseToMap-->>Caller: return ErrMapNotConvertible
else target is map and nil
parseToMap->>parseToMap: try initialize map
alt target not settable
parseToMap-->>Caller: return ErrMapNilDestination
else initialized
parseToMap->>parseToMap: populate entries (string or []string)
parseToMap-->>Caller: return nil
end
else target is map and non-nil
parseToMap->>parseToMap: populate entries
parseToMap-->>Caller: return nil
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🧰 Additional context used📓 Path-based instructions (1)**/*.go📄 CodeRabbit inference engine (AGENTS.md)
Files:
🧠 Learnings (1)📚 Learning: 2025-10-16T07:19:52.418ZApplied to files:
🧬 Code graph analysis (1)binder/mapping.go (1)
⏰ 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). (6)
🔇 Additional comments (5)
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. Comment |
There was a problem hiding this 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 enhances the binder's map binding logic to correctly handle nil map destinations. The changes introduce logic to initialize nil maps if they are settable, or return a descriptive error otherwise. The test suite has been extended to cover these new scenarios, ensuring the binder behaves safely and predictably with zero-value maps. The implementation is solid and the test coverage is thorough. I have one minor suggestion to improve an error message for better clarity.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #3839 +/- ##
==========================================
+ Coverage 92.16% 92.18% +0.01%
==========================================
Files 115 115
Lines 9744 9753 +9
==========================================
+ Hits 8981 8991 +10
+ Misses 488 484 -4
- Partials 275 278 +3
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this 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 refactors the parseToMap function to accept reflect.Value instead of any, enabling proper handling of nil map destinations. The change allows the function to initialize nil maps when they can be set, improving the robustness of map binding operations.
Key changes:
- Modified
parseToMapsignature to acceptreflect.Valueinstead ofanyfor better reflection control - Added nil map handling logic that initializes maps when possible or returns an error when not
- Introduced new error
ErrMapNilDestinationfor cases where nil maps cannot be initialized - Updated all test calls to wrap arguments with
reflect.ValueOf()
Reviewed Changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| binder/mapping.go | Refactored parseToMap to accept reflect.Value, added nil map initialization logic, and updated caller to pass reflect.Value |
| binder/binder.go | Added new error ErrMapNilDestination for nil map handling |
| binder/mapping_test.go | Updated test calls to use reflect.ValueOf() and added tests for nil map scenarios |
| binder/binder_test.go | Updated test calls to use reflect.ValueOf() and added tests for zero-value map initialization |
|
Fixing issues now |
There was a problem hiding this 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
📒 Files selected for processing (4)
binder/binder.go(1 hunks)binder/binder_test.go(2 hunks)binder/mapping.go(2 hunks)binder/mapping_test.go(4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go
📄 CodeRabbit inference engine (AGENTS.md)
**/*.go: Apply formatting using gofumpt (Make target: format)
Optimize struct field alignment using betteralign (Make target: betteralign)
Modernize code using gopls modernize (Make target: modernize)
Files:
binder/binder.gobinder/mapping.gobinder/mapping_test.gobinder/binder_test.go
🧬 Code graph analysis (2)
binder/mapping.go (1)
binder/binder.go (2)
ErrMapNilDestination(12-12)ErrMapNotConvertible(11-11)
binder/mapping_test.go (1)
binder/binder.go (2)
ErrMapNotConvertible(11-11)ErrMapNilDestination(12-12)
🪛 GitHub Actions: golangci-lint
binder/mapping.go
[error] 111-111: unnecessary-format: unnecessary use of formatting function "fmt.Errorf", you can replace it with "errors.New" (revive)
🪛 GitHub Check: lint
binder/mapping.go
[failure] 111-111:
unnecessary-format: unnecessary use of formatting function "fmt.Errorf", you can replace it with "errors.New" (revive)
⏰ 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: Compare
- GitHub Check: repeated
There was a problem hiding this 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 (3)
binder/mapping_test.go (2)
160-168: Consider adding a comment to clarify the addressability pattern.These tests correctly verify lazy initialization of nil maps. The pattern
reflect.ValueOf(&zeroStringMap).Elem()creates an addressablereflect.Value, allowingCanSet()to return true and enabling map initialization. This contrasts with line 170's non-addressable nil map.Consider adding a brief comment to make this distinction explicit:
+ // Test zero-value map with addressable reflect.Value (can be initialized) var zeroStringMap map[string]string err = parseToMap(reflect.ValueOf(&zeroStringMap).Elem(), inputMap)
170-171: Consider adding a comment to clarify non-addressable nil map case.This test correctly verifies that a non-addressable nil map (created via
reflect.ValueOf(map[string]string(nil))) returnsErrMapNilDestinationbecauseCanSet()is false.Consider adding a comment to highlight this edge case:
+ // Test non-addressable nil map (cannot be initialized) err = parseToMap(reflect.ValueOf(map[string]string(nil)), inputMap) require.ErrorIs(t, err, ErrMapNilDestination)binder/mapping.go (1)
114-116: Consider adding a comment to clarify interface unwrapping.This unwrapping logic is correct and handles cases where the destination is wrapped in an
interface{}.A brief comment would clarify the intent:
+ // Unwrap interfaces to get the underlying value if target.Kind() == reflect.Interface && !target.IsNil() { target = target.Elem() }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
binder/mapping.go(2 hunks)binder/mapping_test.go(4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go
📄 CodeRabbit inference engine (AGENTS.md)
**/*.go: Apply formatting using gofumpt (Make target: format)
Optimize struct field alignment using betteralign (Make target: betteralign)
Modernize code using gopls modernize (Make target: modernize)
Files:
binder/mapping_test.gobinder/mapping.go
🧠 Learnings (1)
📚 Learning: 2025-10-16T07:19:52.418Z
Learnt from: grivera64
Repo: gofiber/fiber PR: 3807
File: adapter_test.go:118-144
Timestamp: 2025-10-16T07:19:52.418Z
Learning: In the Fiber codebase, the linter does not allow `require` assertions from within HTTP handlers (including net/http-style handlers). Use `t.Fatalf`, `t.Errorf`, or similar `testing.T` methods for error handling inside handler functions instead.
Applied to files:
binder/mapping.go
🧬 Code graph analysis (2)
binder/mapping_test.go (1)
binder/binder.go (2)
ErrMapNilDestination(12-12)ErrMapNotConvertible(11-11)
binder/mapping.go (1)
binder/binder.go (2)
ErrMapNilDestination(12-12)ErrMapNotConvertible(11-11)
⏰ 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). (6)
- GitHub Check: unit (1.25.x, windows-latest)
- GitHub Check: repeated
- GitHub Check: unit (1.25.x, macos-latest)
- GitHub Check: unit (1.25.x, macos-13)
- GitHub Check: Compare
- GitHub Check: lint
🔇 Additional comments (8)
binder/mapping_test.go (3)
136-136: LGTM: parseToMap calls updated correctly.The calls to
parseToMaphave been properly updated to passreflect.ValueOf(m)andreflect.ValueOf(m2), aligning with the new function signature.Also applies to: 145-145
156-158: Good coverage for unsupported map element types.This test correctly verifies that
map[string]any(with element kindreflect.Interface) is handled gracefully—parseToMapreturns no error and leaves the map empty, as it only processesmap[string]stringandmap[string][]string.
401-401: LGTM: Extended test cases updated correctly.All
parseToMapcalls in the extended tests have been properly updated to passreflect.ValueOf(), and they correctly test edge cases including empty values, unsupported element types, and error paths.Also applies to: 406-406, 410-410
binder/mapping.go (5)
84-84: LGTM: Caller updated correctly.The
parsefunction correctly passes thereflect.Value(ptrVal) directly toparseToMap, matching the updated function signature.
109-112: LGTM: Signature and validation improved.The signature change to
reflect.Valueeliminates redundant reflection, and the generic error message "invalid destination value" correctly addresses previous feedback about not assuming the type is a map at this validation stage.
118-120: LGTM: Early return for non-maps is efficient and well-documented.The check correctly validates that the destination is a string-keyed map before proceeding, and the comment clearly explains the early return behavior.
122-127: Excellent: Lazy initialization with proper nil handling.This lazy initialization logic correctly addresses the PR objectives by:
- Initializing nil maps when possible (addressable via
CanSet())- Returning a descriptive error (
ErrMapNilDestination) when the nil map cannot be initialized- Preventing panics through the
CanSet()check
129-152: LGTM: Type handling is correct and complete.The switch statement correctly handles supported map types:
map[string][]string: Usesmaps.Copyfor efficiencymap[string]string: Takes the last value from multi-value slices (standard behavior)- Unsupported types: Returns nil gracefully (no-op)
The type assertions correctly return
ErrMapNotConvertiblewhen the element kind matches (Slice/String) but the concrete type doesn't (e.g.,map[string][]int), which is well-tested in the test suite.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull Request Overview
Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.
Summary