-
Notifications
You must be signed in to change notification settings - Fork 4
/
source.go
91 lines (80 loc) · 2.01 KB
/
source.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
package keys
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"os"
"time"
)
// Source represents one or a chain of sources
type Source interface {
Get(ctx context.Context) ([]byte, error)
}
// Sources defines a chain of sources
type Sources []Source
// Get iterates sources and returns the first successfully resolved
func (sources Sources) Get(ctx context.Context) ([]byte, error) {
for _, source := range sources {
bts, err := source.Get(ctx)
if err == nil {
return bts, nil
}
}
return nil, ErrNoSourcesResolved
}
const (
httpTimeout = 10 * time.Second
)
// HTTPSource defines a source with a URL to resolve over HTTP
type HTTPSource string
// Get retrieves data from the URL over HTTP
func (source HTTPSource) Get(ctx context.Context) ([]byte, error) {
if source == "" {
return nil, ErrEmptyURL
}
req, err := http.NewRequest(http.MethodGet, string(source), nil)
if err != nil {
return nil, ErrGetKeySource{err}
}
req = req.WithContext(ctx)
client := &http.Client{
Timeout: httpTimeout,
}
res, err := client.Do(req)
if err != nil {
return nil, ErrGetKeySource{err}
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, ErrGetKeySource{fmt.Sprintf("got status code %d got %d", http.StatusOK, res.StatusCode)}
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, ErrReadResponse{err}
}
return body, nil
}
// FileSource defines a path to a file on disk
type FileSource string
// Get retrieves data from the path to a file on disk
func (source FileSource) Get(ctx context.Context) ([]byte, error) {
if source == "" {
return nil, ErrEmptyFilePath
}
f, err := os.Open(string(source))
if err != nil {
return nil, ErrGetKeySource{err}
}
content, err := ioutil.ReadAll(f)
if err != nil {
return nil, ErrReadResponse{err}
}
return content, nil
}
// StringSource defines the source as a string
type StringSource string
// Get converts the string to a byte slice
func (source StringSource) Get(ctx context.Context) ([]byte, error) {
return []byte(source), nil
}