Skip to content

Commit

Permalink
Less troublesome way of identifying content-type (#10770)
Browse files Browse the repository at this point in the history
  • Loading branch information
Giulio2002 authored and VBulikov committed Jul 4, 2024
1 parent 1a050db commit 738288a
Showing 1 changed file with 15 additions and 15 deletions.
30 changes: 15 additions & 15 deletions cl/beacon/beaconhttp/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,41 +97,41 @@ 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 {
WrapEndpointError(err).WriteTo(w)
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)
}
})
}
Expand Down

0 comments on commit 738288a

Please sign in to comment.