Debian Codegraph @

runtimevar/example_openvariable_test.go

raw
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 runtimevar_test
16
17 import (
18 "context"
19 "fmt"
20 "log"
21
22 "gocloud.dev/runtimevar"
23 _ "gocloud.dev/runtimevar/constantvar"
24 )
25
26 func Example_openVariableFromURL() {
27 // Connect to a Variable using a URL.
28 // This example uses "constantvar", an in-memory implementation.
29 // We need to add a blank import line to register the constantvar driver's
30 // URLOpener, which implements runtimevar.VariableURLOpener:
31 // import _ "gocloud.dev/runtimevar/constantvar"
32 // constantvar registers for the "constant" scheme.
33 // All runtimevar.OpenVariable URLs also work with "runtimevar+" or "runtimevar+variable+" prefixes,
34 // e.g., "runtimevar+constant://..." or "runtimevar+variable+constant://...".
35 ctx := context.Background()
36 v, err := runtimevar.OpenVariable(ctx, "constant://?val=hello+world&decoder=string")
37 if err != nil {
38 log.Fatal(err)
39 }
40 defer v.Close()
41
42 // Now we can use the Variable as normal.
43 snapshot, err := v.Latest(ctx)
44 if err != nil {
45 log.Fatal(err)
46 }
47 // It's safe to cast the Value to string since we used the string decoder.
48 fmt.Printf("%s\n", snapshot.Value.(string))
49
50 // Output:
51 // hello world
52 }