Add template practice exercise

This commit is contained in:
raul 2024-05-04 11:30:37 +02:00
parent 81b210b338
commit a6de42db31
3 changed files with 68 additions and 0 deletions

View File

@ -0,0 +1,5 @@
<html>
<body>
<p>Hello {{ .userAgent }}!</p>
</body>
</html>

3
hello-template/go.mod Normal file
View File

@ -0,0 +1,3 @@
module hello-template
go 1.22.2

60
hello-template/main.go Normal file
View File

@ -0,0 +1,60 @@
package main
import (
"embed"
"fmt"
"html/template"
"io/fs"
"log"
"net/http"
)
var (
listenPort string = "1302"
pages = map[string]string{
"/": "assets/index.html",
}
)
//go:embed assets
var assetsFolder embed.FS
func getRoot(w http.ResponseWriter, r *http.Request) {
page, ok := pages[r.URL.Path]
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
tpl, err := template.ParseFS(assetsFolder, page)
if err != nil {
log.Printf("Error occurred parsing template: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
}
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
data := map[string]interface{}{
"userAgent": r.UserAgent(),
}
if err := tpl.Execute(w, data); err != nil {
log.Printf("Great: %v\n", err)
}
}
func main() {
serverRoot, err := fs.Sub(assetsFolder, "assets")
if err != nil {
log.Fatalf("Error occurred setting HTML root: %v\n", err)
}
http.FileServer(http.FS(serverRoot))
http.HandleFunc("/", getRoot)
fmt.Printf("Listening on port %v...\n", listenPort)
err = http.ListenAndServe(":"+listenPort, nil)
if err != nil {
log.Fatal(err)
}
}