如何在Golang中开发简易文件管理器_支持上传下载和删除

用Go实现简易文件管理器需基于http包搭建Web服务,结合os/io操作文件,重点防范目录遍历漏洞,合理路由并安全处理上传(校验文件名、大小、路径)、下载与删除功能。

用 Go 写一个简易文件管理器并不复杂,核心是基于 http 包搭建 Web 服务,配合文件系统操作(osio)实现上传、下载、删除功能。关键在于安全处理路径、合理组织路由、避免目录遍历漏洞,并兼顾基础用户体验。

基础 Web 服务与静态资源支持

先启动一个 HTTP 服务器,提供 HTML 页面和 API 接口。建议将前端页面(如 index.html)放在 ./static 目录下,用 http.FileServer 服务静态资源:

  • http.ServeMux 注册 / 路由返回主页,/static/ 映射到本地 static 文件夹
  • API 接口如 /upload/download/{name}/delete/{name} 单独注册为 handler 函数
  • 确保 index.html 包含表单(enctype="multipart/form-data")和 JS 请求逻辑,减少后端模板依赖

安全地处理文件上传

上传需校验文件名、大小和路径,防止覆盖系统文件或写入非法位置:

  • 使用 r.ParseMultipartForm(32 限制最大内存缓存(如 32MB),超限则转临时磁盘文件
  • 调用 filepath.Base(filename) 提取原始文件名,过滤掉 ..、空字符、控制字符等危险片段
  • 目标路径拼接用 filepath.Join(uploadDir, safeName),再用 filepath.EvalSymlinksstrings.HasPrefix 检查是否仍在允许目录内
  • 示例:若 uploadDir = "./uploads",则 ../etc/passwd 应被拒绝

支持下载与删除的 REST 风格接口

下载和删除都需校验文件是否存在、是否在白名单目录中,且不暴露绝对路径:

  • /download/{name}:用 http.ServeFile 返回文件,但先检查 filepath.Join(uploadDir, name) 是否在 uploadDir 下(可用 filepath.Rel 判断相对路径是否合法)
  • /delete/{name}:接收 DELETE 请求,同样校验路径合法性后调用 os.Remove;成功返回 200,失败返回 404 或 400
  • 所有文件操作前加 os.Stat 判断是否存在,避免 panic;错误统一返回 JSON 格式提示(如 {"error": "file not found"}

最小可行代码结构示意

一个可运行的骨架如下(省略 HTML,聚焦逻辑):

func main() {
	uploadDir := "./uploads"
	os.MkdirAll(uploadDir, 0755)

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/" {
			http.ServeFile(w, r, "static/index.html")
			return
		}
		http.NotFound(w, r)
	})

	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))

	http.HandleFunc("/upload", uploadHandler(uploadDir))
	http.HandleFunc("/download/", downloadHandler(uploadDir))
	http.HandleFunc("/delete/", deleteHandler(uploadDir))

	fmt.Println("Server running on :8080")
	http.ListenAndServe(":8080", nil)
}

func uploadHandler(uploadDir string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "POST" {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
			return
		}
		r.ParseMultipartForm(32 << 20)
		file, _, err := r.FormFile("file")
		if err != nil {
			http.Error(w, "No file received", http.StatusBadRequest)
			return
		}
		defer file.Close()

		filename := filepath.Base(r.FormValue("filename"))
		if filename == "" || strings.Contains(filename, "..") || strings.HasPrefix(filename, ".") {
			http.Error(w, "Invalid filename", http.StatusBadRequest)
			return
		}

		dstPath := filepath.Join(uploadDir, filename)
		if !isInDir(dstPath, uploadDir) {
			http.Error(w, "Access denied", http.StatusForbidden)
			return
		}

		out, err := os.Create(dstPath)
		if err != nil {
			http.Error(w, "Cannot save file", http.StatusInternalServerError)
			return
		}
		defer out.Close()

		if _, err := io.Copy(out, file); err != nil {
			http.Error(w, "Failed to save", http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode(map[string]string{"message": "uploaded"})
	}
}

// isInDir 检查 path 是否在 root 目录下(防御路径穿越)
func isInDir(path, root string) bool {
	rel, err := filepath.Rel(root, path)
	return err == nil && !strings.HasPrefix(rel, "..") && !strings.IsAbs(rel)
}

不复杂但容易忽略路径安全和错误反馈细节,补全 HTML 表单和 JS 请求后即可本地试用。后续可扩展列表展示、分页、权限控制或对接对象存储。