Skip to content

♻️ refactor: use slices.Contains to simplify code#3486

Merged
ReneWerner87 merged 1 commit intogofiber:mainfrom
tongjicoder:main
May 27, 2025
Merged

♻️ refactor: use slices.Contains to simplify code#3486
ReneWerner87 merged 1 commit intogofiber:mainfrom
tongjicoder:main

Conversation

@tongjicoder
Copy link
Contributor

@tongjicoder tongjicoder commented May 27, 2025

Description

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

Fixes # (issue)

Changes introduced

List the new features or adjustments introduced in this pull request. Provide details on benchmarks, documentation updates, changelog entries, and if applicable, the migration guide.

  • Benchmarks: Describe any performance benchmarks and improvements related to the changes.
  • Documentation Update: Detail the updates made to the documentation and links to the changed files.
  • Changelog/What's New: Include a summary of the additions for the upcoming release notes.
  • Migration Guide: If necessary, provide a guide or steps for users to migrate their existing code to accommodate these changes.
  • API Alignment with Express: Explain how the changes align with the Express API.
  • API Longevity: Discuss the steps taken to ensure that the new or updated APIs are consistent and not prone to breaking changes.
  • Examples: Provide examples demonstrating the new features or changes in action.

Type of change

Please delete options that are not relevant.

  • New feature (non-breaking change which adds functionality)
  • 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)

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.

Commit formatting

Please use emojis in commit messages for an easy way to identify the purpose or intention of a commit. Check out the emoji cheatsheet here: CONTRIBUTING.md

Signed-off-by: tongjicoder <tongjicoder@icloud.com>
@tongjicoder tongjicoder requested a review from a team as a code owner May 27, 2025 17:00
@welcome
Copy link

welcome bot commented May 27, 2025

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 27, 2025

Walkthrough

The changes across several files replace manual iteration over slices for membership checks with the standard library function slices.Contains. This refactoring simplifies the code by removing explicit loops and using a built-in utility for containment checks, without altering the logic, control flow, or public interfaces.

Changes

File(s) Change Summary
bind.go Replaced manual MIME type containment check with slices.Contains in custom binder logic.
middleware/cors/cors.go Switched from manual allowed origins loop to slices.Contains for origin validation.
middleware/csrf/csrf.go Replaced manual trusted origins checks with slices.Contains in two functions; added import.
middleware/encryptcookie/utils.go Used slices.Contains instead of manual loop in isDisabled; added import.

Poem

In fields of code where slices grow,
The rabbits hop, refactoring slow.
No more loops to check and see—
slices.Contains brings harmony!
With simpler code, we leap ahead,
And munch on carrots, well content and well-read.
🥕


📜 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 47f47ae and 4923d45.

📒 Files selected for processing (4)
  • bind.go (2 hunks)
  • middleware/cors/cors.go (2 hunks)
  • middleware/csrf/csrf.go (3 hunks)
  • middleware/encryptcookie/utils.go (2 hunks)
🔇 Additional comments (9)
middleware/cors/cors.go (2)

4-4: LGTM: Clean addition of slices import

The import is correctly placed and necessary for the refactoring changes below.


118-120:

Details

❓ Verification inconclusive

Excellent refactoring using slices.Contains

The manual loop for checking origin membership has been elegantly replaced with slices.Contains. This maintains the exact same logic while improving readability and reducing code complexity.

Note: Ensure your project supports Go 1.21+ as slices.Contains was introduced in that version.


🏁 Script executed:

#!/bin/bash
# Description: Verify Go version requirement in go.mod
# Expected: Go version should be 1.21 or higher to support slices.Contains

echo "Checking Go version requirement in go.mod:"
if [ -f "go.mod" ]; then
    grep "^go " go.mod
else
    echo "go.mod not found"
fi

Length of output: 157


🏁 Script executed:

#!/bin/bash
set -e

echo "==> Searching for Go setup in CI workflows..."
if [ -d ".github/workflows" ]; then
  grep -R "actions/setup-go" -n .github/workflows || echo "No actions/setup-go found in workflows"
  grep -R "go-version" -n .github/workflows || echo "No go-version key found in workflows"
else
  echo "No .github/workflows directory"
fi

echo
echo "==> Searching for Go base images in Dockerfiles..."
grep -R "FROM golang:" -n . || echo "No golang base image found"

Length of output: 423


Excellent refactoring – replaced manual loop with slices.Contains

Note that slices.Contains is only available in Go 1.21 and later. Please verify that your project’s Go version is set accordingly:

• Ensure you have a go.mod declaring

go 1.21  

• Update any CI workflows using actions/setup-go with

- uses: actions/setup-go@v3
  with:
    go-version: '1.21'

• If you use Docker, base your image on golang:1.21 or newer

