Created
February 15, 2021 03:23
-
-
Save hallyn/6ab48db33b5c53f2de52f0d507a54f37 to your computer and use it in GitHub Desktop.
Extensible nested yaml fields in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
``` | |
package main | |
import ( | |
"fmt" | |
"os" | |
"gopkg.in/yaml.v2" | |
) | |
var indata string = ` | |
version: 1 | |
field1: "value1" | |
nest: | |
nestF1: v1 | |
nestF2: | | |
Four score and seven years ago, | |
our fathers... | |
` | |
type yaml1 struct { | |
Version string `yaml:"version"` | |
Field1 string `yaml:"field1"` | |
Nested interface{} `yaml:"nest"` | |
} | |
type wrappedYaml struct { | |
Field1 string `yaml:"nestF1"` | |
Field2 string `yaml:"nestF2"` | |
} | |
func main() { | |
c := []byte(indata) | |
fmt.Printf("c is %v\n", c) | |
struct1 := &yaml1{} | |
err := yaml.Unmarshal(c, struct1) | |
if err != nil { | |
fmt.Printf("unmarshall error %v\n", err) | |
os.Exit(1) | |
} | |
fmt.Printf("struct1 is is %v\n", struct1) | |
struct2 := struct1.Nested.(map[interface{}]interface{}) | |
fmt.Printf("wrapped field1 is %v\n", struct2) | |
fmt.Printf("struct2.Field1 is %s\n", struct2["nestF1"]) | |
fmt.Printf("struct2.Field2 is %s\n", struct2["nestF2"]) | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment