Skip to content

🧹 chore: consolidate media-type parameter parsing into internal/mediatype - #4750

Merged
ReneWerner87 merged 4 commits into
gofiber:mainfrom
ninadsutrave:chore/internal-mediatype
Oct 14, 2026
Merged

ReneWerner87 merged 4 commits into
gofiber:mainfrom
ninadsutrave:chore/internal-mediatype

Conversation

@ninadsutrave

@ninadsutrave ninadsutrave commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Description

Cluster 7 of #4604: media-type parameters. internal/mediatype now owns quoted-pair unescaping, parameter iteration and parameter stripping.

  • Unescape replaces unescapeHeaderValue (helpers.go) and the cache middleware's unquoteCacheDirective. The two disagreed on a trailing lone backslash: core rejected it, cache kept it. Unescape keeps the byte and reports it through ok, so each caller behaves exactly as before.
  • Params is the quote-aware parameter walk that lived inside Charset. Charset keeps only its own validation.
  • StripParams replaces the hand-written cut-and-trim in MediaType, Is and etag's isEventStream.

Left alone: NormalizeRequestContentType keeps its own walk, since its quote rules differ from Charset's and merging them would change behavior. forEachMediaRange is a comma-list scanner and belongs to cluster 5.

Related #4604

Changes introduced

  • Benchmarks: benchstat, 10 interleaved runs, allocations unchanged everywhere. Ctx_MediaType 4.47 → 5.51 ns and Ctx_Is 15.96 → 17.97 ns, because StripParams isn't inlined. Ctx_Charset −3.7% to +5.4% across cases; GetOffer, Accepts, parseCacheControlDirectives and Etag within noise. Added Benchmark_Ctx_Charset and Benchmark_Ctx_MediaType.
  • Documentation Update: not needed, internal only.

No behavior change. Like #4653 and #4735, I fuzzed each rewritten path against a verbatim copy of main with throwaway harnesses that aren't in the diff: Charset/MediaType/Is 16.3M execs, getOffer/paramsMatch 11.4M, parseCacheControlDirectives 12.2M (including nil vs empty values), Unescape against both old unescapers 21.0M. No differences.

Type of change

  • Code consistency (non-breaking change which improves code reliability and robustness)

Checklist

  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Added or updated unit tests to validate the effectiveness of the changes or new features. internal/mediatype is at 100% coverage; the old unescaper tests moved there.
  • Ensured that new and existing unit tests pass locally with the changes. make test, make lint (0 issues), make generate, make betteralign, make format, and make audit GOVERSION=go1.26.9.
  • Aimed for optimal performance with minimal allocations in the new code.
  • Provided benchmarks for the new code to analyze and improve upon.

🤖 Maintainers: /generate re-runs the code generators on this branch

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-12T04:50:50.723033Z d8242d0 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f16d7083-76ee-4cb6-870b-2720f0a9e359
📥 Commits

Reviewing files that changed from the base of the PR and between 3229111 and 1306948.

📒 Files selected for processing (5)
  • internal/mediatype/mediatype.go
  • internal/mediatype/mediatype_test.go
  • middleware/cache/cache_test.go
  • middleware/etag/etag.go
  • req.go
💤 Files with no reviewable changes (1)
  • middleware/cache/cache_test.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Walkthrough

The change adds shared media-type parsing and unescaping functions. Request handling, helper matching, and middleware use these functions. Tests and benchmarks cover the shared functions and request methods.

Changes

Media-Type Parsing Consolidation

