Skip to content

Instantly share code, notes, and snippets.

@bluegraybox
Created October 4, 2011 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluegraybox/1260597 to your computer and use it in GitHub Desktop.
Save bluegraybox/1260597 to your computer and use it in GitHub Desktop.
A simple REST key-value store using the spooky framework.
-module(hello_world).
-behaviour(spooky).
-export([init/1, get/2, loop/1]).
init([])->
%% register a process that holds our dict in memory
case whereis(store) of
undefined ->
Pid = spawn(?MODULE, loop, [dict:new()]),
register(store, Pid),
io:format("store Pid=[~p]~n", [Pid]);
Pid ->
io:format("store already registered with Pid=[~p]~n", [Pid])
end,
[{port, 8000}].
get(Req, [])->
Req:ok("/key to get value for key\n/key/value to set value");
get(Req, [Key, NewValue])->
store ! {self(), Key, NewValue},
receive Value ->
Req:ok(io_lib:format("SET ~p=~p", [Key, Value]))
end;
get(Req, [Key])->
store ! {self(), Key},
receive Value ->
Req:ok(io_lib:format("GET ~p=~p", [Key, Value]))
end.
loop(Dict) ->
receive
{Pid, Key, Value} ->
NewDict = dict:store(Key, Value, Dict),
Pid ! Value,
loop(NewDict);
{Pid, Key} ->
case dict:find(Key, Dict) of
{ok, Value} -> Pid ! Value;
error -> Pid ! []
end,
loop(Dict)
end.
@bluegraybox
Copy link
Author

Actually, you might be able to get away with just using the process dictionary, and skip all that 'store' process nonsense. You could also use Spooky's session dictionary. But I hope this is still a useful sketch for how to handle some more complex shared resource.

@bluegraybox
Copy link
Author

This has since spawned an unholy child with the bowling game example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment