Skip to content

Instantly share code, notes, and snippets.

@ga2arch
Created June 6, 2009 18:43
Show Gist options
  • Save ga2arch/124969 to your computer and use it in GitHub Desktop.
Save ga2arch/124969 to your computer and use it in GitHub Desktop.
-module(gtranslate).
-author("Gabriele <carretta63@gmail.com").
-version("0.0.1").
-define(API_URL, "http://ajax.googleapis.com/ajax/services/language/translate").
-export([translate/3, lang_pair/2, request_url/2, check_result/1]).
-import(mochijson2).
lang_pair(Lo, Ld) ->
A = string:substr(Lo, 1, 2),
B = string:substr(Ld, 1, 2),
{ok, A ++ "|" ++ B}.
request_url(Text, Pair) ->
Url = ?API_URL ++ "?v=1.0&q=" ++ edoc_lib:escape_uri(Text) ++
"&langpair=" ++ Pair,
{ok, Url}.
check_result({_, [{_, RTT}]}) ->
binary_to_list(RTT).
check_result(null) ->
binary_to_list(Error).
translate(Lo, Ld, Text) ->
inets:start(),
{ok, Pair} = lang_pair(Lo, Ld),
{ok, Url} = request_url(Text, Pair),
{ok, {{_, _Status, _}, _, Body}} = http:request(Url),
{_, [{_, Result}, {_, Error}, {_, _}]} = mochijson2:decode(Body),
check_result(Result).
%TT = binary_to_list(RTT),
%{ok, RTT}.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment