/
asset.go
58 lines (50 loc) · 1.41 KB
/
asset.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
package web
import (
"os"
"github.com/gobuffalo/packr"
"github.com/pkg/errors"
)
// ErrNotFound is a sentinel error returned by an AssetLoader when the asset
// is not defined.
var ErrNotFound = errors.New("asset not found")
// AssetLoader is a generic interface to something that returns asset data
// by name.
type AssetLoader interface {
// Load loads the specified asset. If the asset couldn't be found, Load
// should return ErrNotFound.
Load(name string) ([]byte, error)
}
// AssetLoaderChain is a chain of asset loaders. It iterates through each
// AssetLoader attempting to load the named asset. If one AssetLoader returns
// ErrNotFound, the next loader in the chain is consulted.
type AssetLoaderChain []AssetLoader
// Load implements AssetLoader.
func (alc AssetLoaderChain) Load(name string) ([]byte, error) {
for _, al := range alc {
switch data, err := al.Load(name); err {
case nil:
return data, nil
case ErrNotFound:
// Try the next AssetLoader in the chain.
default:
return nil, err
}
}
return nil, ErrNotFound
}
// PackrBox is an AssetLoader that loads from a packr.Box.
type PackrBox struct {
packr.Box
}
// Load implements AssetLoader.
func (pb *PackrBox) Load(name string) ([]byte, error) {
// Load "name" from the Box, b.
switch data, err := pb.MustBytes(name); {
case err == nil:
return data, nil
case os.IsNotExist(err):
return nil, ErrNotFound
default:
return nil, err
}
}