-
Notifications
You must be signed in to change notification settings - Fork 4
/
uri_source_cache.go
79 lines (67 loc) · 1.82 KB
/
uri_source_cache.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
package altsrc
import (
"fmt"
"io"
"net/http"
"net/url"
"os"
"runtime"
"strings"
)
func readURI(uriString string) ([]byte, error) {
u, err := url.Parse(uriString)
if err != nil {
return nil, err
}
if u.Host != "" { // i have a host, now do i support the scheme?
switch u.Scheme {
case "http", "https":
res, err := http.Get(uriString)
if err != nil {
return nil, err
}
return io.ReadAll(res.Body)
default:
return nil, fmt.Errorf("%[1]w: scheme of %[2]q is unsupported", Err, uriString)
}
} else if u.Path != "" ||
(runtime.GOOS == "windows" && strings.Contains(u.String(), "\\")) {
if _, notFoundFileErr := os.Stat(uriString); notFoundFileErr != nil {
return nil, fmt.Errorf("%[1]w: cannot read from %[2]q because it does not exist", Err, uriString)
}
return os.ReadFile(uriString)
}
return nil, fmt.Errorf("%[1]w: unable to determine how to load from %[2]q", Err, uriString)
}
type URISourceCache[T any] struct {
file string
m *T
unmarshaller func([]byte, any) error
}
func NewURISourceCache[T any](file string, f func([]byte, any) error) *URISourceCache[T] {
return &URISourceCache[T]{
file: file,
unmarshaller: f,
}
}
func (fsc *URISourceCache[T]) Get() T {
if fsc.m == nil {
res := new(T)
if b, err := readURI(fsc.file); err != nil {
tracef("failed to read uri %[1]q: %[2]v", fsc.file, err)
} else if err := fsc.unmarshaller(b, res); err != nil {
tracef("failed to unmarshal from file %[1]q: %[2]v", fsc.file, err)
} else {
fsc.m = res
}
}
if fsc.m == nil {
tracef("returning empty")
return *(new(T))
}
return *fsc.m
}
type MapAnyAnyURISourceCache = URISourceCache[map[any]any]
func NewMapAnyAnyURISourceCache(file string, f func([]byte, any) error) *MapAnyAnyURISourceCache {
return NewURISourceCache[map[any]any](file, f)
}