Go语言 如果values.yaml文件中不存在属性,如何返回默认值false?

5lwkijsr  于 2023-11-14  发布在  Go
关注(0)|答案(1)|浏览(160)

yaml文件. i有一个如下定义的全局值

  1. global:
  2. logging:
  3. log4j:
  4. enabled: true

字符串
我也有一个助手功能

  1. {{- define "helm-basic-template.logging-enabled" -}}
  2. {{ .Values.global.logging.log4j.enabled | default "false" }}
  3. {{- end -}}


这是可能的属性global.logging.log4j.enabled可能不存在,在这种情况下,我希望帮助函数返回false,否则返回属性的值.然而,它并不像我预期的那样工作.任何想法是什么问题与我的函数?或任何其他更好的方法来重新编写它?谢谢

vngu2lb8

vngu2lb81#

为避免未定义变量,此处需要进行额外的检查。
根据helm document,当对象为空时,if语句判断返回false。
如果值为,则管道的计算结果为false:

  • 布尔值为假
  • 数字零
  • 空字符串
  • nil(空或null)
  • 空集合(Map、切片、元组、字典、数组)

直接使用以下检查。

  1. {{- if .Values.global }}
  2. {{- if .Values.global.logging }}
  3. {{- if .Values.global.logging.log4j }}
  4. {{- if .Values.global.logging.log4j.enabled }}
  5. apiVersion: v1
  6. kind: ConfigMap
  7. metadata:
  8. name: logging-cm
  9. data:
  10. conf.json: |
  11. xxxxx
  12. ...
  13. {{- end }}
  14. {{- end }}
  15. {{- end }}
  16. {{- end }}

字符串
或者采用命名模板方法。

  1. {{- define "helm-basic-template.logging-enabled" -}}
  2. {{- $val := false }}
  3. {{- if .Values.global -}}
  4. {{- if .Values.global.logging -}}
  5. {{- if .Values.global.logging.log4j -}}
  6. {{- if .Values.global.logging.log4j.enabled -}}
  7. {{- $val = true }}
  8. {{- end -}}
  9. {{- end -}}
  10. {{- end -}}
  11. {{- end -}}
  12. {{ $val }}
  13. {{- end -}}


或者使用default设置一个简单的默认值。

  1. {{- define "helm-basic-template.logging-enabled" -}}
  2. {{- .Values.global.logging.log4j.enabled | default false .Values.global.logging.log4j.enabled -}}
  3. {{- end -}}


或者使用dig从值列表中选择键。

  1. {{- define "helm-basic-template.logging-enabled" -}}
  2. {{- dig "logging" "log4j" "enabled" false .Values.global -}}
  3. {{- end -}}

展开查看全部

相关问题