Mercurial Hosting > luan
view src/luan/webserver/handlers/FileHandler.java @ 1139:8126370ea8c0
webserver - add FileHandler
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Mon, 29 Jan 2018 21:31:24 -0700 |
parents | |
children | bf03d687eaff |
line wrap: on
line source
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; } }