github.com/thiagoyeds/go-cloud@v0.26.0/runtimevar/blobvar/example_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 blobvar_test 16 17 import ( 18 "context" 19 "fmt" 20 "log" 21 22 "gocloud.dev/blob/memblob" 23 "gocloud.dev/runtimevar" 24 "gocloud.dev/runtimevar/blobvar" 25 ) 26 27 func ExampleOpenVariable() { 28 // Create a *blob.Bucket. 29 // Here, we use an in-memory implementation and write a sample value. 30 bucket := memblob.OpenBucket(nil) 31 defer bucket.Close() 32 ctx := context.Background() 33 err := bucket.WriteAll(ctx, "cfg-variable-name", []byte("hello world"), nil) 34 if err != nil { 35 log.Fatal(err) 36 } 37 38 // Construct a *runtimevar.Variable that watches the blob. 39 v, err := blobvar.OpenVariable(bucket, "cfg-variable-name", runtimevar.StringDecoder, nil) 40 if err != nil { 41 log.Fatal(err) 42 } 43 defer v.Close() 44 45 // We can now read the current value of the variable from v. 46 snapshot, err := v.Latest(ctx) 47 if err != nil { 48 log.Fatal(err) 49 } 50 // runtimevar.Snapshot.Value is decoded to a string. 51 fmt.Println(snapshot.Value.(string)) 52 53 // Output: 54 // hello world 55 } 56 57 func Example_openVariableFromURL() { 58 // PRAGMA: This example is used on gocloud.dev; PRAGMA comments adjust how it is shown and can be ignored. 59 // PRAGMA: On gocloud.dev, add a blank import: _ "gocloud.dev/runtimevar/blobvar" 60 // PRAGMA: On gocloud.dev, hide lines until the next blank line. 61 ctx := context.Background() 62 63 // runtimevar.OpenVariable creates a *runtimevar.Variable from a URL. 64 // The default opener opens a blob.Bucket via a URL, based on the environment 65 // variable BLOBVAR_BUCKET_URL. 66 67 v, err := runtimevar.OpenVariable(ctx, "blob://myvar.txt?decoder=string") 68 if err != nil { 69 log.Fatal(err) 70 } 71 defer v.Close() 72 }