Thanks to visit codestin.com
Credit goes to github.com

Skip to content

🔥 feat: Add context common request helpers#4007

Merged
ReneWerner87 merged 5 commits intomainfrom
add-full-suite-of-helper-methods-in-ctx.go
Jan 15, 2026
Merged

🔥 feat: Add context common request helpers#4007
ReneWerner87 merged 5 commits intomainfrom
add-full-suite-of-helper-methods-in-ctx.go

Conversation

@gaby
Copy link
Member

@gaby gaby commented Jan 14, 2026

Motivation

  • Provide convenient, zero-allocation helpers on Ctx for common request headers and content-type/accept checks to reduce repeated parsing and allocations.
  • Expose a consistent FullURL string conversion path using the app-level toString helper for parity with other Ctx methods.
  • Surface typed behavior via tests and API/docs so callers can rely on these helpers in handlers and middleware.

Description

  • Added new DefaultCtx helper methods and exposed them on the Ctx interface: FullURL, RequestID, UserAgent, Referer, AcceptLanguage, AcceptEncoding, HasHeader, MediaType, Charset, IsJSON, IsForm, IsMultipart, AcceptsJSON, AcceptsHTML, AcceptsXML, and AcceptsEventStream implemented in ctx.go and listed in ctx_interface_gen.go.
  • Implemented FullURL() to build the full URL and return it via c.app.toString for consistent zero-allocation string handling.
  • Added/expanded tests in ctx_test.go: Test_Ctx_AcceptsHelpers, Test_Ctx_ContentTypeHelpers, Test_Ctx_HeaderHelpers, and Test_Ctx_TypedParsingDefaults to validate accept/header/content-type parsing and case-insensitive header behavior.
  • Updated documentation in docs/api/ctx.md and docs/whats_new.md to document the new helpers and include short usage examples.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 14, 2026

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

Adds numerous Ctx accessor methods (FullURL, RequestID, header and content-type helpers, Accepts* checks), extends the Ctx interface, implements the helpers on DefaultCtx, adds extensive tests and benchmarks, and updates API docs and release notes.

Changes

Cohort / File(s) Summary
Context implementation
ctx.go, req.go
Implemented new DefaultCtx methods: RequestID, FullURL, UserAgent, Referer, AcceptLanguage, AcceptEncoding, HasHeader, MediaType, Charset, IsJSON, IsForm, IsMultipart, AcceptsJSON, AcceptsHTML, AcceptsXML, AcceptsEventStream.
Context interface
ctx_interface_gen.go
Extended Ctx interface to declare the above new methods (inserted at two interface locations).
Tests & benchmarks
ctx_test.go
Added extensive unit tests and benchmarks covering Accept/Content-Type parsing, charset, header helpers, body/compression, routing, rendering, SendFile, cookies/attachments, and many performance benchmarks.
Documentation & release notes
docs/api/ctx.md, docs/whats_new.md
Documented the new Ctx methods and added release notes entries describing the expanded request/context helper API.
Module metadata
go.mod
Updated dependencies referenced by new tests/benchmarks.

Sequence Diagram(s)

(omitted)

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

📒 Documentation

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

Poem

🐰 I hopped through headers, swift and bright,
Added helpers in a single night,
FullURL, RequestID — I stitched with care,
Content-types parsed with whiskered flair,
A carrot cheer for docs now right! 🥕

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding a suite of context helper methods for common request operations.
Description check ✅ Passed The description covers motivation, detailed implementation changes, and test/documentation updates, with most required sections addressed comprehensively.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

🧹 Recent nitpick comments
req.go (1)

314-332: Good implementation, consider using a constant for event-stream MIME type.

The Accepts* methods correctly delegate to the existing Accepts() implementation. AcceptsXML properly checks both application/xml and text/xml variants.

However, AcceptsEventStream uses a hardcoded "text/event-stream" string. For consistency with other MIME type usages (e.g., MIMEApplicationJSON, MIMETextHTML), consider defining a constant like MIMETextEventStream in constants.go.

♻️ Suggested improvement

In constants.go, add:

MIMETextEventStream = "text/event-stream"

Then update AcceptsEventStream:

 func (c *DefaultCtx) AcceptsEventStream() bool {
-	return c.Accepts("text/event-stream") != ""
+	return c.Accepts(MIMETextEventStream) != ""
 }

📜 Recent review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c40ef3f and 04db995.

📒 Files selected for processing (4)
  • ctx.go
  • ctx_interface_gen.go
  • docs/api/ctx.md
  • req.go
🧰 Additional context used
📓 Path-based instructions (3)
**/*.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:

  • ctx.go
  • req.go
  • ctx_interface_gen.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/api/ctx.md
**/*.md

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

Run make markdown to lint all Markdown files when modifying code

Files:

  • docs/api/ctx.md
