Created
February 21, 2010 04:38
-
-
Save darkua/310121 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%%%------------------------------------------------------------------- | |
%%% File: unshort_srv.erl | |
%%% @author Sergio Veiga <> [] | |
%%% @copyright 2010 Sergio Veiga | |
%%% @doc A simple Server to retrieve the original url from a short one | |
%%% | |
%%% @end | |
%%% | |
%%% @since 2010-02-21 by Sergio Veiga | |
%%%------------------------------------------------------------------- | |
-module(unshort_srv). | |
-author('Sergio Veiga'). | |
-behaviour(gen_server). | |
%% API | |
-export([start_link/0,unshort/1]). | |
%% gen_server callbacks | |
-export([init/1, handle_call/3,handle_cast/2, handle_info/2, terminate/2, code_change/3]). | |
-record(state, {}). | |
%%==================================================================== | |
%% API | |
%%==================================================================== | |
%%-------------------------------------------------------------------- | |
%% @spec start_link() -> {ok,Pid} | ignore | {error,Error} | |
%% @doc Starts the server | |
%% @end | |
%%-------------------------------------------------------------------- | |
start_link() -> | |
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). | |
%%-------------------------------------------------------------------- | |
%% @spec unshort() -> {ok,Url} | {error,Error} | |
%% @doc Returns the "long" url | |
%% @end | |
%%-------------------------------------------------------------------- | |
unshort(Url)-> | |
gen_server:call(?MODULE,{unshort,Url}). | |
%%==================================================================== | |
%% gen_server callbacks | |
%%==================================================================== | |
init([]) -> | |
inets:start(), | |
{ok, #state{}}. | |
handle_call({unshort,Url}, _From, State) -> | |
Reply = case http:request(head,{Url,[]},[{autoredirect, false}],[]) of | |
{ok, {{_Version, 200, _ReasonPhrase}, _Headers, _Body}}-> | |
{ok,Url}; | |
{ok, {{_Version, Code, _ReasonPhrase}, Headers, _Body}}-> | |
case proplists:get_value("location",Headers) of | |
undefined -> | |
{error,"HTTP CODE ERROR : "++Code}; | |
ShortUrl-> | |
{ok,ShortUrl} | |
end; | |
{error,Error}-> | |
{error,Error} | |
end, | |
{reply, Reply, State}. | |
handle_cast(_Msg, State) -> | |
{noreply, State}. | |
handle_info(_Info, State) -> | |
{noreply, State}. | |
terminate(_Reason, _State) -> | |
ok. | |
code_change(_OldVsn, State, _Extra) -> | |
{ok, State}. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment