I have a template file template.html
as follow
Hello {{.Name}}, welcome!
and the code
import (
"fmt"
"text/template"
)
func main() {
type person struct {
Name string
}
p := &person{"clinyong"}
t := template.Must(template.New("template.html").ParseFiles("template.html"))
f, err := os.OpenFile("test", os.O_CREATE, 0777)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
err := t.Execute(f, p)
if err != nil {
fmt.Println(err)
}
}
t.Execute(f, p)
calls a error, saying that f is a bad file descriptor.
Is it possible to execute a template output to a file as shown above? I see some examples, the f
in Execute
is almost http.ResponseWriter or os.Stdout.
As @TimCooper said, I need to include os.O_WRONLY
in os.OpenFile
.