将数据流式传输到 Go 模板中? (while 在模板中循环)

问题描述 投票:0回答:0

我正在尝试让我的 Go 程序将数据从标准输入流式传输到模板中。

之前,它将所有数据读入内存, 模板

range
通过它:

scanner := bufio.NewScanner(os.Stdin)
d := make([]string, 0)
for scanner.Scan() {
    d = append(d, scanner.Text())
}

txt := `
{{- range . -}}
    {{- .}}
{{end}}`

template.
    Must(template.New("").Parse(txt)).
    Execute(os.Stdout, d)

这就是我想做的, 除了 Go 的模板中没有

for
/
while
循环:

d := bufio.NewScanner(os.Stdin)

txt := `
{{- while .Scan /* this does not exist */ -}}
    {{- .Text}}
{{end}}`

template.
    Must(template.New("").Parse(txt)).
    Execute(os.Stdout, d)

这是我目前的解决方法:

d := bufio.NewScanner(os.Stdin)

fnmap := template.FuncMap{
    "loop": func(n int) []bool { return make([]bool, n) },
}
txt := `
{{- range loop 999999999 -}}
    {{- if not $.Scan -}}
        {{- break -}}
    {{- end -}}
    {{- $.Text}}
{{end}}`

template.
    Must(template.
        New("").
        Funcs(fnmap).
        Parse(txt)).
    Execute(os.Stdout, d)

然而,它似乎相当不优雅和低效 分配一个巨大的、未使用的切片,只是为了循环。

有没有更好的方法来做到这一点, 也许更类似于我的第二个例子?

loops go while-loop streaming go-templates
© www.soinside.com 2019 - 2024. All rights reserved.