1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2013 Jean-Philippe Caissy <jpcaissy@piji.ca>
4 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
10 # http://www.apache.org/licenses/LICENSE-2.0
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
18 # Provides the `FileServer` action, which is a standard and minimal file server
26 # Returns a `String` copy of `self` without any of the prefixed '/'s
30 # assert "/home/".strip_start_slashes == "home/"
31 # assert "////home/".strip_start_slashes == "home/"
32 # assert "../home/".strip_start_slashes == "../home/"
33 fun strip_start_slashes
: String
35 for i
in chars
.length
.times
do if chars
[i
] != '/' then return substring_from
(i
)
40 # A simple file server
44 # Root of `self` file system
47 redef fun answer
(request
, turi
)
51 var local_file
= root
.join_path
(turi
.strip_start_slashes
)
52 local_file
= local_file
.simplify_path
55 if turi
== "/" then local_file
= root
58 if local_file
.has_prefix
(root
) then
60 if local_file
.file_exists
then
61 response
= new HttpResponse(200)
63 if local_file
.file_stat
.is_dir
then
64 # Show index.html instead of the directory listing
65 var index_file
= local_file
.join_path
("index.html")
66 if index_file
.file_exists
then
67 local_file
= index_file
69 index_file
= local_file
.join_path
("index.htm")
70 if index_file
.file_exists
then local_file
= index_file
74 if local_file
.file_stat
.is_dir
then
75 # Show the directory listing
77 var files
= local_file
.files
79 var links
= new Array[String]
80 if local_file
.length
> 1 then
81 # The extra / is a hack
82 var path
= "/" + (turi
+ "/..").simplify_path
83 links
.add
"<a href=\"{path}\
">..</a>"
86 var path
= (turi
+ "/" + file
).simplify_path
87 links
.add
"<a href=\"{path}\
">{file}</a>"
93 <meta charset="utf-8">
94 <meta http-equiv="X-UA-Compatible" content="IE=edge">
95 <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
96 <title>{{{title}}}</title>
99 <div class="container">
102 <li>{{{links.join("</li>\n\t\t\t<li>")}}}</li>
108 response
.header
["Content-Type"] = media_types
["html"].as(not null)
111 var file
= new IFStream.open
(local_file
)
112 response
.body
= file
.read_all
114 var ext
= local_file
.file_extension
116 var media_type
= media_types
[ext
]
117 if media_type
!= null then response
.header
["Content-Type"] = media_type
123 else response
= new HttpResponse(404)
124 else response
= new HttpResponse(403)