确保 Go 模板中的路径始终以斜杠结尾

Hed*_*dge 1 go-templates kubernetes-helm sprig-template-functions

我正在为一堆部署编写 Helm 图表。我提供的值可以是:

my_value: "/opt/my-path"或者my_value: "/opt/my-path/"

现在我想确保/路径的尽头总是有一个。

我如何使用Go模板来做到这一点?

Yur*_* G. 6

/您可以使用函数修剪后缀trimSuffix,此处的文档为http://masterminds.github.io/sprig/strings.html/ ,并在末尾手动添加。因此,无论原始值是什么,您/最后都会得到一个。例子

值.yaml:

path_with_slash: "/my/path/"
path_without_slash: "/my/path"
Run Code Online (Sandbox Code Playgroud)

在模板文件内:

{{ $path_with_slash := trimSuffix "/" .Values.path_with_slash }}
{{ $path_without_slash := trimSuffix "/" .Values.path_without_slash }}
path_with_slash: "{{ $path_with_slash }}/"
path_without_slash: "{{ $path_without_slash }}/"
Run Code Online (Sandbox Code Playgroud)

渲染文件:

path_with_slash: "/my/path/"
path_without_slash: "/my/path/"
Run Code Online (Sandbox Code Playgroud)