🧠 Learnings (6)
📓 Common learnings
Learnt from: gaby
Repo: gofiber/fiber PR: 3193
File: middleware/cache/cache_test.go:897-897
Timestamp: 2024-11-08T04:10:42.990Z
Learning: In the Fiber framework, `Context()` is being renamed to `RequestCtx()`, and `UserContext()` to `Context()` to improve clarity and align with Go's context conventions.
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`.
📚 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:

  • ctx.go
  • req.go
  • ctx_interface_gen.go
  • docs/api/ctx.md
📚 Learning: 2024-11-08T04:10:42.990Z
Learnt from: gaby
Repo: gofiber/fiber PR: 3193
File: middleware/cache/cache_test.go:897-897
Timestamp: 2024-11-08T04:10:42.990Z
Learning: In the Fiber framework, `Context()` is being renamed to `RequestCtx()`, and `UserContext()` to `Context()` to improve clarity and align with Go's context conventions.

Applied to files:

  • ctx.go
  • req.go
  • ctx_interface_gen.go
  • docs/api/ctx.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:

  • ctx.go
  • req.go
📚 Learning: 2025-12-07T15:07:23.885Z
Learnt from: CR
Repo: gofiber/fiber PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-07T15:07:23.885Z
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:

  • req.go
📚 Learning: 2024-09-25T15:57:10.221Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 3016
File: middleware/csrf/csrf_test.go:188-193
Timestamp: 2024-09-25T15:57:10.221Z
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:

  • req.go
  • docs/api/ctx.md
🧬 Code graph analysis (2)
ctx.go (2)
constants.go (1)
  • HeaderXRequestID (282-282)
client/client.go (1)
  • Get (817-819)
req.go (3)
ctx.go (5)
  • DefaultCtx (53-75)
  • DefaultCtx (141-143)
  • DefaultCtx (153-155)
  • DefaultCtx (161-163)
  • DefaultCtx (497-499)
constants.go (7)
  • HeaderAcceptLanguage (193-193)
  • HeaderAcceptEncoding (192-192)
  • MIMEApplicationJSON (25-25)
  • MIMEApplicationForm (28-28)
  • MIMETextHTML (20-20)
  • MIMEApplicationXML (24-24)
  • MIMETextXML (19-19)
binder/form.go (1)
  • MIMEMultipartForm (11-11)
🪛 LanguageTool
docs/api/ctx.md

[grammar] ~1038-~1038: Ensure spelling is correct
Context: ...("X-Trace-Id") return nil }) ``` ### Referer Returns the Referer request header. `...

(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)

🔇 Additional comments (14)
ctx.go (1)

293-299: LGTM! RequestID implementation is clean.

The fallback logic (response header → request header) correctly handles both middleware-generated IDs and client-provided IDs. This aligns with common request tracing patterns.

req.go (6)

203-214: LGTM! FullURL implementation uses bytebufferpool correctly.

The implementation properly uses bytebufferpool with defer for cleanup, addressing the previous review feedback about zero-allocation string building. The URL construction order (scheme + host + original URL) is correct.


216-234: LGTM! Header accessor methods are consistent and zero-allocation.

The UserAgent(), Referer(), AcceptLanguage(), and AcceptEncoding() methods correctly use c.app.toString() for zero-allocation string handling, consistent with the codebase patterns.


236-239: LGTM! HasHeader correctly checks header presence.

Using len(...) > 0 on Peek() is the appropriate way to check header existence in fasthttp.


241-252: LGTM! MediaType correctly extracts MIME type.

The implementation properly handles edge cases with whitespace around the semicolon separator.


254-297: LGTM! Charset parsing is thorough and handles edge cases.

The implementation correctly:

  • Uses bytes.EqualFold for case-insensitive parameter name matching (as suggested in previous review)
  • Handles quoted charset values
  • Properly iterates through multiple parameters
  • Returns empty string for missing/invalid charsets

299-312: LGTM! Content-type check methods are correct.

Using utils.EqualFold with MIME constants ensures case-insensitive matching per HTTP spec. As per coding guidelines, github.com/gofiber/utils/v2 helpers are preferred for string operations.

ctx_interface_gen.go (2)

98-99: LGTM! Interface declaration for RequestID.

The interface method signature and documentation correctly match the implementation in ctx.go.


176-205: LGTM! Interface declarations for new request helper methods.

All new methods are properly declared with consistent documentation. The interface accurately reflects the implementations in req.go.

docs/api/ctx.md (5)

727-793: LGTM! Documentation for Accepts helper methods.*

Each method has its own headline (addressing previous review feedback), with clear signatures and examples. The AcceptsXML example correctly shows it returns false when the Accept header doesn't include XML types.


812-827: LGTM! FullURL documentation is clear.

The example accurately demonstrates the method's behavior, showing the full URL including query string.


993-1066: LGTM! Header accessor method documentation.

The AcceptEncoding, AcceptLanguage, HasHeader, Referer, and UserAgent methods are well documented with appropriate examples.

