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 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上