Added search/items endpoint for searching all items.

This commit is contained in:
Steve White 2024-10-11 21:15:15 -05:00
parent b426f59be7
commit 012c2bd645
3 changed files with 38 additions and 0 deletions

View File

@ -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)

View File

@ -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").

22
scripts/searchitems.bash Normal file
View File

@ -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"