view src/luan/modules/http/HttpServicer.java @ 1333:25746915a241

merge Luan and LuanState
author Franklin Schmidt <fschmidt@gmail.com>
date Tue, 12 Feb 2019 22:33:40 -0700
parents 503bde9a7c80
children
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.Luan;
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(Luan 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(Luan luan,Request request,LuanException e)
		throws LuanException
	{
//e.printStackTrace();
		synchronized(luan) {
			LuanCloner cloner = new LuanCloner(LuanCloner.Type.INCREMENTAL);
			luan = (Luan)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(Luan 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 = (Luan)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
}