boxes-api/item_handlers.go

242 lines
6.2 KiB
Go

// item_handlers.go
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"github.com/gorilla/mux"
)
// Move all item-related handlers here:
// - GetItemsHandler
// - CreateItemHandler
// - GetItemHandler
// - UpdateItemHandler
// - DeleteItemHandler
// - UploadItemImageHandler
// - GetItemImageHandler
// - SearchItemsHandler
// - GetItemsInBoxHandler
// getItemsHandler handles the GET /items endpoint.
func GetItemsHandler(w http.ResponseWriter, r *http.Request) {
var items []Item
db.Find(&items)
json.NewEncoder(w).Encode(items)
}
// createItemHandler handles the POST /items endpoint.
func CreateItemHandler(w http.ResponseWriter, r *http.Request) {
var item Item
err := json.NewDecoder(r.Body).Decode(&item)
if err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
fmt.Println(item)
db.Create(&item)
// Create a response struct to include the ID
type createItemResponse struct {
ID uint `json:"id"`
Name string `json:"name"`
}
response := createItemResponse{
ID: item.ID,
Name: item.Name,
}
json.NewEncoder(w).Encode(response)
}
// UploadItemImageHandler handles the image upload for an item
func UploadItemImageHandler(w http.ResponseWriter, r *http.Request) {
// Extract the authenticated user from context (assuming this is how AuthMiddleware works)
user, ok := r.Context().Value(userKey).(string)
if !ok || user == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Parse the form data, 10MB limit for file uploads
err := r.ParseMultipartForm(10 << 20)
if err != nil {
http.Error(w, "Unable to parse form", http.StatusBadRequest)
return
}
// Get the file from the form data
file, handler, err := r.FormFile("image")
if err != nil {
http.Error(w, "Error retrieving the file", http.StatusBadRequest)
return
}
defer file.Close()
// Get item ID from the URL
vars := mux.Vars(r)
itemID := vars["id"]
// Validate that the item exists (fetch from DB using itemID)
var item Item
if err := db.First(&item, itemID).Error; err != nil {
http.Error(w, "Item not found", http.StatusNotFound)
return
}
// Save the uploaded file locally or to a storage service
// Ensure the directory exists
if err := os.MkdirAll(*ImageStorage, 0755); err != nil {
http.Error(w, "Unable to create image storage directory", http.StatusInternalServerError)
return
}
filePath := fmt.Sprintf("%s/%s", *ImageStorage, handler.Filename)
outFile, err := os.Create(filePath)
if err != nil {
http.Error(w, "Unable to save the file", http.StatusInternalServerError)
return
}
defer outFile.Close()
// Copy the uploaded file to the destination
_, err = io.Copy(outFile, file)
if err != nil {
http.Error(w, "Unable to save the file", http.StatusInternalServerError)
return
}
// Update the item record in the database with the image path
item.ImagePath = filePath
if err := db.Save(&item).Error; err != nil {
http.Error(w, "Unable to save image path in database", http.StatusInternalServerError)
return
}
fmt.Println("Image upload called")
// Return the image path in the response
w.WriteHeader(http.StatusOK)
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 {
item.ImagePath = "images/default.jpg"
} else if item.ImagePath == "" {
item.ImagePath = "images/default.jpg"
}
// Open the image file
imageFile, err := os.Open(item.ImagePath)
if err != nil {
// Log the error for debugging, but don't return an HTTP error
fmt.Println("Error opening image.", err)
item.ImagePath = "images/default.jpg"
return
}
defer imageFile.Close()
// Determine the content type of the image
imageData, err := io.ReadAll(imageFile)
if err != nil {
fmt.Println("Error reading image")
item.ImagePath = "images/default.jpg"
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)
}
// searchItemsHandler handles the GET /items/search endpoint.
func SearchItemsHandler(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query().Get("q")
if query == "" {
http.Error(w, "Search query is required", http.StatusBadRequest)
return
}
fmt.Println(query)
var items []Item
db.Where("name GLOB ? OR description GLOB ?", "*"+query+"*", "*"+query+"*").Find(&items)
json.NewEncoder(w).Encode(items)
}
// getItemHandler handles the GET /items/{id} endpoint.
func GetItemHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
var item Item
if err := db.First(&item, id).Error; err != nil {
http.Error(w, "Item not found", http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(item)
}
// getItemsInBoxHandler handles the GET /boxes/{id}/items endpoint.
func GetItemsInBoxHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
var items []Item
if err := db.Where("box_id = ?", id).Find(&items).Error; err != nil {
http.Error(w, "Items not found", http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(items)
}
// updateItemHandler handles the PUT /items/{id} endpoint.
func UpdateItemHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
var item Item
if err := db.First(&item, id).Error; err != nil {
http.Error(w, "Item not found", http.StatusNotFound)
return
}
err := json.NewDecoder(r.Body).Decode(&item)
if err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
fmt.Println(item)
db.Save(&item)
json.NewEncoder(w).Encode(item)
}
// deleteItemHandler handles the DELETE /items/{id} endpoint.
func DeleteItemHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
var item Item
if err := db.First(&item, id).Error; err != nil {
http.Error(w, "Item not found", http.StatusNotFound)
return
}
db.Delete(&item)
w.WriteHeader(http.StatusNoContent)
}