Debian Codegraph @

blob/example_test.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
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 // https://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 blob_test
16
17 import (
18 "bytes"
19 "context"
20 "fmt"
21 "io"
22 "log"
23 "os"
24
25 "cloud.google.com/go/storage"
26 "github.com/aws/smithy-go"
27 "gocloud.dev/blob"
28 "gocloud.dev/blob/fileblob"
29
30 _ "gocloud.dev/blob/gcsblob"
31 _ "gocloud.dev/blob/s3blob"
32 )
33
34 func ExampleBucket_NewReader() {
35 // PRAGMA: This example is used on gocloud.dev; PRAGMA comments adjust how it is shown and can be ignored.
36 // PRAGMA: On gocloud.dev, hide lines until the next blank line.
37 ctx := context.Background()
38 var bucket *blob.Bucket
39
40 // Open the key "foo.txt" for reading with the default options.
41 r, err := bucket.NewReader(ctx, "foo.txt", nil)
42 if err != nil {
43 log.Fatal(err)
44 }
45 defer r.Close()
46 // Readers also have a limited view of the blob's metadata.
47 fmt.Println("Content-Type:", r.ContentType())
48 fmt.Println()
49 // Copy from the reader to stdout.
50 if _, err := io.Copy(os.Stdout, r); err != nil {
51 log.Fatal(err)
52 }
53 }
54
55 func ExampleBucket_NewRangeReader() {
56 // PRAGMA: This example is used on gocloud.dev; PRAGMA comments adjust how it is shown and can be ignored.
57 // PRAGMA: On gocloud.dev, hide lines until the next blank line.
58 ctx := context.Background()
59 var bucket *blob.Bucket
60
61 // Open the key "foo.txt" for reading at offset 1024 and read up to 4096 bytes.
62 r, err := bucket.NewRangeReader(ctx, "foo.txt", 1024, 4096, nil)
63 if err != nil {
64 log.Fatal(err)
65 }
66 defer r.Close()
67 // Copy from the read range to stdout.
68 if _, err := io.Copy(os.Stdout, r); err != nil {
69 log.Fatal(err)
70 }
71 }
72
73 func ExampleBucket_NewWriter() {
74 // PRAGMA: This example is used on gocloud.dev; PRAGMA comments adjust how it is shown and can be ignored.
75 // PRAGMA: On gocloud.dev, hide lines until the next blank line.
76 ctx := context.Background()
77 var bucket *blob.Bucket
78
79 // Open the key "foo.txt" for writing with the default options.
80 w, err := bucket.NewWriter(ctx, "foo.txt", nil)
81 if err != nil {
82 log.Fatal(err)
83 }
84 _, writeErr := fmt.Fprintln(w, "Hello, World!")
85 // Always check the return value of Close when writing.
86 closeErr := w.Close()
87 if writeErr != nil {
88 log.Fatal(writeErr)
89 }
90 if closeErr != nil {
91 log.Fatal(closeErr)
92 }
93 }
94
95 func ExampleBucket_NewWriter_cancel() {
96 // PRAGMA: This example is used on gocloud.dev; PRAGMA comments adjust how it is shown and can be ignored.
97 // PRAGMA: On gocloud.dev, hide lines until the next blank line.
98 ctx := context.Background()
99 var bucket *blob.Bucket
100
101 // Create a cancelable context from the existing context.
102 writeCtx, cancelWrite := context.WithCancel(ctx)
103 defer cancelWrite()
104
105 // Open the key "foo.txt" for writing with the default options.
106 w, err := bucket.NewWriter(writeCtx, "foo.txt", nil)
107 if err != nil {
108 log.Fatal(err)
109 }
110
111 // Assume some writes happened and we encountered an error.
112 // Now we want to abort the write.
113
114 if err != nil {
115 // First cancel the context.
116 cancelWrite()
117 // You must still close the writer to avoid leaking resources.
118 w.Close()
119 }
120 }
121
122 func ExampleBucket_Delete() {
123 // PRAGMA: This example is used on gocloud.dev; PRAGMA comments adjust how it is shown and can be ignored.
124 // PRAGMA: On gocloud.dev, hide lines until the next blank line.
125 ctx := context.Background()
126 var bucket *blob.Bucket
127
128 if err := bucket.Delete(ctx, "foo.txt"); err != nil {
129 log.Fatal(err)
130 }
131 }
132
133 func Example() {
134 // Connect to a bucket when your program starts up.
135 // This example uses the file-based implementation in fileblob, and creates
136 // a temporary directory to use as the root directory.
137 dir, cleanup := newTempDir()
138 defer cleanup()
139 bucket, err := fileblob.OpenBucket(dir, nil)
140 if err != nil {
141 log.Fatal(err)
142 }
143 defer bucket.Close()
144
145 // We now have a *blob.Bucket! We can write our application using the
146 // *blob.Bucket type, and have the freedom to change the initialization code
147 // above to choose a different service-specific driver later.
148
149 // In this example, we'll write a blob and then read it.
150 ctx := context.Background()
151 if err := bucket.WriteAll(ctx, "foo.txt", []byte("Go Cloud Development Kit"), nil); err != nil {
152 log.Fatal(err)
153 }
154 b, err := bucket.ReadAll(ctx, "foo.txt")
155 if err != nil {
156 log.Fatal(err)
157 }
158 fmt.Println(string(b))
159
160 // Output:
161 // Go Cloud Development Kit
162 }
163
164 func ExampleBucket_ErrorAs() {
165 // This example is specific to the s3blob implementation; it demonstrates
166 // access to the underlying smithy.APIError type.
167 // The types exposed for ErrorAs by s3blob are documented in
168 // https://godoc.org/gocloud.dev/blob/s3blob#hdr-As
169
170 ctx := context.Background()
171
172 b, err := blob.OpenBucket(ctx, "s3://my-bucket")
173 if err != nil {
174 log.Fatal(err)
175 }
176 defer b.Close()
177
178 _, err = b.ReadAll(ctx, "nosuchfile")
179 if err != nil {
180 var awsErr smithy.APIError
181 if b.ErrorAs(err, &awsErr) {
182 fmt.Println(awsErr.ErrorCode())
183 }
184 }
185 }
186
187 func ExampleBucket_List() {
188 // Connect to a bucket when your program starts up.
189 // This example uses the file-based implementation.
190 dir, cleanup := newTempDir()
191 defer cleanup()
192
193 // Create the file-based bucket.
194 bucket, err := fileblob.OpenBucket(dir, nil)
195 if err != nil {
196 log.Fatal(err)
197 }
198 defer bucket.Close()
199
200 // Create some blob objects for listing: "foo[0..4].txt".
201 ctx := context.Background()
202 for i := range 5 {
203 if err := bucket.WriteAll(ctx, fmt.Sprintf("foo%d.txt", i), []byte("Go Cloud Development Kit"), nil); err != nil {
204 log.Fatal(err)
205 }
206 }
207
208 // Iterate over them.
209 // This will list the blobs created above because fileblob is strongly
210 // consistent, but is not guaranteed to work on all services.
211 li := bucket.List(nil)
212 for {
213 obj, err := li.Next(ctx)
214 if err == io.EOF {
215 break
216 }
217 if err != nil {
218 log.Fatal(err)
219 }
220 fmt.Println(obj.Key)
221 }
222
223 // Alternatively, use All to iterate (and optionally download):
224 fmt.Println()
225 fmt.Println("Now, using an iterator:")
226 li = bucket.List(nil)
227 iter, errFn := li.All(ctx)
228 for obj, download := range iter {
229 var buf bytes.Buffer
230 if err := download(&buf, nil /* default ReaderOptions */); err != nil {
231 log.Fatalf("download of %q failed: %v", obj.Key, err)
232 }
233 fmt.Printf("%s: %s\n", obj.Key, string(buf.Bytes()))
234 }
235 if err := errFn(); err != nil {
236 log.Fatalf("iteration failed: %v", err)
237 }
238
239 // Output:
240 // foo0.txt
241 // foo1.txt
242 // foo2.txt
243 // foo3.txt
244 // foo4.txt
245 //
246 // Now, using an iterator:
247 // foo0.txt: Go Cloud Development Kit
248 // foo1.txt: Go Cloud Development Kit
249 // foo2.txt: Go Cloud Development Kit
250 // foo3.txt: Go Cloud Development Kit
251 // foo4.txt: Go Cloud Development Kit
252 }
253
254 func ExampleBucket_List_withDelimiter() {
255 // Connect to a bucket when your program starts up.
256 // This example uses the file-based implementation.
257 dir, cleanup := newTempDir()
258 defer cleanup()
259
260 // Create the file-based bucket.
261 bucket, err := fileblob.OpenBucket(dir, nil)
262 if err != nil {
263 log.Fatal(err)
264 }
265 defer bucket.Close()
266
267 // Create some blob objects in a hierarchy.
268 ctx := context.Background()
269 for _, key := range []string{
270 "dir1/subdir/a.txt",
271 "dir1/subdir/b.txt",
272 "dir2/c.txt",
273 "d.txt",
274 } {
275 if err := bucket.WriteAll(ctx, key, []byte("Go Cloud Development Kit"), nil); err != nil {
276 log.Fatal(err)
277 }
278 }
279
280 // list lists files in b starting with prefix. It uses the delimiter "/",
281 // and recurses into "directories", adding 2 spaces to indent each time.
282 // It will list the blobs created above because fileblob is strongly
283 // consistent, but is not guaranteed to work on all services.
284 var list func(context.Context, *blob.Bucket, string, string)
285 list = func(ctx context.Context, b *blob.Bucket, prefix, indent string) {
286 iter := b.List(&blob.ListOptions{
287 Delimiter: "/",
288 Prefix: prefix,
289 })
290 for {
291 obj, err := iter.Next(ctx)
292 if err == io.EOF {
293 break
294 }
295 if err != nil {
296 log.Fatal(err)
297 }
298 fmt.Printf("%s%s\n", indent, obj.Key)
299 if obj.IsDir {
300 list(ctx, b, obj.Key, indent+" ")
301 }
302 }
303 }
304 list(ctx, bucket, "", "")
305
306 // Output:
307 // d.txt
308 // dir1/
309 // dir1/subdir/
310 // dir1/subdir/a.txt
311 // dir1/subdir/b.txt
312 // dir2/
313 // dir2/c.txt
314 }
315
316 func ExampleBucket_ListPage() {
317 // Connect to a bucket when your program starts up.
318 // This example uses the file-based implementation.
319 dir, cleanup := newTempDir()
320 defer cleanup()
321
322 // Create the file-based bucket.
323 bucket, err := fileblob.OpenBucket(dir, nil)
324 if err != nil {
325 log.Fatal(err)
326 }
327 defer bucket.Close()
328
329 // Create some blob objects for listing: "foo[0..7].txt".
330 ctx := context.Background()
331 for i := range 8 {
332 if err := bucket.WriteAll(ctx, fmt.Sprintf("foo%d.txt", i), []byte("Go Cloud Development Kit"), nil); err != nil {
333 log.Fatal(err)
334 }
335 }
336
337 // Iterate over them in pages.
338 // This will list the blobs created above because fileblob is strongly
339 // consistent, but is not guaranteed to work on all services.
340
341 // The first page of 3 results.
342 objs, token, err := bucket.ListPage(ctx, blob.FirstPageToken, 3, nil)
343 if err != nil {
344 log.Fatal(err)
345 }
346 for _, obj := range objs {
347 fmt.Println(obj.Key)
348 }
349 fmt.Println("END OF PAGE 1")
350
351 // The second page of 3 results.
352 objs, token, err = bucket.ListPage(ctx, token, 3, nil)
353 if err != nil {
354 log.Fatal(err)
355 }
356 for _, obj := range objs {
357 fmt.Println(obj.Key)
358 }
359 fmt.Println("END OF PAGE 2")
360
361 // The third page with the last 2 results.
362 objs, token, err = bucket.ListPage(ctx, token, 3, nil)
363 if err != nil {
364 log.Fatal(err)
365 }
366 for _, obj := range objs {
367 fmt.Println(obj.Key)
368 }
369 fmt.Println("END OF PAGE 3")
370
371 // There are no more pages, so token is now nil. Calling ListPage again will return io.EOF.
372 if token != nil {
373 fmt.Println("Token was not nil.")
374 }
375
376 // Output:
377 // foo0.txt
378 // foo1.txt
379 // foo2.txt
380 // END OF PAGE 1
381 // foo3.txt
382 // foo4.txt
383 // foo5.txt
384 // END OF PAGE 2
385 // foo6.txt
386 // foo7.txt
387 // END OF PAGE 3
388 }
389
390 func ExampleBucket_As() {
391 // This example is specific to the gcsblob implementation; it demonstrates
392 // access to the underlying cloud.google.com/go/storage.Client type.
393 // The types exposed for As by gcsblob are documented in
394 // https://godoc.org/gocloud.dev/blob/gcsblob#hdr-As
395
396 // This URL will open the bucket "my-bucket" using default credentials.
397 ctx := context.Background()
398 b, err := blob.OpenBucket(ctx, "gs://my-bucket")
399 if err != nil {
400 log.Fatal(err)
401 }
402 defer b.Close()
403
404 // Access storage.Client fields via gcsClient here.
405 var gcsClient *storage.Client
406 if b.As(&gcsClient) {
407 email, err := gcsClient.ServiceAccount(ctx, "project-name")
408 if err != nil {
409 log.Fatal(err)
410 }
411 _ = email
412 } else {
413 log.Println("Unable to access storage.Client through Bucket.As")
414 }
415 }
416
417 func ExampleWriterOptions() {
418 // This example is specific to the gcsblob implementation; it demonstrates
419 // access to the underlying cloud.google.com/go/storage.Writer type.
420 // The types exposed for As by gcsblob are documented in
421 // https://godoc.org/gocloud.dev/blob/gcsblob#hdr-As
422
423 ctx := context.Background()
424
425 b, err := blob.OpenBucket(ctx, "gs://my-bucket")
426 if err != nil {
427 log.Fatal(err)
428 }
429 defer b.Close()
430
431 beforeWrite := func(as func(any) bool) error {
432 var sw *storage.Writer
433 if as(&sw) {
434 fmt.Println(sw.ChunkSize)
435 }
436 return nil
437 }
438
439 options := blob.WriterOptions{BeforeWrite: beforeWrite}
440 if err := b.WriteAll(ctx, "newfile.txt", []byte("hello\n"), &options); err != nil {
441 log.Fatal(err)
442 }
443 }
444
445 func ExampleListObject_As() {
446 // This example is specific to the gcsblob implementation; it demonstrates
447 // access to the underlying cloud.google.com/go/storage.ObjectAttrs type.
448 // The types exposed for As by gcsblob are documented in
449 // https://godoc.org/gocloud.dev/blob/gcsblob#hdr-As
450
451 ctx := context.Background()
452
453 b, err := blob.OpenBucket(ctx, "gs://my-bucket")
454 if err != nil {
455 log.Fatal(err)
456 }
457 defer b.Close()
458
459 iter := b.List(nil)
460 for {
461 obj, err := iter.Next(ctx)
462 if err == io.EOF {
463 break
464 }
465 if err != nil {
466 log.Fatal(err)
467 }
468 // Access storage.ObjectAttrs via oa here.
469 var oa storage.ObjectAttrs
470 if obj.As(&oa) {
471 _ = oa.Owner
472 }
473 }
474 }
475
476 func ExampleListOptions() {
477 // This example is specific to the gcsblob implementation; it demonstrates
478 // access to the underlying cloud.google.com/go/storage.Query type.
479 // The types exposed for As by gcsblob are documented in
480 // https://godoc.org/gocloud.dev/blob/gcsblob#hdr-As
481
482 ctx := context.Background()
483
484 b, err := blob.OpenBucket(ctx, "gs://my-bucket")
485 if err != nil {
486 log.Fatal(err)
487 }
488 defer b.Close()
489
490 beforeList := func(as func(any) bool) error {
491 // Access storage.Query via q here.
492 var q *storage.Query
493 if as(&q) {
494 _ = q.Delimiter
495 }
496 return nil
497 }
498
499 iter := b.List(&blob.ListOptions{Prefix: "", Delimiter: "/", BeforeList: beforeList})
500 for {
501 obj, err := iter.Next(ctx)
502 if err == io.EOF {
503 break
504 }
505 if err != nil {
506 log.Fatal(err)
507 }
508 _ = obj
509 }
510 }
511
512 func ExamplePrefixedBucket() {
513 // PRAGMA: This example is used on gocloud.dev; PRAGMA comments adjust how it is shown and can be ignored.
514 // PRAGMA: On gocloud.dev, hide lines until the next blank line.
515 var bucket *blob.Bucket
516
517 // Wrap the bucket using blob.PrefixedBucket.
518 // The prefix should end with "/", so that the resulting bucket operates
519 // in a subfolder.
520 bucket = blob.PrefixedBucket(bucket, "a/subfolder/")
521
522 // The original bucket is no longer usable; it has been closed.
523 // The wrapped bucket should be closed when done.
524 defer bucket.Close()
525
526 // Bucket operations on <key> will be translated to "a/subfolder/<key>".
527 }
528
529 func ExampleSingleKeyBucket() {
530 // PRAGMA: This example is used on gocloud.dev; PRAGMA comments adjust how it is shown and can be ignored.
531 // PRAGMA: On gocloud.dev, hide lines until the next blank line.
532 var bucket *blob.Bucket
533
534 // Wrap the bucket using blob.SingleKeyBucket.
535 // The bucket always references the provided key.
536 bucket = blob.SingleKeyBucket(bucket, "foo.txt")
537
538 // The original bucket is no longer usable; it has been closed.
539 // The wrapped bucket should be closed when done.
540 defer bucket.Close()
541
542 // Bucket operations will ignore the passed-in key and always reference foo.txt.
543 }
544
545 func ExampleReader_As() {
546 // This example is specific to the gcsblob implementation; it demonstrates
547 // access to the underlying cloud.google.com/go/storage.Reader type.
548 // The types exposed for As by gcsblob are documented in
549 // https://godoc.org/gocloud.dev/blob/gcsblob#hdr-As
550
551 ctx := context.Background()
552
553 b, err := blob.OpenBucket(ctx, "gs://my-bucket")
554 if err != nil {
555 log.Fatal(err)
556 }
557 defer b.Close()
558
559 r, err := b.NewReader(ctx, "gopher.png", nil)
560 if err != nil {
561 log.Fatal(err)
562 }
563 defer r.Close()
564
565 // Access storage.Reader via sr here.
566 var sr *storage.Reader
567 if r.As(&sr) {
568 _ = sr.Attrs
569 }
570 }
571
572 func ExampleAttributes_As() {
573 // This example is specific to the gcsblob implementation; it demonstrates
574 // access to the underlying cloud.google.com/go/storage.ObjectAttrs type.
575 // The types exposed for As by gcsblob are documented in
576 // https://godoc.org/gocloud.dev/blob/gcsblob#hdr-As
577 ctx := context.Background()
578
579 b, err := blob.OpenBucket(ctx, "gs://my-bucket")
580 if err != nil {
581 log.Fatal(err)
582 }
583 defer b.Close()
584
585 attrs, err := b.Attributes(ctx, "gopher.png")
586 if err != nil {
587 log.Fatal(err)
588 }
589
590 var oa storage.ObjectAttrs
591 if attrs.As(&oa) {
592 fmt.Println(oa.Owner)
593 }
594 }
595
596 func newTempDir() (string, func()) {
597 dir, err := os.MkdirTemp("", "go-cloud-blob-example")
598 if err != nil {
599 panic(err)
600 }
601 return dir, func() { os.RemoveAll(dir) }
602 }