File
Blob: config/http.go
| 1 | package config |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "net/http" |
| 7 | |
| 8 | "go.uber.org/zap" |
| 9 | ) |
| 10 | |
| 11 | type HTTPErrorResponse struct { |
| 12 | Code string `json:"code"` |
| 13 | Message string `json:"message"` |
| 14 | Fields map[string]string `json:"fields,omitempty"` |
| 15 | } |
| 16 | |
| 17 | func WriteJSON(w http.ResponseWriter, status int, value any) { |
| 18 | w.Header().Set("Content-Type", "application/json") |
| 19 | w.WriteHeader(status) |
| 20 | _ = json.NewEncoder(w).Encode(value) |
| 21 | } |
| 22 | |
| 23 | // WriteSaveError handles the shared store's save outcomes for document editors. |
| 24 | // It returns false on success so the caller can render its document response. |
| 25 | func WriteSaveError(w http.ResponseWriter, name string, logger *zap.Logger, err error) bool { |
| 26 | if err == nil { |
| 27 | return false |
| 28 | } |
| 29 | status := http.StatusInternalServerError |
| 30 | response := HTTPErrorResponse{Code: "save_failed", Message: "Could not save the configuration on this server."} |
| 31 | switch { |
| 32 | case errors.Is(err, ErrConflict), errors.Is(err, ErrSchemaRegression): |
| 33 | status = http.StatusConflict |
| 34 | response = HTTPErrorResponse{Code: "version_conflict", Message: "Settings changed. Load the latest settings before saving again."} |
| 35 | case errors.Is(err, ErrTooLarge): |
| 36 | status = http.StatusRequestEntityTooLarge |
| 37 | response = HTTPErrorResponse{Code: "validation_failed", Message: "The shared configuration is too large."} |
| 38 | default: |
| 39 | logger.Error("Could not save shared configuration", zap.String("config", name), zap.Error(err)) |
| 40 | if errors.Is(err, ErrDurabilityUncertain) { |
| 41 | status = http.StatusServiceUnavailable |
| 42 | response = HTTPErrorResponse{Code: "outcome_unknown", Message: "The save result is uncertain. Retry the save or refresh to review the current configuration."} |
| 43 | } |
| 44 | } |
| 45 | WriteJSON(w, status, response) |
| 46 | return true |
| 47 | } |