Debian Codegraph @

example/with_v4_option/main.go

raw symbols SCIP
1 // Copyright 2025 The go-yaml Project Contributors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Example: With V4 Option demonstrates using the V4 version preset.
5
6 package main
7
8 import (
9 "bytes"
10 "fmt"
11 "strings"
12
13 "go.yaml.in/yaml/v4"
14 )
15
16 type Config struct {
17 Name string `yaml:"name"`
18 Version string `yaml:"version"`
19 Server ServerConfig `yaml:"server"`
20 Tags []string `yaml:"tags,omitempty"`
21 Metadata map[string]string `yaml:"metadata,omitempty"`
22 }
23
24 type ServerConfig struct {
25 Host string `yaml:"host"`
26 Port int `yaml:"port"`
27 Debug bool `yaml:"debug"`
28 }
29
30 func main() {
31 fmt.Println("Example: v4 Options (Now the Default)")
32 fmt.Println("The new API (Dump, Load, NewDumper, NewLoader) defaults to v4:")
33 fmt.Println(" - 2-space indentation")
34 fmt.Println(" - Compact sequence indentation")
35
36 yamlData := `# Application configuration
37 name: myapp
38 version: 1.0.0
39 # Server settings
40 server:
41 host: localhost
42 port: 8080
43 debug: true
44 tags:
45 - web
46 - api
47 metadata:
48 owner: platform-team
49 env: prod
50 `
51
52 // Load with default options (now v4)
53 loader, err := yaml.NewLoader(strings.NewReader(yamlData))
54 if err != nil {
55 panic(err)
56 }
57
58 var node yaml.Node
59 if err := loader.Load(&node); err != nil {
60 panic(err)
61 }
62
63 fmt.Println("--- Loaded with Default Options (v4) ---")
64 fmt.Printf("Comments preserved: %v\n", node.Content[0].Content[0].HeadComment != "")
65 fmt.Println()
66
67 // Now dump it back with default options (v4: 2-space indent, compact)
68 var buf bytes.Buffer
69 dumper, err := yaml.NewDumper(&buf)
70 if err != nil {
71 panic(err)
72 }
73
74 if err := dumper.Dump(&node); err != nil {
75 panic(err)
76 }
77
78 if err := dumper.Close(); err != nil {
79 panic(err)
80 }
81
82 fmt.Println("--- Default Output (v4: 2-space indent, compact, comments preserved) ---")
83 fmt.Print(buf.String())
84
85 // Compare with v3 defaults for backward compatibility
86 fmt.Println("\n--- For comparison: v3 defaults (4-space indent, non-compact) ---")
87 buf.Reset()
88 dumper2, err := yaml.NewDumper(&buf, yaml.WithV3Defaults())
89 if err != nil {
90 panic(err)
91 }
92
93 if err := dumper2.Dump(&node); err != nil {
94 panic(err)
95 }
96
97 if err := dumper2.Close(); err != nil {
98 panic(err)
99 }
100
101 fmt.Print(buf.String())
102 }