From 88cfe035e032e824c44e3b7bf41312d14a93f9ca Mon Sep 17 00:00:00 2001 From: Patryk Hegenberg Date: Fri, 15 Dec 2023 15:38:43 +0100 Subject: [PATCH] backend: frontend: add file load feature added a feature to load existing json files and load the containing monsters --- handlers/load_file_handler.go | 46 +++++++++++++++++++++++++++++++++++ main.go | 1 + templates/main.html | 24 +++++++++++++++++- 3 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 handlers/load_file_handler.go diff --git a/handlers/load_file_handler.go b/handlers/load_file_handler.go new file mode 100644 index 0000000..cfaaac4 --- /dev/null +++ b/handlers/load_file_handler.go @@ -0,0 +1,46 @@ +package handlers + +import ( + "ddServer/model" + "encoding/json" + "fmt" + "log" + "net/http" +) + +func LoadFileHandler(monsters *[]model.Monster) http.HandlerFunc { + log.Print("LoadFileHandler called") + return func(w http.ResponseWriter, r *http.Request) { + r.ParseMultipartForm(10 << 20) // 10 MB limit + + // Get the file from the request + file, _, err := r.FormFile("uploadFile") + if err != nil { + http.Error(w, "Error retrieving file", http.StatusBadRequest) + return + } + defer file.Close() + + // Parse the file content + decoder := json.NewDecoder(file) + var loadedChars model.Character + err = decoder.Decode(&loadedChars) + if err != nil { + http.Error(w, "Error decoding file content", http.StatusInternalServerError) + return + } + + // Lock the Monsters slice and append the loaded monsters, then unlock the slice + mu.Lock() + defer mu.Unlock() + + // Assuming 'loadedChars' contains an array of Monster objects + for _, monster := range loadedChars.Monster { + *monsters = append(*monsters, monster) + } + + fmt.Printf("%v\n", monsters) + // Send a success response + http.Redirect(w, r, "/monsterTable", http.StatusTemporaryRedirect) + } +} diff --git a/main.go b/main.go index d163e79..5bbd46f 100644 --- a/main.go +++ b/main.go @@ -37,6 +37,7 @@ func main() { routes.HandleFunc("/contact", handlers.ContactHandler(content)) routes.HandleFunc("/monsterTable", handlers.MonsterTableHandler(content, &Monsters)) routes.HandleFunc("/calculate-skills", handlers.SkillCalculationHandler(content)) + routes.HandleFunc("/loadFile", handlers.LoadFileHandler(&Monsters)) // Print the message indicating that 'static' has been included. log.Printf("Eingebunden is %v\n", static) diff --git a/templates/main.html b/templates/main.html index ed4581f..53884fd 100644 --- a/templates/main.html +++ b/templates/main.html @@ -6,6 +6,28 @@

Monster Form

+
+
+ +
+
+
+ +
+
+
@@ -13,6 +35,7 @@ class="input input-bordered w-full max-w-xs">
+ {{ template "monsterform" . }}
- {{ template "monsterform" . }}