Refactoring code to use packages

This commit is contained in:
Muyao CHEN 2024-06-26 22:06:32 +02:00
parent b207b9a293
commit 144e700b15
3 changed files with 10 additions and 8 deletions

View File

@ -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)

View File

@ -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")
}

View File

@ -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 {