首页 > 解决方案 > 如何在golang中检查URL是否可下载?

问题描述

我正在尝试将文件从 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
    }

标签: httpgourl

解决方案


以下是检查 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
    }
}

推荐阅读