Last active
October 23, 2019 23:11
-
-
Save iambenkay/3d63f83e2b329c5367920869ff0a910b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import ( | |
os | |
net | |
net.urllib | |
) | |
const ( | |
methods_with_form = ['POST', 'PUT', 'GET', 'DELETE', 'HEAD'] | |
HEADER_SERVER = 'Server: VWeb\r\n' // TODO add to the headers | |
HTTP_404 = 'HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\n\r\n404 Not Found' | |
HTTP_500 = 'HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/plain\r\n\r\n500 Internal Server Error' | |
) | |
struct Request { | |
mut: | |
url string | |
method string | |
headers map[string]string | |
body string | |
} | |
fn (request mut Request) parse_headers(data []string) { | |
for i, raw in data { | |
if i == 0 { | |
continue | |
} | |
header_raw := raw.split(': ') | |
if header_raw.len != 2 { | |
continue | |
} | |
request.headers[header_raw[0]] = header_raw[1] | |
} | |
} | |
pub fn api(port int) { | |
socket := net.listen(port) or { | |
panic(err) | |
} | |
mut req := Request{} | |
for { | |
connection := socket.accept() or { | |
panic(err) | |
} | |
request_body := connection.read_line() | |
if request_body == '' { | |
connection.write(HTTP_500) | |
connection.close() | |
return | |
} | |
payload := request_body.split("\r\n") | |
req.method = payload[0].split(" ")[0] | |
req.url = payload[0].split(" ")[1] | |
req.parse_headers(payload) | |
req.body = payload[payload.len - 1] | |
println("$req.method $req.url -- --") | |
mut data := '' | |
match '$req.method $req.url' { | |
'GET /api/man' => { data = hello(req) } | |
else => { data = HTTP_404 } | |
} | |
connection.write(data) | |
connection.close() | |
} | |
} | |
fn main(){ | |
api(8000) | |
} | |
fn hello(request Request) string { | |
return 'HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nI am a sample' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment