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