Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby split and parse batched HTTP Response (multipart/mixed)

I'm using the GMail API that allows me to get a batched response of multiple Gmail objects. This comes back in the form of a multipart/mixed HTTP response with a set of separate HTTP responses separated by a boundary as defined in the header. Each of the HTTP sub-Responses is a JSON format.

i.e.

result.response.response_headers = {...
  "content-type"=>"multipart/mixed; boundary=batch_abcdefg"...
}

result.response.body = "----batch_abcdefg
<the response header>
{some JSON}
--batch_abcdefg
<another response header>
{some JSON}
--batch_abcdefg--"

Is there a library or an easy way to convert those responses from the string into a set of separate HTTP responses or JSON objects?

like image 525
Carpela Avatar asked Sep 07 '26 23:09

Carpela


1 Answers

Thanks to Tholle above...

def parse_batch_response(response, json=true)
  # Not the same delimiter in the response as we specify ourselves in the request,
  # so we have to extract it. 
  # This should give us exactly what we need.
  delimiter = response.split("\r\n")[0].strip
  parts = response.split(delimiter)
  # The first part will always be an empty string. Just remove it.
  parts.shift
  # The last part will be the "--". Just remove it.
  parts.pop

  if json  
    # collects the response body as json
    results = parts.map{ |part| JSON.parse(part.match(/{.+}/m).to_s)}
  else
    # collates the separate responses as strings so you can do something with them
    # e.g. you need the response codes
    results = parts.map{ |part| part}
  end
  result
end
like image 51
Carpela Avatar answered Sep 11 '26 20:09

Carpela