在Go AppEngine中读取文件的正确方法

时间:2016-04-19 11:29:39

标签: google-app-engine go

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

在Java中,我读到context.getResourceAsStream,是否有相应的功能?

1 个答案:

答案 0 :(得分:6)

您可以使用与计算机上运行的Go应用中的文件相同的方式读取App Engine上的文件。

要记住的一些事情:

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

  • Go代码只能读取 application 文件的文件,因此如果您想从Go代码中读取文件,则该文件不能与静态文件模式匹配(或者如果它也必须作为静态文件可用,则必须在静态文件处理程序中指定application_readable选项,该处理程序包含/适用于文件details)。

后者在Application configuration页面Static file handlers部分详细说明。引用相关部分:

  

为了提高效率,App Engine与应用程序文件分开存储和提供静态文件。应用程序的文件系统中没有静态文件。如果您有需要由应用程序代码读取的数据文件,则数据文件必须是应用程序文件,并且不能与静态文件模式匹配。

因此,我们假设您的应用根(data旁边)有一个文件夹app.yaml,其中包含list.txt个文件。您可以阅读以下内容:

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

或者,如果您需要/ {需要io.Readeros.File实施io.Reader以及其他许多内容):

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

相关问题:

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?

相关问题