Skip to content
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

🩹 Fix: improper query/body parsing with embedded structs #2906

Merged

Conversation

devhsoj
Copy link
Contributor

@devhsoj devhsoj commented Mar 9, 2024

Description

This PR fixes improper bodyparser/query parsing when using embedded structs within a schema.

Related to #2859

Type of change

  • Enhancement (improvement to existing features and functionality)
  • Documentation update (changes to documentation)
  • Performance improvement (non-breaking change which improves efficiency)
  • Code consistency (non-breaking change which improves code reliability and robustness)

Summary by CodeRabbit

  • Refactor
    • Enhanced comparison logic in equalFieldType to better handle embedded struct fields.
  • New Features
    • Improved parsing logic for various data formats by including the Names field in the process.

@devhsoj devhsoj requested a review from a team as a code owner March 9, 2024 10:12
@devhsoj devhsoj requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team March 9, 2024 10:12
Copy link

welcome bot commented Mar 9, 2024

Thanks for opening this pull request! 🎉 Please check out our contributing guidelines. If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

Copy link
Contributor

coderabbitai bot commented Mar 9, 2024

Walkthrough

The recent changes aim to enhance the parsing logic within the equalFieldType function in mapping.go and extend the parsing process to include a new field Names within TestEmbeddedStruct in ctx_test.go. These updates refine the comparison and parsing mechanisms, making them more robust and inclusive of additional data elements.

Changes

File(s) Summary
binder/mapping.go Enhanced comparison logic by adding a check for embedded struct fields matching a specific type in equalFieldType function
ctx_test.go Added Names field to TestEmbeddedStruct within TestStruct to expand parsing logic for various data formats

Related issues

Poem

Among the code, a rabbit did play,
Crafting changes in its own special way. 🐇
With each tweak and addition made,
Bugs scurried off, no longer to fade. 🐞

"A touch here, a nudge there," it whispered with cheer,
"Now the code sings, crystal clear!" 🎶
In the digital realm, a dance so light,
Bugs banished, all is right. 💻🎉

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

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>.
    • Generate unit-tests for this file.
    • 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 generate unit tests for this file.
    • @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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Review Status

Actionable comments generated: 1

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 0379cc5 and 13e92bc.
Files selected for processing (1)
  • binder/mapping.go (1 hunks)

