gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:23:34 26 4
gpt4 key购买 nike

非常陌生语言 , 不到 10 天。我有一个 http 服务器,我需要 http 服务磁盘内的文件。这里默认使用“net/http”http.ServeFile(w, r, file)。 我的问题是当我下载这些文件时,它们没有文件暂停/恢复支持,只是下载而不显示总大小。 我尝试添加 “Content-Length” header 和“Accept-Ranges” header .但似乎不起作用。

我担心的 Http header 是,

  • 内容长度
  • 内容类型
  • 接受范围
  • 内容处置(附件)

  • 我有文件路径,信息 文件信息 , 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

    大图 sample : 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

    能够帮助?

    最佳答案

    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 - Golang http 服务文件 - 提供并行下载支持 - contentLength 和接受范围不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61428739/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com