1137
|
1 package luan.webserver.handlers;
|
|
2
|
|
3 import java.util.Map;
|
|
4 import java.util.HashMap;
|
|
5 import luan.webserver.Handler;
|
|
6 import luan.webserver.Request;
|
|
7 import luan.webserver.Response;
|
|
8
|
|
9
|
|
10 public class ContentTypeHandler implements Handler {
|
|
11 public final static String CONTENT_TYPE = "Content-Type";
|
|
12
|
|
13 private final Handler handler;
|
|
14
|
|
15 // maps extension to content-type
|
|
16 // key must be lower case
|
|
17 public final Map<String,String> map = new HashMap<String,String>();
|
|
18
|
|
19 // set to null for none
|
|
20 public String contentTypeForNoExtension;
|
|
21
|
|
22 public ContentTypeHandler(Handler handler) {
|
|
23 this(handler,"UTF-8");
|
|
24 }
|
|
25
|
|
26 public ContentTypeHandler(Handler handler,String charset) {
|
|
27 this.handler = handler;
|
|
28 String htmlType = "text/html; charset=" + charset;
|
|
29 String textType = "text/plain; charset=" + charset;
|
|
30 contentTypeForNoExtension = htmlType;
|
|
31 map.put( "html", htmlType );
|
|
32 map.put( "txt", textType );
|
|
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 }
|