view src/luan/modules/http/HttpServicer.java @ 1283:503bde9a7c80

add luan.require() and table.call()
author Franklin Schmidt <fschmidt@gmail.com>
date Fri, 21 Dec 2018 09:12:09 -0700
parents 9fa8b8389578
children 25746915a241
line wrap: on
line source

package luan.modules.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import luan.webserver.Request;
import luan.webserver.Response;
import luan.LuanState;
import luan.LuanFunction;
import luan.LuanException;
import luan.LuanTable;
import luan.LuanCloner;
import luan.modules.PackageLuan;


public final class HttpServicer {
	private static final Logger logger = LoggerFactory.getLogger(HttpServicer.class);

	public static Response service(LuanState luan,Request request,String modName)
		throws LuanException
	{
		try {
			return serviceLuan(luan,request,modName);
		} catch(LuanException e) {
			return handleError(luan,request,e);
		}
	}

	private static Response handleError(LuanState luan,Request request,LuanException e)
		throws LuanException
	{
//e.printStackTrace();
		synchronized(luan) {
			LuanCloner cloner = new LuanCloner(LuanCloner.Type.INCREMENTAL);
			luan = (LuanState)cloner.clone(luan);
		}
		LuanTable module = (LuanTable)luan.require("luan:http/Http.luan");
		return (Response)module.call( "handle_error", request, e.table(luan) );
	}

	private static Response serviceLuan(LuanState luan,Request request,String modName)
		throws LuanException
	{
		LuanFunction fn;
		synchronized(luan) {
			PackageLuan.enableLoad(luan,"luan:http/Http.luan",modName);
			PackageLuan.require(luan,"luan:http/Http.luan");
			Object mod = PackageLuan.load(luan,modName);
			if( mod.equals(Boolean.FALSE) )
				return null;
			if( !(mod instanceof LuanFunction) )
				throw new LuanException( "module '"+modName+"' must return a function" );
			LuanCloner cloner = new LuanCloner(LuanCloner.Type.INCREMENTAL);
			luan = (LuanState)cloner.clone(luan);
			fn = (LuanFunction)cloner.get(mod);
		}

		LuanTable module = (LuanTable)luan.require("luan:http/Http.luan");
		module.call( "new_request", request );
		module.call( "new_response" );

		fn.call(luan);

		return (Response)module.call( "finish" );
	}

	private HttpServicer() {}  // never
}