Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Less troublesome way of identifying content-type (#10770) #11018

Merged
merged 1 commit into from
Jul 4, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading