http - 如何在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
}
解决方案
以下是检查 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
}
}
推荐阅读
- java - How to count the total number of duplicated chars in a string using nested loop?
- clojure - Clojure How to build linux executable
- qt - 应用镜像变换来翻转/反射 QML 控件
- git - 修改 PR 并关闭原件
- sql - 如何删除表中未包含在列表中的所有条目
- mysql - MySQL 数列中的计数值
- c# - 创建在文本框“start()”中键入的按钮,然后按“Enter 键”
- java - ORA-00932: 不一致的数据类型: 预期 - 得到 clob hibernate/springboot
- r - 删除 data.table 每一列的前导零
- linux - 在linux,bash中的单独列中回显2个变量