David Reiss | 8a162a5 | 2008-06-11 01:03:16 +0000 | [diff] [blame] | 1 | -module(server). |
| 2 | |
| 3 | -include("calculator_thrift.hrl"). |
| 4 | |
| 5 | -export([start/0, start/1, handle_function/2, |
| 6 | stop/1, ping/0, add/2, calculate/2, getStruct/1, zip/0]). |
| 7 | |
| 8 | debug(Format, Data) -> |
| 9 | error_logger:info_msg(Format, Data). |
| 10 | |
| 11 | ping() -> |
| 12 | debug("ping()",[]), |
| 13 | ok. |
| 14 | |
| 15 | add(N1, N2) -> |
| 16 | debug("add(~p,~p)",[N1,N2]), |
| 17 | N1+N2. |
| 18 | |
| 19 | calculate(Logid, Work) -> |
| 20 | { Op, Num1, Num2 } = { Work#work.op, Work#work.num1, Work#work.num2 }, |
| 21 | debug("calculate(~p, {~p,~p,~p})", [Logid, Op, Num1, Num2]), |
| 22 | case Op of |
| 23 | ?tutorial_ADD -> Num1 + Num2; |
| 24 | ?tutorial_SUBTRACT -> Num1 - Num2; |
| 25 | ?tutorial_MULTIPLY -> Num1 * Num2; |
| 26 | |
| 27 | ?tutorial_DIVIDE when Num2 == 0 -> |
| 28 | throw(#invalidOperation{what=Op, why="Cannot divide by 0"}); |
| 29 | ?tutorial_DIVIDE -> |
| 30 | Num1 div Num2; |
| 31 | |
| 32 | _Else -> |
| 33 | throw(#invalidOperation{what=Op, why="Invalid operation"}) |
| 34 | end. |
| 35 | |
| 36 | getStruct(Key) -> |
| 37 | debug("getStruct(~p)", [Key]), |
| 38 | #sharedStruct{key=Key, value="RARG"}. |
| 39 | |
| 40 | zip() -> |
| 41 | debug("zip", []), |
| 42 | ok. |
| 43 | |
| 44 | %% |
| 45 | |
| 46 | start() -> |
| 47 | start(9999). |
| 48 | |
| 49 | start(Port) -> |
| 50 | Handler = ?MODULE, |
| 51 | thrift_socket_server:start([{handler, Handler}, |
| 52 | {service, calculator_thrift}, |
| 53 | {port, Port}, |
| 54 | {name, tutorial_server}]). |
| 55 | |
| 56 | stop(Server) -> |
| 57 | thrift_socket_server:stop(Server). |
| 58 | |
| 59 | handle_function(Function, Args) when is_atom(Function), is_tuple(Args) -> |
| 60 | case apply(?MODULE, Function, tuple_to_list(Args)) of |
| 61 | ok -> ok; |
| 62 | Reply -> {reply, Reply} |
| 63 | end. |