-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsource.go
70 lines (57 loc) · 1.39 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
package flowconf
import (
"embed"
"fmt"
"io"
"os"
"strings"
)
// Format represents a string type that specifies a format.
type Format string
const (
unknown Format = "unknown"
Toml Format = "toml"
Json Format = "json"
)
// StaticSource represent a config input
type StaticSource struct {
name string
format Format
reader io.ReadCloser
}
func NewSource(name string, format Format, reader io.ReadCloser) *StaticSource {
return &StaticSource{
name: name,
format: format,
reader: reader,
}
}
func NewSourcesFromFilepaths(filepaths ...string) ([]*StaticSource, error) {
return LoadSourcesWithOpener(osOpener(os.Open), filepaths...)
}
func NewSourcesFromEmbeddedFileSystem(fs embed.FS, filepaths ...string) ([]*StaticSource, error) {
return LoadSourcesWithOpener(embeddedOpener(fs.Open), filepaths...)
}
func LoadSourcesWithOpener(opener Opener, filepaths ...string) ([]*StaticSource, error) {
var sources []*StaticSource
for _, filepath := range filepaths {
f, err := opener.Open(filepath)
if err != nil {
return nil, err
}
sources = append(sources, NewSource(filepath, detectFormat(filepath), f))
if err != nil {
return nil, fmt.Errorf("failed to close opener, %w", err)
}
}
return sources, nil
}
func detectFormat(str string) Format {
if strings.HasSuffix(str, ".toml") {
return Toml
}
if strings.HasSuffix(str, ".json") {
return Json
}
return unknown
}