-
Notifications
You must be signed in to change notification settings - Fork 5
/
assets.go
61 lines (50 loc) · 1.04 KB
/
assets.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
package assets
import (
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
)
var vfs fs.FS
var Path string
const AssetPathConfig = "ASSET_PATH"
func init() {
cwd, err := os.Getwd()
if err != nil {
panic(err)
}
assetPath := "assets"
if os.Getenv(AssetPathConfig) != "" {
assetPath = os.Getenv(AssetPathConfig)
}
Path = FindFileInParents(assetPath, cwd)
vfs = os.DirFS(Path)
}
func Open(fileName string) (fs.File, error) {
return vfs.Open(fileName)
}
func ReadAll(fileName string) ([]byte, error) {
file, err := Open(fileName)
if err != nil {
return nil, fmt.Errorf("error opening file %s: %w", fileName, err)
}
defer file.Close()
data, err := io.ReadAll(file)
if err != nil {
return nil, fmt.Errorf("error reading file %s: %w", fileName, err)
}
return data, nil
}
func FindFileInParents(name, path string) string {
files, err := os.ReadDir(path)
if err != nil {
panic(err)
}
for _, file := range files {
if file.Name() == name {
return filepath.Join(path, name)
}
}
return FindFileInParents(name, filepath.Dir(path))
}