77 lines
1.6 KiB
Go
77 lines
1.6 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
"net/http"
|
||
|
|
||
|
"github.com/gorilla/mux"
|
||
|
)
|
||
|
|
||
|
// getBoxesHandler handles the GET /boxes endpoint.
|
||
|
func GetBoxesHandler(w http.ResponseWriter, r *http.Request) {
|
||
|
fmt.Printf("Received %s request to %s\n", r.Method, r.URL)
|
||
|
var boxes []Box
|
||
|
db.Find(&boxes)
|
||
|
json.NewEncoder(w).Encode(boxes)
|
||
|
}
|
||
|
|
||
|
func GetBoxHandler(w http.ResponseWriter, r *http.Request) {
|
||
|
vars := mux.Vars(r)
|
||
|
id := vars["id"]
|
||
|
|
||
|
var box Box
|
||
|
if err := db.First(&box, id).Error; err != nil {
|
||
|
http.Error(w, "Box not found", http.StatusNotFound)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
json.NewEncoder(w).Encode(box)
|
||
|
}
|
||
|
|
||
|
// createBoxHandler handles the POST /boxes endpoint.
|
||
|
func CreateBoxHandler(w http.ResponseWriter, r *http.Request) {
|
||
|
var box Box
|
||
|
err := json.NewDecoder(r.Body).Decode(&box)
|
||
|
if err != nil {
|
||
|
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
db.Create(&box)
|
||
|
|
||
|
// Create a response struct to include the ID
|
||
|
type createBoxResponse struct {
|
||
|
ID uint `json:"id"`
|
||
|
Name string `json:"name"`
|
||
|
}
|
||
|
|
||
|
response := createBoxResponse{
|
||
|
ID: box.ID,
|
||
|
Name: box.Name,
|
||
|
}
|
||
|
|
||
|
json.NewEncoder(w).Encode(response)
|
||
|
}
|
||
|
|
||
|
// deleteBoxHandler handles the DELETE /boxes/{id} endpoint.
|
||
|
func DeleteBoxHandler(w http.ResponseWriter, r *http.Request) {
|
||
|
vars := mux.Vars(r)
|
||
|
id := vars["id"]
|
||
|
|
||
|
// Retrieve the box from the database
|
||
|
var box Box
|
||
|
if err := db.First(&box, id).Error; err != nil {
|
||
|
http.Error(w, "Box not found", http.StatusNotFound)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
// Optionally, delete associated items (if you want cascading delete)
|
||
|
// db.Where("box_id = ?", id).Delete(&Item{})
|
||
|
|
||
|
// Delete the box
|
||
|
db.Delete(&box)
|
||
|
|
||
|
w.WriteHeader(http.StatusNoContent) // 204 No Content
|
||
|
}
|