Debian Codegraph @

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