73 lines
2.2 KiB
Go
73 lines
2.2 KiB
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/vasyakrg/dns-autoresolver/internal/service"
|
|
)
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, v any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(v)
|
|
}
|
|
|
|
func writeErr(w http.ResponseWriter, status int, msg string) {
|
|
writeJSON(w, status, map[string]string{"error": msg})
|
|
}
|
|
|
|
func (a *API) handleCheck(w http.ResponseWriter, r *http.Request) {
|
|
// pid is guaranteed present and owned by the caller — RequireProjectAccess
|
|
// validated it before this handler ever runs.
|
|
pid, _ := projectIDFrom(r.Context())
|
|
did, err := uuid.Parse(chi.URLParam(r, "did"))
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadRequest, "invalid domain id")
|
|
return
|
|
}
|
|
cs, err := a.Svc.Check(r.Context(), pid, did)
|
|
if err != nil {
|
|
log.Printf("api: check failed: %v", err)
|
|
writeErr(w, http.StatusInternalServerError, "internal error")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, toChangesetResponse(cs))
|
|
}
|
|
|
|
func (a *API) handleApply(w http.ResponseWriter, r *http.Request) {
|
|
// pid is guaranteed present and owned by the caller — RequireProjectAccess
|
|
// validated it before this handler ever runs.
|
|
pid, _ := projectIDFrom(r.Context())
|
|
did, err := uuid.Parse(chi.URLParam(r, "did"))
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadRequest, "invalid domain id")
|
|
return
|
|
}
|
|
var req applyRequest
|
|
if r.Body != nil {
|
|
r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // 1 MiB
|
|
// пустое тело допустимо → значения по умолчанию (prune=false);
|
|
// любая другая ошибка decode (битый JSON, неверные типы) → 400
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil && !errors.Is(err, io.EOF) {
|
|
writeErr(w, http.StatusBadRequest, "invalid request body")
|
|
return
|
|
}
|
|
}
|
|
cs, err := a.Svc.Apply(r.Context(), pid, did, service.ApplyRequest{
|
|
ApplyUpdates: req.ApplyUpdates, ApplyPrunes: req.ApplyPrunes,
|
|
})
|
|
if err != nil {
|
|
log.Printf("api: apply failed: %v", err)
|
|
writeErr(w, http.StatusInternalServerError, "internal error")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, toChangesetResponse(cs))
|
|
}
|