From 144e700b15cfe50b93db8a25744377699857de1f Mon Sep 17 00:00:00 2001 From: Muyao CHEN Date: Wed, 26 Jun 2024 22:06:32 +0200 Subject: [PATCH] Refactoring code to use packages --- main.go => cmd/web/main.go | 5 +++-- handlers.go => pkg/handlers/handlers.go | 7 ++++--- render.go => pkg/render/render.go | 6 +++--- 3 files changed, 10 insertions(+), 8 deletions(-) rename main.go => cmd/web/main.go (67%) rename handlers.go => pkg/handlers/handlers.go (60%) rename render.go => pkg/render/render.go (64%) diff --git a/main.go b/cmd/web/main.go similarity index 67% rename from main.go rename to cmd/web/main.go index 0c7bb13..2ab165e 100644 --- a/main.go +++ b/cmd/web/main.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "go-udemy-web-1/pkg/handlers" "net/http" ) @@ -9,8 +10,8 @@ const portNumber = ":8080" // main is the main application function func main() { - http.HandleFunc("/", Home) - http.HandleFunc("/about", About) + http.HandleFunc("/", handlers.Home) + http.HandleFunc("/about", handlers.About) fmt.Printf("Starting application on port %s\n", portNumber) diff --git a/handlers.go b/pkg/handlers/handlers.go similarity index 60% rename from handlers.go rename to pkg/handlers/handlers.go index 85be798..201c327 100644 --- a/handlers.go +++ b/pkg/handlers/handlers.go @@ -1,15 +1,16 @@ -package main +package handlers import ( + "go-udemy-web-1/pkg/render" "net/http" ) // Home is the about page handler func Home(w http.ResponseWriter, r *http.Request) { - renderTemplate(w, "home.page.tmpl") + render.RenderTemplate(w, "home.page.tmpl") } // About is the about page handler func About(w http.ResponseWriter, r *http.Request) { - renderTemplate(w, "about.page.tmpl") + render.RenderTemplate(w, "about.page.tmpl") } diff --git a/render.go b/pkg/render/render.go similarity index 64% rename from render.go rename to pkg/render/render.go index 97f7f6c..bd0a925 100644 --- a/render.go +++ b/pkg/render/render.go @@ -1,4 +1,4 @@ -package main +package render import ( "fmt" @@ -6,8 +6,8 @@ import ( "net/http" ) -// renderTemplate renders a template file -func renderTemplate(w http.ResponseWriter, tmpl string) { +// renderTemplate renders a HTML template file +func RenderTemplate(w http.ResponseWriter, tmpl string) { parsedTemplate, _ := template.ParseFiles("./templates/" + tmpl) err := parsedTemplate.Execute(w, nil) if err != nil {