/
parse.go
65 lines (51 loc) · 1.38 KB
/
parse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Copyright (c) The Thanos Authors.
// Licensed under the Apache License 2.0.
package clientutil
import (
"net/http"
"strconv"
"time"
"github.com/pkg/errors"
)
// ParseContentLength returns the content length (in bytes) parsed from the Content-Length
// HTTP header in input.
func ParseContentLength(m http.Header) (int64, error) {
const name = "Content-Length"
v, ok := m[name]
if !ok {
return 0, errors.Errorf("%s header not found", name)
}
if len(v) == 0 {
return 0, errors.Errorf("%s header has no values", name)
}
ret, err := strconv.ParseInt(v[0], 10, 64)
if err != nil {
return 0, errors.Wrapf(err, "convert %s", name)
}
return ret, nil
}
// ParseLastModified returns the timestamp parsed from the Last-Modified
// HTTP header in input.
// Passing an second parameter, named f, to specify the time format.
// If f is empty then RFC3339 will be used as default format.
func ParseLastModified(m http.Header, f string) (time.Time, error) {
const (
name = "Last-Modified"
defaultFormat = time.RFC3339
)
v, ok := m[name]
if !ok {
return time.Time{}, errors.Errorf("%s header not found", name)
}
if len(v) == 0 {
return time.Time{}, errors.Errorf("%s header has no values", name)
}
if len(f) == 0 {
f = defaultFormat
}
mod, err := time.Parse(f, v[0])
if err != nil {
return time.Time{}, errors.Wrapf(err, "parse %s", name)
}
return mod, nil
}