changeset 1139:8126370ea8c0

webserver - add FileHandler
author Franklin Schmidt <fschmidt@gmail.com>
date Mon, 29 Jan 2018 21:31:24 -0700
parents 4189027691b7
children bf03d687eaff
files src/luan/webserver/examples/Example.java src/luan/webserver/handlers/FileHandler.java
diffstat 2 files changed, 44 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/src/luan/webserver/examples/Example.java	Mon Jan 29 19:48:21 2018 -0700
+++ b/src/luan/webserver/examples/Example.java	Mon Jan 29 21:31:24 2018 -0700
@@ -14,6 +14,8 @@
 import luan.webserver.handlers.MapHandler;
 import luan.webserver.handlers.SafeHandler;
 import luan.webserver.handlers.LogHandler;
+import luan.webserver.handlers.FileHandler;
+import luan.webserver.handlers.ListHandler;
 
 
 public class Example implements Handler {
@@ -41,6 +43,7 @@
 		Map<String,Handler> map = new HashMap<String,Handler>();
 		map.put("/hello",handler);
 		handler = new MapHandler(map);
+		handler = new ListHandler( handler, new FileHandler() );
 		handler = new SafeHandler(handler);
 		handler = new LogHandler(handler);
 		new Server(8080,handler).start();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/luan/webserver/handlers/FileHandler.java	Mon Jan 29 21:31:24 2018 -0700
@@ -0,0 +1,41 @@
+package luan.webserver.handlers;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import luan.webserver.Handler;
+import luan.webserver.Request;
+import luan.webserver.Response;
+
+
+public final class FileHandler implements Handler {
+	private final File dir;
+
+	public FileHandler() {
+		this(".");
+	}
+
+	public FileHandler(String pathname) {
+		this(new File(pathname));
+	}
+
+	public FileHandler(File dir) {
+		if( !dir.isDirectory() )
+			throw new RuntimeException("must be a directory");
+		this.dir = dir;
+	}
+
+	public Response handle(Request request) {
+		File file = new File(dir,request.path);
+		if( file.isFile() ) {
+			Response response = new Response();
+			try {
+				response.body = new Response.Body( file.length(), new FileInputStream(file) );
+			} catch(FileNotFoundException e) {
+				throw new RuntimeException(e);
+			}
+			return response;
+		}
+		return null;
+	}
+}