view src/luan/modules/http/LuanDomainHandler.java @ 1802:ca98dee04e08 default tip

add Parsers.json_null
author Franklin Schmidt <fschmidt@gmail.com>
date Sun, 21 Apr 2024 21:25:15 -0600
parents 357daf580951
children
line wrap: on
line source

package luan.modules.http;

import goodjava.webserver.Request;
import goodjava.webserver.Response;
import goodjava.webserver.Handler;
import goodjava.webserver.handlers.DomainHandler;
import luan.Luan;
import luan.LuanTable;
import luan.LuanFunction;
import luan.LuanException;
import luan.LuanRuntimeException;
import luan.modules.logging.LuanLogger;


public class LuanDomainHandler implements Handler, DomainHandler.Factory {
	private final DomainHandler domainHandler = new DomainHandler(this);
	private final LuanFunction init;

	public LuanDomainHandler(LuanFunction init) throws LuanException {
		if(init==null) throw new NullPointerException("init required");
		LuanLogger.initThreadLogging();
		this.init = init;
	}

	@Override public Handler newHandler(String domain) {
		Luan luan = newLuan(domain);
		return luan==null ? null : new LuanHandler(luan,domain);
	}

	protected Luan newLuan(final String domain) {
		try {
			Luan luan = new Luan();
			Object rtn = init.call(luan,domain);
			if( !(rtn instanceof Boolean) )
				throw new LuanException("init must return boolean");
			if( !(Boolean)rtn )
				return null;
			LuanFunction reset_luan = new LuanFunction() {
				@Override public Object call(Luan luan,Object[] args) {
					domainHandler.removeHandler(domain);
					return LuanFunction.NOTHING;
				}
			};
			LuanTable Http = (LuanTable)luan.require("luan:http/Http.luan");
			Http.put( luan, "domain", domain );
			Http.put( luan, "reset_luan", reset_luan );
			return luan;
		} catch(LuanException e) {
			throw new LuanRuntimeException(e);
		}
	}

	@Override public Response handle(Request request) {
		return domainHandler.handle(request);
	}
}