Mercurial Hosting > luan
changeset 1604:8a7519dee55c
FileHandler handles if-modified-since
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Fri, 16 Apr 2021 19:19:39 -0600 |
parents | bd125ee375d2 |
children | ef9d96aeb541 |
files | src/goodjava/webserver/Status.java src/goodjava/webserver/handlers/FileHandler.java |
diffstat | 2 files changed, 21 insertions(+), 3 deletions(-) [+] |
line wrap: on
line diff
--- a/src/goodjava/webserver/Status.java Sun Apr 11 14:45:03 2021 -0600 +++ b/src/goodjava/webserver/Status.java Fri Apr 16 19:19:39 2021 -0600 @@ -37,6 +37,7 @@ public static final Status OK = newStatus(200,"OK"); public static final Status MOVED_PERMANENTLY = newStatus(301,"Moved Permanently"); public static final Status FOUND = newStatus(302,"Found"); + public static final Status NOT_MODIFIED = newStatus(304,"Not Modified"); public static final Status BAD_REQUEST = newStatus(400,"Bad Request"); public static final Status NOT_FOUND = newStatus(404,"Not Found"); public static final Status INTERNAL_SERVER_ERROR = newStatus(500,"Internal Server Error");
--- a/src/goodjava/webserver/handlers/FileHandler.java Sun Apr 11 14:45:03 2021 -0600 +++ b/src/goodjava/webserver/handlers/FileHandler.java Fri Apr 16 19:19:39 2021 -0600 @@ -2,16 +2,16 @@ 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.text.ParseException; import java.util.Date; +import java.util.TimeZone; import goodjava.webserver.Handler; import goodjava.webserver.Request; import goodjava.webserver.Response; -import goodjava.webserver.ResponseOutputStream; +import goodjava.webserver.Status; public class FileHandler implements Handler { @@ -40,6 +40,23 @@ File file = file(request); if( file.isFile() ) { Response response = new Response(); + + DateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); + fmt.setTimeZone(TimeZone.getTimeZone("GMT")); + String lastModified = fmt.format(new Date(file.lastModified())); + String ifMod = (String)request.headers.get("if-modified-since"); + if( ifMod != null ) { + try { + Date ifModDate = fmt.parse(ifMod); + if( ifModDate != null && ifModDate.getTime() >= fmt.parse(lastModified).getTime() ) { + response.status = Status.NOT_MODIFIED; + return response; + } + + } catch(ParseException e) {} + } + response.headers.put("last-modified",lastModified); + response.body = new Response.Body( file.length(), new FileInputStream(file) ); return response; }