comparison 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
comparison
equal deleted inserted replaced
1346:efd1c6380f2c 1347:643cf1c37723
1 package luan.lib.webserver.handlers;
2
3 import java.util.Map;
4 import java.util.HashMap;
5 import luan.lib.webserver.Handler;
6 import luan.lib.webserver.Request;
7 import luan.lib.webserver.Response;
8
9
10 public class ContentTypeHandler implements Handler {
11 private final Handler handler;
12
13 // maps extension to content-type
14 // key must be lower case
15 public final Map<String,String> map = new HashMap<String,String>();
16
17 // set to null for none
18 public String contentTypeForNoExtension;
19
20 public ContentTypeHandler(Handler handler) {
21 this(handler,"utf-8");
22 }
23
24 public ContentTypeHandler(Handler handler,String charset) {
25 this.handler = handler;
26 String attrs = charset== null ? "" : "; charset="+charset;
27 String htmlType = "text/html" + attrs;
28 String textType = "text/plain" + attrs;
29 contentTypeForNoExtension = htmlType;
30 map.put( "html", htmlType );
31 map.put( "txt", textType );
32 map.put( "css", "text/css" );
33 // add more as need
34 }
35
36 public Response handle(Request request) {
37 Response response = handler.handle(request);
38 if( response!=null && !response.headers.containsKey("content-type") ) {
39 String path = request.path;
40 int iSlash = path.lastIndexOf('/');
41 int iDot = path.lastIndexOf('.');
42 String type;
43 if( iDot < iSlash ) { // no extension
44 type = contentTypeForNoExtension;
45 } else { // extension
46 String extension = path.substring(iDot+1);
47 type = map.get( extension.toLowerCase() );
48 }
49 if( type != null )
50 response.headers.put("content-type",type);
51 }
52 return response;
53 }
54 }