108 lines
2.7 KiB
Go

package handlers
import (
"encoding/json"
"net/http"
"prak-03-todo/internal/db"
"strconv"
"github.com/gorilla/mux"
)
// CreateGroupHandler handles POST /groups
func CreateGroupHandler(w http.ResponseWriter, r *http.Request) {
var groupRequest struct {
GroupName string `json:"group_name"`
}
err := json.NewDecoder(r.Body).Decode(&groupRequest)
if err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
// Validate input
if groupRequest.GroupName == "" {
http.Error(w, "Group name is required", http.StatusBadRequest)
return
}
// Create group using query function
group, err := db.CreateGroup(groupRequest.GroupName)
if err != nil {
http.Error(w, "Failed to create group", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(group)
}
// RemoveGroupHandler handles DELETE /groups/{groupId}
func RemoveGroupHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
groupID, err := strconv.Atoi(vars["groupId"])
if err != nil {
http.Error(w, "Invalid group ID", http.StatusBadRequest)
return
}
// Delete group using query function
err = db.DeleteGroup(groupID)
if err != nil {
if err.Error() == "group not found" {
http.Error(w, "Group not found", http.StatusNotFound)
return
}
http.Error(w, "Failed to delete group", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("Group ID " + vars["groupId"] + " Removed"))
}
// GetGroupHandler handles GET /groups/{groupId}
func GetGroupHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
groupID, err := strconv.Atoi(vars["groupId"])
if err != nil {
http.Error(w, "Invalid group ID", http.StatusBadRequest)
return
}
// Get group using query function
group, err := db.GetGroupByID(groupID)
if err != nil {
if err.Error() == "group not found" {
http.Error(w, "Group not found", http.StatusNotFound)
return
}
http.Error(w, "Failed to fetch group", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(group)
}
// GetAllGroupsHandler handles GET /groups
func GetAllGroupsHandler(w http.ResponseWriter, r *http.Request) {
groups, err := db.GetAllGroups()
if err != nil {
http.Error(w, "Failed to fetch groups", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(groups)
}
// Home handles GET /
func Home(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello from Task Management API"))
}