1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2016 Alexandre Terrasa <alexandre@moz-code.org>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
23 # Class handler for a route.
25 # **Routing** refers to determining how an application responds to a client request
26 # to a particular endpoint, which is a URI (or path) and a specific HTTP request
27 # method GET, POST, PUT or DELETE (other methods are not suported yet).
29 # Each route can have one or more handler methods, which are executed when the route is matched.
31 # Route handlers definition takes the following form:
37 # redef fun METHOD(req, res) do end
42 # * `MyHandler` is the name of the handler you will add to the app.
43 # * `METHOD` can be replaced by `get`, `post`, `put` or `delete`.
45 # The following example responds with `Hello World!` to GET and POST requests:
51 # redef fun get(req, res) do res.send "Got a GET request"
52 # redef fun post(req, res) do res.send "Got a POST request"
56 # To make your handler responds to a specific route, you have to add it to the app.
58 # Respond to POST request on the root route (`/`), the application's home page:
62 # app.use("/", new MyHandler)
65 # Respond to a request to the `/user` route:
68 # app.use("/user", new MyHandler)
70 abstract class Handler
72 # Call `all(req, res)` if `route` matches `uri`.
73 private fun handle
(route
: AppRoute, uri
: String, req
: HttpRequest, res
: HttpResponse) do
74 if route
.match
(uri
) then
75 if route
isa AppParamRoute then
76 req
.uri_params
= route
.parse_uri_parameters
(uri
)
82 # Handler to all kind of HTTP request methods.
84 # `all` is a special request handler, which is not derived from any
85 # HTTP method. This method is used to respond at a path for all request methods.
87 # In the following example, the handler will be executed for requests to "/user"
88 # whether you are using GET, POST, PUT, DELETE, or any other HTTP request method.
94 # redef fun all(req, res) do res.send "Every request to the homepage"
98 # Using the `all` method you can also implement other HTTP request methods.
104 # redef fun all(req, res) do
105 # if req.method == "MERGE" then
106 # # handle that method
107 # else super # keep handle GET, POST, PUT and DELETE methods
111 fun all
(req
: HttpRequest, res
: HttpResponse) do
112 if req
.method
== "GET" then
114 else if req
.method
== "POST" then
116 else if req
.method
== "PUT" then
118 else if req
.method
== "DELETE" then
121 res
.status_code
= 405
127 # Exemple of route responding to GET requests.
132 # redef fun get(req, res) do res.send "GETrequest received"
135 fun get
(req
: HttpRequest, res
: HttpResponse) do end
139 # Exemple of route responding to POST requests.
144 # redef fun post(req, res) do res.send "POST request received"
147 fun post
(req
: HttpRequest, res
: HttpResponse) do end
151 # Exemple of route responding to PUT requests.
156 # redef fun put(req, res) do res.send "PUT request received"
159 fun put
(req
: HttpRequest, res
: HttpResponse) do end
163 # Exemple of route responding to PUT requests.
165 # class DeleteHandler
168 # redef fun delete(req, res) do res.send "DELETE request received"
171 fun delete
(req
: HttpRequest, res
: HttpResponse) do end
174 # Static files server.
176 # To serve static files such as images, CSS files, and JavaScript files, use the
177 # Popcorn built-in handler `StaticHandler`.
179 # Pass the name of the directory that contains the static assets to the StaticHandler
180 # init method to start serving the files directly.
181 # For example, use the following code to serve images, CSS files, and JavaScript files
182 # in a directory named `public`:
186 # app.use("/", new StaticHandler("public/"))
189 # Now, you can load the files that are in the `public` directory:
192 # http://localhost:3000/images/trollface.jpg
193 # http://localhost:3000/css/style.css
194 # http://localhost:3000/js/app.js
195 # http://localhost:3000/hello.html
198 # Popcorn looks up the files relative to the static directory, so the name of the
199 # static directory is not part of the URL.
200 # To use multiple static assets directories, add the `StaticHandler` multiple times:
203 # app.use("/", new StaticHandler("public/"))
204 # app.use("/", new StaticHandler("files/"))
207 # Popcorn looks up the files in the order in which you set the static directories
208 # with the `use` method.
210 # To create a virtual path prefix (where the path does not actually exist in the file system)
211 # for files that are served by the `StaticHandler`, specify a mount path for the
212 # static directory, as shown below:
215 # app.use("/static/", new StaticHandler("public/"))
218 # Now, you can load the files that are in the public directory from the `/static`
222 # http://localhost:3000/static/images/trollface.jpg
223 # http://localhost:3000/static/css/style.css
224 # http://localhost:3000/static/js/app.js
225 # http://localhost:3000/static/hello.html
228 # However, the path that you provide to the `StaticHandler` is relative to the
229 # directory from where you launch your app.
230 # If you run the app from another directory, it’s safer to use the absolute path of
231 # the directory that you want to serve.
235 # Static files directory to serve.
236 var static_dir
: String
238 # Default file to serve if nothing matches the request.
240 # `null` for no default file.
241 var default_file
: nullable String
243 # Internal file server used to lookup and render files.
244 var file_server
: FileServer is lazy
do
245 var srv
= new FileServer(static_dir
)
246 srv
.show_directory_listing
= false
247 srv
.default_file
= default_file
251 redef fun handle
(route
, uri
, req
, res
) do
252 var answer
= file_server
.answer
(req
, route
.uri_root
(uri
))
253 if answer
.status_code
== 200 then
254 res
.status_code
= answer
.status_code
255 res
.header
.add_all answer
.header
256 res
.files
.add_all answer
.files
258 else if answer
.status_code
!= 404 then
259 res
.status_code
= answer
.status_code
266 # Use the `Router` class to create modular, mountable route handlers.
267 # A Router instance is a complete middleware and routing system; for this reason,
268 # it is often referred to as a “mini-app”.
270 # The following example creates a router as a module, loads a middleware handler in it,
271 # defines some routes, and mounts the router module on a path in the main app.
277 # redef fun get(req, res) do res.send "Site Home"
283 # redef fun all(req, res) do print "User logged"
289 # redef fun get(req, res) do res.send "User Home"
295 # redef fun get(req, res) do res.send "User Profile"
298 # var user_router = new Router
299 # user_router.use("/*", new UserLogger)
300 # user_router.use("/", new UserHome)
301 # user_router.use("/profile", new UserProfile)
304 # app.use("/", new AppHome)
305 # app.use("/user", user_router)
308 # The app will now be able to handle requests to /user and /user/profile, as well
309 # as call the `Time` middleware handler that is specific to the route.
313 # List of handlers to match with requests.
314 private var handlers
= new Map[AppRoute, Handler]
316 # List of handlers to match before every other.
317 private var pre_handlers
= new Map[AppRoute, Handler]
319 # List of handlers to match after every other.
320 private var post_handlers
= new Map[AppRoute, Handler]
322 # Register a `handler` for a route `path`.
324 # Route paths are matched in registration order.
325 fun use
(path
: String, handler
: Handler) do
326 var route
= build_route
(handler
, path
)
327 handlers
[route
] = handler
330 # Register a pre-handler for a route `path`.
332 # Prehandlers are matched before every other handlers in registrastion order.
333 fun use_before
(path
: String, handler
: Handler) do
334 var route
= build_route
(handler
, path
)
335 pre_handlers
[route
] = handler
338 # Register a post-handler for a route `path`.
340 # Posthandlers are matched after every other handlers in registrastion order.
341 fun use_after
(path
: String, handler
: Handler) do
342 var route
= build_route
(handler
, path
)
343 post_handlers
[route
] = handler
346 redef fun handle
(route
, uri
, req
, res
) do
347 if not route
.match
(uri
) then return
348 handle_pre
(route
, uri
, req
, res
)
349 handle_in
(route
, uri
, req
, res
)
350 handle_post
(route
, uri
, req
, res
)
353 private fun handle_pre
(route
: AppRoute, uri
: String, req
: HttpRequest, res
: HttpResponse) do
354 for hroute
, handler
in pre_handlers
do
355 handler
.handle
(hroute
, route
.uri_root
(uri
), req
, res
)
359 private fun handle_in
(route
: AppRoute, uri
: String, req
: HttpRequest, res
: HttpResponse) do
360 for hroute
, handler
in handlers
do
361 handler
.handle
(hroute
, route
.uri_root
(uri
), req
, res
)
362 if res
.sent
then break
366 private fun handle_post
(route
: AppRoute, uri
: String, req
: HttpRequest, res
: HttpResponse) do
367 for hroute
, handler
in post_handlers
do
368 handler
.handle
(hroute
, route
.uri_root
(uri
), req
, res
)
372 private fun build_route
(handler
: Handler, path
: String): AppRoute do
373 if handler
isa Router or handler
isa StaticHandler then
374 return new AppGlobRoute(path
)
375 else if path
.has_suffix
("*") then
376 return new AppGlobRoute(path
)
378 return new AppParamRoute(path
)
383 # Popcorn application.
385 # The `App` is the main point of the application.
386 # It acts as a `Router` that holds the top level route handlers.
388 # Here an example to create a simple web app with Popcorn:
396 # redef fun get(req, res) do res.html "<h1>Hello World!</h1>"
400 # app.use("/", new HelloHandler)
401 # # app.listen("localhost", 3000)
404 # The Popcorn app listens on port 3000 for connections.
405 # The app responds with "Hello World!" for request to the root URL (`/`) or **route**.
406 # For every other path, it will respond with a **404 Not Found**.
408 # The `req` (request) and `res` (response) parameters are the same that nitcorn provides
409 # so you can do anything else you would do in your route without Popcorn involved.
411 # Run the app with the following command:
414 # nitc app.nit && ./app
417 # Then, load [http://localhost:3000](http://localhost:3000) in a browser to see the output.
422 redef class HttpResponse
424 # Was this request sent by a handler?
427 private fun check_sent
do
428 if sent
then print
"Warning: Headers already sent!"
431 # Write data in body response and send it.
432 fun send
(raw_data
: nullable Writable, status
: nullable Int) do
433 if raw_data
!= null then
436 if status
!= null then
445 # Write data as HTML and set the right content type header.
446 fun html
(html
: nullable Writable, status
: nullable Int) do
447 header
["Content-Type"] = media_types
["html"].as(not null)
451 # Write data as CSV and set the right content type header.
452 fun csv
(csv
: nullable CsvDocument, status
: nullable Int) do
453 header
["Content-Type"] = media_types
["csv"].as(not null)
457 send
(csv
.write_to_string
, status
)
461 # Redirect response to `location`
463 # Use by default 303 See Other as it is the RFC
464 # way to redirect web applications to a new URI.
465 fun redirect
(location
: String, status
: nullable Int) do
466 header
["Location"] = location
467 if status
!= null then
476 # TODO The error message should be parameterizable.
477 fun error
(status
: Int) do
478 html
("Error", status
)