Debian Codegraph @

example/node_load_strict_unmarshaler/main.go

raw symbols SCIP
1 // Copyright 2025 The go-yaml Project Contributors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Node Load Strict Unmarshaler demonstrates strict unmarshaling with Nodes.
5
6 package main
7
8 import (
9 "fmt"
10 "log"
11
12 "go.yaml.in/yaml/v4"
13 )
14
15 // Config with strict field checking in custom unmarshaler
16 type Config struct {
17 Name string `yaml:"name"`
18 Port int `yaml:"port"`
19 }
20
21 // UnmarshalYAML implements custom unmarshaling with strict field checking
22 func (c *Config) UnmarshalYAML(node *yaml.Node) error {
23 type plain Config
24 // Use node.Load() to preserve WithKnownFields option
25 // This solves Issue #460 - node.Decode() would lose this option
26 return node.Load((*plain)(c), yaml.WithKnownFields())
27 }
28
29 func main() {
30 fmt.Println("=== Node.Load() with WithKnownFields() ===")
31
32 // Valid YAML - should succeed
33 validYAML := `
34 name: myapp
35 port: 8080
36 `
37
38 var config1 Config
39 err := yaml.Load([]byte(validYAML), &config1)
40 if err != nil {
41 log.Fatal(err)
42 }
43 fmt.Printf("✓ Valid config loaded: %+v\n\n", config1)
44
45 // Invalid YAML with unknown field - should fail
46 // Note: "prto" is intentionally misspelled (should be "port") to demonstrate error detection
47 invalidYAML := `
48 name: myapp
49 prto: 8080
50 unknown: field
51 `
52
53 var config2 Config
54 err = yaml.Load([]byte(invalidYAML), &config2)
55 if err != nil {
56 fmt.Printf("✓ Expected error caught: %v\n", err)
57 } else {
58 fmt.Println("✗ ERROR: Should have failed on unknown fields!")
59 }
60 }