Skip to content

Commit 845f95f

Browse files
gabyReneWerner87
andauthored
🐛 bug: Fix Content-Type comparison in Is() (#3537)
* fix: improve Is content type matching * Update ctx.go --------- Co-authored-by: RW <rene@gofiber.io>
1 parent 1c037c4 commit 845f95f

2 files changed

Lines changed: 16 additions & 4 deletions

File tree

ctx.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -877,10 +877,12 @@ func (c *Ctx) Is(extension string) bool {
877877
return false
878878
}
879879

880-
return strings.HasPrefix(
881-
utils.TrimLeft(c.app.getString(c.fasthttp.Request.Header.ContentType()), ' '),
882-
extensionHeader,
883-
)
880+
ct := c.app.getString(c.fasthttp.Request.Header.ContentType())
881+
if i := strings.IndexByte(ct, ';'); i != -1 {
882+
ct = ct[:i]
883+
}
884+
ct = utils.Trim(ct, ' ')
885+
return utils.EqualFold(ct, extensionHeader)
884886
}
885887

886888
// JSON converts any interface or string to JSON.

ctx_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2091,6 +2091,16 @@ func Test_Ctx_Is(t *testing.T) {
20912091
utils.AssertEqual(t, false, c.Is("html"))
20922092
utils.AssertEqual(t, true, c.Is("txt"))
20932093
utils.AssertEqual(t, true, c.Is(".txt"))
2094+
2095+
// case-insensitive and trimmed
2096+
c.Request().Header.Set(HeaderContentType, "APPLICATION/JSON; charset=utf-8")
2097+
utils.AssertEqual(t, true, c.Is("json"))
2098+
utils.AssertEqual(t, true, c.Is(".json"))
2099+
2100+
// mismatched subtype should not match
2101+
c.Request().Header.Set(HeaderContentType, "application/json+xml")
2102+
utils.AssertEqual(t, false, c.Is("json"))
2103+
utils.AssertEqual(t, false, c.Is(".json"))
20942104
}
20952105

20962106
// go test -v -run=^$ -bench=Benchmark_Ctx_Is -benchmem -count=4

0 commit comments

Comments
 (0)