123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146 |
- package fs
- import (
- "archive/zip"
- "bytes"
- "errors"
- "fmt"
- "io/ioutil"
- "net/http"
- "os"
- "strings"
- )
- var zipData string
- type file struct {
- os.FileInfo
- data []byte
- }
- type statikFS struct {
- files map[string]file
- }
- func Register(data string) {
- zipData = data
- }
- func New() (http.FileSystem, error) {
- if zipData == "" {
- return nil, errors.New("statik/fs: no zip data registered")
- }
- zipReader, err := zip.NewReader(strings.NewReader(zipData), int64(len(zipData)))
- if err != nil {
- return nil, err
- }
- files := make(map[string]file)
- for _, zipFile := range zipReader.File {
- unzipped, err := unzip(zipFile)
- if err != nil {
- return nil, fmt.Errorf("statik/fs: error unzipping file %q: %s", zipFile.Name, err)
- }
- files["/"+zipFile.Name] = file{
- FileInfo: zipFile.FileInfo(),
- data: unzipped,
- }
- }
- return &statikFS{files: files}, nil
- }
- func unzip(zf *zip.File) ([]byte, error) {
- rc, err := zf.Open()
- if err != nil {
- return nil, err
- }
- defer rc.Close()
- return ioutil.ReadAll(rc)
- }
- func (fs *statikFS) Open(name string) (http.File, error) {
- name = strings.Replace(name, "//", "/", -1)
- f, ok := fs.files[name]
- if ok {
- return newHTTPFile(f, false), nil
- }
-
-
- indexName := strings.Replace(name+"/index.html", "//", "/", -1)
- f, ok = fs.files[indexName]
- if !ok {
- return nil, os.ErrNotExist
- }
- return newHTTPFile(f, true), nil
- }
- func newHTTPFile(file file, isDir bool) *httpFile {
- return &httpFile{
- file: file,
- reader: bytes.NewReader(file.data),
- isDir: isDir,
- }
- }
- type httpFile struct {
- file
- reader *bytes.Reader
- isDir bool
- }
- func (f *httpFile) Read(p []byte) (n int, err error) {
- return f.reader.Read(p)
- }
- func (f *httpFile) Seek(offset int64, whence int) (ret int64, err error) {
- return f.reader.Seek(offset, whence)
- }
- func (f *httpFile) Stat() (os.FileInfo, error) {
- return f, nil
- }
- func (f *httpFile) IsDir() bool {
- return f.isDir
- }
- func (f *httpFile) Readdir(count int) ([]os.FileInfo, error) {
-
- return make([]os.FileInfo, 0), nil
- }
- func (f *httpFile) Close() error {
- return nil
- }
|