| 1 | // Copyright 2016 fatedier, fatedier@gmail.com |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package assets |
| 16 | |
| 17 | import ( |
| 18 | "io/fs" |
| 19 | "net/http" |
| 20 | ) |
| 21 | |
| 22 | var ( |
| 23 | // read-only filesystem created by "embed" for embedded files |
| 24 | content fs.FS |
| 25 | |
| 26 | FileSystem http.FileSystem |
| 27 | |
| 28 | // if prefix is not empty, we get file content from disk |
| 29 | prefixPath string |
| 30 | ) |
| 31 | |
| 32 | type emptyFS struct{} |
| 33 | |
| 34 | func (emptyFS) Open(name string) (http.File, error) { |
| 35 | return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrNotExist} |
| 36 | } |
| 37 | |
| 38 | // if path is empty, load assets in memory |
| 39 | // or set FileSystem using disk files |
| 40 | func Load(path string) { |
| 41 | prefixPath = path |
| 42 | switch { |
| 43 | case prefixPath != "": |
| 44 | FileSystem = http.Dir(prefixPath) |
| 45 | case content != nil: |
| 46 | FileSystem = http.FS(content) |
| 47 | default: |
| 48 | FileSystem = emptyFS{} |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | func Register(fileSystem fs.FS) { |
| 53 | subFs, err := fs.Sub(fileSystem, "dist") |
| 54 | if err == nil { |
| 55 | content = subFs |
| 56 | } |
| 57 | } |