Created
February 22, 2019 11:54
-
-
Save sugamasao/45b18492aa1cdc7e83e8400345d5d8a2 to your computer and use it in GitHub Desktop.
YAMLデータのキーを変数経由で指定したい
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 ( | |
"io/ioutil" | |
"log" | |
"reflect" | |
yaml "gopkg.in/yaml.v2" | |
) | |
type Person struct { | |
Name string | |
Age int | |
} | |
type Country struct { | |
Japan Person | |
USA Person | |
} | |
// リフレクションを使うしかないの? | |
func (c *Country) findPerson(fieldName string) Person { | |
pC := reflect.ValueOf(*c) | |
f := pC.FieldByName(fieldName) | |
if !f.IsValid() { | |
log.Fatalf("Notfound Field Name. [%s]", fieldName) | |
} | |
return f.Interface().(Person) | |
} | |
func main() { | |
raw, err := ioutil.ReadFile("./sample.yaml") | |
if err != nil { | |
log.Fatal(err) | |
} | |
var c Country | |
if err := yaml.Unmarshal(raw, &c); err != nil { | |
log.Fatalf("Failed Unmarshal[%v]", err) | |
} | |
log.Printf("Japan -> %v", c.Japan) | |
log.Printf("USA -> %v", c.USA) | |
fieldName := "Japan" | |
person := c.findPerson(fieldName) | |
log.Printf("%s -> %v", fieldName, person) | |
} |
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
japan: | |
name: "田中" | |
age: 20 | |
usa: | |
name: "john" | |
age: 22 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment