go - 从 golang 中的模板创建 yaml 文件

标签 go go-templates

我想从当前的 tmpl 文件创建一个 yaml 文件。基本上我想在 sample.tmpl 中插入值存储在 /templates 中的文件文件夹并在同一文件夹中创建一个新的 yaml 文件 sample.yml

我的 sample.tmpl看起来像

url : {{ .host }}
namespace: {{ .namespace }}

我正在使用以下功能:

func ApplyTemplate(filePath string) (err error) {
    // Variables - host, namespace
    type Eingest struct {
        host      string
        namespace string
    }

    ei := Eingest{host: "example.com", namespace: "finance"}
    var templates *template.Template
    var allFiles []string
    files, err := ioutil.ReadDir(filePath)
    if err != nil {
        fmt.Println(err)
    }

    for _, file := range files {
        filename := file.Name()
        fullPath := filePath + "/" + filename
        if strings.HasSuffix(filename, ".tmpl") {
            allFiles = append(allFiles, fullPath)
        }
    }

    fmt.Println("Files in path: ", allFiles)

    // parses all .tmpl files in the 'templates' folder
    templates, err = template.ParseFiles(allFiles...)
    if err != nil {
        fmt.Println(err)
    }

    s1 := templates.Lookup("sample.tmpl")
    s1.ExecuteTemplate(os.Stdout, "sample.yml", ei)
    fmt.Println()
    return
}

s1.ExecuteTemplate()写入 stdout .如何在同一文件夹中创建新文件?我相信类似的东西用于构建 kubernetes yaml 文件。我们如何使用 golang 模板包实现这一点?

最佳答案

首先:因为您已经查找了模板,所以您应该改用 template.Execute,但同样适用于 ExecuteTemplate

text.Template.Execute需要 io.Writer作为第一个参数。这是一个只有一个方法的接口(interface):Write(p []byte) (n int, err error)

任何具有该方法的类型都实现了该接口(interface),并且可以用作有效参数。一种这样的类型是 os.File .只需创建一个新的 os.File 对象并将其传递给 Execute,如下所示:

// Build the path:
outputPath := filepath.Join(filepath, "sample.yml")

// Create the file:
f, err := os.Create(outputPath)
if err != nil {
  panic(err)
}

defer f.Close() // don't forget to close the file when finished.

// Write template to file:
err = s1.Execute(f, ei)
if err != nil {
  panic(err)
}

注意:不要忘记检查 s1 是否为 nil,如 template.Lookup 中所述.

关于go - 从 golang 中的模板创建 yaml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63627763/

相关文章:

reflection - 在 golang 中将 interface{} 转换为 *[]int

pointers - 如何取消引用作为空接口(interface)传递的指针值?

go - Cast interface{} 以输入模板

templates - 如何使用结构或变量值的字段作为模板名称?

kubernetes-helm - 仅获取文件内容并对此内容运行 `tpl` [kubernetes-helm]

go-templates - 在 Go 模板中实现 for 循环

docker - docker 是否在内部使用 chroot、unshare、nsenter 等系统调用或 lxc 的包装器

go - Go程序"Import cycle not allowed"错误

go - 如何使用不同的数据结构递归循环 map

go - 用go template生成go模板