您的位置:首页 >Golang使用http.FileServer配置静态文件服务
发布于2025-10-14 阅读(0)
扫一扫,手机访问
使用 http.FileServer 可方便提供静态文件服务,通过 http.Dir 指定目录并结合 http.StripPrefix 去除 URL 前缀,实现安全灵活的文件访问,适用于开发环境。

在 Go 语言中,使用内置的 net/http 包可以非常方便地提供静态文件服务。其中 http.FileServer 是一个核心工具,它能将指定目录作为静态文件服务器暴露出去。
要创建一个静态文件服务器,你需要使用 http.FileServer 并传入一个实现了 http.FileSystem 接口的对象,最常见的是 http.Dir,它表示一个本地目录。
示例代码:
package main
import (
"net/http"
)
func main() {
// 将当前目录作为静态文件根目录
fs := http.FileServer(http.Dir("./static/"))
// 将 /static/ 路由映射到文件服务器
http.Handle("/static/", fs)
// 启动 HTTP 服务
http.ListenAndServe(":8080", nil)
}说明:
默认情况下,FileServer 会把整个请求路径传给文件系统。如果你希望去掉 URL 中的前缀(如 /static),需要使用 http.StripPrefix。
正确写法:
http.Handle("/static/", http.StripPrefix("/static/", fs))这样,当访问 /static/images/logo.png 时,StripPrefix 会把 /static/ 去掉,实际查找的是 images/logo.png(相对于指定目录)。
package main
import (
"net/http"
)
func main() {
// 提供 static 目录下的资源,访问路径为 /static/
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
// 提供 uploads 目录下的资源,访问路径为 /uploads/
http.Handle("/uploads/", http.StripPrefix("/uploads/", http.FileServer(http.Dir("./uploads/"))))
// 可选:提供 index.html 作为根路径
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)
})
println("Server is running on http://localhost:8080")
http.ListenAndServe(":8080", nil)
}1. 目录权限:确保 Go 程序有读取目标目录的权限。
2. 路径斜杠:URL 路由以 / 结尾时,Go 会自动处理目录访问和 index.html 默认页。例如访问 /static/ 会尝试返回 ./static/index.html。
3. 安全限制:http.Dir 会阻止通过 .. 路径跳转到父目录之外,防止目录遍历攻击。
4. 生产环境建议:静态文件建议由 Nginx 等反向代理服务器处理,Go 服务专注于业务逻辑。开发阶段使用 FileServer 非常方便。
基本上就这些。使用 http.FileServer 搭建静态服务简单高效,配合 StripPrefix 能灵活控制路径映射。
上一篇:Fedora图标主题设置教程
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9