I have a below code to parse the template file and write the parsed html to 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()
}
and the template file "template.html" is as:
<html>
<head>
<title>First Program</title>
</head>
<body>
{{ . }}
</body>
</html>
Now, Instead of writing parsed/executed file to ResponseWriter, I would like to write those contents to html file say "parsed.html". How can I achieve it. I'm new to Go, so having hard time getting the idea. Thank you.
Here's one way to do it:
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()
Key Point: An *os.File and an http.ResponseWriter both satisfy the io.Writer interface used in the first argument to Execute.