Golang HTTP服务文件-提供并行下载支持-contentLength和接受范围不起作用

时间:2020-04-25 16:17:01

标签: http go download http-headers

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)
        }

然后我仍然可以看到它正在下载而不显示总大小,没有暂停/继续支持。 我试图从

下载文件

样本小文件: https://s2.torrentfast.net/download/Dracula.2020.S01E01.HDTV.x264-PHOENiX[TGx]/[TGx]Downloaded%20from%20torrentgalaxy.to%20.txt

大无花果示例: https://s2.torrentfast.net/download/Need%20For%20Speed%20Most%20Wanted%20Black%20Edition%20repack%20Mr%20DJ/Setup-1.bin

Http Get request response headers(sample small file) screenshot link

可以帮忙吗?

1 个答案:

答案 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的源代码即可。