Skip to content

Conversation

@gaby
Copy link
Member

@gaby gaby commented Dec 4, 2025

Summary

  • This pull request focuses on enhancing code consistency and clarity by migrating all relevant string trimming operations to use the utils.TrimSpace function. This change ensures a unified approach to handling whitespace removal and includes an update to the documentation's v3 migration example to reflect this new standard and resolve variable shadowing issues.

Copilot AI review requested due to automatic review settings December 4, 2025 03:44
@gaby gaby requested a review from a team as a code owner December 4, 2025 03:44
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 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.

Walkthrough

This PR systematically refactors whitespace trimming across the codebase by replacing ad-hoc trim implementations with utils.TrimSpace. Changes span core request/response handling, middleware, tests, and documentation—standardizing on Unicode whitespace trimming rather than space-only trimming.

Changes

Cohort / File(s) Summary
Core request/response handling
client/response.go, ctx.go, req.go
Replace utils.Trim(x, ' ') and strings.TrimSpace with utils.TrimSpace for header and body token parsing
Test files
ctx_test.go, middleware/csrf/csrf_test.go, middleware/session/middleware_test.go
Update trimming calls from strings.TrimSpace and utils.Trim to utils.TrimSpace in compression, CSRF, and session test cases
Middleware
middleware/cache/cache.go, middleware/compress/compress.go, middleware/cors/cors.go, middleware/csrf/csrf.go
Standardize trimming in cache max-age parsing, compression token validation, origin validation, and trusted origin parsing to use utils.TrimSpace
Helpers
helpers.go
Replace utils.Trim(x, ' ') with utils.TrimSpace in offer spec, etag, and address parsing
Documentation
docs/whats_new.md
Update code sample to reflect TrimSpace usage and fix variable shadowing in example

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~15 minutes

  • Large set of homogeneous changes following a consistent refactoring pattern across 12+ files
  • Main effort is verifying trim call replacements maintain intended whitespace handling behavior
  • No control flow changes or new logic introduced

Possibly related PRs

Suggested labels

🧹 Updates, v3, 📒 Documentation

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

Poem

🐰 Whispers of trimming, spaces take flight,
Unicode whitespace, now handled just right,
From Trim to TrimSpace, a standardized way,
The rabbit rejoices—refactoring day! ✨

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 53.85% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description check ⚠️ Warning The PR description is largely incomplete. It provides only a brief summary but lacks critical sections from the template such as 'Fixes #', 'Changes introduced' checklist items, 'Type of change' selection, and detailed 'Checklist' verification. Complete the description by adding the missing template sections: specify the issue number, detail changes introduced with checklist items, select the type of change (Code consistency appears relevant), and verify all checklist requirements are met.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: replacing strings.TrimSpace with utils.TrimSpace across the codebase for consistency.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch replace-strings.trimspace-with-utils.trimspace

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@ReneWerner87 ReneWerner87 added this to v3 Dec 4, 2025
@ReneWerner87 ReneWerner87 added this to the v3 milestone Dec 4, 2025
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @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 focuses on enhancing code consistency and clarity by migrating all relevant string trimming operations to use the utils.TrimSpace function. This change ensures a unified approach to handling whitespace removal and includes an update to the documentation's v3 migration example to reflect this new standard and resolve variable shadowing issues.

Highlights

  • API Consistency: Standardized string trimming operations by replacing various uses of utils.Trim(..., ' ') and strings.TrimSpace with the more specific and consistent utils.TrimSpace function across the codebase.
  • Documentation Update: The v3 migration example in docs/whats_new.md has been updated to reflect the use of utils.TrimSpace and to prevent variable shadowing, improving clarity and correctness.
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 by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

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 pull request 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. 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

  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.

@gaby gaby changed the title 📒 docs: update utils trim example 🧹 chore: Replace strings.TrimSpace with utils.TrimSpace Dec 4, 2025
@codecov
Copy link

codecov bot commented Dec 4, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.64%. Comparing base (7395dc7) to head (c5b8b6c).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3918      +/-   ##
==========================================
- Coverage   91.66%   91.64%   -0.02%     
==========================================
  Files         119      119              
  Lines       10096    10096              
