【问题标题】:Golang http serve file - giving parallel download support - contentLength & accept ranges not workingGolang http 服务文件 - 提供并行下载支持 - contentLength 和接受范围不起作用
【发布时间】: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)
        }

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

下载文件

示例小文件: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

可以帮忙吗?

【问题讨论】:

标签: http go download http-headers


【解决方案1】:

w.Header().Set("Accept-Ranges", "bytes") 不是必需的,因为 Range 会在响应时设置 http.ServeFile。

w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10))错了,可能会响应传输,http.ServerFile会设置这个header。

Content-Length的意思是指定body的长度,Content-Range会记录传输范围的部分和总长度信息。 正确的方法是使用http.ServeFile直接发送文件。 ServeFile 函数会自动处理 Range 和 Cache 的情况。

看看net/http/fs.go的源码就知道了。

【讨论】:

  • 如果服务器没有响应 http HEAD 请求,这种情况会发生吗(无暂停/恢复)?
猜你喜欢
  • 1970-01-01
  • 2020-12-25
  • 1970-01-01
  • 2011-08-09
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-14
相关资源
最近更新 更多