Skip to content

Commit 50fc2f9

Browse files
committed
added a config package and calling template cache creation from main
1 parent 6916dc5 commit 50fc2f9

File tree

4 files changed

+22
-6
lines changed

4 files changed

+22
-6
lines changed

cmd/web/main.go

+12
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,27 @@ package main
22

33
import (
44
"fmt"
5+
"log"
56
"net/http"
67

8+
"github.com/jagottsicher/myGoWebApplication/pkg/config"
79
"github.com/jagottsicher/myGoWebApplication/pkg/handlers"
10+
"github.com/jagottsicher/myGoWebApplication/pkg/render"
811
)
912

1013
const portNumber = ":8080"
1114

1215
// main is the main function
1316
func main() {
17+
var app config.AppConfig
18+
19+
tc, err := render.CreateTemplateCache()
20+
if err != nil {
21+
log.Fatal("cannot create template cache")
22+
}
23+
24+
app.TemplateCache = tc
25+
1426
http.HandleFunc("/", handlers.Home)
1527
http.HandleFunc("/about", handlers.About)
1628

config/config.go

Whitespace-only changes.

pkg/config/config.go

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package config
2+
3+
import "html/template"
4+
5+
// AppConfig is a struct holding die application's configuration
6+
type AppConfig struct {
7+
TemplateCache map[string]*template.Template
8+
}

pkg/render/render.go

+2-6
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,7 @@ import (
1111
// rendernTemplate serves as a wrapper and renders
1212
// a layout and a template from folder /templates to a desired writer
1313
func RenderTemplate(w http.ResponseWriter, tpml string) {
14-
// create a template cache
15-
tc, err := createTemplateCache()
16-
if err != nil {
17-
log.Fatalln("error creating template cache ", err)
18-
}
14+
// get the template cache from the app config
1915

2016
// get the right template from cache
2117
t, ok := tc[tpml]
@@ -38,7 +34,7 @@ func RenderTemplate(w http.ResponseWriter, tpml string) {
3834
}
3935
}
4036

41-
func createTemplateCache() (map[string]*template.Template, error) {
37+
func CreateTemplateCache() (map[string]*template.Template, error) {
4238
theCache := map[string]*template.Template{}
4339

4440
// get all available files *-page.tpml from folder ./templates

0 commit comments

Comments
 (0)