URL encode in Erlang
AFAIK there’s no URL encoder in the standard libraries exclude edoc_lib:escape_uri. Think I ‘borrowed’ the following code from YAWS or maybe one of the other Erlang web servers
% Utility function to convert a 'form' of name-value pairs into a URL encoded
% content string.
urlencode(Form) ->
RevPairs = lists:foldl(fun({K,V},Acc) -> [[quote_plus(K),$=,quote_plus(V)] | Acc] end, [],Form),
lists:flatten(revjoin(RevPairs,$&,[])).
quote_plus(Atom) when is_atom(Atom) ->
quote_plus(atom_to_list(Atom));
quote_plus(Int) when is_integer(Int) ->
quote_plus(integer_to_list(Int));
quote_plus(String) ->
quote_plus(String, []).
quote_plus([], Acc) ->
lists:reverse(Acc);
quote_plus([C | Rest], Acc) when ?QS_SAFE(C) ->
quote_plus(Rest, [C | Acc]);
quote_plus([$\s | Rest], Acc) ->
quote_plus(Rest, [$+ | Acc]);
quote_plus([C | Rest], Acc) ->
<> = <>,
quote_plus(Rest, [hexdigit(Lo), hexdigit(Hi), ?PERCENT | Acc]).
revjoin([], _Separator, Acc) ->
Acc;
revjoin([S | Rest],Separator,[]) ->
Here’s a “fork” of the edoc_lib:escape_uri function that improves on the UTF-8 support and also supports binaries
escape_uri(S) when is_list(S) ->
escape_uri(unicode:characters_to_binary(S));
escape_uri(<>) when C >= $a, C =< $z ->
[C] ++ escape_uri(Cs);
escape_uri(<>) when C >= $A, C =< $Z ->
[C] ++ escape_uri(Cs);
escape_uri(<>) when C >= $0, C =< $9 ->
[C] ++ escape_uri(Cs);
escape_uri(<>) when C == $. ->
[C] ++ escape_uri(Cs);
escape_uri(<>) when C == $- ->
[C] ++ escape_uri(Cs);
escape_uri(<>) when C == $_ ->
[C] ++ escape_uri(Cs);
escape_uri(<>) ->
escape_byte(C) ++ escape_uri(Cs);
escape_uri(<<>>) ->
"".
escape_byte(C) ->
"%" ++ hex_octet(C).
hex_octet(N) when N =< 9 ->
[$0 + N];
hex_octet(N) when N > 15 ->
hex_octet(N bsr 4) ++ hex_octet(N band 15);
hex_octet(N) ->
[N - 10 + $a].
Читайте також:
- flash socket policy-file-request in Erlang
- Agner: a repository of libraries and applications
- Tutorial: Developing in Erlang with Webmachine, ErlyDTL, and Riak
- Mustache is a framework templating system
- Python + CouchDB
- md5 в Erlang
- Erlang Meter
- Erlang CouchDB fault-tolerance
- Python and lists:flatten. Such as in Erlang
- Tahoe-LAFS - P2P файлова система, що дозволяє використовувати "хмару" серверів не довіряючи ним