golang dynamically parsing files
Posted
by
Brian Voelker
on Stack Overflow
See other posts from Stack Overflow
or by Brian Voelker
Published on 2012-10-09T18:48:47Z
Indexed on
2012/10/09
21:38 UTC
Read the original article
Hit count: 244
go
For parsing files i have setup a variable for template.ParseFiles and i currently have to manually set each file.
Two things:
How would i be able to walk through a main folder and a multitude of subfolders and automatically add them to ParseFiles so i dont have to manually add each file individually?
How would i be able to call a file with the same name in a subfolder because currently I get an error at runtime if i add same name file in ParseFiles.
var templates = template.Must(template.ParseFiles(
"index.html", // main file
"subfolder/index.html" // subfolder with same filename errors on runtime
"includes/header.html", "includes/footer.html",
))
func main() {
// Walk and ParseFiles
filepath.Walk("files", func(path string, info os.FileInfo, err error) {
if !info.IsDir() {
// Add path to ParseFiles
}
return
})
http.HandleFunc("/", home)
http.ListenAndServe(":8080", nil)
}
func home(w http.ResponseWriter, r *http.Request) {
render(w, "index.html")
}
func render(w http.ResponseWriter, tmpl string) {
err := templates.ExecuteTemplate(w, tmpl, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
© Stack Overflow or respective owner