如何让 template.Execute() 写入文件而不是 response.Writer?

How can I make template.Execute() to write to a file rather than to response.Writer?

我有下面的代码来解析模板文件并将解析的 html 写入 ResponseWriter:-

package main

import (
    "net/http"
    "html/template"
)

func handler(w http.ResponseWriter, r *http.Request) {
    t, _ := template.ParseFiles("view.html")
    t.Execute(w, "Hello World!")
}

func main() {
    server := http.Server{
        Addr: "127.0.0.1:8080",
    }
    http.HandleFunc("/view", handler)
    server.ListenAndServe()
}  

模板文件"template.html"如下:

<html>
<head>
    <title>First Program</title>
</head>
<body>
    {{ . }}
</body>
</html>  

现在,我不想将 parsed/executed 文件写入 ResponseWriter,而是将这些内容写入 html 文件,比如 "parsed.html"。我怎样才能实现它。我是 Go 的新手,所以很难理解。谢谢。

这是一种方法:

t, err := template.ParseFiles("view.html")
if err != nil {
    // handle error
}

// Create the file
f, err := os.Create("parsed.html")
if err != nil {
    // handle error
}

// Execute the template to the file.
err = t.Execute(f, "Hello World!")
if err != nil {
    // handle error
}

// Close the file when done.
f.Close()

Run it on the playground

要点:*os.File 和 http.ResponseWriter 都满足 Execute 的第一个参数中使用的 io.Writer 接口。