Use html/template or text/template with template.Must to parse templates once at startup and store the result in a variable for reuse. This avoids the expensive parsing step on every request.
import (
"html/template"
"log"
)
var templates = template.Must(template.ParseFiles("templates/home.html"))
func handler(w http.ResponseWriter, r *http.Request) {
if err := templates.Execute(w, data); err != nil {
log.Println(err)
}
}
For multiple files, use template.ParseGlob or template.ParseFiles with multiple arguments. Store the *template.Template in a package-level variable initialized at startup.