From 012c2bd6457c94b7aeab96eda2a924b3b0ce1f09 Mon Sep 17 00:00:00 2001 From: Steve White Date: Fri, 11 Oct 2024 21:15:15 -0500 Subject: [PATCH] Added search/items endpoint for searching all items. --- handlers.go | 14 ++++++++++++++ main.go | 2 ++ scripts/searchitems.bash | 22 ++++++++++++++++++++++ 3 files changed, 38 insertions(+) create mode 100644 scripts/searchitems.bash diff --git a/handlers.go b/handlers.go index 62bbdc1..cab39ef 100644 --- a/handlers.go +++ b/handlers.go @@ -260,6 +260,20 @@ func GetItemImageHandler(w http.ResponseWriter, r *http.Request) { 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) diff --git a/main.go b/main.go index 80a1fed..e697402 100644 --- a/main.go +++ b/main.go @@ -58,6 +58,8 @@ func main() { 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") + fmt.Println("Registering route for search items...") + router.Handle("/search/items", AuthMiddleware(http.HandlerFunc(SearchItemsHandler))).Methods("GET", "OPTIONS") // Add a new route for uploading an image with AuthMiddleware router.HandleFunc("/items/{id}/upload", UploadItemImageHandler). Methods("POST"). diff --git a/scripts/searchitems.bash b/scripts/searchitems.bash new file mode 100644 index 0000000..7eb7927 --- /dev/null +++ b/scripts/searchitems.bash @@ -0,0 +1,22 @@ +#!/bin/bash + +# API base URL +API_BASE_URL="http://localhost:8080" + +# Login credentials +USERNAME="boxuser" +PASSWORD="boxuser" + +# Get a new JWT token +TOKEN=$(curl -s -X POST -H "Content-Type: application/json" \ + -d "{\"username\":\"$USERNAME\", \"password\":\"$PASSWORD\"}" \ + "$API_BASE_URL/login" | jq -r '.token') + +# Request all items using the obtained token +curl -X GET \ + http://localhost:8080/search/items?q=brand \ + -H "Authorization: Bearer $TOKEN" \ + -H 'Content-Type: application/json' + +# Print the response +echo "$response"