/
resource.go
70 lines (54 loc) · 1.21 KB
/
resource.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 common
import (
"flag"
"fmt"
"os"
"strings"
)
var (
FlagIoFileResource *bool
resourcesDirectory string
resourcesMimeTypes = make(map[string]string)
)
const (
FlagNameIoFileResource = "io.file.resources"
)
func init() {
FlagIoFileResource = flag.Bool(FlagNameIoFileResource, !IsRunningAsExecutable(), "read resource from filesystem")
}
func ResourcesDirectory() string {
return resourcesDirectory
}
func ReadResource(filename string) ([]byte, string, error) {
var ba []byte
var err error
if app.Resources == nil {
return nil,"", fmt.Errorf("resources are not initialized")
}
if resourcesDirectory == "" {
de,_ := app.Resources.ReadDir(".")
if len(de) == 1 {
resourcesDirectory = de[0].Name()
}
}
path := filename
if !strings.HasPrefix(path, resourcesDirectory) {
path = strings.Join([]string{resourcesDirectory, filename}, "/")
}
if *FlagIoFileResource {
ba, _ = os.ReadFile(path)
}
if ba == nil {
ba, err = app.Resources.ReadFile(path)
}
if Error(err) {
return nil, "", err
}
mimeType, ok := resourcesMimeTypes[filename]
if !ok {
mt := DetectMimeType(filename, ba)
mimeType = mt.MimeType
resourcesMimeTypes[filename] = mimeType
}
return ba, mimeType, nil
}