-
Notifications
You must be signed in to change notification settings - Fork 302
/
http.go
96 lines (86 loc) · 2.38 KB
/
http.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Copyright © 2019 The Things Network Foundation, The Things Industries B.V.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package fetch
import (
"io/ioutil"
"net/http"
"net/url"
"path"
"time"
"github.com/gregjones/httpcache"
"go.thethings.network/lorawan-stack/v3/pkg/errors"
)
type httpFetcher struct {
baseFetcher
httpClient *http.Client
root *url.URL
}
func (f httpFetcher) File(pathElements ...string) ([]byte, error) {
if len(pathElements) == 0 {
return nil, errFilenameNotSpecified.New()
}
start := time.Now()
p := path.Join(pathElements...)
url, err := realURLPath(f.root, p)
if err != nil {
return nil, err
}
resp, err := f.httpClient.Get(url)
if err != nil {
return nil, errCouldNotFetchFile.WithCause(err).WithAttributes("filename", p)
}
if err = errors.FromHTTP(resp); err != nil {
return nil, errCouldNotFetchFile.WithCause(err).WithAttributes("filename", p)
}
defer resp.Body.Close()
result, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errCouldNotReadFile.WithCause(err).WithAttributes("filename", p)
}
f.observeLatency(time.Since(start))
return result, nil
}
// FromHTTP returns an object to fetch files from a webserver.
func FromHTTP(client *http.Client, rootURL string, cache bool) (Interface, error) {
if client == nil {
client = http.DefaultClient
}
if cache {
cp := *client
client = &cp
client.Transport = &httpcache.Transport{
Transport: client.Transport,
Cache: httpcache.NewMemoryCache(),
MarkCachedResponses: true,
}
}
var root *url.URL
if rootURL != "" {
var err error
root, err = url.Parse(rootURL)
if err != nil {
return nil, err
}
if !root.IsAbs() {
return nil, errSchemeNotSpecified.New()
}
}
return httpFetcher{
baseFetcher: baseFetcher{
latency: fetchLatency.WithLabelValues("http", rootURL),
},
httpClient: client,
root: root,
}, nil
}