Last active
October 11, 2018 13:56
-
-
Save lboulard/078a8ee56d95c136c75c82bf42e21233 to your computer and use it in GitHub Desktop.
Parse YAML dual type field
This file contains hidden or 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
module lboulard.net/go/playfield/flexible-yaml | |
require gopkg.in/yaml.v2 v2.2.1 |
This file contains hidden or 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
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= | |
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= | |
gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE= | |
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= |
This file contains hidden or 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" | |
"log" | |
yaml "gopkg.in/yaml.v2" | |
) | |
const FILE = "t.yaml" | |
var test1 = ` | |
- target: Single Target | |
- target: | |
- Target 1 | |
- Target 2 | |
- ignored: invalid key will appears empty (bug ?) | |
` | |
type TargetList []string | |
func (t *TargetList) UnmarshalYAML(unmarshall func(interface{}) error) error { | |
var target interface{} | |
if err := unmarshall(&target); err != nil { | |
return err | |
} | |
switch v := target.(type) { | |
case string: // value is a single string | |
*t = append(*t, v) | |
case []interface{}: // value is a list | |
// We want a list of string. Nothing else. | |
for _, w := range v { | |
if s, ok := w.(string); ok { | |
*t = append(*t, s) | |
} else { | |
return fmt.Errorf("cannot unmarshal %q to string", w) | |
} | |
} | |
default: | |
return fmt.Errorf("cannot unmarshal %q to string or list of strings", v) | |
} | |
return nil | |
} | |
type T []struct { | |
Target TargetList | |
} | |
func main() { | |
t := T{} | |
err := yaml.Unmarshal([]byte(test1), &t) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("--- t:\n%+v\n", t) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment