第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在golang中檢查URL是否可下載?

如何在golang中檢查URL是否可下載?

Go
臨摹微笑 2022-10-10 17:01:57
我正在嘗試將文件從 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    }
查看完整描述

1 回答

?
米脂

TA貢獻1836條經(jīng)驗 獲得超3個贊

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

    }

}


查看完整回答
反對 回復 2022-10-10
  • 1 回答
  • 0 關注
  • 167 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號