Comment on lines +185 to +201
// Is the field an embedded struct?
if structFieldKind == reflect.Struct {
// Loop over embedded struct fields
for j := 0; j < structField.NumField(); j++ {
structFieldField := structField.Field(j)

// Can this embedded field be changed?
if !structFieldField.CanSet() {
continue
}

// Is the embedded struct field type equal to the input?
if structFieldField.Kind() == kind {
return true
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The addition of the check for embedded struct fields in the equalFieldType function is a significant improvement to the query parsing mechanism. This change allows for a more accurate and reliable parsing of queries that include embedded structs, directly addressing the issue highlighted in the related problem report.

However, there are a few considerations and potential improvements to ensure the robustness and maintainability of this solution:

  1. Performance Considerations: The nested loop introduced for checking embedded struct fields could potentially impact performance, especially for structs with a large number of fields or deeply nested embedded structs. It might be beneficial to benchmark this change with various struct configurations to understand its impact on performance.

  2. Recursion for Deeply Nested Structs: The current implementation handles one level of embedded structs. If there are structs embedded within embedded structs, this implementation might not correctly identify the field type. Consider using a recursive approach to handle arbitrary levels of nested structs.

  3. Error Handling and Logging: While the current implementation focuses on enhancing the comparison logic, adding error handling or logging for unexpected scenarios (e.g., when reflection operations fail) could improve the robustness and debuggability of the code.

  4. Code Comments and Documentation: Adding detailed comments explaining the logic behind handling embedded structs and the rationale for this approach would enhance the maintainability of the code. Future contributors would benefit from understanding the context and reasoning behind these changes.

Overall, this enhancement is a valuable addition to the system, and with some refinements, it can be further improved to ensure its effectiveness and maintainability.

Consider implementing the suggested improvements to address potential performance concerns, support deeper levels of nested structs, and enhance the maintainability of the code.

@gaby
Copy link
Member

gaby commented Mar 10, 2024

@devhsoj This needs a unit-test using the example provided in #2859 That way we can verify it fixes the issue

Copy link

codecov bot commented Mar 10, 2024

Codecov Report

Attention: Patch coverage is 0% with 7 lines in your changes are missing coverage. Please review.

Project coverage is 82.82%. Comparing base (fcb8537) to head (5228ca9).

Files Patch % Lines
binder/mapping.go 0.00% 6 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2906      +/-   ##
==========================================
+ Coverage   82.66%   82.82%   +0.16%     
==========================================
  Files         116      116              
  Lines        8368     8375       +7     
==========================================
+ Hits         6917     6937      +20     
+ Misses       1107     1097      -10     
+ Partials      344      341       -3     
Flag Coverage Δ
unittests 82.82% <0.00%> (+0.16%) ⬆️

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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 13e92bc and 389f9a9.
Files selected for processing (1)
  • ctx_test.go (4 hunks)
Additional comments: 5
ctx_test.go (5)
  • 1358-1369: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [1-1]

Looks good! The test cases in TestCtx_ParamsInt effectively cover the functionality of the ParamsInt method, including edge cases and default value behavior.

  • 1358-1369: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [1-1]

The test Test_Ctx_extractIPsFromHeader correctly verifies the extraction of IP addresses from the X-Forwarded-For header, including handling of various edge cases.

  • 1358-1369: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [1-1]

The test Test_Ctx_extractIPsFromHeader_EnableValidateIp effectively verifies the extraction of IP addresses with IP validation enabled, ensuring that only valid IPs are considered.

  • 1358-1369: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [1-1]

The test Test_Ctx_GetRespHeaders correctly verifies the functionality of the GetRespHeaders method, ensuring that all response headers, including those with multiple values, are correctly returned.

  • 1358-1369: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [1-1]

The test Test_Ctx_GetReqHeaders effectively verifies the functionality of the GetReqHeaders method, ensuring that all request headers, including those with multiple values, are correctly returned.

@devhsoj
Copy link
Contributor Author

devhsoj commented Mar 10, 2024

@gaby

Thanks for the feedback, I just pushed updates to the Test_Ctx_Parsers unit tests that adds an embedded struct TestEmbeddedStruct to the TestStruct struct used for parsing that verifies that my changes work against an identical example to #2859 along with body parsing: (json, form, multiform, xml), headers, and cookies.

@devhsoj devhsoj changed the title 🩹 Fix: improper query parsing with embedded structs 🩹 Fix: improper context parsing with embedded structs Mar 10, 2024
@devhsoj devhsoj changed the title 🩹 Fix: improper context parsing with embedded structs 🩹 Fix: improper query/body parsing with embedded structs Mar 10, 2024
@ReneWerner87
Copy link
Member

think we can take over the customization for now
but it could be that we will change the code, because we want to refactor the binding completely

in this pull request
#2006
but it is good to have this fix in the master already

@gaby @sixcolors @efectn
can you check, not that I have overlooked something

@gaby
Copy link
Member

gaby commented Mar 17, 2024

@ReneWerner87 My only concern is codecov shows that those new lines are not covered by the updated tests.

@ReneWerner87
Copy link
Member

since we will be refactoring later anyway, it's not a big deal, otherwise we will increase the coverage even later

@ReneWerner87 ReneWerner87 merged commit e25a31b into gofiber:main Mar 17, 2024
13 of 15 checks passed
Copy link

welcome bot commented Mar 17, 2024

Congrats on merging your first pull request! 🎉 We here at Fiber are proud of you! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

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.

3 participants