Debian Codegraph @

internal/website/content/howto/blob/_index.md

raw
1 ---
2 title: "Blob"
3 date: 2019-07-09T16:46:29-07:00
4 lastmod: 2019-07-29T12:00:00-07:00
5 showInSidenav: true
6 toc: true
7 ---
8
9 Blobs are a common abstraction for storing unstructured data on Cloud storage
10 services and accessing them via HTTP. This guide shows how to work with
11 blobs in the Go CDK.
12
13 <!--more-->
14
15 The [`blob` package][] supports operations like reading and writing blobs (using standard
16 [`io` package][] interfaces), deleting blobs, and listing blobs in a bucket.
17
18 Subpackages contain driver implementations of blob for various services,
19 including Cloud and on-prem solutions. You can develop your application
20 locally using [`fileblob`][], then deploy it to multiple Cloud providers with
21 minimal initialization reconfiguration.
22
23 [`blob` package]: https://godoc.org/gocloud.dev/blob
24 [`io` package]: https://golang.org/pkg/io/
25 [`fileblob`]: https://godoc.org/gocloud.dev/blob/fileblob
26
27 ## Opening a Bucket {#opening}
28
29 The first step in interacting with unstructured storage is
30 to instantiate a portable [`*blob.Bucket`][] for your storage service.
31
32 The easiest way to do so is to use [`blob.OpenBucket`][] and a service-specific URL
33 pointing to the bucket, making sure you ["blank import"][] the driver package to
34 link it in.
35
36 ```go
37 import (
38 "gocloud.dev/blob"
39 _ "gocloud.dev/blob/<driver>"
40 )
41 ...
42 bucket, err := blob.OpenBucket(context.Background(), "<driver-url>")
43 if err != nil {
44 return fmt.Errorf("could not open bucket: %v", err)
45 }
46 defer bucket.Close()
47 // bucket is a *blob.Bucket; see usage below
48 ...
49 ```
50
51 See [Concepts: URLs][] for general background and the [guide below][] for URL usage
52 for each supported service.
53
54 Alternatively, if you need
55 fine-grained control over the connection settings, you can call the constructor
56 function in the driver package directly.
57
58 ```go
59 import "gocloud.dev/blob/<driver>"
60 ...
61 bucket, err := <driver>.OpenBucket(...)
62 ...
63 ```
64
65 You may find the [`wire` package][] useful for managing your initialization code
66 when switching between different backing services.
67
68 See the [guide below][] for constructor usage for each supported service.
69
70 [`wire` package]: http://github.com/google/wire
71 [`*blob.Bucket`]: https://godoc.org/gocloud.dev/blob#Bucket
72 [`blob.OpenBucket`]: https://godoc.org/gocloud.dev/blob#OpenBucket
73 ["blank import"]: https://golang.org/doc/effective_go.html#blank_import
74 [Concepts: URLs]: {{< ref "/concepts/urls.md" >}}
75 [guide below]: {{< ref "#services" >}}
76
77 ### Prefixed Buckets {#prefix}
78
79 You can wrap a `*blob.Bucket` to always operate on a subfolder of the bucket
80 using `blob.PrefixedBucket`:
81
82 {{< goexample "gocloud.dev/blob.ExamplePrefixedBucket" >}}
83
84 Alternatively, you can configure the prefix directly in the `blob.OpenBucket`
85 URL:
86
87 {{< goexample "gocloud.dev/blob.Example_openFromURLWithPrefix" >}}
88
89 ### Single Key Buckets {#singlekey}
90
91 You can wrap a `*blob.Bucket` to always operate on a single key
92 using `blob.SingleKeyBucket`:
93
94 {{< goexample "gocloud.dev/blob.ExampleSingleKeyBucket" >}}
95
96 Alternatively, you can configure the single key directly in the `blob.OpenBucket`
97 URL:
98
99 {{< goexample "gocloud.dev/blob.Example_openFromURLWithSingleKey" >}}
100
101 The resulting bucket will ignore the `key` parameter to its functions,
102 and always refer to the single key. This can be useful to allow configuration
103 of a specific "file" via a single URL.
104
105 `List` functions will not work on single key buckets.
106
107 ## Using a Bucket {#using}
108
109 Once you have opened a bucket for the storage provider you want, you can
110 store and access data from it using the standard Go I/O patterns described
111 below. Other operations like listing and reading metadata are documented in the
112 [`blob` package documentation][].
113
114 [`blob` package documentation]: https://godoc.org/gocloud.dev/blob
115
116 ### Writing Data to a Bucket {#writing}
117
118 To write data to a bucket, you create a writer, write data to it, and then
119 close the writer. Closing the writer commits the write to the provider,
120 flushing any buffers, and releases any resources used while writing, so you
121 must always check the error of `Close`.
122
123 The writer implements [`io.Writer`][], so you can use any functions that take
124 an `io.Writer` like `io.Copy` or `fmt.Fprintln`.
125
126 {{< goexample src="gocloud.dev/blob.ExampleBucket_NewWriter" imports="0" >}}
127
128 In some cases, you may want to cancel an in-progress write to avoid the blob
129 being created or overwritten. A typical reason for wanting to cancel a write
130 is encountering an error in the stream your program is copying from. To abort
131 a write, you cancel the `Context` you pass to the writer. Again, you must
132 always `Close` the writer to release the resources, but in this case you can
133 ignore the error because the write's failure is expected.
134
135 {{< goexample src="gocloud.dev/blob.ExampleBucket_NewWriter_cancel" imports="0" >}}
136
137 [`io.Writer`]: https://golang.org/pkg/io/#Writer
138
139 ### Reading Data from a Bucket {#reading}
140
141 Once you have written data to a bucket, you can read it back by creating a
142 reader. The reader implements [`io.Reader`][], so you can use any functions
143 that take an `io.Reader` like `io.Copy` or `io/io.ReadAll`. You must
144 always close a reader after using it to avoid leaking resources.
145
146 {{< goexample src="gocloud.dev/blob.ExampleBucket_NewReader" imports="0" >}}
147
148 Many storage providers provide efficient random-access to data in buckets. To
149 start reading from an arbitrary offset in the blob, use `NewRangeReader`.
150
151 {{< goexample src="gocloud.dev/blob.ExampleBucket_NewRangeReader" imports="0" >}}
152
153 [`io.Reader`]: https://golang.org/pkg/io/#Reader
154
155 ### Deleting a Bucket {#deleting}
156
157 You can delete blobs using the `Bucket.Delete` method.
158
159 {{< goexample src="gocloud.dev/blob.ExampleBucket_Delete" imports="0" >}}
160
161 ## Other Usage Samples
162
163 * [CLI Tutorial]({{< ref "/tutorials/cli-uploader.md" >}})
164 * [CLI Sample](https://github.com/google/go-cloud/tree/master/samples/gocdk-blob)
165 * [Guestbook sample](https://gocloud.dev/tutorials/guestbook/)
166 * [blob package examples](https://godoc.org/gocloud.dev/blob#pkg-examples)
167
168 ## Supported Storage Services {#services}
169
170 ### Google Cloud Storage {#gcs}
171
172 [Google Cloud Storage][] (GCS) URLs in the Go CDK closely resemble the URLs
173 you would see in the [`gsutil`][] CLI.
174
175 [Google Cloud Storage]: https://cloud.google.com/storage/
176 [`gsutil`]: https://cloud.google.com/storage/docs/gsutil
177
178 `blob.OpenBucket` will use Application Default Credentials; if you have
179 authenticated via [`gcloud auth application-default login`][], it will use those credentials. See
180 [Application Default Credentials][GCP creds] to learn about authentication
181 alternatives, including using environment variables.
182
183 [GCP creds]: https://cloud.google.com/docs/authentication/production
184 [`gcloud auth application-default login`]: https://cloud.google.com/sdk/gcloud/reference/auth/application-default/login
185
186 {{< goexample "gocloud.dev/blob/gcsblob.Example_openBucketFromURL" >}}
187
188 Full details about acceptable URLs can be found under the API reference for
189 [`gcsblob.URLOpener`][].
190
191 [`gcsblob.URLOpener`]: https://godoc.org/gocloud.dev/blob/gcsblob#URLOpener
192
193 #### GCS Constructor {#gcs-ctor}
194
195 The [`gcsblob.OpenBucket`][] constructor opens a GCS bucket. You must first
196 create a `*net/http.Client` that sends requests authorized by [Google Cloud
197 Platform credentials][GCP creds]. (You can reuse the same client for any
198 other API that takes in a `*gcp.HTTPClient`.) You can find functions in the
199 [`gocloud.dev/gcp`][] package to set this up for you.
200
201 {{< goexample "gocloud.dev/blob/gcsblob.ExampleOpenBucket" >}}
202
203 [`gcsblob.OpenBucket`]: https://godoc.org/gocloud.dev/blob/gcsblob#OpenBucket
204 [`gocloud.dev/gcp`]: https://godoc.org/gocloud.dev/gcp
205
206 ### S3 {#s3}
207
208 S3 URLs in the Go CDK closely resemble the URLs you would see in the [AWS CLI][].
209 You should specify the `region` query parameter to ensure your application
210 connects to the correct region.
211
212 It will create an AWS Config based on the AWS SDK V2; see [AWS V2 Config][] to learn more.
213
214 Full details about acceptable URLs can be found under the API reference for
215 [`s3blob.URLOpener`][].
216
217 {{< goexample "gocloud.dev/blob/s3blob.Example_openBucketFromURL" >}}
218
219 [AWS CLI]: https://aws.amazon.com/cli/
220 [AWS V2 Config]: https://aws.github.io/aws-sdk-go-v2/docs/configuring-sdk/
221 [`s3blob.URLOpener`]: https://godoc.org/gocloud.dev/blob/s3blob#URLOpener
222
223 #### S3 Constructor {#s3-ctor}
224
225 The [`s3blob.OpenBucket`][] constructor opens an [S3][] bucket. You must first
226 create an AWS Config with the same region as your bucket:
227
228 {{< goexample "gocloud.dev/blob/s3blob.ExampleOpenBucket" >}}
229
230 [`s3blob.OpenBucket`]: https://godoc.org/gocloud.dev/blob/s3blob#OpenBucket
231 [S3]: https://aws.amazon.com/s3/
232
233 #### S3-Compatible Servers {#s3-compatible}
234
235 The Go CDK can also interact with [S3-compatible storage servers][] that
236 recognize the same REST HTTP endpoints as S3, like [Minio][], [Ceph][], or
237 [SeaweedFS][]. You can change the endpoint by changing the [`Endpoint` field][]
238 on the `*aws.Config` you pass to `s3blob.OpenBucket`. If you are using
239 `blob.OpenBucket`, you can switch endpoints by using the S3 URL using query
240 parameters like so:
241
242 ```go
243 bucket, err := blob.OpenBucket("s3://mybucket?" +
244 "endpoint=my.minio.local:8080&" +
245 "disable_https=true&" +
246 "s3ForcePathStyle=true")
247 ```
248
249 See [`aws.V2ConfigFromURLParams`][] for more details on supported URL options for S3.
250
251 [`aws.V2ConfigFromURLParams`]: https://godoc.org/gocloud.dev/aws#V2ConfigFromURLParams
252 [`Endpoint` field]: https://godoc.org/github.com/aws/aws-sdk-go/aws#Config.Endpoint
253 [Ceph]: https://ceph.com/
254 [Minio]: https://www.minio.io/
255 [SeaweedFS]: https://github.com/chrislusf/seaweedfs
256 [S3-compatible storage servers]: https://en.wikipedia.org/wiki/Amazon_S3#S3_API_and_competing_services
257
258 ### Azure Blob Storage {#azure}
259
260 Azure Blob Storage URLs in the Go CDK allow you to identify [Azure Blob Storage][] containers
261 when opening a bucket with `blob.OpenBucket`. Go CDK uses the environment
262 variables `AZURE_STORAGE_ACCOUNT`, `AZURE_STORAGE_KEY`, and
263 `AZURE_STORAGE_SAS_TOKEN`, among others, to configure the credentials.
264
265 {{< goexample "gocloud.dev/blob/azureblob.Example_openBucketFromURL" >}}
266
267 Full details about acceptable URLs can be found under the API reference for
268 [`azureblob.URLOpener`][].
269
270 [Azure Blob Storage]: https://azure.microsoft.com/en-us/services/storage/blobs/
271 [`azureblob.URLOpener`]: https://godoc.org/gocloud.dev/blob/azureblob#URLOpener
272
273 #### Azure Blob Constructor {#azure-ctor}
274
275 The [`azureblob.OpenBucket`][] constructor opens an Azure Blob Storage container.
276 `azureblob` operates on [Azure Storage Block Blobs][]. You must first create
277 an Azure Service Client before you can open a container.
278
279 {{< goexample "gocloud.dev/blob/azureblob.ExampleOpenBucket" >}}
280
281 [Azure Storage Block Blobs]: https://docs.microsoft.com/en-us/rest/api/storageservices/understanding-block-blobs--append-blobs--and-page-blobs#about-block-blobs
282 [`azureblob.OpenBucket`]: https://godoc.org/gocloud.dev/blob/azureblob#OpenBucket
283
284 ### Local Storage {#local}
285
286 The Go CDK provides blob drivers for storing data in memory and on the local
287 filesystem. These are primarily intended for testing and local development,
288 but may be useful in production scenarios where an NFS mount is used.
289
290 Local storage URLs take the form of either `mem://` or `file:///` URLs.
291 Memory URLs are always `mem://` with no other information and always create a
292 new bucket. File URLs convert slashes to the operating system's native file
293 separator, so on Windows, `C:\foo\bar` would be written as
294 `file:///C:/foo/bar`.
295
296 ```go
297 import (
298 "gocloud.dev/blob"
299 _ "gocloud.dev/blob/fileblob"
300 _ "gocloud.dev/blob/memblob"
301 )
302
303 // ...
304
305 bucket1, err := blob.OpenBucket(ctx, "mem://")
306 if err != nil {
307 return err
308 }
309 defer bucket1.Close()
310
311 bucket2, err := blob.OpenBucket(ctx, "file:///path/to/dir")
312 if err != nil {
313 return err
314 }
315 defer bucket2.Close()
316 ```
317
318 #### Local Storage Constructors {#local-ctor}
319
320 You can create an in-memory bucket with [`memblob.OpenBucket`][]:
321
322 {{< goexample "gocloud.dev/blob/memblob.ExampleOpenBucket" >}}
323
324 You can use a local filesystem directory with [`fileblob.OpenBucket`][]:
325
326 {{< goexample "gocloud.dev/blob/fileblob.ExampleOpenBucket" >}}
327
328 [`fileblob.OpenBucket`]: https://godoc.org/gocloud.dev/blob/fileblob#OpenBucket
329 [`memblob.OpenBucket`]: https://godoc.org/gocloud.dev/blob/memblob#OpenBucket
330