view src/goodjava/webserver/handlers/ContentTypeHandler.java @ 1611:f67f972bd648

make postgres.luan optional
author Franklin Schmidt <fschmidt@gmail.com>
date Sat, 15 May 2021 17:24:07 -0600
parents fa066aaa068c
children fe611f6e3c28
line wrap: on
line source

package goodjava.webserver.handlers;

import java.util.Map;
import java.util.HashMap;
import goodjava.logging.Logger;
import goodjava.logging.LoggerFactory;
import goodjava.webserver.Handler;
import goodjava.webserver.Request;
import goodjava.webserver.Response;


public class ContentTypeHandler implements Handler {
	private static final Logger logger = LoggerFactory.getLogger(ContentTypeHandler.class);

	// maps extension to content-type
	// key must be lower case
	public static final Map<String,String> map = new HashMap<String,String>();
	static {
		String textType = "text/plain; charset=utf-8";
		map.put( "txt", textType );
		map.put( "luan", textType );
		map.put( "luano", textType );
		map.put( "log", textType );
		map.put( "html", "text/html; charset=utf-8" );
		map.put( "css", "text/css; charset=utf-8" );
		map.put( "js", "application/javascript; charset=utf-8" );
		map.put( "json", "application/json; charset=utf-8" );
		map.put( "mp4", "video/mp4" );
		map.put( "jpg", "image/jpeg" );
		map.put( "jpeg", "image/jpeg" );
		map.put( "png", "image/png" );
		// add more as need
	}

	public static String getExtension(String path) {
		int iSlash = path.lastIndexOf('/');
		int iDot = path.lastIndexOf('.');
		return iDot > iSlash ? path.substring(iDot+1).toLowerCase() : null;
	}

	private final Handler handler;

	public ContentTypeHandler(Handler handler) {
		this.handler = handler;
	}

	public Response handle(Request request) {
		Response response = handler.handle(request);
		if( response!=null && response.status.code==200 && !response.headers.containsKey("Content-Type") ) {
			String extension = getExtension(request.path);
			if( extension != null ) {
				String type = map.get(extension);
				if( type != null )
					response.headers.put("Content-Type",type);
				else
					logger.info("no type defined for extension: "+extension);
			}
		}
		return response;
	}
}