Skip to content

♻️ refactor: use maps.Copy to simplify code#3490

Merged
ReneWerner87 merged 1 commit intogofiber:mainfrom
alexandear-org:refactor/use-maps-copy
May 28, 2025
Merged

♻️ refactor: use maps.Copy to simplify code#3490
ReneWerner87 merged 1 commit intogofiber:mainfrom
alexandear-org:refactor/use-maps-copy

Conversation

@alexandear
Copy link
Contributor

Description

There is a new function added in the Go 1.21 standard library, which can make the code more concise and easy to read.

Changes introduced

  • Pure refactoring: replace some for loops with maps.Copy.

Type of change

  • Enhancement (improvement to existing features and functionality)

Checklist

Before you submit your pull request, please make sure you meet these requirements:

  • Followed the inspiration of the Express.js framework for new functionalities, making them similar in usage.
  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Updated the documentation in the /docs/ directory for Fiber's documentation.
  • Added or updated unit tests to validate the effectiveness of the changes or new features.
  • Ensured that new and existing unit tests pass locally with the changes.
  • Verified that any new dependencies are essential and have been agreed upon by the maintainers/community.
  • Aimed for optimal performance with minimal allocations in the new code.
  • Provided benchmarks for the new code to analyze and improve upon.

Copilot AI review requested due to automatic review settings May 28, 2025 09:55
@alexandear alexandear requested a review from a team as a code owner May 28, 2025 09:55
@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 28, 2025

Walkthrough

The changes update several locations in the codebase to use the Go standard library's maps.Copy function for copying map entries, replacing manual for-loop iterations. Imports of the maps package are added where needed. No changes are made to public APIs or control flow.

Changes

Files Change Summary
binder/mapping.go Replaced manual map copying in parseToMap with maps.Copy.
client/request.go Used maps.Copy in Cookie.SetCookies and PathParam.SetParams.
middleware/logger/tags.go Switched to maps.Copy for merging custom tag functions.

Suggested labels

🧹 Updates, v3

Suggested reviewers

  • gaby
  • sixcolors
  • efectn
  • ReneWerner87

Poem

A bunny hopped from loop to loop,
But found a shortcut in the group—
With maps.Copy, swift and neat,
Map copying is now a treat!
Less code to write, more time to play,
The rabbit cheers for Go today! 🐇✨


📜 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 557095b and d43e055.

📒 Files selected for processing (3)
  • binder/mapping.go (2 hunks)
  • client/request.go (3 hunks)
  • middleware/logger/tags.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: unit (1.24.x, macos-latest)
  • GitHub Check: unit (1.24.x, windows-latest)
  • GitHub Check: repeated
  • GitHub Check: unit (1.24.x, macos-13)
  • GitHub Check: lint
  • GitHub Check: Compare
🔇 Additional comments (7)
binder/mapping.go (2)

6-6: Excellent addition of the maps package import.

The import is correctly added to support the new maps.Copy functionality.


119-119: Perfect use of maps.Copy for cleaner code.

Replacing the manual map copying loop with maps.Copy(newMap, data) is an excellent refactoring. This leverages the Go 1.21 standard library function, making the code more concise and readable while maintaining identical behavior.

middleware/logger/tags.go (2)

5-5: Clean import addition for maps package.

The import statement is properly placed and supports the refactoring to use maps.Copy.


208-208: Excellent simplification of custom tag merging.

The replacement of manual iteration with maps.Copy(tagFunctions, cfg.CustomTags) is a great improvement. This clearly expresses the intent of merging custom tags into the default tag functions while maintaining the same overriding behavior.

client/request.go (3)

9-9: Properly added maps import for the refactoring.

The import statement is correctly positioned and enables the use of maps.Copy throughout the file.


752-752: Great refactoring in SetCookies method.

Using maps.Copy(c, m) instead of manual iteration is much cleaner and more expressive. This clearly shows the intent of copying all cookies from the provided map to the Cookie instance.


802-802: Excellent consistency in SetParams method.

The use of maps.Copy(p, m) follows the same pattern as the Cookie refactoring, providing consistent code style across the codebase. This simplifies the bulk setting of path parameters.

✨ Finishing Touches
  • 📝 Generate Docstrings

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

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR refactors manual map-merging loops to use the new Go 1.21 maps.Copy function for conciseness and readability.
Key changes:

  • Replaced custom tag loop in the logger middleware with maps.Copy.
  • Simplified cookie and path‐param setters by swapping loops for maps.Copy.
  • Updated binder mapping logic to use maps.Copy.

Reviewed Changes

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

File Description
middleware/logger/tags.go Replaced manual merge of cfg.CustomTags with maps.Copy
client/request.go Swapped loops in SetCookies/SetParams for maps.Copy
binder/mapping.go Replaced loop populating newMap with maps.Copy

@codecov
Copy link

codecov bot commented May 28, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.74%. Comparing base (557095b) to head (d43e055).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3490      +/-   ##
==========================================
- Coverage   83.75%   83.74%   -0.01%     
==========================================
  Files         120      120              
  Lines       12246    12239       -7     
==========================================
- Hits        10257    10250       -7     
  Misses       1564     1564              
  Partials      425      425              
Flag Coverage Δ
unittests 83.74% <100.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ReneWerner87
Copy link
Member

@alexandear can you provide benchmark results
for-loop-copy vs maps.Copy

@ReneWerner87 ReneWerner87 added this to v3 May 28, 2025
@ReneWerner87 ReneWerner87 added this to the v3 milestone May 28, 2025
@alexandear
Copy link
Contributor Author

@alexandear can you provide benchmark results for-loop-copy vs maps.Copy

var pathParam = PathParam{}

func BenchmarkSetParams(b *testing.B) {
	params := map[string]string{
		"a": "1",
		"b": "2",
		"c": "3",
	}

	b.Run("for-loop", func(b *testing.B) {
		for b.Loop() {
			for k, v := range params {
				pathParam[k] = v
			}
		}
	})

	b.Run("maps-copy", func(b *testing.B) {
		for b.Loop() {
			maps.Copy(pathParam, params)
		}
	})
}
$ go test -benchmem -run=^$ -bench ^BenchmarkSetParams$ github.com/gofiber/fiber/v3/client
goos: darwin
goarch: arm64
pkg: github.com/gofiber/fiber/v3/client
cpu: Apple M4 Pro
BenchmarkSetParams/for-loop-12          20934620                57.04 ns/op            0 B/op        0 allocs/op
BenchmarkSetParams/maps-copy-12         20611929                59.74 ns/op            0 B/op        0 allocs/op
PASS
ok      github.com/gofiber/fiber/v3/client      2.675s

@ReneWerner87
Copy link
Member

ok thx

@ReneWerner87 ReneWerner87 merged commit 9562053 into gofiber:main May 28, 2025
14 of 15 checks passed
@github-project-automation github-project-automation bot moved this to Done in v3 May 28, 2025
@alexandear alexandear deleted the refactor/use-maps-copy branch May 28, 2025 10:57
@ReneWerner87
Copy link
Member

the 2ns is coming from function overhead
https://dave.cheney.net/2020/04/25/inlining-optimisations-in-go

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.

4 participants