diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..a9bd2e7 Binary files /dev/null and b/.DS_Store differ diff --git a/handlers.go b/handlers.go index dca636d..92fa3f1 100644 --- a/handlers.go +++ b/handlers.go @@ -223,6 +223,45 @@ func UploadItemImageHandler(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(map[string]string{"imagePath": filePath}) } +// GetItemImageHandler retrieves an item's image by item ID. +func GetItemImageHandler(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + itemID := vars["id"] + fmt.Println("Getting image") + // Retrieve the item from the database + var item Item + if err := db.First(&item, itemID).Error; err != nil { + http.Error(w, "Item not found", http.StatusNotFound) + return + } + + // Check if the item has an associated image + if item.ImagePath == "" { + http.Error(w, "Item has no image", http.StatusNotFound) + return + } + + // Open the image file + imageFile, err := os.Open(item.ImagePath) + if err != nil { + http.Error(w, "Unable to open image file", http.StatusInternalServerError) + return + } + defer imageFile.Close() + + // Determine the content type of the image + imageData, err := io.ReadAll(imageFile) + if err != nil { + http.Error(w, "Unable to read image file", http.StatusInternalServerError) + return + } + contentType := http.DetectContentType(imageData) + + // Set the content type header and write the image data to the response + w.Header().Set("Content-Type", contentType) + w.Write(imageData) +} + // getItemHandler handles the GET /items/{id} endpoint. func GetItemHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) diff --git a/main.go b/main.go index f39f382..80a1fed 100644 --- a/main.go +++ b/main.go @@ -57,6 +57,7 @@ func main() { router.Handle("/boxes/{id}/items", AuthMiddleware(http.HandlerFunc(GetItemsInBoxHandler))).Methods("GET", "OPTIONS") router.Handle("/items/{id}", AuthMiddleware(http.HandlerFunc(UpdateItemHandler))).Methods("PUT", "OPTIONS") router.Handle("/items/{id}", AuthMiddleware(http.HandlerFunc(DeleteItemHandler))).Methods("DELETE", "OPTIONS") + router.Handle("/items/{id}/image", AuthMiddleware(http.HandlerFunc(GetItemImageHandler))).Methods("GET", "OPTIONS") // Add a new route for uploading an image with AuthMiddleware router.HandleFunc("/items/{id}/upload", UploadItemImageHandler). Methods("POST"). diff --git a/tests.bash b/tests.bash index fe3cde2..4489979 100755 --- a/tests.bash +++ b/tests.bash @@ -1,7 +1,7 @@ #!/bin/bash # API base URL -API_BASE_URL="http://localhost:8080" +API_BASE_URL="http://10.0.0.66:8080" # Login credentials USERNAME="boxuser"