Mercurial Hosting > luan
diff src/luan/webserver/handlers/ContentTypeHandler.java @ 1137:c123ee15f99b
add webserver
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Mon, 29 Jan 2018 18:49:59 -0700 |
parents | |
children | 49fb4e83484f |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/luan/webserver/handlers/ContentTypeHandler.java Mon Jan 29 18:49:59 2018 -0700 @@ -0,0 +1,54 @@ +package luan.webserver.handlers; + +import java.util.Map; +import java.util.HashMap; +import luan.webserver.Handler; +import luan.webserver.Request; +import luan.webserver.Response; + + +public class ContentTypeHandler implements Handler { + public final static String CONTENT_TYPE = "Content-Type"; + + private final Handler handler; + + // maps extension to content-type + // key must be lower case + public final Map<String,String> map = new HashMap<String,String>(); + + // set to null for none + public String contentTypeForNoExtension; + + public ContentTypeHandler(Handler handler) { + this(handler,"UTF-8"); + } + + public ContentTypeHandler(Handler handler,String charset) { + this.handler = handler; + String htmlType = "text/html; charset=" + charset; + String textType = "text/plain; charset=" + charset; + contentTypeForNoExtension = htmlType; + map.put( "html", htmlType ); + map.put( "txt", textType ); + // add more as need + } + + public Response handle(Request request) { + Response response = handler.handle(request); + if( response!=null && !response.headers.containsKey(CONTENT_TYPE) ) { + String path = request.path; + int iSlash = path.lastIndexOf('/'); + int iDot = path.lastIndexOf('.'); + String type; + if( iDot < iSlash ) { // no extension + type = contentTypeForNoExtension; + } else { // extension + String extension = path.substring(iDot+1); + type = map.get( extension.toLowerCase() ); + } + if( type != null ) + response.headers.put(CONTENT_TYPE,type); + } + return response; + } +}