examples: annotate examples
[nit.git] / lib / nitcorn / examples / src / htcpcp_server.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2015 Guilherme Mansur<guilhermerpmansur@gmail.com>
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 # Hyper Text Coffee Pot Control Protocol
18
19 # A server that implements HTCPCP. At the moment there are no additions.
20 module htcpcp_server is example
21
22 import nitcorn
23
24 # Nitcorn Action used to answer requests.
25 class HTCPCPAction
26 super Action
27
28 # Brewing status.
29 var brewing = false
30
31 # Teapot status.
32 var is_teapot = false
33
34 redef fun answer(http_request, turi) do
35 var message: String
36 var method = http_request.method
37 var response: HttpResponse
38
39 if is_teapot then
40 response = new HttpResponse(418)
41 response.body = "I'm a teapot!\n"
42 response.header["Content-Type"] = "text"
43 return response
44 end
45
46 if method == "POST" or method == "BREW" then
47 if brewing then
48 message = "Pot Busy"
49 response = new HttpResponse(400)
50 else
51 message = "Brewing a new pot of coffee\n"
52 brewing = true
53 response = new HttpResponse(200)
54 end
55 else if method == "WHEN" then
56 if brewing then
57 message = "Stopped adding milk, your coffee is ready!\n"
58 brewing = false
59 response = new HttpResponse(200)
60 else
61 message = "There is no coffee brewing!\n"
62 response = new HttpResponse(405)
63 end
64 else if method == "PROPFIND" or method == "GET" then
65 if brewing then
66 message = "The pot is busy\n"
67 else
68 message = "The pot is ready to brew more coffee\n"
69 end
70 response = new HttpResponse(200)
71 else
72 message = "Unknown method: {method}"
73 brewing = false
74 response = new HttpResponse(405)
75 end
76
77 response.header["Content-Type"] = "text"
78 response.body = message
79
80 return response
81 end
82 end
83
84 # Nitcorn server.
85 class HTCPCServer
86
87 # Port to listen to.
88 var port: Int
89
90 # Start listening.
91 fun run do
92 var vh = new VirtualHost("localhost:{port}")
93 vh.routes.add new Route("/", new HTCPCPAction)
94 var factory = new HttpFactory.and_libevent
95 factory.config.virtual_hosts.add vh
96 print "Nit4Coffee is now running at port: {port}"
97 factory.run
98 end
99 end
100
101 var server = new HTCPCServer(1227)
102
103 server.run