Created
December 5, 2010 21:52
-
-
Save asim/729510 to your computer and use it in GitHub Desktop.
key value store, the humble beginnings
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
local config = { host="localhost", port=6379 } | |
local socket = require("socket") | |
local server = assert(socket.bind(config.host, config.port)) | |
local ip, port = server:getsockname() | |
print(string.format("listening on %s:%s", ip, port)) | |
local store = {} | |
local function add(key, value) | |
store[key] = value | |
return "OK" | |
end | |
local function get(key) | |
local value = store[key] | |
if value then | |
return value | |
else | |
return "NULL" | |
end | |
end | |
local function del(key) | |
local value = store[key] | |
store[key] = nil | |
if value then | |
return value | |
else | |
return "NULL" | |
end | |
end | |
local function processEvent(request) | |
local command,data = string.match(request, "(%a%a%a) (.+)") | |
if command == "GET" then | |
local key = string.match(data, "/([^/]+)") | |
if key then | |
r = get(key) | |
print(string.format("key: %s returned value: %s", key, r)) | |
end | |
elseif command == "PUT" then | |
local key,value = string.match(data, "/([^/]+)/(.+)") | |
if key and value then | |
r = add(key, value) | |
print(string.format("key: %s insert value: %s", key, value)) | |
end | |
end | |
if not r then | |
print("invalid request") | |
return "NULL" | |
else | |
return r | |
end | |
end | |
local function main() | |
while true do | |
local client = server:accept() | |
client:settimeout(10) | |
local request, err = client:receive() | |
if not err then | |
local response = processEvent(request) | |
client:send(response .. "\n") | |
end | |
client:close() | |
end | |
end | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment