parsav  http.t at [59e1d7d56a]

File http.t artifact 6d6c40fc94 part of check-in 59e1d7d56a


-- vim: ft=terra
local m = {}
local util = dofile('common.lua')

struct m.header {
	key: rawstring
	value: rawstring
}
struct m.page {
	respcode: uint16
	body: lib.mem.ptr(int8)
	headers: lib.mem.ptr(m.header)
}

local resps = {
	[200] = 'OK';
	[201] = 'Created';
	[301] = 'Moved Permanently';
	[302] = 'Found';
	[303] = 'See Other';
	[307] = 'Temporary Redirect';
	[404] = 'Not Found';
	[401] = 'Unauthorized';
	[403] = 'Forbidden';
	[418] = 'I\'m a teapot';
	[405] = 'Method Not Allowed';
	[500] = 'Internal Server Error';
}
local resptext = symbol(rawstring)
local resplen = symbol(intptr)
local respbranches = {}
for k,v in pairs(resps) do
	local txt = string.format('%u %s\r\n',k,v)
	respbranches[#respbranches + 1] = quote
		case [uint16](k) then resptext = [txt] resplen = [#txt] end
	end
end
m.codestr = terra(code: uint16)
	var [resptext] var [resplen]
	switch code do [respbranches] end
	return resptext, resplen
end
m.page.methods = {
	free = terra(self: &m.page)
		self.body:free()
		self.headers:free()
	end;
	send = terra(self: &m.page, con: &lib.net.mg_connection)
		var code: rawstring
		var [resptext] var [resplen]
		switch self.respcode do [respbranches] end
		lib.net.mg_send(con, "HTTP/1.1 ", 9)
		lib.net.mg_send(con, resptext, resplen)
		for i = 0, self.headers.ct do
			var h = self.headers.ptr[i]
			lib.net.mg_send(con, h.key, lib.str.sz(h.key))
			lib.net.mg_send(con, ": ", 2)
			lib.net.mg_send(con, h.value, lib.str.sz(h.value))
			lib.net.mg_send(con, "\r\n", 2)
		end
		lib.net.mg_printf(con, 'Content-Length: %llu\r\n\r\n', self.body.ct)
		lib.net.mg_send(con,self.body.ptr,self.body.ct)
	end;
}
return m