-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfilter_map.go
More file actions
34 lines (28 loc) · 926 Bytes
/
filter_map.go
File metadata and controls
34 lines (28 loc) · 926 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package template
import (
"errors"
"fmt"
"github.com/kaptinlin/filter"
)
// registerMapFilters registers all map-related filters.
func registerMapFilters() {
defaultRegistry.MustRegister("extract", extractFilter)
}
// extractFilter retrieves a nested value from a map, slice, or array using a dot-separated key path.
// It returns an empty string for KeyNotFound and IndexOutOfRange errors to preserve template ergonomics.
func extractFilter(value any, args ...any) (any, error) {
if len(args) < 1 {
return nil, fmt.Errorf("%w: extract filter requires a key path argument", ErrInsufficientArgs)
}
result, err := filter.Extract(value, toString(args[0]))
if err == nil {
return result, nil
}
if errors.Is(err, filter.ErrKeyNotFound) || errors.Is(err, filter.ErrIndexOutOfRange) {
return "", nil
}
if errors.Is(err, filter.ErrInvalidKeyType) {
return nil, ErrContextInvalidKeyType
}
return nil, err
}