package main import ( "fmt" "html/template" "net/http" "os" "path/filepath" "strings" "github.com/joho/godotenv" ) // 定义静态文件根目录 var rootPath string // FileInfo 包含文件的元数据信息 type FileInfo struct { Name string Size string IsDir bool Href string } func main() { err := godotenv.Load() if err != nil { fmt.Println("Error loading .env file") return } rootPath = os.Getenv("FILE_PATH") http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { dir := r.URL.Path[1:] dir = rootPath + "/" + dir dir = strings.Replace(dir, "\\", "/", -1) fileInfo, err := os.Stat(dir) if err != nil { //fmt.Println("File does not exist") } else if fileInfo.Mode().IsRegular() { file, _ := os.Open(dir) defer file.Close() http.ServeContent(w, r, fileInfo.Name(), fileInfo.ModTime(), file) } else { fileInfos, err := listDir(dir) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } tmpl, err := template.ParseFiles("templates/index.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } tmpl.Execute(w, fileInfos) } }) http.ListenAndServe(":"+os.Getenv("PORT"), nil) } func listDir(dir string) ([]FileInfo, error) { file, err := os.Open(dir) if err != nil { return nil, err } defer file.Close() names, err := file.Readdirnames(-1) if err != nil { return nil, err } var fileInfos []FileInfo for _, name := range names { fileInfo, err := os.Stat(filepath.Join(dir, name)) if err != nil { return nil, err } Href := filepath.Join(dir, name) //Href = strings.Replace(Href, filepath.Join(rootPath), "", -1) size := fileInfo.Size() formattedSize := formatFileSize(size) fileInfos = append(fileInfos, FileInfo{ Name: name, Size: formattedSize, IsDir: fileInfo.IsDir(), Href: Href, }) } return fileInfos, nil } func formatFileSize(size int64) string { units := []string{"B", "KB", "MB", "GB"} var unitIndex int var fileSize float64 for size > 1024 && unitIndex < len(units)-1 { fileSize = float64(size) / 1024 size = size / 1024 unitIndex++ } fileSize = float64(size) return fmt.Sprintf("%.2f %s", fileSize, units[unitIndex]) }