I am wondering whether my template usage in main.go could be better. For example in other code I notice:

var views = template.Must(template.ParseGlob("static/*.tmpl"))

Defined outside main, hence the templates are loaded on process start. And then in the handler:

views.ExecuteTemplate(w, "passwordprompt.tmpl", map[string]interface{}{})

In my own code, I am wondering if it is worth applying the same practice. Is it possible with functions & the code below?

func handleIndex(w http.ResponseWriter, r *http.Request) {
    funcs := template.FuncMap{
        "nameBusStopID": func(s string) string { return bs.nameBusStopID(s) },
        "getenv":        os.Getenv,

    t, err := template.New("").Funcs(funcs).ParseFiles("templates/index.html")

    if err != nil {
        log.WithError(err).Error("template failed to parse")
        http.Error(w, err.Error(), http.StatusInternalServerError)

    arriving, err := busArrivals(r.URL.Query().Get("id"))
    if err != nil {
        log.WithError(err).Error("failed to retrieve bus timings")

    t.ExecuteTemplate(w, "index.html", arriving)    

Please feel free to critique all the code.

  • \$\begingroup\$ could you also post your templates/index.html file here ? \$\endgroup\$ – felix Jan 2 at 23:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.