github.com/cornelk/go-cloud@v0.17.1/blob/fileblob/example_test.go (about)

     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 fileblob_test
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"io/ioutil"
    21  	"log"
    22  	"os"
    23  	"path/filepath"
    24  	"strings"
    25  
    26  	"github.com/cornelk/go-cloud/blob"
    27  	"github.com/cornelk/go-cloud/blob/fileblob"
    28  )
    29  
    30  func ExampleOpenBucket() {
    31  	// PRAGMA: This example is used on github.com/cornelk/go-cloud; PRAGMA comments adjust how it is shown and can be ignored.
    32  
    33  	// The directory you pass to fileblob.OpenBucket must exist first.
    34  	const myDir = "path/to/local/directory"
    35  	if err := os.MkdirAll(myDir, 0777); err != nil {
    36  		log.Fatal(err)
    37  	}
    38  
    39  	// Create a file-based bucket.
    40  	bucket, err := fileblob.OpenBucket(myDir, nil)
    41  	if err != nil {
    42  		log.Fatal(err)
    43  	}
    44  	defer bucket.Close()
    45  }
    46  
    47  func Example_openBucketFromURL() {
    48  	// Create a temporary directory.
    49  	dir, err := ioutil.TempDir("", "go-cloud-fileblob-example")
    50  	if err != nil {
    51  		log.Fatal(err)
    52  	}
    53  	defer os.RemoveAll(dir)
    54  
    55  	// On Unix, append the dir to "file://".
    56  	// On Windows, convert "\" to "/" and add a leading "/":
    57  	dirpath := filepath.ToSlash(dir)
    58  	if os.PathSeparator != '/' && !strings.HasPrefix(dirpath, "/") {
    59  		dirpath = "/" + dirpath
    60  	}
    61  
    62  	// blob.OpenBucket creates a *blob.Bucket from a URL.
    63  	ctx := context.Background()
    64  	b, err := blob.OpenBucket(ctx, "file://"+dirpath)
    65  	if err != nil {
    66  		log.Fatal(err)
    67  	}
    68  	defer b.Close()
    69  
    70  	// Now we can use b to read or write files to the container.
    71  	err = b.WriteAll(ctx, "my-key", []byte("hello world"), nil)
    72  	if err != nil {
    73  		log.Fatal(err)
    74  	}
    75  	data, err := b.ReadAll(ctx, "my-key")
    76  	if err != nil {
    77  		log.Fatal(err)
    78  	}
    79  	fmt.Println(string(data))
    80  
    81  	// Output:
    82  	// hello world
    83  }