生产环境应优先使用 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 就不能再改 headerfunc 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 分钟)proxy_read_timeout 和 proxy_send_timeout,否则会在 Go 之前切断连接真正

filepath.Join 就直接 os.Open,没意识到 ../ 在 URL 解码后仍可能绕过。必须用 filepath.Clean 再比对前缀,且允许目录末尾带斜杠,否则 /files/../etc/passwd 清洗后变成 /etc/passwd,一比对就失败。这个细节漏掉,等于把服务器裸奔在公网。