Skip to content

Instantly share code, notes, and snippets.

@wemgl
Last active March 10, 2019 14:29
Show Gist options
  • Save wemgl/5f86b35ea355d721b74a0c6bd3d16d64 to your computer and use it in GitHub Desktop.
Save wemgl/5f86b35ea355d721b74a0c6bd3d16d64 to your computer and use it in GitHub Desktop.
Example of parsing templates and handling HTTP requests
// templates references the specified templates and caches the parsed results
// to help speed up response times.
var templates = template.Must(template.ParseFiles("./templates/base.html", "./templates/body.html"))
// index is the handler responsible for rending the index page for the site.
func index() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b := struct {
Title template.HTML
BusinessName string
Slogan string
}{
Title: template.HTML("Business | Landing"),
BusinessName: "Business,",
Slogan: "we get things done.",
}
err := templates.ExecuteTemplate(w, "base", &b)
if err != nil {
http.Error(w, fmt.Sprintf("index: couldn't parse template: %v", err), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment