【问题标题】:How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list using golang?如何使用 golang 下载包含所有文件和子目录的 HTTP 目录,因为它们出现在在线文件/文件夹列表中?
【发布时间】:2021-12-17 13:56:16
【问题描述】:

目前我正在使用以下功能下载文件,我也想从 URL 下载文件夹

任何帮助将不胜感激

 package main
        
        import (
            "fmt"
            "io"
            "net/http"
            "os"
        )
        
        func main() {
            fileUrl := "http://example.com/file.txt"
            err := DownloadFile("./example.txt", fileUrl)
            if err != nil {
                panic(err)
            }
            fmt.Println("Downloaded: " + fileUrl)
        }
        
        // DownloadFile will download a url to a local file.
        func DownloadFile(filepath string, url string) error {
        
            // Get the data
            resp, err := http.Get(url)
            contentType = resp.Header.Get("Content-Type")  
    
            if err != nil {
                return err
            }
            defer resp.Body.Close()
    
    if contentType == "application/octet-stream" {
            // Create the file
            out, err := os.Create(filepath)
            if err != nil {
                return err
            }
            defer out.Close()
        
            // Write the body to file
            _, err = io.Copy(out, resp.Body)
            return err
        }
        }else{
        fmt.Println("Requested URL is not downloadable")
        }

我参考了以下链接: How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?

但我想在 golang 中使用它

【问题讨论】:

  • 使用 go query 在 HTML 中查找链接。使用您拥有的代码下载。

标签: html http go download get


【解决方案1】:

在这里您可以找到wget --recursive 实现的算法:https://www.gnu.org/software/wget/manual/html_node/Recursive-Download.html

基本上,您访问该页面,然后解析 HTML 并跟踪每个 href 链接(如果需要,还可以使用 css 链接),可以这样提取:https://vorozhko.net/get-all-links-from-html-page-with-go-lang

获得所有链接后,只需对它们发出请求,并根据 Content-Type 标头,如果它不是 text/html,则保存它,如果是,则解析它以获取链接。

【讨论】:

    猜你喜欢
    • 2014-06-20
    • 2011-10-30
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多