Files
ddc/internal/server/respond.go
T
2026-10-25 20:24:50 -04:00

48 lines
1.3 KiB
Go
Executable File

package server
import (
"encoding/json"
"errors"
"net/http"
"ddc/internal/diskspace"
"ddc/internal/files"
"ddc/internal/jobs"
"ddc/internal/preferences"
)
func writeJSON(writer http.ResponseWriter, status int, payload any) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
writer.WriteHeader(status)
json.NewEncoder(writer).Encode(payload)
}
func writeError(writer http.ResponseWriter, status int, message string) {
writeJSON(writer, status, map[string]string{"error": message})
}
func writeFailure(writer http.ResponseWriter, err error) {
writeError(writer, statusFor(err), err.Error())
}
func decodeJSON(request *http.Request, target any) error {
decoder := json.NewDecoder(request.Body)
decoder.DisallowUnknownFields()
return decoder.Decode(target)
}
func statusFor(err error) int {
switch {
case errors.Is(err, jobs.ErrJobNotFound):
return http.StatusNotFound
case errors.Is(err, jobs.ErrJobBusy), errors.Is(err, files.ErrDestinationExists):
return http.StatusConflict
case errors.Is(err, jobs.ErrInvalidRequest), errors.Is(err, preferences.ErrInvalid):
return http.StatusBadRequest
case errors.Is(err, diskspace.ErrInsufficientSpace):
return http.StatusInsufficientStorage
default:
return http.StatusInternalServerError
}
}