-
Notifications
You must be signed in to change notification settings - Fork 327
/
embed.go
93 lines (75 loc) · 1.69 KB
/
embed.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
package assets
import (
"embed"
"fmt"
"io/fs"
"os"
"path"
"go.uber.org/zap"
)
var (
//go:embed src/*
ff embed.FS
)
// Files return files from assets path or falls back to embedded files
//
// @todo try to find a way to merge this with auth/assets
func Files(log *zap.Logger, aPath string) (files fs.FS) {
var err error
if len(aPath) > 0 {
if files, err = fromPath(aPath); err != nil {
// log warning but fallback to embedded assets
log.Warn(
fmt.Sprintf("failed to use custom assets path (HTTP_SERVER_ASSETS_PATH=%s)", aPath),
zap.Error(err),
)
}
}
if files == nil {
aPath = "embedded"
files, err = fs.Sub(ff, "src")
if err != nil {
// something is seriously wrong, we might as well panic
panic(err)
}
}
return
}
func fromPath(path string) (assets fs.FS, err error) {
// at least favicon file should exist in the custom asset path
// otherwise we default to embedded files
const check = "favicon32x32.png"
var (
fi os.FileInfo
)
if fi, err = os.Stat(path); err != nil {
return
}
if !fi.IsDir() {
return nil, fmt.Errorf("expecting directory")
}
assets = os.DirFS(path)
if _, err = assets.Open(check); err != nil {
return nil, err
}
return
}
func DirEntries(dir string) (fileNames, subDirs []string, err error) {
dirEntries, err := fs.ReadDir(ff, path.Join("src", dir))
if err != nil {
return nil, nil, err
}
for _, dirEntry := range dirEntries {
fileInfo, err := dirEntry.Info()
if err != nil {
return nil, nil, err
}
// if the entry is a directory skip it
if fileInfo.IsDir() {
subDirs = append(subDirs, dirEntry.Name())
continue
}
fileNames = append(fileNames, dirEntry.Name())
}
return fileNames, subDirs, err
}