Initial DDC release
This commit is contained in:
commit
434f6441da
57 files changed
+4606
No files matched your search
Executable
+47
@@ -0,0 +1,47 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user