|
| 1 | +# Function HTTP server |
| 2 | + |
| 3 | +## Simple HTTP server |
| 4 | + |
| 5 | +The fastest way to start a HTTP server is to use the `startHTTPServer` function. |
| 6 | +The function takes two arguments; the first argument is the options, and the second is a unary |
| 7 | +function that takes a `Request` and return a `Task` of a `Response`. |
| 8 | + |
| 9 | +```js |
| 10 | +import Task from "https://deno.land/x/[email protected]/library/Task.js"; |
| 11 | +import Response from "https://deno.land/x/[email protected]/library/Response.js"; |
| 12 | +import startHTTPServer from "./library/server.js"; |
| 13 | + |
| 14 | +startHTTPServer({ port: 8080 }, request => Task.of(Response.OK({}, request.raw))); |
| 15 | +``` |
| 16 | + |
| 17 | +You can test this simple server by executing it your file |
| 18 | + |
| 19 | +```bash |
| 20 | +$ deno run --allow-net server.js |
| 21 | +``` |
| 22 | + |
| 23 | +```bash |
| 24 | +$ curl localhost:8080 -d "Hello, Hoge!" |
| 25 | +> Hello, Hoge! |
| 26 | +``` |
| 27 | + |
| 28 | +## Routing |
| 29 | + |
| 30 | +The main routing tool that comes bundled with this library is conveniently called `route`. |
| 31 | +It takes a non-zero number of arguments which are defined by a pair of functions. |
| 32 | +The first function of the pair is used to assert whether or not to execute the second function. |
| 33 | +The assertion function takes a `Request` and return a `Boolean`, the handling function takes a `Request` and |
| 34 | +must return a `Task` of a `Response`. |
| 35 | + |
| 36 | +```js |
| 37 | +import Task from "https://deno.land/x/[email protected]/library/Task.js"; |
| 38 | +import Response from "https://deno.land/x/[email protected]/library/Response.js"; |
| 39 | +import { route } from "./library/route.js"; |
| 40 | +import { encodeText } from "./library/utilities.js"; |
| 41 | + |
| 42 | +startHTTPServer( |
| 43 | + { port: 8080 }, |
| 44 | + route( |
| 45 | + [ |
| 46 | + request => request.headers.method === 'GET', |
| 47 | + _ => Task.of(Response.OK({ 'content-type': 'text/plain' }, encodeText("Hello, Hoge!"))) |
| 48 | + ] |
| 49 | + ); |
| 50 | +); |
| 51 | +``` |
| 52 | + |
| 53 | +### Routing handlers |
| 54 | + |
| 55 | +Because the pattern is common, this library also offers a collection of handler that automatically creates |
| 56 | +the assertion function. Each handler takes a `String` or a `RegExp` and a unary function. |
| 57 | + |
| 58 | +```js |
| 59 | +import Task from "https://deno.land/x/[email protected]/library/Task.js"; |
| 60 | +import Response from "https://deno.land/x/[email protected]/library/Response.js"; |
| 61 | +import { handlers, route } from "./library/route.js"; |
| 62 | +import { encodeText } from "./library/utilities.js"; |
| 63 | + |
| 64 | +startHTTPServer( |
| 65 | + { port: 8080 }, |
| 66 | + route( |
| 67 | + handlers.get('/', _ => Task.of(Response.OK({ 'content-type': 'text/plain' }, encodeText("Hello, Hoge!")))) |
| 68 | + ); |
| 69 | +); |
| 70 | +``` |
| 71 | + |
| 72 | +#### Routing with the `explodeRequest` utility |
| 73 | + |
| 74 | +The function `explodeRequest` is a utility that will parse the headers and serialize the body of a `Request`, for |
| 75 | +convenience. The function takes two arguments; a binary function that returns a `Task` of `Response` and a `Request`. |
| 76 | + |
| 77 | +The binary function handler will be called with an object containing the original headers, the parsed query string |
| 78 | +and other parameters; the second argument is the body of request serialized based on the content type. |
| 79 | + |
| 80 | +```js |
| 81 | +import { explodeRequest } from "./library/utilities.js"; |
| 82 | + |
| 83 | +startHTTPServer( |
| 84 | + { port: 8080 }, |
| 85 | + route( |
| 86 | + handlers.get('/users', explodeRequest(({ filters }) => retrieveUsers(filters))), |
| 87 | + handlers.post(/\/users\/(?<userID>.+)$/, explodeRequest(({ userID }, { data: user }) => updateUser(userID, user))) |
| 88 | + ) |
| 89 | +); |
| 90 | +``` |
| 91 | + |
| 92 | +For this sample, a `GET` request made with a query string will be parsed as an object. |
| 93 | + |
| 94 | +```bash |
| 95 | +$ curl localhost:8080/users?filters[status]=active |
| 96 | +``` |
| 97 | + |
| 98 | +And, a `POST` request with a body as JSON will be parsed as well. |
| 99 | + |
| 100 | +```bash |
| 101 | +$ curl localhost:8080/users/hoge -X POST -H "Content-Type: application/json" -d "{\"data\":{\"fullName\":\"Hoge\"}}" |
| 102 | +``` |
| 103 | + |
| 104 | + The function `explodeRequest` should cover most use-cases but if you need to create your own parser, check out the |
| 105 | + [`parseRequest`](#parsing-requests) function. |
| 106 | + |
| 107 | +#### Composing routes |
| 108 | + |
| 109 | +Finally, you can compose your routes for increased readability. |
| 110 | + |
| 111 | +```js |
| 112 | +const userRoutes = [ handlers.get('/', handleRetrieveUsers), ... ]; |
| 113 | +const sensorRoutes = [ handlers.get('/', handleRetrieveSensors), ... ]; |
| 114 | + |
| 115 | +startHTTPServer({ port: 8080 }, route(...userRoutes, ...sensorRoutes)); |
| 116 | +``` |
| 117 | + |
| 118 | +### Middleware |
| 119 | + |
| 120 | +Before talking about middlewares, I think it is important to talk about the power of function composition and couple of |
| 121 | +things special about `startHTTPServer` and `route`: |
| 122 | + |
| 123 | + 1. The function `startHTTPServer` takes a unary function that must return a `Task` of `Response`. |
| 124 | + 2. The function `route`, will always return early if the argument is not a `Request`. |
| 125 | + |
| 126 | +So for example, if you needed to discard any request with a content type that is not `application/json`, you could |
| 127 | +do the following. |
| 128 | + |
| 129 | +```js |
| 130 | +import { compose } from "https://x.nest.land/[email protected]/source/index.js"; |
| 131 | + |
| 132 | +startHTTPServer( |
| 133 | + { port: 8080 }, |
| 134 | + compose( |
| 135 | + route(...routes), |
| 136 | + request => request.headers.accept !== 'application/json' |
| 137 | + ? Task.of(Response.BadRequest({}, new Uint8Array([]))) |
| 138 | + : request |
| 139 | + ) |
| 140 | +); |
| 141 | +``` |
| 142 | + |
| 143 | + |
| 144 | +## Deno |
| 145 | + |
| 146 | +This codebase uses [Deno](https://deno.land/#installation). |
| 147 | + |
| 148 | +### MIT License |
| 149 | + |
| 150 | +Copyright © 2020 - Sebastien Filion |
| 151 | + |
| 152 | +Permission is hereby granted, free of charge, to any person obtaining a copy |
| 153 | +of this software and associated documentation files (the "Software"), to deal |
| 154 | +in the Software without restriction, including without limitation the rights |
| 155 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 156 | +copies of the Software, and to permit persons to whom the Software is |
| 157 | +furnished to do so, subject to the following conditions: |
| 158 | + |
| 159 | +The above copyright notice and this permission notice shall be included in all |
| 160 | +copies or substantial portions of the Software. |
| 161 | + |
| 162 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 163 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 164 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 165 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 166 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 167 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 168 | +SOFTWARE. |
0 commit comments