render html
This commit is contained in:
18
main.go
18
main.go
@@ -3,24 +3,28 @@ package main
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
var portNumber = ":8080"
|
||||
|
||||
// Home is the home 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, fmt.Sprintf("This is the about page and 2 + 2 is %d", sum))
|
||||
renderTemplate(w, "about.page.tmpl")
|
||||
}
|
||||
|
||||
// addValues adds twu integers and return the sum
|
||||
func addValues(x, y int) int {
|
||||
return x + y
|
||||
func renderTemplate(w http.ResponseWriter, tmpl string) {
|
||||
parsedTemplate, _ := template.ParseFiles("./templates/" + tmpl)
|
||||
err := parsedTemplate.Execute(w, nil)
|
||||
if err != nil {
|
||||
fmt.Println("error parsing template:", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// main is the main application function
|
||||
@@ -28,6 +32,6 @@ func main() {
|
||||
http.HandleFunc("/", Home)
|
||||
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)
|
||||
}
|
||||
|
||||
11
templates/about.page.tmpl
Normal file
11
templates/about.page.tmpl
Normal 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
11
templates/home.page.tmpl
Normal 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>
|
||||
Reference in New Issue
Block a user