github.com/zooyer/miskit@v1.0.71/utils/webfs/webmfs.go (about) 1 package webfs 2 3 import ( 4 "errors" 5 "io" 6 "io/fs" 7 "net/http" 8 "os" 9 "time" 10 ) 11 12 type memFile struct { 13 name string 14 data []byte 15 offset int64 16 } 17 18 type webMFS struct { 19 files map[string][]byte 20 } 21 22 func (f *memFile) Readdir(count int) ([]fs.FileInfo, error) { 23 return nil, nil 24 } 25 26 func (f *memFile) Stat() (fs.FileInfo, error) { 27 return f, nil 28 } 29 30 func (f *memFile) Read(buf []byte) (int, error) { 31 if f.offset == f.Size() { 32 return 0, io.EOF 33 } 34 35 var n = copy(buf, f.data[f.offset:]) 36 f.offset += int64(n) 37 38 return n, nil 39 } 40 41 func (f *memFile) Seek(offset int64, whence int) (int64, error) { 42 var size = f.Size() 43 44 var startOffset int64 45 46 switch whence { 47 case io.SeekStart: 48 startOffset = 0 49 case io.SeekCurrent: 50 startOffset = f.offset 51 case io.SeekEnd: 52 startOffset = size 53 } 54 55 if startOffset+offset < 0 { 56 return 0, errors.New("an attempt was made to move the file pointer before the beginning of the file") 57 } 58 59 if startOffset+offset < size { 60 f.offset = offset 61 } else { 62 f.offset = size 63 } 64 65 return f.offset, nil 66 } 67 68 func (f *memFile) Close() error { 69 return nil 70 } 71 72 func (f *memFile) Name() string { 73 return f.name 74 } 75 76 func (f *memFile) Size() int64 { 77 return int64(len(f.data)) 78 } 79 80 func (f *memFile) Mode() fs.FileMode { 81 return 0666 82 } 83 84 func (f *memFile) ModTime() time.Time { 85 return time.Now() 86 } 87 88 func (f *memFile) IsDir() bool { 89 return false 90 } 91 92 func (f *memFile) Sys() interface{} { 93 return f 94 } 95 96 // WebMFS 文件系统目录,嵌入式文件系统 97 func WebMFS(files map[string][]byte) http.FileSystem { 98 return &webMFS{ 99 files: files, 100 } 101 } 102 103 func (w *webMFS) Open(name string) (http.File, error) { 104 data, exists := w.files[name] 105 if !exists { 106 return nil, os.ErrNotExist 107 } 108 109 return &memFile{name: name, data: data}, nil 110 }