github.com/zooyer/miskit@v1.0.71/utils/webfs/webefs.go (about)

     1  package webfs
     2  
     3  import (
     4  	"embed"
     5  	"fmt"
     6  	"net/http"
     7  	"path"
     8  	"path/filepath"
     9  	"strings"
    10  )
    11  
    12  // webEFS web嵌入文件系统
    13  type webEFS struct {
    14  	Path  string
    15  	Embed http.FileSystem
    16  }
    17  
    18  // WebEFS 文件系统目录,嵌入式文件系统
    19  func WebEFS(path string, fs embed.FS) http.FileSystem {
    20  	return &webEFS{
    21  		Path:  path,
    22  		Embed: http.FS(fs),
    23  	}
    24  }
    25  
    26  // Open 代码与http.Dir.Open函数相似
    27  func (w *webEFS) Open(filename string) (http.File, error) {
    28  	if filepath.Separator != '/' && strings.ContainsRune(filename, filepath.Separator) {
    29  		return nil, fmt.Errorf("http: invalid character in file path %v", filename)
    30  	}
    31  	dir := w.Path
    32  	if dir == "" {
    33  		dir = "."
    34  	}
    35  	fullName := filepath.Join(dir, filepath.FromSlash(path.Clean("/"+filename)))
    36  	// embed暂不支持windows separator, 统一转为"/"处理
    37  	fullName = strings.ReplaceAll(fullName, "\\", "/")
    38  
    39  	return w.Embed.Open(fullName)
    40  }