backend/http: support content-range response header

This commit is contained in:
Arnie97
2022-03-20 18:12:48 +08:00
committed by Nick Craig-Wood
parent ebac854512
commit 6a5b7664f7
5 changed files with 146 additions and 58 deletions

39
lib/rest/headers.go Normal file
View File

@@ -0,0 +1,39 @@
package rest
import (
"net/http"
"strconv"
"strings"
)
// ParseSizeFromHeaders parses HTTP response headers to get the full file size.
// Returns -1 if the headers did not exist or were invalid.
func ParseSizeFromHeaders(headers http.Header) (size int64) {
size = -1
var contentLength = headers.Get("Content-Length")
if len(contentLength) != 0 {
var err error
if size, err = strconv.ParseInt(contentLength, 10, 64); err != nil {
return -1
}
}
var contentRange = headers.Get("Content-Range")
if len(contentRange) == 0 {
return size
}
if !strings.HasPrefix(contentRange, "bytes ") {
return -1
}
slash := strings.IndexRune(contentRange, '/')
if slash < 0 {
return -1
}
ret, err := strconv.ParseInt(contentRange[slash+1:], 10, 64)
if err != nil {
return -1
}
return ret
}