Skip to content

Commit

Permalink
added application config and improved template caching mechanism
Browse files Browse the repository at this point in the history
  • Loading branch information
flashl1ght committed Mar 10, 2024
1 parent d9c7a5f commit f041fac
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 15 deletions.
13 changes: 13 additions & 0 deletions cmd/web/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,28 @@ package main

import (
"fmt"
"log"
"net/http"

"github.com/flashl1ght/myFirstGoApp/pkg/config"
"github.com/flashl1ght/myFirstGoApp/pkg/handlers"
"github.com/flashl1ght/myFirstGoApp/pkg/render"
)

const portNumber = ":8080"

// main is the main application function
func main() {
var app config.AppConfig

templateCache, err := render.CreateTemplateCache()
if err != nil {
log.Fatal("cannot create template cache")
}

app.TemplateCache = templateCache

render.NewTemplates(&app)

http.HandleFunc("/", handlers.Home)
http.HandleFunc("/about", handlers.About)
Expand Down
10 changes: 10 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package config

import (
"html/template"
)

// AppConfig holds the application config
type AppConfig struct {
TemplateCache map[string]*template.Template
}
32 changes: 17 additions & 15 deletions pkg/render/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,38 +6,40 @@ import (
"log"
"net/http"
"path/filepath"

"github.com/flashl1ght/myFirstGoApp/pkg/config"
)

var app *config.AppConfig

// NewTemplates sets the config for the template package
func NewTemplates(a *config.AppConfig) {
app = a
}

// RenderTemplate renders templates using html/template
func RenderTemplate(w http.ResponseWriter, tmpl string) {
// create a template cache
tc, err := createTemplateCache()
if err != nil {
log.Fatal(err)
}
// get the template cache frokm the app config
templateCache := app.TemplateCache

// get requested template from cache
t, ok := tc[tmpl]
t, ok := templateCache[tmpl]
if !ok {
log.Fatal(err)
log.Fatal("could not get template from template cache")
}

buffer := new(bytes.Buffer)

err = t.Execute(buffer, nil)
if err != nil {
log.Println(err)
}
_ = t.Execute(buffer, nil)

//render the template
_, err = buffer.WriteTo(w)
_, err := buffer.WriteTo(w)
if err != nil {
log.Println(err)
log.Println("error writting template to browser", err)
}
}

// createTemplateCache caches all templates found in ./templates
func createTemplateCache() (map[string]*template.Template, error) {
func CreateTemplateCache() (map[string]*template.Template, error) {
templateCache := map[string]*template.Template{}

// get all *.page.gohtml files from ./templates
Expand Down

0 comments on commit f041fac

Please sign in to comment.