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

想快速用 Golang 搭建一个能访问本地文件的静态服务器?不需要引入复杂框架,Go 自带的 net/http 库就能轻松实现。核心功能靠 http.ServeFile,几行代码就能让指定目录下的文件通过浏览器访问。
使用 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 用于去掉路由前缀,避免路径错乱。
添加基本安全控制
直接暴露文件系统有风险,建议加点简单防护:
- 禁止列出上级目录:确保 Dir 路径不包含 ../ 等跳转符号
- 限制可访问路径:不要把根目录 / 或敏感路径暴露出去
- 自定义 404 页面:文件不存在时返回友好提示
例如检查文件是否存在再决定是否 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 组合起来足够应付大多数静态文件服务场景,开发调试或内网共享都很方便。










