要支持续传,响应先带 Accept-Ranges: bytes。
解析 Range 头里的起止字节,越界回 416。
命中片段返回 206,回 200 客户端会从头重下。
Content-Range 写清起止和文件总长。
没有 Range 头才走完整下载,并按总长回。
# 请求
GET /files/report.zip
Range: bytes=1024-2047
# 响应
HTTP/1.1 206 Partial Content
Accept-Ranges: bytes
Content-Range: bytes 1024-2047/10485760
Content-Length: 1024
# 服务端解析要点(伪代码)
rng = req.headers.get("Range") # bytes=1024-2047
unit, _, spec = rng.partition("=") # spec = "1024-2047"
s, _, e = spec.partition("-")
start = int(s or 0)
end = int(e) if e else size - 1
if start >= size or end < start:
return 416, {"Content-Range": "bytes */%d" % size}
length = end - start + 1 # 按实际区间算,别信客户端跨度
THE END






暂无评论内容