Simplify parsing multipart responses

This commit is contained in:
Till Faelligen 2024-08-02 20:17:00 +02:00
parent 48a3ce0d85
commit c024c15a6e
No known key found for this signature in database
GPG key ID: 3DF82D8AB9211D4E

View file

@ -848,38 +848,37 @@ func (r *downloadRequest) fetchRemoteFile(
var reader io.Reader var reader io.Reader
var parseErr error var parseErr error
if isMultiPart { if isMultiPart {
r.Logger.Info("Downloaded file using authenticated endpoint") r.Logger.Debug("Downloaded file using authenticated endpoint")
var params map[string]string var params map[string]string
_, params, err = mime.ParseMediaType(resp.Header.Get("Content-Type")) _, params, err = mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil { if err != nil {
panic(err) panic(err)
} }
if params["boundary"] == "" { if params["boundary"] == "" {
return "", false, fmt.Errorf("no boundary header found on %s", r.MediaMetadata.Origin) return "", false, fmt.Errorf("no boundary header found on media %s from %s", r.MediaMetadata.MediaID, r.MediaMetadata.Origin)
} }
mr := multipart.NewReader(resp.Body, params["boundary"]) mr := multipart.NewReader(resp.Body, params["boundary"])
first := true // Get the first, JSON, part
for { p, multipartErr := mr.NextPart()
var p *multipart.Part if multipartErr != nil {
p, err = mr.NextPart() return "", false, multipartErr
if err == io.EOF {
break
}
if err != nil {
return "", false, err
} }
if !first { if p.Header.Get("Content-Type") != "application/json" {
readCloser := io.NopCloser(p) return "", false, fmt.Errorf("first part of the response must be application/json")
contentLength, reader, parseErr = r.GetContentLengthAndReader(p.Header.Get("Content-Length"), readCloser, maxFileSizeBytes) }
// TODO: Once something is defined, parse the JSON content
// Get the actual media content
p, multipartErr = mr.NextPart()
if multipartErr != nil {
return "", false, multipartErr
}
contentLength, reader, parseErr = r.GetContentLengthAndReader(p.Header.Get("Content-Length"), p, maxFileSizeBytes)
// For multipart requests, we need to get the Content-Type of the second part, which is the actual media // For multipart requests, we need to get the Content-Type of the second part, which is the actual media
r.MediaMetadata.ContentType = types.ContentType(p.Header.Get("Content-Type")) r.MediaMetadata.ContentType = types.ContentType(p.Header.Get("Content-Type"))
break
}
first = false
}
} else { } else {
// The reader returned here will be limited either by the Content-Length // The reader returned here will be limited either by the Content-Length
// and/or the configured maximum media size. // and/or the configured maximum media size.