-
Notifications
You must be signed in to change notification settings - Fork 4
/
simpleserver.fpl
91 lines (76 loc) · 2.66 KB
/
simpleserver.fpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import socket
class App{
func __init__(self, name){
self.name=name
self.pages=[]
}
func page(self, route, methods=[]){
return lambda x{return Page(x, route, methods, self)}
}
func __str__(self){
return f"<App {self.name}>"
}
func extract_data(self, method: str, request: str, args: list){
for page in self.pages{
if request==page.route and (method in page.methods or len(page.methods)==0){
return ("200 OK", page(**args))
}
}
return ("404 NOT FOUND", "")
}
func start(self, port=8000, verbose=True){
if verbose{
print(f"Starting server at {socket.gethostbyname(socket.gethostname())}:{port}")
}
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock{
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((socket.gethostbyname(socket.gethostname()), port))
sock.listen(socket.SOMAXCONN)
while True{
client, info=sock.accept()
response=repr(client.recv(1024))
try{
raw=response.split("\n")[0]
if verbose{
print(raw)
}
method=raw.split(" ")[0]
request="".join(raw.split(" ")[1])
args={}
if "?" in request{
args_="".join(request.split("?")[1:]).split("&")
for itm in args_{
if "=" in itm{
args[itm[0:itm.find("=")-1]]=itm[itm.find("=")+1:]
}
}
request=request[0:request.find("?")-1]
}
type, data=self.extract_data(method,request,args)
client.sendall(f"HTTP/1.0 {type}\r\n\r\n")
client.sendall(data)
}
except Exception e{
print(e)
}
client.close()
}
}
print("Closing server")
}
}
class Page{
func __init__(self, funct, route, methods, app){
self.route=route
self.methods=methods
self.funct=funct
self.app=app
self.app.pages.append(self)
}
func __call__(self, **args){
return self.__dict__["funct"](**args)
}
func __str__(self){
return f"<Page '{self.route}' {self.__dict__['funct']}>"
}
}