Mercurial Hosting > luan
changeset 1140:bf03d687eaff
webserver - add dir handling
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Mon, 29 Jan 2018 22:21:59 -0700 |
parents | 8126370ea8c0 |
children | 14927c34cbb7 |
files | src/luan/webserver/handlers/FileHandler.java |
diffstat | 1 files changed, 42 insertions(+), 9 deletions(-) [+] |
line wrap: on
line diff
--- a/src/luan/webserver/handlers/FileHandler.java Mon Jan 29 21:31:24 2018 -0700 +++ b/src/luan/webserver/handlers/FileHandler.java Mon Jan 29 22:21:59 2018 -0700 @@ -2,13 +2,20 @@ import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; +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 luan.webserver.Handler; import luan.webserver.Request; import luan.webserver.Response; +import luan.webserver.ResponseOutputStream; public final class FileHandler implements Handler { + public boolean showDirs = true; private final File dir; public FileHandler() { @@ -26,16 +33,42 @@ } public Response handle(Request request) { - File file = new File(dir,request.path); - if( file.isFile() ) { - Response response = new Response(); - try { + try { + File file = new File(dir,request.path); + if( file.isFile() ) { + Response response = new Response(); response.body = new Response.Body( file.length(), new FileInputStream(file) ); - } catch(FileNotFoundException e) { - throw new RuntimeException(e); + return response; } - return response; + if( request.path.endsWith("/") && file.isDirectory() && showDirs ) { + DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz"); + Response response = new Response(); + response.headers.put( "Content-Type", "text/html; charset=UTF-8" ); + Writer writer = new OutputStreamWriter( new ResponseOutputStream(response) ); + writer.write( "<!doctype html><html>" ); + writer.write( "<head><style>td{padding: 2px 8px}</style></head>" ); + writer.write( "<body>" ); + writer.write( "<h1>Directory: "+request.path+"</h1>" ); + writer.write( "<table border=0>" ); + for( File child : file.listFiles() ) { + String name = child.getName(); + if( child.isDirectory() ) + name += '/'; + writer.write( "<tr>" ); + writer.write( "<td><a href='"+name+"'>"+name+"</a></td>" ); + writer.write( "<td>"+child.length()+" bytes</td>" ); + writer.write( "<td>"+fmt.format(new Date(child.lastModified()))+"</td>" ); + writer.write( "</tr>" ); + } + writer.write( "</table>" ); + writer.write( "</body>" ); + writer.write( "</html>" ); + writer.close(); + return response; + } + return null; + } catch(IOException e) { + throw new RuntimeException(e); } - return null; } }