Major refactor to library
This commit is contained in:
74
pkg/handlers/hooks.go
Normal file
74
pkg/handlers/hooks.go
Normal file
@@ -0,0 +1,74 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"git.warky.dev/wdevs/whatshooked/pkg/config"
|
||||
"git.warky.dev/wdevs/whatshooked/pkg/logging"
|
||||
)
|
||||
|
||||
// Hooks returns the list of all configured hooks
|
||||
func (h *Handlers) Hooks(w http.ResponseWriter, r *http.Request) {
|
||||
hooks := h.hookMgr.ListHooks()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(hooks)
|
||||
}
|
||||
|
||||
// AddHook adds a new hook to the system
|
||||
func (h *Handlers) AddHook(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var hook config.Hook
|
||||
if err := json.NewDecoder(r.Body).Decode(&hook); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
h.hookMgr.AddHook(hook)
|
||||
|
||||
// Update config
|
||||
h.config.Hooks = h.hookMgr.ListHooks()
|
||||
if h.configPath != "" {
|
||||
if err := config.Save(h.configPath, h.config); err != nil {
|
||||
logging.Error("Failed to save config", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
// RemoveHook removes a hook from the system
|
||||
func (h *Handlers) RemoveHook(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.hookMgr.RemoveHook(req.ID); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
// Update config
|
||||
h.config.Hooks = h.hookMgr.ListHooks()
|
||||
if h.configPath != "" {
|
||||
if err := config.Save(h.configPath, h.config); err != nil {
|
||||
logging.Error("Failed to save config", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
||||
}
|
||||
Reference in New Issue
Block a user