comparison src/goodjava/webserver/handlers/ContentTypeHandler.java @ 1402:27efb1fcbcb5

move luan.lib to goodjava
author Franklin Schmidt <fschmidt@gmail.com>
date Tue, 17 Sep 2019 01:35:01 -0400
parents src/luan/lib/webserver/handlers/ContentTypeHandler.java@ba4fc39423a4
children 2c06a7ff4173
comparison
equal deleted inserted replaced
1401:ef1620aa99cb 1402:27efb1fcbcb5
1 package goodjava.webserver.handlers;
2
3 import java.util.Map;
4 import java.util.HashMap;
5 import goodjava.webserver.Handler;
6 import goodjava.webserver.Request;
7 import goodjava.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 map.put( "mp4", "video/mp4" );
34 // add more as need
35 }
36
37 public Response handle(Request request) {
38 Response response = handler.handle(request);
39 if( response!=null && !response.headers.containsKey("content-type") ) {
40 String path = request.path;
41 int iSlash = path.lastIndexOf('/');
42 int iDot = path.lastIndexOf('.');
43 String type;
44 if( iDot < iSlash ) { // no extension
45 type = contentTypeForNoExtension;
46 } else { // extension
47 String extension = path.substring(iDot+1);
48 type = map.get( extension.toLowerCase() );
49 }
50 if( type != null )
51 response.headers.put("content-type",type);
52 }
53 return response;
54 }
55 }