Skip to content

Commit fc803ec

Browse files
🐛 bug: Fix Range() handling of HTTP 416 per RFC 9110 (#3552)
* fix range compliance * Update ctx.go Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> * Update ctx.go --------- Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
1 parent 9d683ba commit fc803ec

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

ctx.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1384,7 +1384,9 @@ func (c *DefaultCtx) Range(size int) (Range, error) {
13841384
})
13851385
}
13861386
if len(rangeData.Ranges) < 1 {
1387-
return rangeData, ErrRangeUnsatisfiable
1387+
c.Status(StatusRequestedRangeNotSatisfiable)
1388+
c.Set(HeaderContentRange, "bytes */"+strconv.Itoa(size))
1389+
return rangeData, ErrRequestedRangeNotSatisfiable
13881390
}
13891391

13901392
return rangeData, nil

ctx_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2991,6 +2991,25 @@ func Test_Ctx_Range(t *testing.T) {
29912991
testRange("seconds=0-1")
29922992
}
29932993

2994+
func Test_Ctx_Range_Unsatisfiable(t *testing.T) {
2995+
t.Parallel()
2996+
app := New()
2997+
app.Get("/", func(c Ctx) error {
2998+
_, err := c.Range(10)
2999+
if err != nil {
3000+
return err
3001+
}
3002+
return c.SendString("ok")
3003+
})
3004+
3005+
req := httptest.NewRequest(MethodGet, "http://example.com/", nil)
3006+
req.Header.Set(HeaderRange, "bytes=20-30")
3007+
resp, err := app.Test(req)
3008+
require.NoError(t, err)
3009+
require.Equal(t, StatusRequestedRangeNotSatisfiable, resp.StatusCode)
3010+
require.Equal(t, "bytes */10", resp.Header.Get(HeaderContentRange))
3011+
}
3012+
29943013
// go test -v -run=^$ -bench=Benchmark_Ctx_Range -benchmem -count=4
29953014
func Benchmark_Ctx_Range(b *testing.B) {
29963015
app := New()

docs/api/ctx.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1216,6 +1216,9 @@ Returns a struct containing the type and a slice of ranges.
12161216
Only the canonical `bytes` unit is recognized and any optional
12171217
whitespace around range specifiers will be ignored, as specified
12181218
in RFC 9110.
1219+
If none of the requested ranges are satisfiable, the method automatically
1220+
sets the HTTP status code to **416 Range Not Satisfiable** and populates the
1221+
`Content-Range` header with the current representation size.
12191222

12201223
```go title="Signature"
12211224
func (c fiber.Ctx) Range(size int) (Range, error)

0 commit comments

Comments
 (0)