Mercurial Hosting > luan
view src/luan/webserver/handlers/FileHandler.java @ 1148:49fb4e83484f
webserver - change headers to lower case
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Sun, 04 Feb 2018 17:11:06 -0700 |
parents | bf03d687eaff |
children | 668f29bc52ea |
line wrap: on
line source
package luan.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 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() { 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) { 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) ); 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); } } }