examples: add two nitcorn examples
[nit.git] / examples / nitcorn / src / nitcorn_hello_world.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 # Hello World Web server example
18 #
19 # The main page, `index.html`, is served dynamicly with `MyAction`.
20 # The rest of the Web site fetches files from the local directory
21 # `www/hello_world/`.
22 module nitcorn_hello_world
23
24 import nitcorn
25
26 class MyAction
27 super Action
28
29 redef fun answer(http_request, turi)
30 do
31 var response = new HttpResponse(200)
32 var title = "Hello World from Nitcorn!"
33 response.body = """
34 <!DOCTYPE html>
35 <head>
36 <meta charset="utf-8">
37 <meta http-equiv="X-UA-Compatible" content="IE=edge">
38 <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
39 <title>{{{title}}}</title>
40 </head>
41 <body>
42 <div class="container">
43 <h1>{{{title}}}</h1>
44 <p>See also a <a href="/dir/">directory</a>.</p>
45 </div>
46 </body>
47 </html>"""
48 return response
49 end
50 end
51
52 var vh = new VirtualHost("localhost:8080")
53
54 # Serve index.html with our custom handler
55 vh.routes.add new Route("/index.html", new MyAction)
56
57 # Serve everything else with a standard `FileServer` with a root at "www/hello_world/"
58 vh.routes.add new Route(null, new FileServer("www/hello_world/"))
59
60 # Avoid executing when running tests
61 if "NIT_TESTING".environ == "true" then exit 0
62
63 var factory = new HttpFactory.and_libevent
64 factory.config.virtual_hosts.add vh
65 factory.run