render html

This commit is contained in:
2024-04-16 12:16:17 -06:00
parent 3d374a90c2
commit 54d3976f90
3 changed files with 33 additions and 7 deletions

18
main.go
View File

@@ -3,24 +3,28 @@ package main
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"text/template"
) )
var portNumber = ":8080" var portNumber = ":8080"
// Home is the home page handler // Home is the home 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, fmt.Sprintf("This is the about page and 2 + 2 is %d", sum))
} }
// addValues adds twu integers and return 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)
if err != nil {
fmt.Println("error parsing template:", err)
return
}
} }
// main is the main application function // main is the main application function
@@ -28,6 +32,6 @@ func main() {
http.HandleFunc("/", Home) http.HandleFunc("/", Home)
http.HandleFunc("/about", About) http.HandleFunc("/about", About)
fmt.Println(fmt.Sprintf("Staritn application on port %s", portNumber)) fmt.Println(fmt.Sprintf("Starting application on port %s", portNumber))
_ = http.ListenAndServe(portNumber, nil) _ = http.ListenAndServe(portNumber, nil)
} }

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

@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>This is de about page</h1>
</body>
</html>

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

@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>This is de home page</h1>
</body>
</html>