This document describes how to store and retrieve data using the Cloud Storage client library. It assumes that you completed the tasks described in Setting up for Cloud Storage to activate a Cloud Storage bucket and download the client libraries. It also assumes that you know how to build an App Engine application.
For additional code samples, see Cloud Storage client libraries
Required imports
The imports in the file required for App Engine and for Cloud Storage are:
google.golang.org/appengine
,google.golang.org/appengine/file
cloud.google.com/go/storage
as shown in the following snippet:
Specifying the Cloud Storage bucket
Before you can execute any Cloud Storage operation, you must supply the bucket name. The easiest way to do this is to use the default bucket for your project, which can be obtained from the App Engine context, as shown in this snippet:
Writing to Cloud Storage
To write a file to Cloud Storage:
When the file is created, the sample specifies Cloud Storage headers (x-goog-meta-foo
and x-goog-meta-bar
). This optional code introduces the notion
of using Cloud Storage headers, which you
can apply to:
- Affect request behavior
- Specify access to the file in the bucket different from the defaults (see x-goog-acl)
- Write file metadata.
The x-goog-meta-*
headers shown
above are custom file metadata that you can set; these headers are always
returned with the file. Note that the space available for custom headers and
their data is limited to a few kilobytes, so use these carefully.
Because the code sample doesn't set x-goog-acl
, the default
Cloud Storage ACL of public read
is applied to the object when it is written to the bucket.
Finally, notice the call to Close()
the file after you finish the write. If
you don't do this, the file is not written to Cloud Storage. Be aware
that after you call Close()
, you cannot append to the file.
Reading from Cloud Storage
To read a file from Cloud Storage:Listing bucket contents
This sample code shows how to list the contents of the bucket:
Deleting files in Cloud Storage
The code below demonstrates how to delete a file from Cloud Storage using the
ObjectHandle.delete()
method.
This example cleans up the files that were written to the bucket in the Writing to Cloud Storage section.
What's next
- Visit the API Reference documentation.
- See the Cloud Storage documentation for more guides and tutorials.