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 ( import (
"fmt" "fmt"
"go-udemy-web-1/pkg/handlers"
"net/http" "net/http"
) )
@ -9,8 +10,8 @@ const portNumber = ":8080"
// main is the main application function // main is the main application function
func main() { func main() {
http.HandleFunc("/", Home) http.HandleFunc("/", handlers.Home)
http.HandleFunc("/about", About) http.HandleFunc("/about", handlers.About)
fmt.Printf("Starting application on port %s\n", portNumber) fmt.Printf("Starting application on port %s\n", portNumber)

View File

@ -1,15 +1,16 @@
package main package handlers
import ( import (
"go-udemy-web-1/pkg/render"
"net/http" "net/http"
) )
// Home is the about page handler // Home is the about page handler
func Home(w http.ResponseWriter, r *http.Request) { 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 // About is the about page handler
func About(w http.ResponseWriter, r *http.Request) { 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 ( import (
"fmt" "fmt"
@ -6,8 +6,8 @@ import (
"net/http" "net/http"
) )
// renderTemplate renders a template file // renderTemplate renders a HTML template file
func renderTemplate(w http.ResponseWriter, tmpl string) { func RenderTemplate(w http.ResponseWriter, tmpl string) {
parsedTemplate, _ := template.ParseFiles("./templates/" + tmpl) parsedTemplate, _ := template.ParseFiles("./templates/" + tmpl)
err := parsedTemplate.Execute(w, nil) err := parsedTemplate.Execute(w, nil)
if err != nil { if err != nil {