[ADP-125] Content-Range
概述
Content-Range
標頭指定在部分回應中返回資源的哪一部分,或在無法滿足範圍請求時告知客戶端資源的總大小。這個功能對於涉及大型檔案下載或串流的場景特別有用,確保有效利用頻寬並提供更好的數據傳輸過程控制。 在設計支援範圍請求的 API 時,必須遵守 RFC 9110 中概述的規範。Content-Range
標頭應僅與 206 Partial Content
回應一起使用,表示成功的部分內容傳遞,或與 416 Range Not Satisfiable
回應一起使用,表示請求的範圍無效。
指導
當 API 設計為支援範圍請求並成功回應時,應返回 Content-Range。
httpContent-Range: bytes 0-499/1234 Content-Range: bytes 500-999/1234 Content-Range: bytes 500-1233/*
當範圍請求 API 無法滿足請求時,應返回 Content-Range(如 RFC 9110 所建議)。
httpHTTP/1.1 416 Range Not Satisfiable Content-Range: bytes */1234
如 RFC 9110 所規定,該標頭應僅與 206 或 416 回應一起使用。
實現細節
語法
Content-Range
標頭具有以下語法:
http
Content-Range: <unit> <range-start>-<range-end>/<size>
Content-Range: <unit> <range-start>-<range-end>/
Content-Range: <unit> /<size>
<unit>
: 範圍的測量單位(通常為 "bytes")。<range-start>
: 範圍的起始位置。<range-end>
: 範圍的結束位置。<size>
: 資源的總大小,如果未知則為 "*"。
與 206 Partial Content 一起使用
當回應部分內容時,包含 Content-Range
標頭以指定正在發送的範圍:
http
Content-Range: bytes 0-499/1234
Content-Range: bytes 500-999/1234
Content-Range: bytes 500-1233/*
與 416 Range Not Satisfiable 一起使用
當範圍請求無法滿足時,包含 Content-Range
標頭以告知客戶端資源的總大小:
http
HTTP/1.1 416 Range Not Satisfiable
Content-Range: bytes */1234
Content-Type: application/problem+json
{
"title": "Range Not Satisfiable",
"detail": "The range specified is not valid for the resource.",
"status": 416
}
示例
OpenAPI 3.1.0 示例
yaml
openapi: 3.1.0
info:
title: Range Request API
version: 1.0.0
paths:
/resource:
get:
summary: Get partial content
parameters:
- name: Range
in: header
required: true
schema:
type: string
example: bytes=0-499
responses:
'206':
description: Partial Content
headers:
Content-Range:
description: Indicates the range of bytes returned
schema:
type: string
example: bytes 0-499/1234
content:
application/octet-stream:
schema:
type: string
format: binary
'416':
description: Range Not Satisfiable
headers:
Content-Range:
description: Indicates the size of the full resource
schema:
type: string
example: bytes */1234
content:
application/problem+json:
schema:
type: object
properties:
type:
type: string
format: uri
example: https://example.com/probs/range-not-satisfiable
title:
type: string
example: 範圍不滿足
status:
type: integer
example: 416
detail:
type: string
example: 指定的範圍對於該資源無效。
instance:
type: string
format: uri
example: /resource?id=123