| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
package main |
| 7 |
|
| 8 |
import ( |
| 9 |
"fmt" |
| 10 |
"log" |
| 11 |
|
| 12 |
"go.yaml.in/yaml/v4" |
| 13 |
) |
| 14 |
|
| 15 |
type ServerConfig struct { |
| 16 |
Host string `yaml:"host"` |
| 17 |
Port int `yaml:"port"` |
| 18 |
TLS bool `yaml:"tls"` |
| 19 |
} |
| 20 |
|
| 21 |
func main() { |
| 22 |
config := ServerConfig{ |
| 23 |
Host: "localhost", |
| 24 |
Port: 8080, |
| 25 |
TLS: true, |
| 26 |
} |
| 27 |
|
| 28 |
fmt.Println("=== Node.Dump() with Different Options ===") |
| 29 |
|
| 30 |
|
| 31 |
var node1 yaml.Node |
| 32 |
if err := node1.Dump(&config); err != nil { |
| 33 |
log.Fatal(err) |
| 34 |
} |
| 35 |
fmt.Println("1. Default (v4):") |
| 36 |
printNode(&node1) |
| 37 |
|
| 38 |
|
| 39 |
var node2 yaml.Node |
| 40 |
if err := node2.Dump(&config, yaml.WithIndent(4)); err != nil { |
| 41 |
log.Fatal(err) |
| 42 |
} |
| 43 |
fmt.Println("2. With 4-space indent:") |
| 44 |
printNode(&node2) |
| 45 |
|
| 46 |
|
| 47 |
var node3 yaml.Node |
| 48 |
if err := node3.Dump(&config, yaml.WithV3Defaults()); err != nil { |
| 49 |
log.Fatal(err) |
| 50 |
} |
| 51 |
fmt.Println("3. With V3 preset:") |
| 52 |
printNode(&node3) |
| 53 |
|
| 54 |
|
| 55 |
var node4 yaml.Node |
| 56 |
if err := node4.Dump(&config, |
| 57 |
yaml.WithIndent(2), |
| 58 |
yaml.WithExplicitStart(), |
| 59 |
); err != nil { |
| 60 |
log.Fatal(err) |
| 61 |
} |
| 62 |
fmt.Println("4. With explicit start marker:") |
| 63 |
printNode(&node4) |
| 64 |
} |
| 65 |
|
| 66 |
func printNode(node *yaml.Node) { |
| 67 |
data, err := yaml.Dump(node) |
| 68 |
if err != nil { |
| 69 |
log.Fatal(err) |
| 70 |
} |
| 71 |
fmt.Printf("%s\n", data) |
| 72 |
} |