61 lines
1.6 KiB
Go
61 lines
1.6 KiB
Go
|
|
package server
|
||
|
|
|
||
|
|
import (
|
||
|
|
"encoding/json"
|
||
|
|
"fmt"
|
||
|
|
"net/http"
|
||
|
|
"net/url"
|
||
|
|
"strings"
|
||
|
|
|
||
|
|
"scm.bstein.dev/bstein/soteria/internal/api"
|
||
|
|
)
|
||
|
|
|
||
|
|
func (s *Server) handlePolicies(w http.ResponseWriter, r *http.Request) {
|
||
|
|
switch r.Method {
|
||
|
|
case http.MethodGet:
|
||
|
|
writeJSON(w, http.StatusOK, api.BackupPolicyListResponse{Policies: s.listPolicies()})
|
||
|
|
case http.MethodPost:
|
||
|
|
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
|
||
|
|
var req api.BackupPolicyUpsertRequest
|
||
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||
|
|
writeError(w, http.StatusBadRequest, fmt.Sprintf("invalid JSON: %v", err))
|
||
|
|
return
|
||
|
|
}
|
||
|
|
policy, err := s.upsertPolicy(r.Context(), req)
|
||
|
|
if err != nil {
|
||
|
|
writeError(w, http.StatusBadRequest, err.Error())
|
||
|
|
return
|
||
|
|
}
|
||
|
|
writeJSON(w, http.StatusOK, policy)
|
||
|
|
default:
|
||
|
|
writeError(w, http.StatusMethodNotAllowed, "method not allowed")
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func (s *Server) handlePolicyByID(w http.ResponseWriter, r *http.Request) {
|
||
|
|
if r.Method != http.MethodDelete {
|
||
|
|
writeError(w, http.StatusMethodNotAllowed, "method not allowed")
|
||
|
|
return
|
||
|
|
}
|
||
|
|
encodedID := strings.TrimPrefix(r.URL.Path, "/v1/policies/")
|
||
|
|
if encodedID == "" {
|
||
|
|
writeError(w, http.StatusBadRequest, "policy id is required")
|
||
|
|
return
|
||
|
|
}
|
||
|
|
id, err := url.PathUnescape(encodedID)
|
||
|
|
if err != nil {
|
||
|
|
writeError(w, http.StatusBadRequest, "invalid policy id")
|
||
|
|
return
|
||
|
|
}
|
||
|
|
removed, err := s.deletePolicy(r.Context(), id)
|
||
|
|
if err != nil {
|
||
|
|
writeError(w, http.StatusBadGateway, err.Error())
|
||
|
|
return
|
||
|
|
}
|
||
|
|
if !removed {
|
||
|
|
writeError(w, http.StatusNotFound, "policy not found")
|
||
|
|
return
|
||
|
|
}
|
||
|
|
writeJSON(w, http.StatusOK, map[string]string{"deleted": id})
|
||
|
|
}
|