diff src/luan/lib/webserver/handlers/ContentTypeHandler.java @ 1347:643cf1c37723

move webserver to lib and bug fixes
author Franklin Schmidt <fschmidt@gmail.com>
date Mon, 25 Feb 2019 13:02:33 -0700
parents src/luan/webserver/handlers/ContentTypeHandler.java@7e7c2d0c3b99
children ba4fc39423a4
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/luan/lib/webserver/handlers/ContentTypeHandler.java	Mon Feb 25 13:02:33 2019 -0700
@@ -0,0 +1,54 @@
+package luan.lib.webserver.handlers;
+
+import java.util.Map;
+import java.util.HashMap;
+import luan.lib.webserver.Handler;
+import luan.lib.webserver.Request;
+import luan.lib.webserver.Response;
+
+
+public class ContentTypeHandler implements Handler {
+	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 attrs = charset== null ? "" : "; charset="+charset;
+		String htmlType = "text/html" + attrs;
+		String textType = "text/plain" + attrs;
+		contentTypeForNoExtension = htmlType;
+		map.put( "html", htmlType );
+		map.put( "txt", textType );
+		map.put( "css", "text/css" );
+		// 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;
+	}
+}