GoLang 的全新功能,不到10天。我有一个http服务器,我需要http服务磁盘中的文件。默认情况下,这是使用“ net / http” http.ServeFile(w,r,file)。 我的问题是,当我下载这些文件时,它们没有文件暂停/恢复支持,只是下载而没有显示总大小。我尝试添加“ Content-Length”标头和“ Accept-范围”标题。但似乎不起作用。
我担心的Http标头
我有文件路径, info 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
可以帮忙吗?
答案 0 :(得分:0)
w.Header().Set("Accept-Ranges", "bytes")
不是必需的,因为响应时Range将设置http.ServeFile
。
w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10))
是错误的,可能响应传输,并且http.ServerFile
将设置此标头。
Content-Length
的含义是指定主体的长度,Content-Range
将记录传输范围的部分以及总长度信息。 正确的方法是使用http.ServeFile
直接发送文件。 ServeFile函数将自动处理Range和Cache的情况。
只需查看net/http/fs.go
的源代码即可。