From 738288a781a7b926cbe116be82867635b675bfff Mon Sep 17 00:00:00 2001 From: Giulio rebuffo Date: Sat, 22 Jun 2024 00:00:32 +0200 Subject: [PATCH] Less troublesome way of identifying content-type (#10770) --- cl/beacon/beaconhttp/api.go | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/cl/beacon/beaconhttp/api.go b/cl/beacon/beaconhttp/api.go index d38775093c8..149e5864b04 100644 --- a/cl/beacon/beaconhttp/api.go +++ b/cl/beacon/beaconhttp/api.go @@ -97,19 +97,30 @@ func HandleEndpoint[T any](h EndpointHandler[T]) http.HandlerFunc { } // TODO: potentially add a context option to buffer these contentType := r.Header.Get("Accept") - contentTypes := strings.Split(contentType, ",") // early return for event stream if slices.Contains(w.Header().Values("Content-Type"), "text/event-stream") { return } switch { - case slices.Contains(contentTypes, "application/octet-stream"): + case contentType == "*/*", contentType == "", strings.Contains(contentType, "text/html"), strings.Contains(contentType, "application/json"): + if !isNil(ans) { + w.Header().Set("Content-Type", "application/json") + err := json.NewEncoder(w).Encode(ans) + if err != nil { + // this error is fatal, log to console + log.Error("beaconapi failed to encode json", "type", reflect.TypeOf(ans), "err", err) + } + } else { + w.WriteHeader(200) + } + case strings.Contains(contentType, "application/octet-stream"): sszMarshaler, ok := any(ans).(ssz.Marshaler) if !ok { NewEndpointError(http.StatusBadRequest, ErrorSszNotSupported).WriteTo(w) return } + w.Header().Set("Content-Type", "application/octet-stream") // TODO: we should probably figure out some way to stream this in the future :) encoded, err := sszMarshaler.EncodeSSZ(nil) if err != nil { @@ -117,21 +128,10 @@ func HandleEndpoint[T any](h EndpointHandler[T]) http.HandlerFunc { return } w.Write(encoded) - case contentType == "*/*", contentType == "", slices.Contains(contentTypes, "text/html"), slices.Contains(contentTypes, "application/json"): - if !isNil(ans) { - w.Header().Add("content-type", "application/json") - err := json.NewEncoder(w).Encode(ans) - if err != nil { - // this error is fatal, log to console - log.Error("beaconapi failed to encode json", "type", reflect.TypeOf(ans), "err", err) - } - } else { - w.WriteHeader(200) - } - case slices.Contains(contentTypes, "text/event-stream"): + case strings.Contains(contentType, "text/event-stream"): return default: - http.Error(w, "content type must be application/json, application/octet-stream, or text/event-stream", http.StatusBadRequest) + http.Error(w, fmt.Sprintf("content type must include application/json, application/octet-stream, or text/event-stream, got %s", contentType), http.StatusBadRequest) } }) }