Correct way to read file in Go AppEngine

2019-02-25 02:24发布

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?

1条回答
Deceive 欺骗
2楼-- · 2019-02-25 02:57

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:

For efficiency, App Engine stores and serves static files separately from application files. Static files are not available in the application's file system. If you have data files that need to be read by the application code, the data files must be application files, and must not be matched by a static file pattern.

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?

查看更多
登录 后发表回答