Skip to content

Instantly share code, notes, and snippets.

@rightfold
Created August 15, 2013 21:22
Show Gist options
  • Save rightfold/6245031 to your computer and use it in GitHub Desktop.
Save rightfold/6245031 to your computer and use it in GitHub Desktop.
defmodule Session do
def get key, req do
case :cowboy_req.cookie "session_id", req do
{ :undefined, req } -> { nil, req }
{ session_id, req } ->
case :gen_server.call SessionStore, { :get, session_id, key } do
{ :ok, value } -> { value, req }
nil -> { nil, req }
end
end
end
def set key, value, req do
{ session_id, req } =
case :cowboy_req.cookie "session_id", req do
{ :undefined, req } ->
session_id = :uuid.to_string :uuid.v4
req = :cowboy_req.set_resp_cookie "session_id", session_id, [], req
{ session_id, req }
{ session_id, req } -> { session_id, req }
end
:gen_server.cast SessionStore, { :set, session_id, key, value }
req
end
end
defmodule SessionStore do
use GenServer.Behaviour
def start_link do
:gen_server.start_link { :local, __MODULE__ }, __MODULE__, [], []
end
def init _args do
tid = :ets.new :sessions, [:set]
{ :ok, tid }
end
def handle_call { :get, session, key }, _from, tid do
result =
case :ets.lookup tid, { session, key } do
[] -> nil
[ { _, value } ] -> { :ok, value }
end
{ :reply, result, tid }
end
def handle_cast { :set, session, key, value }, tid do
:ets.insert tid, { { session, key }, value }
{ :noreply, tid }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment