从Golang中的模板创建Yaml文件

问题描述

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

我的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.Executeio.Writer作为第一个参数。这是具有单个方法的接口:Write(p []byte) (n int,err error)

具有该方法的任何类型都将实现接口,并且可以用作有效参数。 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是否为空,如template.Lookup中所述。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...