douzhi8244 2019-03-06 04:17
浏览 47
已采纳

在Go中找不到来自url的公共文件

I am trying to get the content of a publicly available file using ioutil.ReadFile() but it doesn't find the file: panic: open http://www.pdf995.com/samples/pdf.pdf: No such file or directory

Here's my code:

// Reading and writing files are basic tasks needed for
// many Go programs. First we'll look at some examples of
// reading files.

package main

import (
    "fmt"
    "io/ioutil"
)

// Reading files requires checking most calls for errors.
// This helper will streamline our error checks below.
func check(e error) {
    if e != nil {
        panic(e)
    }
}

func main() {
    fileInUrl, err := ioutil.ReadFile("http://www.pdf995.com/samples/pdf.pdf")
    if err != nil {
        panic(err)
    }
    fmt.Printf("HERE --- fileInUrl: %+v", fileInUrl)
}

Here's a go playground example

  • 写回答

1条回答 默认 最新

  • duannima8347 2019-03-06 04:38
    关注

    ioutil.ReadFile() does not support http.

    If you look at the source code(https://golang.org/src/io/ioutil/ioutil.go?s=1503:1549#L42), open the file using os.Open.

    I think I can do this coding.

    package main
    
    import (
        "io"
        "net/http"
        "os"
    )
    
    func main() {
    
        fileUrl := "http://www.pdf995.com/samples/pdf.pdf"
    
        if err := DownloadFile("example.pdf", fileUrl); err != nil {
            panic(err)
        }
    }
    
    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
    }
    

    but, go playgound not protocol(go error dial tcp: Protocol not available).

    so, You have to do it PC.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波