middleware/encryptcookie/utils.go (2)

11-11: LGTM: Import added for refactoring

The slices import is correctly positioned and needed for the function simplification below.


108-108: Perfect simplification of isDisabled function

The function has been elegantly simplified using slices.Contains(except, key). This replaces what was likely a manual loop while maintaining the exact same functionality. The code is now more readable and concise.

middleware/csrf/csrf.go (3)

7-7: LGTM: Import correctly added

The slices import is properly positioned and supports the refactoring changes in the functions below.


300-302: Excellent refactoring in originMatchesHost

The manual loop checking if the origin exists in trustedOrigins has been cleanly replaced with slices.Contains(trustedOrigins, origin). This maintains the same logic while improving code clarity and reducing complexity.


333-335: Great consistency in refererMatchesHost

Similar to the origin check above, the referer validation has been simplified using slices.Contains(trustedOrigins, referer). This creates a consistent pattern across both validation functions and improves maintainability.

bind.go (2)

5-5: LGTM: Import properly added

The slices import is correctly placed and supports the refactoring in the Body function.


257-259: Outstanding refactoring of MIME type checking

The nested loop that checked if the content type matched any of the custom binder's MIME types has been excellently simplified using slices.Contains(customBinder.MIMETypes(), ctype). This maintains the exact same logic flow (including the early return when a match is found) while significantly improving code readability and reducing complexity.

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

@tongjicoder tongjicoder changed the title refactor: use slices.Contains to simplify code ♻️ refactor: use slices.Contains to simplify code May 27, 2025
@codecov
Copy link

codecov bot commented May 27, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.82%. Comparing base (47f47ae) to head (4923d45).
Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3486      +/-   ##
==========================================
+ Coverage   83.76%   83.82%   +0.05%     
==========================================
  Files         120      120              
  Lines       12254    12246       -8     
==========================================
  Hits        10265    10265              
+ Misses       1564     1558       -6     
+ Partials      425      423       -2     
Flag Coverage Δ
unittests 83.82% <100.00%> (+0.05%) ⬆️

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

i like the idea but its slower at the moment

var (
	trustedOrigins = []string{
		"https://example.com",
		"https://static.example.com",
		"https://api.example.com",
		"https://cdn.example.com",
	}
	benchResult bool
	origin      = "https://api.example.com"
)

func BenchmarkTrustedOrigin(b *testing.B) {
	b.Run("for-loop", func(b *testing.B) {
		var found bool
		for b.Loop() {
			found = false
			for _, trusted := range trustedOrigins {
				if origin == trusted {
					found = true
					break
				}
			}
		}
		benchResult = found
	})

	b.Run("slices-contains", func(b *testing.B) {
		var found bool
		for b.Loop() {
			found = slices.Contains(trustedOrigins, origin)
		}
		benchResult = found
	})
}

go test . -v -bench=BenchmarkTrustedOrigin -benchmem -run=^$ -count=10 -benchtime=1s

BenchmarkTrustedOrigin
BenchmarkTrustedOrigin/for-loop
BenchmarkTrustedOrigin/for-loop-12         	336528759	         3.393 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/for-loop-12         	362601940	         3.289 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/for-loop-12         	344624821	         3.359 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/for-loop-12         	365122392	         3.283 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/for-loop-12         	363269287	         3.280 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/for-loop-12         	371663353	         3.310 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/for-loop-12         	368393098	         3.265 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/for-loop-12         	372288208	         3.247 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/for-loop-12         	373938900	         3.252 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/for-loop-12         	369771962	         3.285 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/slices-contains
BenchmarkTrustedOrigin/slices-contains-12  	285687927	         4.280 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/slices-contains-12  	280973828	         4.195 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/slices-contains-12  	287838032	         4.146 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/slices-contains-12  	287695272	         4.163 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/slices-contains-12  	287824887	         4.165 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/slices-contains-12  	285173107	         4.183 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/slices-contains-12  	285460174	         4.218 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/slices-contains-12  	289958115	         4.157 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/slices-contains-12  	285688381	         4.292 ns/op	       0 B/op	       0 allocs/op
BenchmarkTrustedOrigin/slices-contains-12  	287636770	         4.177 ns/op	       0 B/op	       0 allocs/op

@ReneWerner87
Copy link
Member

1ns slower is acceptable the function will certainly be optimized later

@ReneWerner87 ReneWerner87 merged commit 557095b into gofiber:main May 27, 2025
14 of 15 checks passed
@welcome
Copy link

welcome bot commented May 27, 2025

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

@ReneWerner87 ReneWerner87 added this to v3 May 27, 2025
@ReneWerner87 ReneWerner87 added this to the v3 milestone May 27, 2025
@efectn efectn moved this to Done in v3 Jun 25, 2025
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