github.com/thiagoyeds/go-cloud@v0.26.0/blob/example_openbucket_test.go (about)

     1  // Copyright 2019 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  	"context"
    19  	"fmt"
    20  	"log"
    21  
    22  	"gocloud.dev/blob"
    23  	_ "gocloud.dev/blob/memblob"
    24  )
    25  
    26  func Example_openFromURL() {
    27  	ctx := context.Background()
    28  
    29  	// Connect to a bucket using a URL.
    30  	// This example uses "memblob", the in-memory implementation.
    31  	// We need to add a blank import line to register the memblob driver's
    32  	// URLOpener, which implements blob.BucketURLOpener:
    33  	// import _ "gocloud.dev/blob/memblob"
    34  	// memblob registers for the "mem" scheme.
    35  	// All blob.OpenBucket URLs also work with "blob+" or "blob+bucket+" prefixes,
    36  	// e.g., "blob+mem://" or "blob+bucket+mem://".
    37  	b, err := blob.OpenBucket(ctx, "mem://")
    38  	if err != nil {
    39  		log.Fatal(err)
    40  	}
    41  	defer b.Close()
    42  
    43  	// Now we can use b to read or write to blobs in the bucket.
    44  	if err := b.WriteAll(ctx, "my-key", []byte("hello world"), nil); err != nil {
    45  		log.Fatal(err)
    46  	}
    47  	data, err := b.ReadAll(ctx, "my-key")
    48  	if err != nil {
    49  		log.Fatal(err)
    50  	}
    51  	fmt.Println(string(data))
    52  	// Output:
    53  	// hello world
    54  }
    55  
    56  func Example_openFromURLWithPrefix() {
    57  	// PRAGMA: This example is used on gocloud.dev; PRAGMA comments adjust how it is shown and can be ignored.
    58  	// PRAGMA: On gocloud.dev, hide lines until the next blank line.
    59  	ctx := context.Background()
    60  
    61  	// Connect to a bucket using a URL, using the "prefix" query parameter to
    62  	// target a subfolder in the bucket.
    63  	// The prefix should end with "/", so that the resulting bucket operates
    64  	// in a subfolder.
    65  	b, err := blob.OpenBucket(ctx, "mem://?prefix=a/subfolder/")
    66  	if err != nil {
    67  		log.Fatal(err)
    68  	}
    69  	defer b.Close()
    70  
    71  	// Bucket operations on <key> will be translated to "a/subfolder/<key>".
    72  }