view src/luan/modules/http/LuanDomainHandler.java @ 1839:908a43d14206

add Http.link_to_domain
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 30 Jan 2025 18:14:15 -0700
parents 09e90d94b7b5
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);
		LuanHandler handler = new LuanHandler(luan,domain);
		String luanDomain = handler.getDomain();
		if( !luanDomain.equals(domain) )
			return domainHandler.getHandler(luanDomain);
		return handler;
	}

	protected Luan newLuan(final String domain) {
		try {
			Luan luan = new Luan();
			init.call(luan,domain);
			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);
	}
}