生产环境应优先使用 http.ServeContent 实现安全文件下载:它支持范围请求、自动设置 Content-Length 和 ETag,并可防止路径遍历;需配合 filepath.Clean、前缀校验、os.FileInfo 的 ModTime 和准确文件大小使用。

Go 标准库的 http.ServeFile 和 http.ServeContent 都能实现文件下载,但直接用 http.ServeFile 有路径遍历风险,且无法自定义响应头(如 Content-Disposition),生产环境应避免。
用 http.ServeContent 安全地提供文件下载
这是最稳妥的方式:它支持范围请求(Range)、自动设置 Content-Length 和 ETag,还能防止路径穿越。关键在于传入一个可 seek 的 io.ReadSeeker 和准确的 modtime。
- 先用
filepath.Clean规范路径,再检查是否在允许目录内(例如strings.HasPrefix(cleanPath, allowedDir)) - 用
os.Open打开文件后,用file.Stat()获取os.FileInfo,它的ModTime()可直接传给http.ServeContent -
http.ServeContent第四个参数(contentLength)必须是真实文件大小,别传 -1 —— 否则会退化为流式传输,丢失Content-Length和缓存能力
func downloadHandler(w http.ResponseWriter, r *http.Request) {
filename := r.URL.Query().Get("f")
cleanPath := filepath.Clean(filename)
fullPath := filepath.Join("/var/www/files", cleanPath)
// 路径校验:禁止跳出指定目录
if !strings.HasPrefix(fullPath, "/var/www/files") {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
file, err := os.Open(fullPath)
if err != nil {
http.Error(w, "File not found", http.StatusNotFound)
return
}
defer file.Close()
info, _ := file.Stat()
w.Header().Set("Content-Disposition", `attachment; filename="`+info.Name()+`"`)
http.ServeContent(w, r, info.Name(), info.ModTime(), file)
}
手动设置 Content-Disposition 并流式传输
当文件来自非本地存储(比如从 S3 或数据库读取),无法用 http.ServeContent 时,需手动控制响应头并调用 io.Copy。此时必须显式设置 Content-Length(否则浏览器无法显示进度)和 Content-Type(否则可能触发错误解析)。
- 如果源数据不支持
Seek(如io.Reader),就无法支持断点续传,Content-Length必须已知 - 用
mime.TypeByExtension推断类型比硬编码更安全,但注意它只查扩展名,不校验内容 - 务必在
io.Copy前设置所有响应头,一旦写入 body 就不能再改 header
func downloadFromReader(w http.ResponseWriter, r *http.Request) {
reader := getSomeDataReader() // e.g., from S3 or bytes.Buffer
size := int64(1024000) // must know size in advance
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Length", strconv.FormatInt(size, 10))
w.Header().Set("Content-Disposition", `attachment; filename="data.bin"`)
io.Copy(w, reader)
}
处理大文件时的内存与超时问题
默认的 http.Server 读写超时(ReadTimeout/WriteTimeout)对大文件下载不友好,容易中断。同时,不要把整个文件读进内存再返回 —— 即使是 os.ReadFile + w.Write 这种写法,在 GB 级文件下也会 OOM。
- 用
http.TimeoutHandler包裹 handler 是无效的,它只限制 handler 执行时间,不包括后续流式写入 - 应在
http.Server实例上单独设置ReadHeaderTimeout(防慢速 HTTP 头攻击)和IdleTimeout(防连接空闲耗尽资源),而WriteTimeout应设为 0(禁用)或足够长(如 30 分钟) - 确保反向代理(如 Nginx)也调高了
proxy_read_timeout和proxy_send_timeout,否则会在 Go 之前切断连接
真正容易被忽略的是路径校验逻辑 —— 很多人只做 filepath.Join 就直接 os.Open,没意识到 ../ 在 URL 解码后仍可能绕过。必须用 filepath.Clean 再比对前缀,且允许目录末尾带斜杠,否则 /files/../etc/passwd 清洗后变成 /etc/passwd,一比对就失败。这个细节漏掉,等于把服务器裸奔在公网。










