Mercurial Hosting > luan
diff src/goodjava/webserver/handlers/FileHandler.java @ 1402:27efb1fcbcb5
move luan.lib to goodjava
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Tue, 17 Sep 2019 01:35:01 -0400 |
parents | src/luan/lib/webserver/handlers/FileHandler.java@643cf1c37723 |
children | 8a7519dee55c |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/goodjava/webserver/handlers/FileHandler.java Tue Sep 17 01:35:01 2019 -0400 @@ -0,0 +1,51 @@ +package goodjava.webserver.handlers; + +import java.io.File; +import java.io.FileInputStream; +import java.io.Writer; +import java.io.OutputStreamWriter; +import java.io.IOException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import goodjava.webserver.Handler; +import goodjava.webserver.Request; +import goodjava.webserver.Response; +import goodjava.webserver.ResponseOutputStream; + + +public class FileHandler implements Handler { + 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; + } + + File file(Request request) { + return new File(dir,request.path); + } + + public Response handle(Request request) { + try { + File file = file(request); + if( file.isFile() ) { + Response response = new Response(); + response.body = new Response.Body( file.length(), new FileInputStream(file) ); + return response; + } + return null; + } catch(IOException e) { + throw new RuntimeException(e); + } + } +}