Skip to content

Instantly share code, notes, and snippets.

@derdesign
Created November 6, 2012 00:52
Show Gist options
  • Save derdesign/4021678 to your computer and use it in GitHub Desktop.
Save derdesign/4021678 to your computer and use it in GitHub Desktop.
OTP gen_server Implementation
-module(test_server).
-behaviour(gen_server).
% Callback exports
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
% API exports
-export([start_link/0]).
% Server state
-record(state, {count = 0}).
% API functions
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
update_request_count(#state{count = Count} = State) ->
State#state{count = Count + 1}.
% Callback functions
init([]) ->
{ok, #state{count=0}}.
handle_call(greeting, _From, State) ->
Reply = "Hello World!",
{reply, Reply, update_request_count(State)};
handle_call(get_count, _From, #state{count = Count} = State) ->
Reply = Count,
{reply, Reply, update_request_count(State)};
handle_call(_Request, _From, State) ->
{reply, ok, update_request_count(State)}.
handle_cast(_Request, 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