Serving HTML Templates

This commit is contained in:
Muyao CHEN 2024-06-26 18:10:56 +02:00
parent 4eefdfe47c
commit ab6184e675
3 changed files with 37 additions and 24 deletions

View File

@ -1,8 +1,8 @@
package main package main
import ( import (
"errors"
"fmt" "fmt"
"html/template"
"net/http" "net/http"
) )
@ -10,43 +10,26 @@ const portNumber = ":8080"
// 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) {
fmt.Fprintf(w, "This is the home page") 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) {
sum := addValues(2, 2) renderTemplate(w, "about.page.tmpl")
fmt.Fprintf(w, "This is the about page and 2 + 2 is %d", sum)
} }
// addValues adds two integers and returns the sum func renderTemplate(w http.ResponseWriter, tmpl string) {
func addValues(x, y int) int { parsedTemplate, _ := template.ParseFiles("../..//templates/" + tmpl)
return x + y err := parsedTemplate.Execute(w, nil)
}
// About is the about page handler
func Divide(w http.ResponseWriter, r *http.Request) {
f, err := divideValues(100.0, 0.0)
if err != nil { if err != nil {
fmt.Fprintf(w, "Cannot divide by 0\n") fmt.Println("error parsing template:", err)
return
} }
fmt.Fprintf(w, "%f divided by %f is %f\n", 100.0, 0.0, f)
}
func divideValues(x, y float32) (float32, error) {
if y <= 0 {
err := errors.New("cannot divide by zero")
return 0, err
}
return x / y, nil
} }
// main is the main application function // main is the main application function
func main() { func main() {
http.HandleFunc("/", Home) http.HandleFunc("/", Home)
http.HandleFunc("/about", About) http.HandleFunc("/about", About)
http.HandleFunc("/divide", Divide)
fmt.Printf("Starting application on port %s\n", portNumber) fmt.Printf("Starting application on port %s\n", portNumber)

15
templates/about.page.tmpl Normal file
View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<h1>This is the about page</h1>
</body>
</html>

15
templates/home.page.tmpl Normal file
View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<h1>This is the home page</h1>
</body>
</html>