Note: The "Referer" spelling is intentional - it matches the HTTP specification's historical misspelling of "Referrer".


1141-1152: LGTM! RequestID documentation.

The example clearly shows the expected return value format (UUID).


1200-1283: LGTM! Content-Type helper method documentation.

The Charset, IsForm, IsJSON, IsMultipart, and MediaType methods are thoroughly documented with practical examples showing the Content-Type header context.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.


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.

@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 significantly enhances the Ctx interface by introducing a comprehensive set of helper methods. These additions aim to simplify common operations related to HTTP request headers, content types, and URL construction, reducing boilerplate code and improving developer experience. The changes promote more consistent and efficient handling of HTTP request details within the application, making it easier for developers to interact with request information.

Highlights

  • New Ctx Header Helpers: Introduced a suite of new Ctx helper methods for streamlined access to common request headers, including RequestID, UserAgent, Referer, AcceptLanguage, AcceptEncoding, and HasHeader.
  • New Ctx Content-Type Helpers: Added Ctx helper methods to easily parse and check Content-Type headers, such as MediaType, Charset, IsJSON, IsForm, and IsMultipart.
  • New Ctx Accept Header Helpers: Provided Ctx helper methods for Accept header checks, including AcceptsJSON, AcceptsHTML, AcceptsXML, and AcceptsEventStream.
  • FullURL Method: Implemented FullURL on Ctx for consistent, zero-allocation retrieval of the complete request URL.
  • Expanded Test Coverage: Expanded test coverage in ctx_test.go to validate the functionality and case-insensitivity of the new header and content-type helpers, as well as typed parsing defaults.
  • Updated Documentation: Updated API documentation (docs/api/ctx.md) and the 'What's New' guide (docs/whats_new.md) to reflect the newly added Ctx methods and provide usage examples.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

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.

@ReneWerner87 ReneWerner87 added this to v3 Jan 14, 2026
@ReneWerner87 ReneWerner87 added this to the v3 milestone Jan 14, 2026
@gaby gaby changed the title chore: add Ctx header/content-type/accept helpers, FullURL, tests & docs 🧹 chore: Add context common helpers Jan 14, 2026
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 introduces a set of convenient helper methods on Ctx for handling common HTTP headers, content types, and URLs. The changes are well-tested and documented. My review focuses on improving the performance of a couple of these new helpers to better align with the goal of providing low-allocation utilities.

@codecov
Copy link

codecov bot commented Jan 14, 2026

Codecov Report

❌ Patch coverage is 97.36842% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.07%. Comparing base (c64599e) to head (04db995).
⚠️ Report is 9 commits behind head on main.

Files with missing lines Patch % Lines
req.go 97.22% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4007      +/-   ##
==========================================
- Coverage   91.09%   91.07%   -0.03%     
==========================================
  Files         119      119              
  Lines       10863    10946      +83     
==========================================
+ Hits         9896     9969      +73     
- Misses        610      618       +8     
- Partials      357      359       +2     
Flag Coverage Δ
unittests 91.07% <97.36%> (-0.03%) ⬇️

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.

@gaby gaby marked this pull request as ready for review January 15, 2026 01:12
@gaby gaby requested a review from a team as a code owner January 15, 2026 01:12
@gaby gaby moved this to In Progress in v3 Jan 15, 2026
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 adds convenient zero-allocation helper methods to the Ctx interface for common request header and content-type operations, improving developer experience and reducing boilerplate code in handlers and middleware.

Changes:

  • Added 17 new helper methods to DefaultCtx for common HTTP header and content-type checks
  • Implemented comprehensive test coverage with unit tests and edge case handling
  • Updated documentation in both API docs and what's new guide

Reviewed changes

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

Show a summary per file
File Description
ctx.go Implements 17 new helper methods including FullURL, RequestID, header accessors, media type helpers, and Accept header checkers
ctx_interface_gen.go Exposes the new helper methods on the Ctx interface with proper documentation
ctx_test.go Adds comprehensive test coverage with 4 new test functions covering all new helpers and edge cases
docs/api/ctx.md Documents the new helper methods with code examples organized into logical sections
docs/whats_new.md Lists all 17 new methods in the what's new documentation

Copy link
Member

@ReneWerner87 ReneWerner87 left a comment

Choose a reason for hiding this comment

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

@gaby nice idea
can you check my comments

@gaby gaby changed the title 🧹 chore: Add context common helpers 🔥 feat: Add context common helpers Jan 15, 2026
@gaby gaby changed the title 🔥 feat: Add context common helpers 🔥 feat: Add context common request helpers Jan 15, 2026
@ReneWerner87 ReneWerner87 merged commit b32523b into main Jan 15, 2026
18 checks passed
@github-project-automation github-project-automation bot moved this from In Progress to Done in v3 Jan 15, 2026
@ReneWerner87 ReneWerner87 deleted the add-full-suite-of-helper-methods-in-ctx.go branch January 15, 2026 15:16
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