Commit 94593fe6 authored by Xavier Thompson's avatar Xavier Thompson

Add httpserver.pyx demo

parent 4d4e9c9b
from stdlib.string cimport Str
from stdlib.format cimport format
from stdlib.socket cimport *
from stdlib.http cimport HTTPRequest
from stdlib.url cimport URI
from libc.stdio cimport puts, printf
def main():
cdef Str recv, body, resp
cdef size_t length
cdef Str CRLFCRLF = Str("\r\n\r\n")
with nogil:
a = getaddrinfo(NULL, Str("3490"), AF_UNSPEC, SOCK_STREAM, 0, AI_PASSIVE)[0]
s = socket(a.family, a.socktype, a.protocol)
s.setsockopt(SO_REUSEADDR, 1)
s.bind(a.sockaddr)
s.listen(5)
printf("listening on http://%s:3490\n", Str.to_c_str(a.sockaddr.to_string()))
loop = True
while loop:
with gil:
try:
with nogil:
s1 = s.accept()
except OSError as e:
print(e)
continue
recv = s1.recvuntil(CRLFCRLF, 1024)
printf('Received:\n==========\n%s\n==========\n\n', Str.to_c_str(recv))
request = HTTPRequest(recv)
if request.ok:
status = Str("HTTP/1.0 200 OK")
content_length_key = Str('Content-Length')
if content_length_key in request.headers:
content_length_value = request.headers[content_length_key]
length = content_length_value.__int__()
body = recv.substr(request._pos)
while body.__len__() < length:
remaining = length - body.__len__()
body = s1.recvinto(consume body, remaining)
printf('Received body:\n==========\n%s\n==========\n\n', Str.to_c_str(body))
resp = format("{}\r\nContent-Length: {}{}{}", status, length, CRLFCRLF, body)
if body == Str("quit"):
loop = False
else:
resp = status + CRLFCRLF
else:
if recv == Str('quit'):
loop = False
status = Str("HTTP/1.0 418 I'M A TEAPOT")
resp = status + CRLFCRLF
printf("Sending:\n==========\n%s\n==========\n\n\n", Str.to_c_str(resp))
s1.sendall(resp)
s1.shutdown(SHUT_WR)
s1.close()
s.close()
main()
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment