Skip to content

Instantly share code, notes, and snippets.

@invokesus
Created August 5, 2021 16:37
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 invokesus/22cb519ac54842676995d99b43d01225 to your computer and use it in GitHub Desktop.
Save invokesus/22cb519ac54842676995d99b43d01225 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
from dataclasses import dataclass
from http.server import HTTPServer, BaseHTTPRequestHandler
H = {}
@dataclass
class Path:
method: str = None
key: str = None
value: str = None
class S(BaseHTTPRequestHandler):
def parsePath(self, path):
path = path.strip("/")
parsedPath = Path()
if path.startswith("get?key="):
parsedPath.method = "get"
path = path.removeprefix("get?key=")
value = H.get(path, "null")
parsedPath.key = path
parsedPath.value = value
return parsedPath
elif path.startswith("set?"):
parsedPath.method = "set"
path = path.removeprefix("set?")
key, value = path.split("=",1)
H[key] = value
parsedPath.key = key
parsedPath.value = value
return parsedPath
else:
return None
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
parsedPath = self.parsePath(self.path)
if parsedPath.method == "get":
self.wfile.write((parsedPath.value+"\n").encode("utf8"))
return
if __name__ == "__main__":
addr = "localhost"
port = 4000
httpd = HTTPServer((addr, port), S)
httpd.serve_forever()
#!/usr/bin/env bash
#ncat -e ./server.sh -kl 4000
#set -x
mkdir -p /tmp/cache
IFS=$' \t\n\r'
declare -A H
read -r request path _
if [ "$request" != "GET" ]; then
printf 'HTTP/1.1 404 Not Found\r\n\r\n'
exit
fi
IFS='/?='
read -r _ method key value < <(printf '%s\n' "$path")
unset IFS
printf 'HTTP/1.1 200 OK\r\n\r\n'
case $method in
"get")
#echo ${H["$value"]:-"null"}
cat /tmp/cache/$value 2>/dev/null || echo null
;;
"set")
#H[$key]="$value"
echo $value >/tmp/cache/$key
;;
esac
#echo $method, $key, $value
exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment