Writing tests for main package and for GET handlers

This commit is contained in:
Muyao CHEN
2024-07-01 22:34:16 +02:00
parent dc7ece7d12
commit 21478b20ae
8 changed files with 312 additions and 18 deletions

View File

@ -2,6 +2,7 @@ package render
import (
"bytes"
"fmt"
"go-udemy-web-1/internal/config"
"go-udemy-web-1/internal/models"
"html/template"
@ -12,7 +13,12 @@ import (
"github.com/justinas/nosurf"
)
var app *config.AppConfig
var functions = template.FuncMap{}
var (
app *config.AppConfig
pathToTemplates = "./templates"
)
// NewTemplates sets the config for the template package
func NewTemplates(a *config.AppConfig) {
@ -65,8 +71,8 @@ func RenderTemplate(w http.ResponseWriter, r *http.Request, tmpl string, td *mod
func CreateTemplateCache() (map[string]*template.Template, error) {
myCache := map[string]*template.Template{}
// get all of the files named *.page.tmpl from ./templates
pages, err := filepath.Glob("./templates/*.page.tmpl")
// get all of the files named *.page.tmpl from templates
pages, err := filepath.Glob(fmt.Sprintf("%s/*.page.tmpl", pathToTemplates))
if err != nil {
return myCache, err
}
@ -74,18 +80,18 @@ func CreateTemplateCache() (map[string]*template.Template, error) {
// range through all files ending with *page.tmpl
for _, page := range pages {
name := filepath.Base(page)
ts, err := template.New(name).ParseFiles(page)
ts, err := template.New(name).Funcs(functions).ParseFiles(page)
if err != nil {
return myCache, err
}
matches, err := filepath.Glob("./templates/*.layout.tmpl")
matches, err := filepath.Glob(fmt.Sprintf("%s/*.layout.tmpl", pathToTemplates))
if err != nil {
return myCache, err
}
if len(matches) > 0 {
ts, err = ts.ParseGlob("./templates/*.layout.tmpl")
ts, err = ts.ParseGlob(fmt.Sprintf("%s/*.layout.tmpl", pathToTemplates))
if err != nil {
return myCache, err
}