【发布时间】:2016-08-11 13:20:08
【问题描述】:
使用 Google AppEngine (Go) 读取文件的正确方法是什么?
在我读到的Java中有context.getResourceAsStream,有没有与之等效的函数?
【问题讨论】:
标签: google-app-engine go
使用 Google AppEngine (Go) 读取文件的正确方法是什么?
在我读到的Java中有context.getResourceAsStream,有没有与之等效的函数?
【问题讨论】:
标签: google-app-engine go
您可以在 App Engine 上读取文件,就像在计算机上运行的 Go 应用程序中读取文件一样。
注意事项:
您应该使用相对文件路径而不是绝对路径。工作目录是应用的根文件夹(app.yaml 文件所在的位置)。
只有 application 文件可以被 Go 代码读取,所以如果你想从 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.Reader(os.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?
【讨论】: