examples: annotate examples
[nit.git] / lib / nitcorn / examples / src / simple_file_server.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Basic file server on port 80 by default, may require `root` to execute
18 #
19 # To be safe, it is recommended to run this program with its own username:
20 # `sudo file_server -u nitcorn:www`
21 module simple_file_server is example
22
23 import nitcorn
24 import privileges
25
26 # Prepare options
27 var opts = new OptionContext
28 var opt_drop = new OptionUserAndGroup.for_dropping_privileges
29 var opt_port = new OptionInt("Server port", 80, "--port", "-p")
30 var opt_help = new OptionBool("Print this message", "--help", "-h")
31 opts.add_option(opt_drop, opt_port, opt_help)
32 opts.parse args
33
34 # Check options errors and help
35 if not opts.errors.is_empty or opt_help.value then
36 print opts.errors.join("\n")
37 print "Usage: file_server [Options]"
38 opts.usage
39 exit 1
40 end
41
42 # Serve everything with a standard FilesHandler
43 var vh = new VirtualHost("localhost:{opt_port.value}")
44 vh.routes.add new Route(null, new FileServer("www/hello_world/"))
45 var factory = new HttpFactory.and_libevent
46 factory.config.virtual_hosts.add vh
47
48 # Drop to a low-privileged user
49 var user_group = opt_drop.value
50 if user_group != null then user_group.drop_privileges
51
52 factory.run