view src/luan/webserver/examples/Example.java @ 1137:c123ee15f99b

add webserver
author Franklin Schmidt <fschmidt@gmail.com>
date Mon, 29 Jan 2018 18:49:59 -0700
parents
children 4189027691b7
line wrap: on
line source

package luan.webserver.examples;

import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import org.apache.log4j.BasicConfigurator;
import luan.webserver.Handler;
import luan.webserver.Request;
import luan.webserver.Response;
import luan.webserver.ResponseOutputStream;
import luan.webserver.Server;
import luan.webserver.handlers.MapHandler;
import luan.webserver.handlers.SafeHandler;


public class Example implements Handler {

	public Response handle(Request request) {
		Response response = new Response();
		response.headers.put( "Content-Type", "text/plain; charset=UTF-8" );
		try {
			Writer writer = new OutputStreamWriter( new ResponseOutputStream(response) );
			writer.write("Hello World\n");
			writer.close();
		} catch(IOException e) {
			throw new RuntimeException("shouldn't happen",e);
		}
		return response;
	}

	public static void simple() throws IOException {
		Handler handler = new Example();
		new Server(8080,handler).start();
	}

	public static void fancy() throws IOException {
		Handler handler = new Example();
		Map<String,Handler> map = new HashMap<String,Handler>();
		map.put("/hello",handler);
		handler = new MapHandler(map);
		handler = new SafeHandler(handler);
		new Server(8080,handler).start();
	}

	public static void main(String[] args) throws Exception {
		BasicConfigurator.configure();
		fancy();
	}
}