Mercurial Hosting > luan
annotate src/luan/webserver/handlers/ContentTypeHandler.java @ 1234:7e7c2d0c3b99
minor
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Thu, 12 Apr 2018 18:25:18 -0600 |
parents | 668f29bc52ea |
children |
rev | line source |
---|---|
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 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) { | |
1165
668f29bc52ea
clean up content-type
Franklin Schmidt <fschmidt@gmail.com>
parents:
1148
diff
changeset
|
21 this(handler,"utf-8"); |
1137 | 22 } |
23 | |
24 public ContentTypeHandler(Handler handler,String charset) { | |
25 this.handler = handler; | |
1165
668f29bc52ea
clean up content-type
Franklin Schmidt <fschmidt@gmail.com>
parents:
1148
diff
changeset
|
26 String attrs = charset== null ? "" : "; charset="+charset; |
668f29bc52ea
clean up content-type
Franklin Schmidt <fschmidt@gmail.com>
parents:
1148
diff
changeset
|
27 String htmlType = "text/html" + attrs; |
668f29bc52ea
clean up content-type
Franklin Schmidt <fschmidt@gmail.com>
parents:
1148
diff
changeset
|
28 String textType = "text/plain" + attrs; |
1137 | 29 contentTypeForNoExtension = htmlType; |
30 map.put( "html", htmlType ); | |
31 map.put( "txt", textType ); | |
1234 | 32 map.put( "css", "text/css" ); |
1137 | 33 // add more as need |
34 } | |
35 | |
36 public Response handle(Request request) { | |
37 Response response = handler.handle(request); | |
1165
668f29bc52ea
clean up content-type
Franklin Schmidt <fschmidt@gmail.com>
parents:
1148
diff
changeset
|
38 if( response!=null && !response.headers.containsKey("content-type") ) { |
1137 | 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 ) | |
1165
668f29bc52ea
clean up content-type
Franklin Schmidt <fschmidt@gmail.com>
parents:
1148
diff
changeset
|
50 response.headers.put("content-type",type); |
1137 | 51 } |
52 return response; | |
53 } | |
54 } |