From a6de42db31425bc6e0761bc3e7365b847e71df2d Mon Sep 17 00:00:00 2001 From: raul Date: Sat, 4 May 2024 11:30:37 +0200 Subject: [PATCH] Add template practice exercise --- hello-template/assets/index.html | 5 +++ hello-template/go.mod | 3 ++ hello-template/main.go | 60 ++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 hello-template/assets/index.html create mode 100644 hello-template/go.mod create mode 100644 hello-template/main.go diff --git a/hello-template/assets/index.html b/hello-template/assets/index.html new file mode 100644 index 0000000..7c4d884 --- /dev/null +++ b/hello-template/assets/index.html @@ -0,0 +1,5 @@ + + +

Hello {{ .userAgent }}!

+ + diff --git a/hello-template/go.mod b/hello-template/go.mod new file mode 100644 index 0000000..0510c62 --- /dev/null +++ b/hello-template/go.mod @@ -0,0 +1,3 @@ +module hello-template + +go 1.22.2 diff --git a/hello-template/main.go b/hello-template/main.go new file mode 100644 index 0000000..f79dcb2 --- /dev/null +++ b/hello-template/main.go @@ -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) + } +}