Debian Codegraph @

example/multiple_options_loader/main.go

raw symbols SCIP
1 // Copyright 2025 The go-yaml Project Contributors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Multiple Options Loader demonstrates using multiple options together.
5
6 package main
7
8 import (
9 "fmt"
10 "io"
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 Tags []string `yaml:"tags,omitempty"`
20 }
21
22 func main() {
23 fmt.Println("Example 9: Loader with Multiple Options")
24 fmt.Println("(WithSingleDocument + WithKnownFields)")
25
26 // First test: unknown field should fail
27 multiDocWithUnknown := `---
28 name: app1
29 version: 1.0.0
30 unknownField: this-will-be-rejected
31 ---
32 name: app2
33 version: 2.0.0
34 `
35
36 loader1, err := yaml.NewLoader(
37 strings.NewReader(multiDocWithUnknown),
38 yaml.WithSingleDocument(),
39 yaml.WithKnownFields(),
40 )
41 if err != nil {
42 panic(err)
43 }
44
45 var strictCfg Config
46 err = loader1.Load(&strictCfg)
47 if err != nil {
48 fmt.Printf("✓ Got expected error (unknown field): %v\n\n", err)
49 } else {
50 fmt.Printf("Unexpected: no error for unknown field\n\n")
51 }
52
53 // Second test: valid document with all options
54 validDoc := `---
55 name: validapp
56 version: 1.0.0
57 tags:
58 - valid
59 ---
60 name: app2
61 version: 2.0.0
62 `
63
64 loader2, err := yaml.NewLoader(
65 strings.NewReader(validDoc),
66 yaml.WithSingleDocument(),
67 yaml.WithKnownFields(),
68 )
69 if err != nil {
70 panic(err)
71 }
72
73 var validCfg Config
74 if err := loader2.Load(&validCfg); err != nil {
75 panic(err)
76 }
77 fmt.Printf("✓ First doc loaded: %+v\n", validCfg)
78
79 // Second call should return EOF due to WithSingleDocument
80 var secondCfg Config
81 err = loader2.Load(&secondCfg)
82 if err == io.EOF {
83 fmt.Println("✓ Second Load() returned io.EOF (WithSingleDocument enforced)")
84 } else {
85 fmt.Printf("Unexpected: got %v\n", err)
86 }
87 }