Go YAML 파일 Unmarshal

1 개요[ | ]

Go YAML 파일 Unmarshal

2 단일 문서[ | ]

id: 1
name: Reds
colors:
- Crimson
- Red
- Ruby
- Maroon
package main

import (
	"fmt"
	"os"

	"gopkg.in/yaml.v3"
)

type ColorGroup struct {
	ID     int
	Name   string
	Colors []string
}

func main() {
	yamlBytes, err := os.ReadFile("a.yaml")
	if err != nil {
		fmt.Println("ReadFile error:", err)
		return
	}
	var cg ColorGroup
	err = yaml.Unmarshal(yamlBytes, &cg)
	if err != nil {
		fmt.Println("Unmarshal error:", err)
		return
	}
	fmt.Printf("%+v", cg)
}

3 여러 문서[ | ]

---
name: Ed
text: Knock knock.
---
name: Sam
text: Who's there?
---
name: Ed
text: Go fmt.
---
name: Sam
text: Go fmt who?
---
name: Ed
text: Go fmt yourself!
package main

import (
	"fmt"
	"io"
	"log"
	"os"

	"gopkg.in/yaml.v3"
)

type Message struct {
	Name string `yaml:"name"`
	Text string `yaml:"text"`
}

func main() {
	f, err := os.Open("messages.yaml")
	if err != nil {
		panic(err)
	}
	dec := yaml.NewDecoder(f)
	for {
		var m Message
		if err := dec.Decode(&m); err == io.EOF {
			break
		} else if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%+v\n", m)
	}
}

4 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}