Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse binary in Erlang

If I have the following binary: <<"GET http://www.google.com HTTP/1.1">>, how can I split it up so that I can retrieve only the host (http://www.google.com) ?

I started with something like:

get_host(<<$G, Rest/binary>>) -> get_host(Rest);
get_host(<<$E, Rest/binary>>) -> get_host(Rest);
get_host(<<$T, Rest/binary>>) -> get_host(Rest);

but I am not sure how to go on from here. I was thinking of reversing Rest and starting over from the end of the binary.

like image 582
hyperboreean Avatar asked Jul 27 '26 22:07

hyperboreean


1 Answers

It seems you're trying to implement a minimal parser for HTTP 1.1. This is one solution that does follow the specifications for HTTP 1.1 and parses the first line of a http request. Without knowing your specific situation I would in most cases recommend using a generic HTTP parser before a simplified "split binary" or similar.

1> erlang:decode_packet(http,<<"GET http://www.google.com HTTP/1.1\n">>,[]).  
{ok,{http_request,'GET',
              {absoluteURI,http,"www.google.com",undefined,"/"},
              {1,1}},
<<>>}
like image 131
D.Nibon Avatar answered Jul 30 '26 17:07

D.Nibon