MCPcopy Create free account
hub / github.com/google/go-cloud / Example_jsonDecoder

Function Example_jsonDecoder

runtimevar/example_test.go:31–65  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

29)
30
31func Example_jsonDecoder() {
32 // PRAGMA: This example is used on gocloud.dev; PRAGMA comments adjust how it is shown and can be ignored.
33 // PRAGMA: On gocloud.dev, hide lines until the next blank line.
34 ctx := context.Background()
35
36 // Config is the sample config struct we're going to parse our JSON into.
37 type Config struct {
38 Host string
39 Port int
40 }
41
42 // A sample JSON config that will decode into Config.
43 const jsonConfig = `{"Host": "gocloud.dev", "Port": 8080}`
44
45 // Construct a Decoder that decodes raw bytes into our config.
46 decoder := runtimevar.NewDecoder(Config{}, runtimevar.JSONDecode)
47
48 // Next, a construct a *Variable using a constructor or URL opener.
49 // This example uses constantvar.
50 // If you're using a URL opener, you can't decode JSON into a struct, but
51 // you can use the query parameter "decoder=jsonmap" to decode into a map.
52 v := constantvar.NewBytes([]byte(jsonConfig), decoder)
53 defer v.Close()
54 // snapshot.Value will be of type Config.
55
56 // PRAGMA: On gocloud.dev, hide the rest of the function.
57 snapshot, err := v.Latest(ctx)
58 if err != nil {
59 log.Fatalf("Error in retrieving variable: %v", err)
60 }
61 fmt.Printf("Config: %+v\n", snapshot.Value.(Config))
62
63 // Output:
64 // Config: {Host:gocloud.dev Port:8080}
65}
66
67func Example_stringDecoder() {
68 // Construct a *Variable using a constructor from one of the

Callers

nothing calls this directly

Calls 4

NewDecoderFunction · 0.92
NewBytesFunction · 0.92
LatestMethod · 0.80
CloseMethod · 0.65

Tested by

no test coverage detected