hyperboreean
hyperboreean

Reputation: 8333

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.

Upvotes: 2

Views: 1886

Answers (3)

legoscia
legoscia

Reputation: 41528

I would recommend erlang:decode_packet for this, but to show how it can be done, here is a pair of functions that strips the leading "GET " and then returns everything up to the first space (but crashes if there is no space).

get_host(<<"GET ", Rest/binary>>) ->
    get_host2(Rest, <<>>).

get_host2(<<" ", _/binary>>, Acc) ->
    Acc;
get_host2(<<C, Rest/binary>>, Acc) ->
    get_host2(Rest, <<Acc/binary, C>>).

Basically, I put each byte that is not a space into my "accumulator", and when I find the space I return my accumulator. This is a common trick that is more often seen with lists. (With lists you will want to put new items at the front of the list and reverse the list at the end, to avoid your O(N) algorithm turning into O(N²), but that is not needed for binaries.)

Upvotes: 3

D.Nibon
D.Nibon

Reputation: 2919

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}},
<<>>}

Upvotes: 10

Jonke
Jonke

Reputation: 6533

The simple answer (but probably not what you really is asking for)

B = <<"GET http://www.google.com HTTP/1.1">> .
{_,H}=split_binary(B,4). 
split_binary(H,21).

Upvotes: 0

Related Questions