Layer / File(s) Summary
Shared media-type parsing
internal/mediatype/*
Adds functions to strip media-type parameters, iterate over parameters, and unescape values. Adds tests and benchmarks for these functions.
Request media-type parsing
req.go, ctx_test.go
Request methods use the shared parsing functions. Charset tests cover a quoted value ending in a backslash, and benchmarks measure charset and media-type extraction.
Helper and middleware adoption
helpers.go, errors_internal.go, helpers_test.go, middleware/cache/*, middleware/etag/etag.go
Helper matching and cache directive parsing use shared unescaping. ETag event-stream detection uses shared parameter stripping. Removes local unescape helpers and their tests.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Suggested reviewers: claude

Merge Risk: ⚪ Minimal · up to 13069

No material behavior change requiring a fix was established; the PR is mergeable after normal checks.

Security architecture risk: ⚪ Minimal · up to 13069

The shared parser preserves the existing callers, validation decisions, and header-handling outcomes. The review found no material security risk introduced or worsened by this consolidation.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The relevant exposure remains header-controlled request classification, charset extraction, content negotiation, cache directive interpretation, and response event-stream classification. Consolidation couples these consumers to one implementation but adds no new caller authority or trust transition in the inspected paths.

Trust Boundaries and Controls

  • observed — Source comparison shows that malformed escape rejection remains at Charset and negotiation consumers. Cache parsing still strips surrounding quotes before unescaping and retains its previous tolerance. The shared parser therefore does not replace these distinct policies with weaker universal acceptance.
Pre-merge checks · Passed 4 · Failed 1

Failed Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 73.91% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks (4 passed)
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: consolidating media-type parameter parsing in internal/mediatype.
Description check Passed The description explains the purpose, affected components, behavior compatibility, benchmarks, tests, fuzzing, and checklist status. It identifies the related issue and explains why documentation and …
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

A rabbit checks the headers with care,
Finds semicolons tucked in there.
Escaped quotes now pass along,
Backslashes keep their proper song.
The tests hop through each parsing case,
Then benchmark at a steady pace.

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

The consolidation preserves existing behavior and includes focused coverage for the extracted functionality.

0 open findings

What changed in this PR

Consolidates media-type parameter parsing into internal/mediatype without changing behavior.

Changes:

  • Adds shared parameter stripping, iteration, and quoted-pair unescaping.
  • Migrates request, cache, negotiation, and ETag handling.
  • Moves relevant tests and adds benchmarks.
File Description
req.go Uses shared media-type helpers.
helpers.go Reuses shared unescaping.
errors_internal.go Removes obsolete error.
ctx_test.go Adds request-helper benchmarks.
helpers_test.go Removes migrated tests.
internal/​mediatype/​mediatype.go Implements consolidated parsing helpers.
internal/​mediatype/​mediatype_test.go Tests and benchmarks new helpers.
middleware/​cache/​cachecontrol.go Reuses shared unescaping.
middleware/​cache/​cache_test.go Removes obsolete helper tests.
middleware/​etag/​etag.go Reuses parameter stripping.

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@codecov

codecov Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.71429% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 95.32%. Comparing base (9438d7e) to head (1306948).

Files with missing lines Patch % Lines
helpers.go 50.00% 0 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4750      +/-   ##
==========================================
+ Coverage   95.30%   95.32%   +0.01%     
==========================================
  Files         142      142              
  Lines       18028    17941      -87     
==========================================
- Hits        17182    17102      -80     
+ Misses        530      526       -4     
+ Partials      316      313       -3     
Flag Coverage Δ
unittests 95.32% <85.71%> (+0.01%) ⬆️

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

☔ View full report in Codecov by Harness.
📢 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 ReneWerner87 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Checked 3229111 against its merge base.

Behavior. Differential runs of the new code against verbatim copies of the old: Charset/MediaType/Is 1.8M execs, Unescape against both old unescapers 4.8M execs. No difference. Unescape and Params are neutral in time and allocations too.

codecov/patch. The two remaining lines are the !ok branches in paramsMatch and getOffer. They cannot be reached: fasthttp.VisitHeaderParams passes either a token (a backslash is not a token byte) or the inside of a quoted-string that ends at the first unescaped quote, and it returns without calling the visitor on an unterminated one. Both are uncovered on main as well, so nothing to add.

Performance. The one cost is StripParams. On main MediaType calls bytealg.IndexByte and nothing else. Here it is MediaType -> StripParams -> utils.CutByte -> bytealg.IndexByte: neither helper fits the inline budget (cost 151 and 100, budget 80), and CutByte also builds the after slice that StripParams drops.

I measured three ways to go (benchstat, 12 interleaved runs, arm64, all four columns from one run, allocations unchanged):

main 1. PR as is 2. helper kept, one frame less 3. cut written inline
MediaType 6.61 ns 7.81 ns (+17% to +22%) 6.90 ns (+4% to +5%) 6.25 ns (-4% to -6%)
Is 13.11 ns 14.67 ns (+12% to +14%) 13.47 ns (+3% to +4%) 12.86 ns (-2% to -3%)
IsJSON 9.58 ns 10.76 ns (+12% to +15%) 9.94 ns (+3% to +6%) 9.29 ns (-3% to -5%)
Benchmark_Etag 117.1 ns 119.1 ns (+1.7%) 118.6 ns (+1.2%) 116.9 ns (~)
geomean, 19 cases +14.9% +3.7% -3.7%

The ns values are the application/json case, the ranges cover six Content-Type shapes.

  1. Keep the PR as is. One generic helper, 1.2 to 1.6 ns per call.
  2. Keep the helper, drop one frame. StripParams([]byte) []byte with bytes.IndexByte instead of utils.CutByte; Is hands it the header bytes, etag converts with utils.UnsafeBytes. About 0.3 ns per call. Code is in the fold below.
  3. Write the cut inline at the three call sites. No helper, three lines per site. Faster than main, because main trims twice and Is no longer goes through toString (one allocation per Is call under Immutable: true, on main as well).

1 and 2 keep the param strip in internal/mediatype, which is what #4604 asks for in cluster 7. 3 gives that up and is the only one without a cost. A helper that inlines is not really available: the only shape that fits lands exactly on the budget (80 of 80) and modernize rejects it, and the shape the linter accepts costs 81.

@ninadsutrave @gofiber/maintainers which way do you prefer?

The suggestion blocks below are option 3, so it is one batch if we go that way; no need to apply them before this is settled. With the four applied, the root package, internal/mediatype, middleware/etag and middleware/cache pass, golangci-lint v2.12.2 reports 0 issues, and a differential fuzz against main's code (2.0M execs) finds no difference. StripParams, Test_StripParams and Benchmark_StripParams would then have no caller and can go.

Option 2 in code
// internal/mediatype
func StripParams(ct []byte) []byte {
	if i := bytes.IndexByte(ct, ';'); i >= 0 {
		ct = ct[:i]
	}
	return utils.TrimSpace(ct)
}

// req.go, Is
ct := mediatype.StripParams(r.c.fasthttp.Request.Header.ContentType())
return utils.EqualFold(utils.UnsafeString(ct), extensionHeader)

// middleware/etag, isEventStream
ct := mediatype.StripParams(utils.UnsafeBytes(c.GetRespHeader(fiber.HeaderContentType)))
return utils.EqualFold(utils.UnsafeString(ct), fiber.MIMETextEventStream)

Comment thread req.go Resolved
Comment thread req.go Resolved
Comment thread middleware/etag/etag.go Resolved
Comment thread middleware/etag/etag.go Resolved
@ninadsutrave

Copy link
Copy Markdown
Contributor Author

@ReneWerner87 thanks for measuring all three. I'd go with 2: it keeps the param strip in internal/mediatype, which is what cluster 7 asks for, so the cluster can be closed. MediaType/Is aren't on the default request path, so the ~0.3 ns only shows up when an app calls them, and since Is no longer goes through toString, it also drops the allocation under Immutable: true.

@gaby what do you think? If you'd rather keep these hand-written, as #4637 did for its hot paths, I'm happy to switch to 3. I'll hold off on changes until we settle it.

@gaby

gaby commented Oct 12, 2026

Copy link
Copy Markdown
Member

I think the media type ones should be in gofiber/utils, @ReneWerner87 ?

@ninadsutrave

Copy link
Copy Markdown
Contributor Author

@gaby happy to go either way. If they belong in gofiber/utils, I can move Unescape, Params and StripParams there in a separate PR first and switch this one over to use them. Let me know what you and @ReneWerner87 prefer.

@ReneWerner87

Copy link
Copy Markdown
Member

@gaby I'd leave them in internal/mediatype for now. Nothing outside this repo needs them: contrib, storage, template and recipes don't parse media-type params anywhere, and all callers here are core, cache and etag.

They're also not really generic. Unescape returns the trailing backslash plus an ok flag only because core and cache disagree on that case, and Params hands back the raw quoted values. I wouldn't want to freeze that as public API. And NormalizeRequestContentType needs fasthttp, so it would have to stay here anyway and we'd end up with the media-type code in two repos.

That's also what we wrote in #4604: internal for new helpers, utils only for generic byte primitives. If something else needs the quoted-pair unescape later, we can still move that one.

@ninadsutrave fine with option 2 from my side.

@ninadsutrave

Copy link
Copy Markdown
Contributor Author

Thanks both. Applied option 2 and merged main. Ctx_Is is within noise of main on my machine (16.4 vs 16.3 ns, p=0.39), and make lint / tests pass.

@ReneWerner87 ReneWerner87 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks. Re-checked 1306948 against main: MediaType is on par now, Is is about 0.4 ns slower and no longer allocates under Immutable. The red codecov/patch is the two !ok branches in paramsMatch/getOffer that VisitHeaderParams never reaches, same as on main.

@ReneWerner87
ReneWerner87 merged commit 9d6d7b6 into gofiber:main Oct 14, 2026
25 of 26 checks passed
@welcome

welcome Bot commented Oct 14, 2026

Copy link
Copy Markdown

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

@github-project-automation github-project-automation Bot moved this to Done in v3 Oct 14, 2026
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