==========================================
- Hits         9254     9252       -2     
- Misses        534      535       +1     
- Partials      308      309       +1     
Flag Coverage Δ
unittests 91.64% <100.00%> (-0.02%) ⬇️

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.

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 refactors the codebase to consistently use utils.TrimSpace for trimming whitespace, which is a good improvement for code consistency. The changes are mostly correct, but I've identified one instance in helpers.go where the new function is used with an incorrect type, which will lead to a compilation error. I've provided a specific comment and a code suggestion to fix this issue. The documentation update is also a nice improvement.

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 updates the codebase to consistently use utils.TrimSpace() instead of utils.Trim(x, ' ') and strings.TrimSpace(), and fixes a documentation example to avoid variable shadowing.

  • Standardizes whitespace trimming to use utils.TrimSpace() across the entire codebase
  • Updates the v3 migration example in documentation to use correct function calls and avoid shadowing the s variable

Reviewed changes

Copilot reviewed 12 out of 12 changed files in this pull request and generated no comments.

Show a summary per file
File Description
req.go Replaced multiple utils.Trim(x, ' ') calls with utils.TrimSpace(x) in request parsing functions
middleware/session/middleware_test.go Changed strings.TrimSpace to utils.TrimSpace for consistency
middleware/csrf/csrf_test.go Updated two instances of utils.Trim to utils.TrimSpace in cookie parsing tests
middleware/csrf/csrf.go Replaced utils.Trim with utils.TrimSpace when processing trusted origins
middleware/cors/cors.go Updated origin trimming to use utils.TrimSpace
middleware/compress/compress.go Changed token comparison to use utils.TrimSpace
middleware/cache/cache.go Standardized both utils.Trim and strings.TrimSpace to utils.TrimSpace
helpers.go Updated multiple instances in helper functions to use utils.TrimSpace
docs/whats_new.md Fixed v3 migration example to use utils.TrimSpace instead of utils.Trim and renamed s to str to avoid shadowing
ctx_test.go Changed strings.TrimSpace to utils.TrimSpace in compression tests
ctx.go Updated transfer encoding and WebSocket checks to use utils.TrimSpace
client/response.go Replaced utils.Trim with utils.TrimSpace in String() method

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.

Actionable comments posted: 0

🧹 Nitpick comments (1)
middleware/cache/cache.go (1)

426-459: Cache-Control parsing now consistently uses utils.TrimSpace

Normalizing each directive with utils.TrimSpace(utils.ToLower(part)) in both parseMaxAge and allowsSharedCache keeps Cache-Control handling case-insensitive and whitespace-tolerant while aligning with utils-based helpers. If you touch this again, you could optionally factor that normalization into a tiny helper to avoid repeating the same line in both functions, but it's not critical.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7395dc7 and c5b8b6c.

