【问题标题】:Creating yaml files from template in golang从 golang 中的模板创建 yaml 文件
【发布时间】:2020-08-28 05:06:04
【问题描述】:

我想从当前的 tmpl 文件创建一个 yaml 文件。基本上我想在/templates 文件夹中存储的sample.tmpl 文件中插入值,并在同一文件夹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 模板包来实现这一点?

【问题讨论】:

  • 如果 yaml 是个好主意,golang stdlib 中会有一个 yaml 包。请不要使用 yaml。从不。
  • 最聪明的地鼠。

标签: go go-templates


【解决方案1】:

首先:由于您已经查找过模板,您应该改用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 是否为nil,如template.Lookup 中所述。

【讨论】:

    猜你喜欢
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 2021-11-22
    • 2017-01-03
    • 1970-01-01
    • 2021-11-23
    • 2012-04-25
    相关资源
    最近更新 更多