backend: frontend: cleaned up the codebase and added more logging for debuging

This commit is contained in:
Patryk Hegenberg 2023-12-06 17:24:33 +01:00
parent faf7c2f782
commit 3a77eb1593
11 changed files with 152 additions and 38 deletions

View file

@ -7,18 +7,28 @@ import (
"net/http"
)
// AboutHandler returns an http.HandlerFunc that handles requests to the /about endpoint.
// It renders the about.html template and passes in the title "Dungeons & Dragons Monster Generator".
func AboutHandler(content embed.FS) http.HandlerFunc {
log.Print("AboutHandler called")
return func(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFS(content, "templates/base.html", "templates/header.html", "templates/main.html", "templates/footer.html", "templates/about.html")
log.Print("AboutHandler request received")
// Parse the template files
tmplFiles := []string{"templates/base.html", "templates/header.html", "templates/main.html", "templates/footer.html", "templates/about.html"}
tmpl, err := template.ParseFS(content, tmplFiles...)
if err != nil {
log.Printf("Template parsing error: %v\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = tmpl.ExecuteTemplate(w, "about", map[string]interface{}{
// Execute the template with the provided data
data := map[string]interface{}{
"Title": "Dungeons & Dragons Monster Generator",
})
}
err = tmpl.ExecuteTemplate(w, "about", data)
if err != nil {
log.Printf("Template execution error: %v\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)

View file

@ -7,21 +7,28 @@ import (
"strconv"
)
// AddMonster is a http.HandlerFunc that adds a new monster to the Monsters slice.
// It expects a POST request with form data containing the details of the monster.
// The monster is then appended to the Monsters slice and a redirect response is sent.
func AddMonster(Monsters *[]model.Monster) http.HandlerFunc {
log.Print("AddMonster called")
return func(w http.ResponseWriter, r *http.Request) {
// TODO
// Check if the request method is POST
if r.Method != http.MethodPost {
log.Print("Method not allowed")
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Parse the form data
err := r.ParseForm()
if err != nil {
log.Printf("Error parsing form data: %s", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Create a new monster with the form data
monster := model.Monster{
Name: r.FormValue("name"),
Source: r.FormValue("source"),
@ -73,19 +80,33 @@ func AddMonster(Monsters *[]model.Monster) http.HandlerFunc {
},
},
}
// Lock the Monsters slice, append the monster, and unlock the slice
mu.Lock()
defer mu.Unlock()
*Monsters = append(*Monsters, monster)
log.Printf("Monster hinzugefügt. Anzahl der Monster jetzt: %d\n", len(*Monsters))
// Log the number of monsters and redirect to the monster table
log.Printf("Monster added. Number of monsters now: %d\n", len(*Monsters))
http.Redirect(w, r, "/monsterTable", http.StatusFound)
}
}
// parseInt konvertiert einen String zu einem Integer und gibt 0 zurück, wenn die Konvertierung fehlschlägt
// parseInt converts a string to an integer and returns 0 if the conversion fails
func parseInt(s string) int {
// Add logging statement to print the input string
log.Println("Input string:", s)
// Atoi is used to convert the string to an integer
i, err := strconv.Atoi(s)
// If there is an error in the conversion, return 0 and log the error
if err != nil {
log.Println("Conversion error:", err)
return 0
}
// Log the converted integer
log.Println("Converted integer:", i)
// Return the converted integer
return i
}

View file

@ -7,15 +7,22 @@ import (
"net/http"
)
// ContactHandler handles the contact page request.
// It takes the content embed.FS as a parameter and returns an http.HandlerFunc.
// The returned http.HandlerFunc renders the contact page using the provided templates.
func ContactHandler(content embed.FS) http.HandlerFunc {
log.Print("ContactHandler called")
return func(w http.ResponseWriter, r *http.Request) {
log.Print("ContactHandler called")
// Parse the templates
tmpl, err := template.ParseFS(content, "templates/base.html", "templates/header.html", "templates/main.html", "templates/footer.html", "templates/about.html", "templates/contact.html")
if err != nil {
log.Printf("Template parsing error: %v\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Execute the contact template
err = tmpl.ExecuteTemplate(w, "contact", map[string]interface{}{
"Title": "Dungeons & Dragons Monster Generator",
})

View file

@ -8,25 +8,48 @@ import (
"net/http"
)
// FormHandler returns an http.HandlerFunc that handles form submissions.
// It takes the content embed.FS, a pointer to a slice of model.Monster,
// and a filename string as parameters.
// The function parses the template files from the content FS,
// executes the template with the provided data, and renders it as a response.
func FormHandler(content embed.FS, monsters *[]model.Monster, filename string) http.HandlerFunc {
log.Print("FormHandler called")
// Lock the mutex to ensure exclusive access to the monsters slice.
mu.Lock()
defer mu.Unlock()
return func(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFS(content, "templates/base.html", "templates/header.html", "templates/main.html", "templates/footer.html", "templates/monsterForm.html", "templates/monster.html", "templates/monsterTable.html")
log.Print("FormHandler handler called")
// Parse the template files.
templateFiles := []string{
"templates/base.html",
"templates/header.html",
"templates/main.html",
"templates/footer.html",
"templates/monsterForm.html",
"templates/monster.html",
"templates/monsterTable.html",
}
tmpl, err := template.ParseFS(content, templateFiles...)
if err != nil {
log.Printf("Template parsing error: %v\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = tmpl.ExecuteTemplate(w, "base", map[string]interface{}{
// Execute the template and render the response.
data := map[string]interface{}{
"Title": "Dungeons & Dragons Monster Generator",
"Monsters": *monsters,
})
}
err = tmpl.ExecuteTemplate(w, "base", data)
if err != nil {
log.Printf("Template execution error: %v\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
log.Printf("Template mit %d Monstern gerendert\n", len(*monsters))
log.Printf("Template rendered with %d Monsters\n", len(*monsters))
}
}

View file

@ -8,19 +8,26 @@ import (
"net/http"
)
// MainHandler
// MainHandler handles the main HTTP request.
// It returns an http.HandlerFunc that renders the main page
// with the provided content and monsters.
func MainHandler(content embed.FS, monsters *[]model.Monster) http.HandlerFunc {
log.Print("MainHandler called")
return func(w http.ResponseWriter, r *http.Request) {
log.Print("MainHandler called")
// Parse the templates from the embedded file system
tmpl, err := template.ParseFS(content, "templates/main.html", "templates/monsterForm.html", "templates/monster.html", "templates/monsterTable.html", "templates/base.html")
if err != nil {
log.Printf("Template parsing error: %v\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Lock the mutex to ensure exclusive access to the monsters slice
mu.Lock()
defer mu.Unlock()
// Execute the main template with the provided data
err = tmpl.ExecuteTemplate(w, "main", map[string]interface{}{
"Title": "Dungeons & Dragons Monster Generator",
"Monsters": *monsters,

View file

@ -8,15 +8,22 @@ import (
"net/http"
)
// MonsterTableHandler returns a http.HandlerFunc that handles requests to display a table of monsters.
func MonsterTableHandler(content embed.FS, monsters *[]model.Monster) http.HandlerFunc {
log.Print("AboutHandler called")
log.Print("MonsterTableHandler called")
return func(w http.ResponseWriter, r *http.Request) {
log.Print("Handling request for monster table")
// Parse the template files
tmpl, err := template.ParseFS(content, "templates/base.html", "templates/header.html", "templates/main.html", "templates/footer.html", "templates/monsterTable.html", "templates/monster.html")
if err != nil {
log.Printf("Template parsing error: %v\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Execute the template and pass the necessary data
err = tmpl.ExecuteTemplate(w, "monsterTable", map[string]interface{}{
"Title": "Dungeons & Dragons Monster Generator",
"Monsters": *monsters,

View file

@ -13,53 +13,59 @@ import (
var mu sync.Mutex
// submitHandler verarbeitet die Formulardaten
// SubmitHandler processes the form data.
func SubmitHandler(content embed.FS, chars *[]model.Character, Monsters *[]model.Monster, filename string) http.HandlerFunc {
log.Print("SubmitHandler called")
return func(w http.ResponseWriter, r *http.Request) {
log.Print("SubmitHandler called")
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Formulardaten parsen
// Parse form data.
err := r.ParseForm()
if err != nil {
log.Printf("Error parsing form data: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Monster-Objekt erstellen
// Create monster object.
filename := r.FormValue("filename")
// Charakter-Objekt erstellen oder aktualisieren
// Create or update character object.
mu.Lock()
defer mu.Unlock()
char := model.GetOrCreateCharacter(filename, *chars)
char.Monster = append(char.Monster, *Monsters...)
// Charakterdaten in JSON umwandeln
// Convert character data to JSON.
charJSON, err := json.Marshal(char)
if err != nil {
log.Printf("Error marshalling character data to JSON: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// JSON-Daten in die Datei schreiben
// Write JSON data to file.
err = model.WriteToFile(filename, charJSON)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Dateiinhalt lesen
fileContent, err := os.ReadFile(filename)
if err != nil {
log.Printf("Error writing JSON data to file: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Datei zum Download anbieten
// Read file contents.
fileContent, err := os.ReadFile(filename)
if err != nil {
log.Printf("Error reading file contents: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Offer file for download.
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
w.Header().Set("Content-Type", "application/json")
w.Write(fileContent)