Files
dns-autoresolver/internal/api/handlers.go
T

57 lines
1.5 KiB
Go

package api
import (
"encoding/json"
"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) {
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(), did)
if err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
writeJSON(w, http.StatusOK, toChangesetResponse(cs))
}
func (a *API) handleApply(w http.ResponseWriter, r *http.Request) {
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 {
// пустое тело допустимо → значения по умолчанию (prune=false)
_ = json.NewDecoder(r.Body).Decode(&req)
}
cs, err := a.Svc.Apply(r.Context(), did, service.ApplyRequest{
ApplyUpdates: req.ApplyUpdates, ApplyPrunes: req.ApplyPrunes,
})
if err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
writeJSON(w, http.StatusOK, toChangesetResponse(cs))
}