Go模板如何递归搜索所有键 无需知晓路径获取指定键对应值
结论
可以实现,Go模板支持两种方式实现不提前确认完整路径检索指定键值,完全覆盖你提到的docker image inspect中查找Cmd的场景。
方案1:显式匹配已知可能路径(推荐用于你举的场景)
你提到的Cmd仅存在两个已知的可能路径,直接在模板中同时指定两个路径输出即可,写法最简单性能最高:
docker image inspect <镜像ID/镜像名> --format '{{range .}}ContainerConfig.Cmd: {{.ContainerConfig.Cmd}}{{"\n"}}Config.Cmd: {{.Config.Cmd}}{{"\n"}}{{end}}'
执行后会直接输出两个路径下的Cmd值,不存在的路径会输出空值,不会报错。
方案2:通用递归遍历(适合不知道所有可能路径的场景)
如果完全不清楚键的可能路径,可以写递归模板遍历整个返回结构,自动匹配目标键:
docker image inspect <镜像ID/镜像名> --format ' {{- define "findKey" -}} {{- $targetKey := .Key -}} {{- $currentVal := .Value -}} {{- if kindIs "map" $currentVal | or (kindIs "struct" $currentVal) -}} {{- range $k, $v := $currentVal -}} {{- if eq $k $targetKey -}} {{- printf "%s: %v\n" $k $v -}} {{- end -}} {{- template "findKey" dict "Key" $targetKey "Value" $v -}} {{- end -}} {{- else if kindIs "slice" $currentVal -}} {{- range $_, $v := $currentVal -}} {{- template "findKey" dict "Key" $targetKey "Value" $v -}} {{- end -}} {{- end -}} {{- end -}} {{- range . -}} {{- template "findKey" dict "Key" "Cmd" "Value" . -}} {{- end -}} '
需要查找其他键时,只要把命令中Key对应的Cmd替换成目标键名即可。
注意事项
- 递归遍历在返回结构层级很深、内容很大的时候性能会比直接指定路径差,路径可能性少的场景优先使用方案1
- 键名匹配是大小写敏感的,需要和Docker输出的键名完全一致才能匹配成功
内容的提问来源于stack exchange,提问作者sebastian_t
相关产品推荐
相关产品推荐

