【问题标题】:How to check whether a URL is downloadable or not in golang?如何在golang中检查URL是否可下载?
【发布时间】:2021-12-13 09:19:44
【问题描述】:

我正在尝试将文件从 url 下载到本地文件。

我想测试请求的 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)
        if err != nil {
            return err
        }
        defer resp.Body.Close()
    
        // 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
    }

【问题讨论】:

  • URL 是一个 URL,而不是文件或文件夹。通过 HTTP GET 请求 URL 将产生字节流(响应)主体和 Content-Type 元数据(在 HTTP 标头中发送)。如果您将某对(body-data, content-type)视为“文件”或“文件夹”,则取决于您。

标签: http go url


【解决方案1】:

以下是检查 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")
        return nil
    }
}

【讨论】:

    猜你喜欢
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 2013-09-13
    • 2018-02-27
    相关资源
    最近更新 更多