Repository navigation
🧹 chore: consolidate media-type parameter parsing into internal/mediatype - #4750
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info
WalkthroughThe 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. ChangesMedia-Type Parsing Consolidation
Priority: ➖ Normal Estimated code review effort: 3 (Moderate) | ~20 minutes Change: Refactor Suggested reviewers: Merge Risk: ⚪ Minimal · up to
|
There was a problem hiding this comment.
🟢 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 Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
ReneWerner87
left a comment
There was a problem hiding this comment.
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.
- Keep the PR as is. One generic helper, 1.2 to 1.6 ns per call.
- Keep the helper, drop one frame.
StripParams([]byte) []bytewithbytes.IndexByteinstead ofutils.CutByte;Ishands it the header bytes, etag converts withutils.UnsafeBytes. About 0.3 ns per call. Code is in the fold below. - Write the cut inline at the three call sites. No helper, three lines per site. Faster than main, because main trims twice and
Isno longer goes throughtoString(one allocation perIscall underImmutable: 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)|
@ReneWerner87 thanks for measuring all three. I'd go with 2: it keeps the param strip in @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. |
|
I think the media type ones should be in gofiber/utils, @ReneWerner87 ? |
|
@gaby happy to go either way. If they belong in gofiber/utils, I can move |
|
@gaby I'd leave them in They're also not really generic. 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. |
|
Thanks both. Applied option 2 and merged main. |
ReneWerner87
left a comment
There was a problem hiding this comment.
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.
|
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 |
Description
Cluster 7 of #4604: media-type parameters.
internal/mediatypenow owns quoted-pair unescaping, parameter iteration and parameter stripping.UnescapereplacesunescapeHeaderValue(helpers.go) and the cache middleware'sunquoteCacheDirective. The two disagreed on a trailing lone backslash: core rejected it, cache kept it.Unescapekeeps the byte and reports it throughok, so each caller behaves exactly as before.Paramsis the quote-aware parameter walk that lived insideCharset.Charsetkeeps only its own validation.StripParamsreplaces the hand-written cut-and-trim inMediaType,Isand etag'sisEventStream.Left alone:
NormalizeRequestContentTypekeeps its own walk, since its quote rules differ fromCharset's and merging them would change behavior.forEachMediaRangeis a comma-list scanner and belongs to cluster 5.Related #4604
Changes introduced
Ctx_MediaType4.47 → 5.51 ns andCtx_Is15.96 → 17.97 ns, becauseStripParamsisn't inlined.Ctx_Charset−3.7% to +5.4% across cases;GetOffer,Accepts,parseCacheControlDirectivesandEtagwithin noise. AddedBenchmark_Ctx_CharsetandBenchmark_Ctx_MediaType.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/Is16.3M execs,getOffer/paramsMatch11.4M,parseCacheControlDirectives12.2M (including nil vs empty values),Unescapeagainst both old unescapers 21.0M. No differences.Type of change
Checklist
internal/mediatypeis at 100% coverage; the old unescaper tests moved there.make test,make lint(0 issues),make generate,make betteralign,make format, andmake audit GOVERSION=go1.26.9.🤖 Maintainers:
/generatere-runs the code generators on this branch