Validate Template at Startup Go

Validate Template at Startup - Go

We are starting to follow the MVC pattern therefore the following structure:

└── section-6
    ├── controllers
    │   └── static.go
    ├── go.mod
    ├── go.sum
    ├── main.go
    ├── templates
    │   ├── contact.gohtml
    │   ├── faq.gohtml
    │   └── home.gohtml
    └── views
        └── template.go

Notice the following:

  • The templates are within the template directory.

  • views directory contains template.go which have the following:

package views

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
)

func Parse(filepath string) (Template, error) {

	tpl, err := template.ParseFiles(filepath)
	if err != nil {
		return Template{}, fmt.Errorf("parsing template: %w", err)
	}

	return Template{
		htmlTpl: tpl,
	}, nil
}

type Template struct {
	htmlTpl *template.Template
}

func (t Template) Execute(w http.ResponseWriter, data interface{}) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	err := t.htmlTpl.Execute(w, nil)
	if err != nil {
		log.Printf("executing template: %v", err)
		http.Error(w, "There was an error executing the template", http.StatusInternalServerError)
		return
	}

}
  • controllers directory contains static.go which have the following:
package controllers

import (
	"net/http"

	"github.com/rabocse/lenslocked/views"
)

func StaticHandler(tpl views.Template) http.HandlerFunc {

	return func(w http.ResponseWriter, r *http.Request) {
		tpl.Execute(w, nil)

	}
}
  • And, finally this is how the main.go looks like:
package main

import (
	"fmt"
	"net/http"
	"path/filepath"

	"github.com/go-chi/chi/v5"
	"github.com/rabocse/lenslocked/controllers"
	"github.com/rabocse/lenslocked/views"
)

func main() {

	r := chi.NewRouter()

	tpl, err := views.Parse(filepath.Join("templates", "home.gohtml"))
	if err != nil {
		panic(err)
	}
	r.Get("/", controllers.StaticHandler(tpl))

	tpl, err = views.Parse(filepath.Join("templates", "contact.gohtml"))
	if err != nil {
		panic(err)
	}
	r.Get("/contact", controllers.StaticHandler(tpl))

	tpl, err = views.Parse(filepath.Join("templates", "faq.gohtml"))
	if err != nil {
		panic(err)
	}
	r.Get("/faq", controllers.StaticHandler(tpl))

	r.NotFound(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "Page Not Found", http.StatusNotFound)
	})

	fmt.Println("Starting the server on :3000...")
	http.ListenAndServe(":3000", r)

}

 Share!

 
comments powered by Disqus