Debian Codegraph @

example/with_v4_override/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 Override demonstrates overriding V4 preset options.
5
6 package main
7
8 import (
9 "bytes"
10 "fmt"
11
12 "go.yaml.in/yaml/v4"
13 )
14
15 type Config struct {
16 Name string `yaml:"name"`
17 Server map[string]string `yaml:"server"`
18 Tags []string `yaml:"tags"`
19 }
20
21 func main() {
22 fmt.Println("Example: Overriding yaml.WithV4Defaults() options")
23
24 cfg := Config{
25 Name: "myapp",
26 Server: map[string]string{
27 "host": "localhost",
28 "port": "8080",
29 },
30 Tags: []string{"web", "api"},
31 }
32
33 // Test 1: v4 options - should use 2-space indent
34 fmt.Println("1. yaml.WithV4Defaults() - 2-space indent:")
35 var buf bytes.Buffer
36 dumper, err := yaml.NewDumper(&buf, yaml.WithV4Defaults())
37 if err != nil {
38 panic(err)
39 }
40 if err := dumper.Dump(&cfg); err != nil {
41 panic(err)
42 }
43 if err := dumper.Close(); err != nil {
44 panic(err)
45 }
46 fmt.Print(buf.String())
47
48 // Test 2: v4 options then WithIndent(3) - WithIndent(3) overrides
49 fmt.Println("\n2. WithV4Defaults(), then WithIndent(3) - should use 3-space indent:")
50 buf.Reset()
51 dumper2, err := yaml.NewDumper(&buf, yaml.WithV4Defaults(), yaml.WithIndent(3))
52 if err != nil {
53 panic(err)
54 }
55 if err := dumper2.Dump(&cfg); err != nil {
56 panic(err)
57 }
58 if err := dumper2.Close(); err != nil {
59 panic(err)
60 }
61 fmt.Print(buf.String())
62
63 // Test 3: WithIndent(5) then v4 options - v4 options override to 2
64 fmt.Println("\n3. WithIndent(5), then WithV4Defaults() - should use 2-space indent (v4 wins):")
65 buf.Reset()
66 dumper3, err := yaml.NewDumper(&buf, yaml.WithIndent(5), yaml.WithV4Defaults())
67 if err != nil {
68 panic(err)
69 }
70 if err := dumper3.Dump(&cfg); err != nil {
71 panic(err)
72 }
73 if err := dumper3.Close(); err != nil {
74 panic(err)
75 }
76 fmt.Print(buf.String())
77
78 fmt.Println("\nConclusion: Options are applied left-to-right, later options override earlier ones.")
79 }