【发布时间】:2020-08-09 05:29:37
【问题描述】:
GoLang 非常新,不到 10 天。我有一个 http 服务器,我需要 http 服务磁盘内的文件。这里默认使用“net/http”http.ServeFile(w, r, file)。 我的问题是当我下载这些文件时,它们没有文件暂停/恢复支持,但只是下载而不显示总大小。我尝试添加 “Content-Length”标题和“Accept-范围”标题。但似乎不起作用。
我担心的Http Headers是,
- 内容长度
- 内容类型
- 接受范围
- 内容处置(附件)
我有文件路径、信息 FileInfo、w http.ResponseWriter, r http.Request 在服务功能之前。首先我尝试添加
w.Header().Set("Accept-Ranges", "bytes")
if w.Header().Get("Content-Encoding") == "" {
w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10))
}
到
func (s *Server) serveFiles(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/download/") {
url := strings.TrimPrefix(r.URL.Path, "/download/")
//dldir is absolute
dldir := s.state.Config.DownloadDirectory
file := filepath.Join(dldir, url)
//only allow fetches/deletes inside the dl dir
if !strings.HasPrefix(file, dldir) || dldir == file {
http.Error(w, "Nice try\n"+dldir+"\n"+file, http.StatusBadRequest)
return
}
info, err := os.Stat(file)
if err != nil {
http.Error(w, "File stat error: "+err.Error(), http.StatusBadRequest)
return
}
switch r.Method {
case "GET":
if info.IsDir() {
w.Header().Set("Content-Type", "application/zip")
w.WriteHeader(200)
//write .zip archive directly into response
a := archive.NewZipWriter(w)
a.AddDir(file)
a.Close()
} else {
w.Header().Set("Accept-Ranges", "bytes")
if w.Header().Get("Content-Encoding") == "" {
w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10))
}
http.ServeFile(w, r, file)
}
然后我仍然可以看到它正在下载而不显示总大小,不支持暂停/恢复。 我试图从
下载文件Http Get request response headers(sample small file) screenshot link
可以帮忙吗?
【问题讨论】:
-
我现在正在尝试golang.org/pkg/net/http/#ServeContent 方法。由于服务器正在重建,示例文件目前可能不可用
-
仍未解决
标签: http go download http-headers