doc.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. // Copyright 2016 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /*
  15. Package storage provides an easy way to work with Google Cloud Storage.
  16. Google Cloud Storage stores data in named objects, which are grouped into buckets.
  17. More information about Google Cloud Storage is available at
  18. https://cloud.google.com/storage/docs.
  19. See https://pkg.go.dev/cloud.google.com/go for authentication, timeouts,
  20. connection pooling and similar aspects of this package.
  21. # Creating a Client
  22. To start working with this package, create a [Client]:
  23. ctx := context.Background()
  24. client, err := storage.NewClient(ctx)
  25. if err != nil {
  26. // TODO: Handle error.
  27. }
  28. The client will use your default application credentials. Clients should be
  29. reused instead of created as needed. The methods of [Client] are safe for
  30. concurrent use by multiple goroutines.
  31. You may configure the client by passing in options from the [google.golang.org/api/option]
  32. package. You may also use options defined in this package, such as [WithJSONReads].
  33. If you only wish to access public data, you can create
  34. an unauthenticated client with
  35. client, err := storage.NewClient(ctx, option.WithoutAuthentication())
  36. To use an emulator with this library, you can set the STORAGE_EMULATOR_HOST
  37. environment variable to the address at which your emulator is running. This will
  38. send requests to that address instead of to Cloud Storage. You can then create
  39. and use a client as usual:
  40. // Set STORAGE_EMULATOR_HOST environment variable.
  41. err := os.Setenv("STORAGE_EMULATOR_HOST", "localhost:9000")
  42. if err != nil {
  43. // TODO: Handle error.
  44. }
  45. // Create client as usual.
  46. client, err := storage.NewClient(ctx)
  47. if err != nil {
  48. // TODO: Handle error.
  49. }
  50. // This request is now directed to http://localhost:9000/storage/v1/b
  51. // instead of https://storage.googleapis.com/storage/v1/b
  52. if err := client.Bucket("my-bucket").Create(ctx, projectID, nil); err != nil {
  53. // TODO: Handle error.
  54. }
  55. Please note that there is no official emulator for Cloud Storage.
  56. # Buckets
  57. A Google Cloud Storage bucket is a collection of objects. To work with a
  58. bucket, make a bucket handle:
  59. bkt := client.Bucket(bucketName)
  60. A handle is a reference to a bucket. You can have a handle even if the
  61. bucket doesn't exist yet. To create a bucket in Google Cloud Storage,
  62. call [BucketHandle.Create]:
  63. if err := bkt.Create(ctx, projectID, nil); err != nil {
  64. // TODO: Handle error.
  65. }
  66. Note that although buckets are associated with projects, bucket names are
  67. global across all projects.
  68. Each bucket has associated metadata, represented in this package by
  69. [BucketAttrs]. The third argument to [BucketHandle.Create] allows you to set
  70. the initial [BucketAttrs] of a bucket. To retrieve a bucket's attributes, use
  71. [BucketHandle.Attrs]:
  72. attrs, err := bkt.Attrs(ctx)
  73. if err != nil {
  74. // TODO: Handle error.
  75. }
  76. fmt.Printf("bucket %s, created at %s, is located in %s with storage class %s\n",
  77. attrs.Name, attrs.Created, attrs.Location, attrs.StorageClass)
  78. # Objects
  79. An object holds arbitrary data as a sequence of bytes, like a file. You
  80. refer to objects using a handle, just as with buckets, but unlike buckets
  81. you don't explicitly create an object. Instead, the first time you write
  82. to an object it will be created. You can use the standard Go [io.Reader]
  83. and [io.Writer] interfaces to read and write object data:
  84. obj := bkt.Object("data")
  85. // Write something to obj.
  86. // w implements io.Writer.
  87. w := obj.NewWriter(ctx)
  88. // Write some text to obj. This will either create the object or overwrite whatever is there already.
  89. if _, err := fmt.Fprintf(w, "This object contains text.\n"); err != nil {
  90. // TODO: Handle error.
  91. }
  92. // Close, just like writing a file.
  93. if err := w.Close(); err != nil {
  94. // TODO: Handle error.
  95. }
  96. // Read it back.
  97. r, err := obj.NewReader(ctx)
  98. if err != nil {
  99. // TODO: Handle error.
  100. }
  101. defer r.Close()
  102. if _, err := io.Copy(os.Stdout, r); err != nil {
  103. // TODO: Handle error.
  104. }
  105. // Prints "This object contains text."
  106. Objects also have attributes, which you can fetch with [ObjectHandle.Attrs]:
  107. objAttrs, err := obj.Attrs(ctx)
  108. if err != nil {
  109. // TODO: Handle error.
  110. }
  111. fmt.Printf("object %s has size %d and can be read using %s\n",
  112. objAttrs.Name, objAttrs.Size, objAttrs.MediaLink)
  113. # Listing objects
  114. Listing objects in a bucket is done with the [BucketHandle.Objects] method:
  115. query := &storage.Query{Prefix: ""}
  116. var names []string
  117. it := bkt.Objects(ctx, query)
  118. for {
  119. attrs, err := it.Next()
  120. if err == iterator.Done {
  121. break
  122. }
  123. if err != nil {
  124. log.Fatal(err)
  125. }
  126. names = append(names, attrs.Name)
  127. }
  128. Objects are listed lexicographically by name. To filter objects
  129. lexicographically, [Query.StartOffset] and/or [Query.EndOffset] can be used:
  130. query := &storage.Query{
  131. Prefix: "",
  132. StartOffset: "bar/", // Only list objects lexicographically >= "bar/"
  133. EndOffset: "foo/", // Only list objects lexicographically < "foo/"
  134. }
  135. // ... as before
  136. If only a subset of object attributes is needed when listing, specifying this
  137. subset using [Query.SetAttrSelection] may speed up the listing process:
  138. query := &storage.Query{Prefix: ""}
  139. query.SetAttrSelection([]string{"Name"})
  140. // ... as before
  141. # ACLs
  142. Both objects and buckets have ACLs (Access Control Lists). An ACL is a list of
  143. ACLRules, each of which specifies the role of a user, group or project. ACLs
  144. are suitable for fine-grained control, but you may prefer using IAM to control
  145. access at the project level (see [Cloud Storage IAM docs].
  146. To list the ACLs of a bucket or object, obtain an [ACLHandle] and call [ACLHandle.List]:
  147. acls, err := obj.ACL().List(ctx)
  148. if err != nil {
  149. // TODO: Handle error.
  150. }
  151. for _, rule := range acls {
  152. fmt.Printf("%s has role %s\n", rule.Entity, rule.Role)
  153. }
  154. You can also set and delete ACLs.
  155. # Conditions
  156. Every object has a generation and a metageneration. The generation changes
  157. whenever the content changes, and the metageneration changes whenever the
  158. metadata changes. [Conditions] let you check these values before an operation;
  159. the operation only executes if the conditions match. You can use conditions to
  160. prevent race conditions in read-modify-write operations.
  161. For example, say you've read an object's metadata into objAttrs. Now
  162. you want to write to that object, but only if its contents haven't changed
  163. since you read it. Here is how to express that:
  164. w = obj.If(storage.Conditions{GenerationMatch: objAttrs.Generation}).NewWriter(ctx)
  165. // Proceed with writing as above.
  166. # Signed URLs
  167. You can obtain a URL that lets anyone read or write an object for a limited time.
  168. Signing a URL requires credentials authorized to sign a URL. To use the same
  169. authentication that was used when instantiating the Storage client, use
  170. [BucketHandle.SignedURL].
  171. url, err := client.Bucket(bucketName).SignedURL(objectName, opts)
  172. if err != nil {
  173. // TODO: Handle error.
  174. }
  175. fmt.Println(url)
  176. You can also sign a URL without creating a client. See the documentation of
  177. [SignedURL] for details.
  178. url, err := storage.SignedURL(bucketName, "shared-object", opts)
  179. if err != nil {
  180. // TODO: Handle error.
  181. }
  182. fmt.Println(url)
  183. # Post Policy V4 Signed Request
  184. A type of signed request that allows uploads through HTML forms directly to Cloud Storage with
  185. temporary permission. Conditions can be applied to restrict how the HTML form is used and exercised
  186. by a user.
  187. For more information, please see the [XML POST Object docs] as well
  188. as the documentation of [BucketHandle.GenerateSignedPostPolicyV4].
  189. pv4, err := client.Bucket(bucketName).GenerateSignedPostPolicyV4(objectName, opts)
  190. if err != nil {
  191. // TODO: Handle error.
  192. }
  193. fmt.Printf("URL: %s\nFields; %v\n", pv4.URL, pv4.Fields)
  194. # Credential requirements for signing
  195. If the GoogleAccessID and PrivateKey option fields are not provided, they will
  196. be automatically detected by [BucketHandle.SignedURL] and
  197. [BucketHandle.GenerateSignedPostPolicyV4] if any of the following are true:
  198. - you are authenticated to the Storage Client with a service account's
  199. downloaded private key, either directly in code or by setting the
  200. GOOGLE_APPLICATION_CREDENTIALS environment variable (see [Other Environments]),
  201. - your application is running on Google Compute Engine (GCE), or
  202. - you are logged into [gcloud using application default credentials]
  203. with [impersonation enabled].
  204. Detecting GoogleAccessID may not be possible if you are authenticated using a
  205. token source or using [option.WithHTTPClient]. In this case, you can provide a
  206. service account email for GoogleAccessID and the client will attempt to sign
  207. the URL or Post Policy using that service account.
  208. To generate the signature, you must have:
  209. - iam.serviceAccounts.signBlob permissions on the GoogleAccessID service
  210. account, and
  211. - the [IAM Service Account Credentials API] enabled (unless authenticating
  212. with a downloaded private key).
  213. # Errors
  214. Errors returned by this client are often of the type [googleapi.Error].
  215. These errors can be introspected for more information by using [errors.As]
  216. with the richer [googleapi.Error] type. For example:
  217. var e *googleapi.Error
  218. if ok := errors.As(err, &e); ok {
  219. if e.Code == 409 { ... }
  220. }
  221. # Retrying failed requests
  222. Methods in this package may retry calls that fail with transient errors.
  223. Retrying continues indefinitely unless the controlling context is canceled, the
  224. client is closed, or a non-transient error is received. To stop retries from
  225. continuing, use context timeouts or cancellation.
  226. The retry strategy in this library follows best practices for Cloud Storage. By
  227. default, operations are retried only if they are idempotent, and exponential
  228. backoff with jitter is employed. In addition, errors are only retried if they
  229. are defined as transient by the service. See the [Cloud Storage retry docs]
  230. for more information.
  231. Users can configure non-default retry behavior for a single library call (using
  232. [BucketHandle.Retryer] and [ObjectHandle.Retryer]) or for all calls made by a
  233. client (using [Client.SetRetry]). For example:
  234. o := client.Bucket(bucket).Object(object).Retryer(
  235. // Use WithBackoff to change the timing of the exponential backoff.
  236. storage.WithBackoff(gax.Backoff{
  237. Initial: 2 * time.Second,
  238. }),
  239. // Use WithPolicy to configure the idempotency policy. RetryAlways will
  240. // retry the operation even if it is non-idempotent.
  241. storage.WithPolicy(storage.RetryAlways),
  242. )
  243. // Use a context timeout to set an overall deadline on the call, including all
  244. // potential retries.
  245. ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
  246. defer cancel()
  247. // Delete an object using the specified strategy and timeout.
  248. if err := o.Delete(ctx); err != nil {
  249. // Handle err.
  250. }
  251. # Sending Custom Headers
  252. You can add custom headers to any API call made by this package by using
  253. [callctx.SetHeaders] on the context which is passed to the method. For example,
  254. to add a [custom audit logging] header:
  255. ctx := context.Background()
  256. ctx = callctx.SetHeaders(ctx, "x-goog-custom-audit-<key>", "<value>")
  257. // Use client as usual with the context and the additional headers will be sent.
  258. client.Bucket("my-bucket").Attrs(ctx)
  259. # Experimental gRPC API
  260. This package includes support for the Cloud Storage gRPC API, which is currently
  261. in preview. This implementation uses gRPC rather than the current JSON & XML
  262. APIs to make requests to Cloud Storage. Kindly contact the Google Cloud Storage gRPC
  263. team at gcs-grpc-contact@google.com with a list of GCS buckets you would like to
  264. allowlist to access this API. The Go Storage gRPC library is not yet generally
  265. available, so it may be subject to breaking changes.
  266. To create a client which will use gRPC, use the alternate constructor:
  267. ctx := context.Background()
  268. client, err := storage.NewGRPCClient(ctx)
  269. if err != nil {
  270. // TODO: Handle error.
  271. }
  272. // Use client as usual.
  273. If the application is running within GCP, users may get better performance by
  274. enabling Google Direct Access (enabling requests to skip some proxy steps). To enable,
  275. set the environment variable `GOOGLE_CLOUD_ENABLE_DIRECT_PATH_XDS=true` and add
  276. the following side-effect imports to your application:
  277. import (
  278. _ "google.golang.org/grpc/balancer/rls"
  279. _ "google.golang.org/grpc/xds/googledirectpath"
  280. )
  281. [Cloud Storage IAM docs]: https://cloud.google.com/storage/docs/access-control/iam
  282. [XML POST Object docs]: https://cloud.google.com/storage/docs/xml-api/post-object
  283. [Cloud Storage retry docs]: https://cloud.google.com/storage/docs/retry-strategy
  284. [Other Environments]: https://cloud.google.com/storage/docs/authentication#libauth
  285. [gcloud using application default credentials]: https://cloud.google.com/sdk/gcloud/reference/auth/application-default/login
  286. [impersonation enabled]: https://cloud.google.com/sdk/gcloud/reference#--impersonate-service-account
  287. [IAM Service Account Credentials API]: https://console.developers.google.com/apis/api/iamcredentials.googleapis.com/overview
  288. [custom audit logging]: https://cloud.google.com/storage/docs/audit-logging#add-custom-metadata
  289. */
  290. package storage // import "cloud.google.com/go/storage"