Commits

Anonymous committed fea416e

preliminary xhr erlang-side implementation

Comments (0)

Files changed (1)

+-module(xhr).
+-record(xhr, {
+		  ready_state = 0,
+		  status = 0,
+		  method = get,
+		  url,
+		  headers = [],
+		  body,
+		  http_options = [],
+		  options = [{sync, false}, 
+					 {stream, self}],
+		  request_id
+		 }).
+-define(is_xhr(X), is_record(X, xhr)).
+-export([new/0,
+		 open/3,
+		 send/1]).
+
+
+new() ->
+	#xhr{}.
+
+
+open(XHR, Method, URL) when (?is_xhr(XHR) andalso
+							 is_list(Method) andalso
+							 is_list(URL)) ->
+	{ok, XHR#xhr{method=method_string_to_atom(Method),
+				 url=URL}}.
+
+
+send(XHR=#xhr{ready_state=0, method=Method, http_options=HTTPOptions, options=Options}) ->
+	case http:request(Method, request(XHR), HTTPOptions, Options) of
+		{ok, RequestId} ->
+			{ok, XHR#xhr{ready_state=1, request_id=RequestId}};
+		{error, Reason} ->
+			{error, Reason}
+	end.
+
+
+request(#xhr{method=M, url=URL, headers=Headers}) when ((M == get) orelse
+														(M == options) orelse
+														(M == trace)) ->
+	{URL, Headers};
+request(#xhr{url=URL, headers=Headers, body=Body}) ->
+	{URL, Headers, content_type(Headers), Body}.
+
+
+content_type(Headers) ->
+	proplists:get_value(Headers, "content-type", "text/plain").
+
+
+method_string_to_atom(Method) ->
+	method_ustring_to_atom(string:to_upper(Method)).
+
+method_ustring_to_atom("GET") ->
+	get;
+method_ustring_to_atom("PUT") ->
+	put;
+method_ustring_to_atom("POST") ->
+	post;
+method_ustring_to_atom("DELETE") ->
+	delete;
+method_ustring_to_atom("TRACE") ->
+	trace;
+method_ustring_to_atom("OPTIONS") ->
+	options.