MCPcopy Create free account
hub / github.com/google/go-cloud / ExampleBucket_List

Function ExampleBucket_List

blob/example_test.go:192–257  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

190}
191
192func ExampleBucket_List() {
193 // Connect to a bucket when your program starts up.
194 // This example uses the file-based implementation.
195 dir, cleanup := newTempDir()
196 defer cleanup()
197
198 // Create the file-based bucket.
199 bucket, err := fileblob.OpenBucket(dir, nil)
200 if err != nil {
201 log.Fatal(err)
202 }
203 defer bucket.Close()
204
205 // Create some blob objects for listing: "foo[0..4].txt".
206 ctx := context.Background()
207 for i := range 5 {
208 if err := bucket.WriteAll(ctx, fmt.Sprintf("foo%d.txt", i), []byte("Go Cloud Development Kit"), nil); err != nil {
209 log.Fatal(err)
210 }
211 }
212
213 // Iterate over them.
214 // This will list the blobs created above because fileblob is strongly
215 // consistent, but is not guaranteed to work on all services.
216 li := bucket.List(nil)
217 for {
218 obj, err := li.Next(ctx)
219 if err == io.EOF {
220 break
221 }
222 if err != nil {
223 log.Fatal(err)
224 }
225 fmt.Println(obj.Key)
226 }
227
228 // Alternatively, use All to iterate (and optionally download):
229 fmt.Println()
230 fmt.Println("Now, using an iterator:")
231 li = bucket.List(nil)
232 iter, errFn := li.All(ctx)
233 for obj, download := range iter {
234 var buf bytes.Buffer
235 if err := download(&buf, nil /* default ReaderOptions */); err != nil {
236 log.Fatalf("download of %q failed: %v", obj.Key, err)
237 }
238 fmt.Printf("%s: %s\n", obj.Key, string(buf.Bytes()))
239 }
240 if err := errFn(); err != nil {
241 log.Fatalf("iteration failed: %v", err)
242 }
243
244 // Output:
245 // foo0.txt
246 // foo1.txt
247 // foo2.txt
248 // foo3.txt
249 // foo4.txt

Callers

nothing calls this directly

Calls 7

OpenBucketFunction · 0.92
newTempDirFunction · 0.85
WriteAllMethod · 0.80
ListMethod · 0.80
AllMethod · 0.80
CloseMethod · 0.65
NextMethod · 0.65

Tested by

no test coverage detected