Created
October 4, 2011 00:11
-
-
Save bluegraybox/1260597 to your computer and use it in GitHub Desktop.
A simple REST key-value store using the spooky framework.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.