lib/nitcorn: update examples as they don't need to check for tests
[nit.git] / lib / nitcorn / examples / 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 # An action that responds by displaying a static html content.
27 class StaticAction
28 super Action
29
30 redef fun answer(http_request, turi)
31 do
32 var response = new HttpResponse(200)
33 var title = "Hello World from Nitcorn!"
34 response.body = """
35 <!DOCTYPE html>
36 <head>
37 <meta charset="utf-8">
38 <meta http-equiv="X-UA-Compatible" content="IE=edge">
39 <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
40 <title>{{{title}}}</title>
41 </head>
42 <body>
43 <div class="container">
44 <h1>{{{title}}}</h1>
45 <p>See also a <a href="/dir/">directory</a>.</p>
46 </div>
47 </body>
48 </html>"""
49 return response
50 end
51 end
52
53 # An action that uses parameterized uris to customize the output.
54 class ParamAction
55 super Action
56
57 redef fun answer(http_request, turi)
58 do
59 var response = new HttpResponse(200)
60 var name = http_request.param("name")
61 if name == null then
62 response.body = "No name..."
63 else
64 response.body = "Hello {name}"
65 end
66 return response
67 end
68 end
69
70
71 var vh = new VirtualHost("localhost:8080")
72
73 # Serve index.html with our custom handler
74 vh.routes.add new Route("/index.html", new StaticAction)
75 vh.routes.add new Route("/hello/:name", new ParamAction)
76
77 # Serve everything else with a standard `FileServer` with a root at "www/hello_world/"
78 vh.routes.add new Route(null, new FileServer("www/hello_world/"))
79
80 var factory = new HttpFactory.and_libevent
81 factory.config.virtual_hosts.add vh
82 factory.run