答案:用Go的net/http库可快速搭建静态服务器,http.ServeFile用于单个文件,http.FileServer配合http.Dir可服务整个目录,通过StripPrefix处理路由前缀,并建议添加路径安全检查与自定义404以增强安全性。

想快速用 Golang 搭建一个能访问本地文件的静态服务器?不需要引入复杂框架,Go 自带的 net/http 库就能轻松实现。核心功能靠 http.ServeFile,几行代码就能让指定目录下的文件通过浏览器访问。
如果你只想暴露某个具体文件(比如一个 PDF 或图片),可以直接用 http.ServeFile。它接收响应写入器、请求和文件路径,自动设置头部并返回内容。
package main
import (
"net/http"
)
func fileHandler(w http.ResponseWriter, r *http.Request) {
// 指定要返回的文件路径
filePath := "./files/example.pdf"
http.ServeFile(w, r, filePath)
}
func main() {
http.HandleFunc("/download", fileHandler)
http.ListenAndServe(":8080", nil)
}
访问 http://localhost:8080/download 就会触发下载或展示 example.pdf。
更常见的是开放整个目录,让用户浏览多个文件。可以用 http.FileServer 配合 http.Dir 实现。
立即学习“go语言免费学习笔记(深入)”;
package main
import (
"net/http"
)
func main() {
// 设置文件服务根目录
fs := http.FileServer(http.Dir("./static/"))
// 路由 /files/ 开头的请求到文件服务器
http.Handle("/files/", http.StripPrefix("/files/", fs))
http.ListenAndServe(":8080", nil)
}
假设 static 目录下有 image.png 和 doc.txt,访问 http://localhost:8080/files/image.png 就能查看对应资源。StripPrefix 用于去掉路由前缀,避免路径错乱。
直接暴露文件系统有风险,建议加点简单防护:
例如检查文件是否存在再决定是否 ServeFile:
func safeFileHandler(w http.ResponseWriter, r *http.Request) {
path := "./static" + r.URL.Path
_, err := os.Stat(path)
if os.IsNotExist(err) {
http.NotFound(w, r)
return
}
http.ServeFile(w, r, path)
}
基本上就这些。Golang 的 http 包设计简洁,ServeFile 和 FileServer 组合起来足够应付大多数静态文件服务场景,开发调试或内网共享都很方便。
以上就是如何用 Golang 搭建一个静态文件服务器_Golang HTTP ServeFile 应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号