📒 Files selected for processing (12)
  • client/response.go (1 hunks)
  • ctx.go (2 hunks)
  • ctx_test.go (2 hunks)
  • docs/whats_new.md (1 hunks)
  • helpers.go (3 hunks)
  • middleware/cache/cache.go (2 hunks)
  • middleware/compress/compress.go (1 hunks)
  • middleware/cors/cors.go (1 hunks)
  • middleware/csrf/csrf.go (1 hunks)
  • middleware/csrf/csrf_test.go (2 hunks)
  • middleware/session/middleware_test.go (2 hunks)
  • req.go (5 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.go

📄 CodeRabbit inference engine (AGENTS.md)

Prefer github.com/gofiber/utils/v2 helpers (for example, utils.Trim) when performing common operations such as string manipulation, whenever it is practical and appropriate for the surrounding code

Files:

  • middleware/csrf/csrf.go
  • middleware/cors/cors.go
  • middleware/compress/compress.go
  • ctx.go
  • req.go
  • middleware/session/middleware_test.go
  • client/response.go
  • middleware/csrf/csrf_test.go
  • middleware/cache/cache.go
  • helpers.go
  • ctx_test.go
**/*_test.go

📄 CodeRabbit inference engine (AGENTS.md)

When adding Go tests, always invoke t.Parallel() at the start of each test and subtest to maximize concurrency

Files:

  • middleware/session/middleware_test.go
  • middleware/csrf/csrf_test.go
  • ctx_test.go
docs/**

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Review and update the contents of the docs folder if necessary when modifying code

Files:

  • docs/whats_new.md
**/*.md

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Run make markdown to lint all Markdown files when modifying code

Files:

  • docs/whats_new.md
🧠 Learnings (13)
📓 Common learnings
Learnt from: CR
Repo: gofiber/fiber PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-11-26T13:34:08.100Z
Learning: Applies to **/*.go : Prefer `github.com/gofiber/utils/v2` helpers (for example, `utils.Trim`) when performing common operations such as string manipulation, whenever it is practical and appropriate for the surrounding code
📚 Learning: 2025-11-26T13:34:08.100Z
Learnt from: CR
Repo: gofiber/fiber PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-11-26T13:34:08.100Z
Learning: Applies to **/*.go : Prefer `github.com/gofiber/utils/v2` helpers (for example, `utils.Trim`) when performing common operations such as string manipulation, whenever it is practical and appropriate for the surrounding code

Applied to files:

  • middleware/cors/cors.go
  • ctx.go
  • req.go
  • middleware/session/middleware_test.go
  • client/response.go
  • middleware/cache/cache.go
  • helpers.go
  • ctx_test.go
  • docs/whats_new.md
📚 Learning: 2025-09-28T17:39:26.644Z
Learnt from: arturmelanchyk
Repo: gofiber/fiber PR: 3768
File: client/request.go:162-166
Timestamp: 2025-09-28T17:39:26.644Z
Learning: In fasthttp-based code like gofiber, using utils.UnsafeString(key) instead of string(key) is acceptable when values are used immediately within the same call stack and not stored for later use, as it avoids allocations and aligns with fasthttp's zero-allocation design philosophy.

Applied to files:

  • middleware/session/middleware_test.go
  • docs/whats_new.md
📚 Learning: 2024-11-15T07:56:21.623Z
Learnt from: ReneWerner87
Repo: gofiber/fiber PR: 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:

  • middleware/session/middleware_test.go
📚 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:

  • middleware/session/middleware_test.go
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 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:

  • middleware/session/middleware_test.go
📚 Learning: 2025-10-16T07:15:26.529Z
Learnt from: grivera64
Repo: gofiber/fiber PR: 3807
File: adapter_test.go:118-144
Timestamp: 2025-10-16T07:15:26.529Z
Learning: In Fiber v3, net/http handlers (http.Handler, http.HandlerFunc, or raw func(http.ResponseWriter, *http.Request)) can be passed directly to routing methods like app.Get(), app.Post(), etc. The framework automatically detects and wraps them internally via toFiberHandler/collectHandlers. The github.com/gofiber/fiber/v3/middleware/adaptor package is legacy and should not be suggested for tests or code using native net/http handler support.

Applied to files:

  • middleware/session/middleware_test.go
📚 Learning: 2024-07-26T21:00:12.902Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 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:

  • middleware/session/middleware_test.go
📚 Learning: 2024-11-10T23:44:13.704Z
Learnt from: gaby
Repo: gofiber/fiber PR: 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:

  • middleware/session/middleware_test.go
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 3016
File: middleware/csrf/csrf_test.go:188-193
Timestamp: 2024-10-08T19:06:06.583Z
Learning: In the Fiber framework tests, using `ctx.Response.Header.Cookie` may not be suitable for parsing cookies from the response header, as it requires a `*Cookie` and fills it rather than returning a string value; thus, manual parsing of the `Set-Cookie` header may be necessary.

Applied to files:

  • middleware/csrf/csrf_test.go
📚 Learning: 2024-09-25T17:08:07.693Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 3016
File: middleware/csrf/csrf_test.go:164-165
Timestamp: 2024-09-25T17:08:07.693Z
Learning: In the `Test_CSRF_WithSession_Middleware` function, calling `session.NewWithStore()` without arguments is acceptable, as the default configuration is sufficient.

Applied to files:

  • middleware/csrf/csrf_test.go
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: gaby
Repo: gofiber/fiber PR: 3056
File: middleware/encryptcookie/utils.go:20-23
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests for key length enforcement in both `EncryptCookie` and `DecryptCookie` functions have been added to ensure robust validation and prevent potential runtime errors.

Applied to files:

  • middleware/csrf/csrf_test.go
📚 Learning: 2024-06-30T00:38:06.580Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 3051
File: middleware/session/session.go:215-216
Timestamp: 2024-06-30T00:38:06.580Z
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:

  • middleware/csrf/csrf_test.go
🧬 Code graph analysis (1)
req.go (2)
constants.go (1)
  • HeaderRange (236-236)
error.go (1)
  • ErrRangeMalformed (32-32)
⏰ 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: Agent
  • GitHub Check: lint
  • GitHub Check: unit (1.25.x, windows-latest)
  • GitHub Check: unit (1.25.x, macos-latest)
  • GitHub Check: repeated
  • GitHub Check: Compare
🔇 Additional comments (13)
middleware/cors/cors.go (1)

51-74: LGTM! Improved whitespace handling in origin validation.

The change from utils.Trim(origin, ' ') to utils.TrimSpace(origin) is appropriate and improves robustness by handling all Unicode whitespace characters (tabs, newlines, etc.) rather than just ASCII spaces. This aligns with the coding guideline to prefer github.com/gofiber/utils/v2 helpers.

As per coding guidelines, preferring utils/v2 helpers for string manipulation.

middleware/session/middleware_test.go (1)

127-143: LGTM! Consistent use of utils helpers in test code.

The migration from strings.TrimSpace to utils.TrimSpace follows the project's coding guideline to prefer github.com/gofiber/utils/v2 helpers. The import was correctly added, and the usage in the comma-separated key parsing is appropriate.

As per coding guidelines, preferring utils/v2 helpers for string manipulation.

middleware/csrf/csrf.go (1)

69-91: LGTM! Consistent whitespace normalization for trusted origins.

The change from utils.Trim(origin, ' ') to utils.TrimSpace(origin) is consistent with the CORS middleware (middleware/cors/cors.go line 57) and provides more robust whitespace handling for origin validation. This standardizes the approach across the codebase.

As per coding guidelines, preferring utils/v2 helpers for string manipulation.

middleware/csrf/csrf_test.go (2)

306-311: LGTM! Test updated to use utils.TrimSpace for header parsing.

The test code correctly adopts utils.TrimSpace for parsing Set-Cookie headers, maintaining consistency with the production code changes. This is appropriate for HTTP header parsing where various whitespace characters may be present.

As per coding guidelines, preferring utils/v2 helpers for string manipulation.


478-483: LGTM! Consistent test update for Set-Cookie parsing.

This change mirrors the update at line 307, ensuring both CSRF session tests use the same whitespace trimming approach. The consistency is good for maintainability.

client/response.go (1)

92-95: LGTM! Enhanced response body trimming.

The change from utils.Trim(string(r.Body()), ' ') to utils.TrimSpace(string(r.Body())) improves the robustness of the String() method by handling all types of whitespace characters (newlines, tabs, carriage returns, etc.) that may appear at the start or end of HTTP response bodies.

As per coding guidelines, preferring utils/v2 helpers for string manipulation.

middleware/compress/compress.go (1)

12-19: LGTM! Improved token parsing for HTTP headers.

The change from utils.Trim(part, ' ') to utils.TrimSpace(part) enhances the hasToken function to properly handle all whitespace characters in HTTP header values. This is consistent with the broader PR changes to standardize whitespace trimming across header parsing logic.

As per coding guidelines, preferring utils/v2 helpers for string manipulation.

ctx_test.go (1)

711-711: Encoding token trimming change looks good

Using utils.TrimSpace(enc) in both compression tests keeps the intent (trimming leading/trailing whitespace from each Content-Encoding token) while aligning with the project’s preference for utils helpers. No further changes needed. As per coding guidelines, this is the preferred helper for string manipulation.

Also applies to: 945-945

helpers.go (1)

539-539: Standardizing whitespace trimming with utils.TrimSpace is appropriate

Switching to utils.TrimSpace in getOffer, isEtagStale, and parseAddr unifies whitespace handling, likely broadening support beyond plain spaces without affecting correctness, and follows the repo’s guidance to prefer utils helpers. As per coding guidelines, this is the desired direction.

Also applies to: 663-663, 698-698

docs/whats_new.md (1)

2218-2229: Updated utils example looks correct; remember markdown linting

The switch to utils.TrimSpace and utils.ToString plus the str rename is consistent with the v3 utils guidance and avoids variable shadowing. Please also run make markdown so markdown lint stays green for this doc change.

req.go (2)

487-501: Content-Type normalization via utils.TrimSpace is appropriate

Trimming ct with utils.TrimSpace before the comparison makes the Is check more robust to stray whitespace while staying consistent with utils usage.


741-816: Range header parsing whitespace handling looks solid

Normalizing Range with utils.TrimSpace (for the full header, type, ranges, and per-range bounds) improves tolerance of optional whitespace without changing the core parsing or validation rules (bytes type check, bounds via utils.ParseUint, malformed/error paths). This aligns with the broader move to utils.TrimSpace.

ctx.go (1)

385-424: Transfer-Encoding and WebSocket upgrade trimming changes are consistent

Using utils.TrimSpace for Transfer-Encoding tokens and the Connection: upgrade value keeps the logic correct while standardizing on the utils helpers for whitespace normalization and case-insensitive parsing. No functional regressions stand out.

Also applies to: 426-440

@ReneWerner87 ReneWerner87 merged commit 233bced into main Dec 4, 2025
29 checks passed
@ReneWerner87 ReneWerner87 deleted the replace-strings.trimspace-with-utils.trimspace branch December 4, 2025 07:13
@github-project-automation github-project-automation bot moved this to Done in v3 Dec 4, 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