Files
at-container-registry/pkg/hold/oci/http_helpers.go

39 lines
1.2 KiB
Go

// Package oci provides HTTP helpers for OCI registry endpoints in the hold service.
// It includes utilities for JSON encoding/decoding of request/response bodies
// and standardized error responses for XRPC endpoints.
package oci
import (
"encoding/json"
"fmt"
"log/slog"
"net/http"
)
// DecodeJSON decodes JSON request body into the provided value
// Returns an error if decoding fails
func DecodeJSON(r *http.Request, v any) error {
if err := json.NewDecoder(r.Body).Decode(v); err != nil {
return fmt.Errorf("invalid JSON body: %w", err)
}
return nil
}
// RespondJSON writes a JSON response with the given status code
func RespondJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(v); err != nil {
// If encoding fails, we can't do much since headers are already sent
// Log the error but don't try to send another response
slog.Error("Failed to encode JSON response", "error", err)
}
}
// RespondError writes a JSON error response with the given status code and message
func RespondError(w http.ResponseWriter, status int, message string) {
RespondJSON(w, status, map[string]string{
"error": message,
})
}