AppEngine中正确读取文件的方法

AppEngine中正确读取文件的方法

本文介绍了在Go AppEngine中正确读取文件的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Google AppEngine读取文件的正确方法是什么()?



在Java中,我读过 context.getResourceAsStream ,是否有任何等价的函数?

解决方案

您可以从App Engine上的文件读取,就像您可以从计算机上运行的Go应用程序中的文件中读取一样。 b
$ b

请注意以下几点:


  • 您应该使用 relative 文件路径而不是绝对路径。工作目录是您的应用程序的根文件夹(其中 app.yaml 文件所在的位置)。

  • > Go代码只能读取 application 文件中的文件,因此如果您想从Go代码读取文件,则该文件不能与静态文件模式匹配(或者它必须是也可以作为静态文件提供,必须在包含/应用于该文件的静态文件处理程序中指定 application_readable 选项) href =https://cloud.google.com/appengine/docs/go/config/appconfig =nofollow noreferrer>应用程序配置页面,部分。引用相关部分:

    假设您的应用程序根目录中有一个文件夹 data (位于 app.yaml )和一个文件 list.txt 。您可以阅读其内容,如下所示:

      if content,err:= ioutil.Readfile(data / list.txt) ; err!= nil {
    //无法读取文件,处理错误
    } else {
    //成功,对内容做
    }

    或者如果您想/需要(实现 io.Reader 以及许多其他):

      f,err:= os.Open(data / list.txt)//用于读取访问。 
    if err!= nil {
    //无法打开文件,日志/句柄错误
    返回
    }
    推迟f.Close()
    / /您可以在这里阅读f

    相关问题:





    静态页面在Google App Engine中返回404

    我如何将我的服务器的私钥存储在谷歌应用程序引擎中?


    What's the correct way to read a file using Google AppEngine (Go)?

    In Java I read there are context.getResourceAsStream, is there any equivalent function for that?

    解决方案

    You can read from files on App Engine the same way you can read from files in a Go app running on your computer.

    Some things to keep in mind:

    • You should use relative file paths instead of absolute. The working directory is the root folder of your app (where the app.yaml file resides).

    • Only files that are application files can be read by Go code, so if you want to read a file from Go code, the file must not be matched by a static file pattern (or if it must be available as a static file too, application_readable option must be specified at the static file handler which includes/applies to the file, details).

    The latter is detailed on the Application configuration page, Section Static file handlers. Quoting the relevant part:

    So let's say you have a folder data in your app's root (next to app.yaml), and a file list.txt in it. You may read its content like this:

    if content, err := ioutil.Readfile("data/list.txt"); err != nil {
        // Failed to read file, handle error
    } else {
        // Success, do something with content
    }
    

    Or if you want / need an io.Reader (os.File implements io.Reader along with many other):

    f, err := os.Open("data/list.txt") // For read access.
    if err != nil {
        // Failed to open file, log / handle error
        return
    }
    defer f.Close()
    // Here you may read from f
    

    Related questions:

    Google App Engine Golang no such file or directory

    Static pages return 404 in Google App Engine

    How do I store the private key of my server in google app engine?

    这篇关于在Go AppEngine中正确读取文件的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 00:31