github.com/thiagoyeds/go-cloud@v0.26.0/runtimevar/filevar/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 filevar_test
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"io/ioutil"
    21  	"log"
    22  
    23  	"gocloud.dev/runtimevar"
    24  	"gocloud.dev/runtimevar/filevar"
    25  )
    26  
    27  func ExampleOpenVariable() {
    28  	// Create a temporary file to hold our config.
    29  	f, err := ioutil.TempFile("", "")
    30  	if err != nil {
    31  		log.Fatal(err)
    32  	}
    33  	if _, err := f.Write([]byte("hello world")); err != nil {
    34  		log.Fatal(err)
    35  	}
    36  
    37  	// Construct a *runtimevar.Variable pointing at f.
    38  	v, err := filevar.OpenVariable(f.Name(), runtimevar.StringDecoder, nil)
    39  	if err != nil {
    40  		log.Fatal(err)
    41  	}
    42  	defer v.Close()
    43  
    44  	// We can now read the current value of the variable from v.
    45  	snapshot, err := v.Latest(context.Background())
    46  	if err != nil {
    47  		log.Fatal(err)
    48  	}
    49  	// runtimevar.Snapshot.Value is decoded to a string.
    50  	fmt.Println(snapshot.Value.(string))
    51  
    52  	// Output:
    53  	// hello world
    54  }
    55  
    56  func Example_openVariableFromURL() {
    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, add a blank import: _ "gocloud.dev/runtimevar/filevar"
    59  	// PRAGMA: On gocloud.dev, hide lines until the next blank line.
    60  	ctx := context.Background()
    61  
    62  	// runtimevar.OpenVariable creates a *runtimevar.Variable from a URL.
    63  
    64  	v, err := runtimevar.OpenVariable(ctx, "file:///path/to/config.txt?decoder=string")
    65  	if err != nil {
    66  		log.Fatal(err)
    67  	}
    68  	defer v.Close()
    69  }