Advertisement
Guest User

Untitled

a guest
Dec 11th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 1.17 KB | None | 0 0
  1. -module(hello_handler).
  2. -behaviour(cowboy_http_handler).
  3.  
  4. -export([init/3]).
  5. -export([handle/2]).
  6. -export([terminate/3]).
  7.  
  8. -record(state, {
  9. }).
  10.  
  11. init(_, Req, _Opts) ->
  12.     {ok, Req, #state{}}.
  13.  
  14. handle(Req, State=#state{}) ->
  15.     {QueryBin, Req1} = cowboy_req:qs(Req),
  16.     QueryStr = binary_to_list(QueryBin),
  17.     QueryTokens = string:tokens(QueryStr, "%20"),
  18.     ReplyStr = string:split(QueryTokens, "&", all),
  19.     Op = lists:nth(1, ReplyStr),
  20.  
  21.     Result = case Op of
  22.         "sum" -> integer_to_binary(list_to_integer(lists:nth(2, ReplyStr)) + list_to_integer(lists:nth(3, ReplyStr)));
  23.         "sub" -> integer_to_binary(list_to_integer(lists:nth(2, ReplyStr)) - list_to_integer(lists:nth(3, ReplyStr)));
  24.         "mul" -> integer_to_binary(list_to_integer(lists:nth(2, ReplyStr)) * list_to_integer(lists:nth(3, ReplyStr)));
  25.         "div" -> float_to_binary(list_to_integer(lists:nth(2, ReplyStr)) / list_to_integer(lists:nth(3, ReplyStr)))
  26.     end,
  27.  
  28.     io:fwrite("~p~n",[Result]),
  29.  
  30.     {ok, Req2} = cowboy_req:reply(200,
  31.         [{<<"content-type">>, <<"text/plain">>}],
  32.         [Result],
  33.         Req1),
  34.     {ok, Req2, State}.
  35.  
  36. terminate(_Reason, _Req, _State) ->
  37.     ok.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement