view http/src/luan/modules/http/Http.luan @ 497:55f9f74f1e55

Http.request is now pure luan
author Franklin Schmidt <fschmidt@gmail.com>
date Sun, 17 May 2015 19:25:47 -0600
parents 598123096772
children ee55be414a34
line wrap: on
line source

local Luan = require "luan:Luan"
local ipairs = Luan.ipairs
local pairs = Luan.pairs
local set_metatable = Luan.set_metatable
local Io = require "luan:Io"
local Html = require "luan:Html"
local url_encode = Html.url_encode


local singular_metatable = {}

function singular_metatable.__index(table,key)
	local list = table.__plural[key]
	return list and list[1]
end

function singular_metatable.__new_index(table,key,value)
	table.__plural[key] = {value}
end

function singular_metatable.__pairs(table)
	local iter = pairs(table.__plural)
	return function()
		local key, value = iter()
		return key, value and value[1]
	end
end


local function new_common(this)
	this = this or {}
	this.headers = {}
	this.header = {__plural=this.headers}
	set_metatable(this.header,singular_metatable)
	return this
end


function new_request(this)
	this = new_common(this)
	this.method = "GET"  -- default
	-- this.path
	-- this.protocol
	this.scheme = "http"  -- default
	this.parameters = {}
	this.parameter = {__plural=this.parameters}
	set_metatable(this.parameter,singular_metatable)
	this.cookie = {}

	function this.url()
		local string_uri = Io.uri "string:"
		local out = string_uri.text_writer()

		out.write( this.scheme, "://", this.header.host, this.path )
		if this.method ~= "POST" then
			local and_char = "?"
			for name, values in pairs(this.parameters) do
				for _, value in ipairs(values) do
					out.write( and_char, url_encode(name), "=", url_encode(value) )
					and_char = "&"
				end
			end
		end

		out.close()
		return string_uri.read_text()
	end

	return this
end

-- request = new_request{}  -- filled in by HttpServicer



function init_for_test()

	test = test or {}

	test.welcome_file = "index.html"

	function get_page(path)
		if test.welcome_file ~= nil and path.matches ".*/" then
			path = path .. test.welcome_file
		end
		local old_out = Io.stdout
		local mod = require("site:"..path)
		mod.respond()
		text_writer.close()
		Io.stdout = old_out
		return result.read_text()
	end

	test.cookies = test.cookies or {}

	request = new_request{}
	request.cookies = test.cookies

	response = {

		text_writer = function()
			result = Io.uri "string:"
			text_writer = result.text_writer()
			return text_writer
		end;

		set_cookie = function(name,value)
			test.cookies[name] = value
		end;

		remove_cookie = function(name)
			test.cookies[name] = nil
		end;

		send_redirect = function(url)
			response.redirect = url
		end;

		headers = {};

	}

end