| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
} |