From 92b54aacc0de5446dd5497c39897b0bbff72e626 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Hoguin?= Date: Wed, 13 Jun 2018 09:54:12 +0200 Subject: Rebuild using Asciideck --- .gitignore | 1 + _build/Makefile | 13 +- _build/themes/ninenines/layouts/index.html | 4 +- articles/cowboy-2.0.0-pre.4/index.html | 113 +- articles/cowboy-2.0.0-rc.1/index.html | 68 +- articles/cowboy-2.0.0-rc.2/index.html | 42 +- articles/cowboy-2.0.0/index.html | 57 +- articles/cowboy-2.1.0/index.html | 50 +- articles/cowboy-2.2.0/index.html | 51 +- articles/cowboy-2.3.0/index.html | 18 +- articles/cowboy-2.4.0/index.html | 36 +- articles/cowboy2-qs/index.html | 191 +- articles/dont-let-it-crash/index.html | 137 +- articles/erlang-scalability/index.html | 155 +- articles/erlang-validate-utf8/index.html | 284 +- articles/erlang.mk-and-relx/index.html | 139 +- .../index.html | 21 +- articles/erlanger-playbook/index.html | 86 +- articles/farwest-funded/index.html | 30 +- articles/gun-1.0.0-rc.1/index.html | 45 +- articles/index.html | 89 +- articles/index.xml | 145 +- articles/january-2014-status/index.html | 165 +- articles/ml-archives/index.html | 16 +- articles/on-open-source/index.html | 135 +- articles/page/2/index.html | 56 +- articles/ranch-1.3/index.html | 109 +- articles/ranch-ftp/index.html | 279 +- articles/the-elephant-in-the-room/index.html | 158 +- articles/the-story-so-far/index.html | 246 +- articles/tictactoe/index.html | 109 +- articles/website-update/index.html | 68 +- articles/xerl-0.1-empty-modules/index.html | 183 +- articles/xerl-0.2-two-modules/index.html | 224 +- articles/xerl-0.3-atomic-expressions/index.html | 171 +- articles/xerl-0.4-expression-separator/index.html | 64 +- articles/xerl-0.5-intermediate-module/index.html | 176 +- docs/en/cowboy/2.0/guide/constraints/index.html | 175 +- docs/en/cowboy/2.0/guide/cookies/index.html | 171 +- docs/en/cowboy/2.0/guide/erlang_web/index.html | 218 +- docs/en/cowboy/2.0/guide/flow_diagram/index.html | 121 +- .../en/cowboy/2.0/guide/getting_started/index.html | 181 +- docs/en/cowboy/2.0/guide/handlers/index.html | 106 +- docs/en/cowboy/2.0/guide/index.html | 196 +- docs/en/cowboy/2.0/guide/introduction/index.html | 77 +- docs/en/cowboy/2.0/guide/listeners/index.html | 128 +- docs/en/cowboy/2.0/guide/loop_handlers/index.html | 157 +- docs/en/cowboy/2.0/guide/middlewares/index.html | 100 +- .../cowboy/2.0/guide/migrating_from_1.0/index.html | 468 +-- docs/en/cowboy/2.0/guide/modern_web/index.html | 131 +- docs/en/cowboy/2.0/guide/multipart/index.html | 220 +- docs/en/cowboy/2.0/guide/req/index.html | 484 +-- docs/en/cowboy/2.0/guide/req_body/index.html | 167 +- .../en/cowboy/2.0/guide/resource_design/index.html | 245 +- docs/en/cowboy/2.0/guide/resp/index.html | 408 +-- .../en/cowboy/2.0/guide/rest_flowcharts/index.html | 284 +- docs/en/cowboy/2.0/guide/rest_handlers/index.html | 409 +-- .../en/cowboy/2.0/guide/rest_principles/index.html | 169 +- docs/en/cowboy/2.0/guide/routing/index.html | 304 +- docs/en/cowboy/2.0/guide/specs/index.html | 1144 ++---- docs/en/cowboy/2.0/guide/static_files/index.html | 194 +- docs/en/cowboy/2.0/guide/streams/index.html | 68 +- docs/en/cowboy/2.0/guide/ws_handlers/index.html | 338 +- docs/en/cowboy/2.0/guide/ws_protocol/index.html | 74 +- .../en/cowboy/2.0/manual/cowboy.set_env/index.html | 124 +- .../2.0/manual/cowboy.start_clear/index.html | 159 +- .../cowboy/2.0/manual/cowboy.start_tls/index.html | 165 +- .../2.0/manual/cowboy.stop_listener/index.html | 87 +- docs/en/cowboy/2.0/manual/cowboy/index.html | 135 +- docs/en/cowboy/2.0/manual/cowboy_app/index.html | 178 +- .../2.0/manual/cowboy_constraints.int/index.html | 92 +- .../manual/cowboy_constraints.nonempty/index.html | 90 +- .../2.0/manual/cowboy_constraints/index.html | 85 +- .../2.0/manual/cowboy_handler.terminate/index.html | 115 +- .../en/cowboy/2.0/manual/cowboy_handler/index.html | 108 +- docs/en/cowboy/2.0/manual/cowboy_http/index.html | 272 +- docs/en/cowboy/2.0/manual/cowboy_http2/index.html | 139 +- docs/en/cowboy/2.0/manual/cowboy_loop/index.html | 140 +- .../cowboy/2.0/manual/cowboy_middleware/index.html | 123 +- .../2.0/manual/cowboy_req.binding/index.html | 122 +- .../2.0/manual/cowboy_req.bindings/index.html | 82 +- .../2.0/manual/cowboy_req.body_length/index.html | 86 +- .../cowboy_req.delete_resp_header/index.html | 94 +- .../2.0/manual/cowboy_req.has_body/index.html | 76 +- .../2.0/manual/cowboy_req.has_resp_body/index.html | 83 +- .../manual/cowboy_req.has_resp_header/index.html | 95 +- .../cowboy/2.0/manual/cowboy_req.header/index.html | 129 +- .../2.0/manual/cowboy_req.headers/index.html | 87 +- .../cowboy/2.0/manual/cowboy_req.host/index.html | 88 +- .../2.0/manual/cowboy_req.host_info/index.html | 84 +- .../2.0/manual/cowboy_req.match_cookies/index.html | 134 +- .../2.0/manual/cowboy_req.match_qs/index.html | 134 +- .../cowboy/2.0/manual/cowboy_req.method/index.html | 102 +- .../2.0/manual/cowboy_req.parse_cookies/index.html | 94 +- .../2.0/manual/cowboy_req.parse_header/index.html | 359 +- .../2.0/manual/cowboy_req.parse_qs/index.html | 118 +- .../cowboy/2.0/manual/cowboy_req.path/index.html | 87 +- .../2.0/manual/cowboy_req.path_info/index.html | 84 +- .../cowboy/2.0/manual/cowboy_req.peer/index.html | 95 +- .../cowboy/2.0/manual/cowboy_req.port/index.html | 88 +- .../cowboy/2.0/manual/cowboy_req.push/index.html | 161 +- docs/en/cowboy/2.0/manual/cowboy_req.qs/index.html | 86 +- .../2.0/manual/cowboy_req.read_body/index.html | 165 +- .../2.0/manual/cowboy_req.read_part/index.html | 200 +- .../manual/cowboy_req.read_part_body/index.html | 150 +- .../cowboy_req.read_urlencoded_body/index.html | 140 +- .../cowboy/2.0/manual/cowboy_req.reply/index.html | 189 +- .../2.0/manual/cowboy_req.resp_header/index.html | 119 +- .../2.0/manual/cowboy_req.resp_headers/index.html | 75 +- .../cowboy/2.0/manual/cowboy_req.scheme/index.html | 93 +- .../2.0/manual/cowboy_req.set_resp_body/index.html | 151 +- .../manual/cowboy_req.set_resp_cookie/index.html | 189 +- .../manual/cowboy_req.set_resp_header/index.html | 129 +- .../manual/cowboy_req.set_resp_headers/index.html | 116 +- .../2.0/manual/cowboy_req.stream_body/index.html | 126 +- .../2.0/manual/cowboy_req.stream_reply/index.html | 170 +- .../en/cowboy/2.0/manual/cowboy_req.uri/index.html | 199 +- .../2.0/manual/cowboy_req.version/index.html | 85 +- docs/en/cowboy/2.0/manual/cowboy_req/index.html | 519 +-- docs/en/cowboy/2.0/manual/cowboy_rest/index.html | 811 ++--- .../2.0/manual/cowboy_router.compile/index.html | 93 +- docs/en/cowboy/2.0/manual/cowboy_router/index.html | 117 +- docs/en/cowboy/2.0/manual/cowboy_static/index.html | 221 +- docs/en/cowboy/2.0/manual/cowboy_stream/index.html | 497 +-- .../cowboy/2.0/manual/cowboy_websocket/index.html | 355 +- .../cowboy/2.0/manual/http_status_codes/index.html | 267 +- docs/en/cowboy/2.0/manual/index.html | 178 +- docs/en/cowboy/2.1/guide/constraints/index.html | 175 +- docs/en/cowboy/2.1/guide/cookies/index.html | 171 +- docs/en/cowboy/2.1/guide/erlang_web/index.html | 218 +- docs/en/cowboy/2.1/guide/flow_diagram/index.html | 121 +- .../en/cowboy/2.1/guide/getting_started/index.html | 181 +- docs/en/cowboy/2.1/guide/handlers/index.html | 106 +- docs/en/cowboy/2.1/guide/index.html | 201 +- docs/en/cowboy/2.1/guide/introduction/index.html | 77 +- docs/en/cowboy/2.1/guide/listeners/index.html | 128 +- docs/en/cowboy/2.1/guide/loop_handlers/index.html | 157 +- docs/en/cowboy/2.1/guide/middlewares/index.html | 100 +- .../cowboy/2.1/guide/migrating_from_1.0/index.html | 480 +-- .../cowboy/2.1/guide/migrating_from_2.0/index.html | 185 +- docs/en/cowboy/2.1/guide/modern_web/index.html | 131 +- docs/en/cowboy/2.1/guide/multipart/index.html | 220 +- docs/en/cowboy/2.1/guide/req/index.html | 484 +-- docs/en/cowboy/2.1/guide/req_body/index.html | 167 +- .../en/cowboy/2.1/guide/resource_design/index.html | 245 +- docs/en/cowboy/2.1/guide/resp/index.html | 437 +-- .../en/cowboy/2.1/guide/rest_flowcharts/index.html | 284 +- docs/en/cowboy/2.1/guide/rest_handlers/index.html | 413 +-- .../en/cowboy/2.1/guide/rest_principles/index.html | 169 +- docs/en/cowboy/2.1/guide/routing/index.html | 304 +- docs/en/cowboy/2.1/guide/specs/index.html | 1144 ++---- docs/en/cowboy/2.1/guide/static_files/index.html | 194 +- docs/en/cowboy/2.1/guide/streams/index.html | 68 +- docs/en/cowboy/2.1/guide/ws_handlers/index.html | 340 +- docs/en/cowboy/2.1/guide/ws_protocol/index.html | 74 +- .../en/cowboy/2.1/manual/cowboy.set_env/index.html | 124 +- .../2.1/manual/cowboy.start_clear/index.html | 159 +- .../cowboy/2.1/manual/cowboy.start_tls/index.html | 165 +- .../2.1/manual/cowboy.stop_listener/index.html | 87 +- docs/en/cowboy/2.1/manual/cowboy/index.html | 135 +- docs/en/cowboy/2.1/manual/cowboy_app/index.html | 178 +- .../2.1/manual/cowboy_constraints.int/index.html | 92 +- .../manual/cowboy_constraints.nonempty/index.html | 90 +- .../2.1/manual/cowboy_constraints/index.html | 85 +- .../2.1/manual/cowboy_handler.terminate/index.html | 115 +- .../en/cowboy/2.1/manual/cowboy_handler/index.html | 108 +- docs/en/cowboy/2.1/manual/cowboy_http/index.html | 272 +- docs/en/cowboy/2.1/manual/cowboy_http2/index.html | 139 +- docs/en/cowboy/2.1/manual/cowboy_loop/index.html | 140 +- .../cowboy/2.1/manual/cowboy_middleware/index.html | 123 +- .../2.1/manual/cowboy_req.binding/index.html | 122 +- .../2.1/manual/cowboy_req.bindings/index.html | 82 +- .../2.1/manual/cowboy_req.body_length/index.html | 86 +- .../cowboy/2.1/manual/cowboy_req.cert/index.html | 108 +- .../cowboy_req.delete_resp_header/index.html | 94 +- .../2.1/manual/cowboy_req.has_body/index.html | 76 +- .../2.1/manual/cowboy_req.has_resp_body/index.html | 83 +- .../manual/cowboy_req.has_resp_header/index.html | 95 +- .../cowboy/2.1/manual/cowboy_req.header/index.html | 129 +- .../2.1/manual/cowboy_req.headers/index.html | 87 +- .../cowboy/2.1/manual/cowboy_req.host/index.html | 88 +- .../2.1/manual/cowboy_req.host_info/index.html | 84 +- .../cowboy/2.1/manual/cowboy_req.inform/index.html | 139 +- .../2.1/manual/cowboy_req.match_cookies/index.html | 134 +- .../2.1/manual/cowboy_req.match_qs/index.html | 134 +- .../cowboy/2.1/manual/cowboy_req.method/index.html | 102 +- .../2.1/manual/cowboy_req.parse_cookies/index.html | 94 +- .../2.1/manual/cowboy_req.parse_header/index.html | 359 +- .../2.1/manual/cowboy_req.parse_qs/index.html | 118 +- .../cowboy/2.1/manual/cowboy_req.path/index.html | 87 +- .../2.1/manual/cowboy_req.path_info/index.html | 84 +- .../cowboy/2.1/manual/cowboy_req.peer/index.html | 97 +- .../cowboy/2.1/manual/cowboy_req.port/index.html | 88 +- .../cowboy/2.1/manual/cowboy_req.push/index.html | 162 +- docs/en/cowboy/2.1/manual/cowboy_req.qs/index.html | 86 +- .../2.1/manual/cowboy_req.read_body/index.html | 165 +- .../2.1/manual/cowboy_req.read_part/index.html | 200 +- .../manual/cowboy_req.read_part_body/index.html | 150 +- .../cowboy_req.read_urlencoded_body/index.html | 140 +- .../cowboy/2.1/manual/cowboy_req.reply/index.html | 190 +- .../2.1/manual/cowboy_req.resp_header/index.html | 119 +- .../2.1/manual/cowboy_req.resp_headers/index.html | 75 +- .../cowboy/2.1/manual/cowboy_req.scheme/index.html | 93 +- .../2.1/manual/cowboy_req.set_resp_body/index.html | 151 +- .../manual/cowboy_req.set_resp_cookie/index.html | 189 +- .../manual/cowboy_req.set_resp_header/index.html | 129 +- .../manual/cowboy_req.set_resp_headers/index.html | 116 +- .../cowboy/2.1/manual/cowboy_req.sock/index.html | 83 +- .../2.1/manual/cowboy_req.stream_body/index.html | 126 +- .../2.1/manual/cowboy_req.stream_reply/index.html | 171 +- .../en/cowboy/2.1/manual/cowboy_req.uri/index.html | 199 +- .../2.1/manual/cowboy_req.version/index.html | 85 +- docs/en/cowboy/2.1/manual/cowboy_req/index.html | 549 +-- docs/en/cowboy/2.1/manual/cowboy_rest/index.html | 843 ++--- .../2.1/manual/cowboy_router.compile/index.html | 93 +- docs/en/cowboy/2.1/manual/cowboy_router/index.html | 117 +- docs/en/cowboy/2.1/manual/cowboy_static/index.html | 221 +- docs/en/cowboy/2.1/manual/cowboy_stream/index.html | 497 +-- .../cowboy/2.1/manual/cowboy_websocket/index.html | 355 +- .../cowboy/2.1/manual/http_status_codes/index.html | 267 +- docs/en/cowboy/2.1/manual/index.html | 178 +- docs/en/cowboy/2.2/guide/constraints/index.html | 175 +- docs/en/cowboy/2.2/guide/cookies/index.html | 171 +- docs/en/cowboy/2.2/guide/erlang_web/index.html | 218 +- docs/en/cowboy/2.2/guide/flow_diagram/index.html | 121 +- .../en/cowboy/2.2/guide/getting_started/index.html | 181 +- docs/en/cowboy/2.2/guide/handlers/index.html | 106 +- docs/en/cowboy/2.2/guide/index.html | 211 +- docs/en/cowboy/2.2/guide/introduction/index.html | 77 +- docs/en/cowboy/2.2/guide/listeners/index.html | 128 +- docs/en/cowboy/2.2/guide/loop_handlers/index.html | 157 +- docs/en/cowboy/2.2/guide/middlewares/index.html | 100 +- .../cowboy/2.2/guide/migrating_from_1.0/index.html | 480 +-- .../cowboy/2.2/guide/migrating_from_2.0/index.html | 185 +- .../cowboy/2.2/guide/migrating_from_2.1/index.html | 199 +- .../cowboy/2.2/guide/migrating_from_2.2/index.html | 44 +- docs/en/cowboy/2.2/guide/modern_web/index.html | 131 +- docs/en/cowboy/2.2/guide/multipart/index.html | 220 +- docs/en/cowboy/2.2/guide/req/index.html | 484 +-- docs/en/cowboy/2.2/guide/req_body/index.html | 167 +- .../en/cowboy/2.2/guide/resource_design/index.html | 245 +- docs/en/cowboy/2.2/guide/resp/index.html | 478 +-- .../en/cowboy/2.2/guide/rest_flowcharts/index.html | 284 +- docs/en/cowboy/2.2/guide/rest_handlers/index.html | 413 +-- .../en/cowboy/2.2/guide/rest_principles/index.html | 169 +- docs/en/cowboy/2.2/guide/routing/index.html | 304 +- docs/en/cowboy/2.2/guide/specs/index.html | 1151 ++---- docs/en/cowboy/2.2/guide/static_files/index.html | 194 +- docs/en/cowboy/2.2/guide/streams/index.html | 68 +- docs/en/cowboy/2.2/guide/ws_handlers/index.html | 340 +- docs/en/cowboy/2.2/guide/ws_protocol/index.html | 74 +- .../en/cowboy/2.2/manual/cowboy.set_env/index.html | 124 +- .../2.2/manual/cowboy.start_clear/index.html | 159 +- .../cowboy/2.2/manual/cowboy.start_tls/index.html | 165 +- .../2.2/manual/cowboy.stop_listener/index.html | 87 +- docs/en/cowboy/2.2/manual/cowboy/index.html | 135 +- docs/en/cowboy/2.2/manual/cowboy_app/index.html | 178 +- .../2.2/manual/cowboy_constraints.int/index.html | 92 +- .../manual/cowboy_constraints.nonempty/index.html | 90 +- .../2.2/manual/cowboy_constraints/index.html | 85 +- .../2.2/manual/cowboy_handler.terminate/index.html | 115 +- .../en/cowboy/2.2/manual/cowboy_handler/index.html | 108 +- docs/en/cowboy/2.2/manual/cowboy_http/index.html | 321 +- docs/en/cowboy/2.2/manual/cowboy_http2/index.html | 139 +- docs/en/cowboy/2.2/manual/cowboy_loop/index.html | 140 +- .../cowboy/2.2/manual/cowboy_middleware/index.html | 123 +- .../2.2/manual/cowboy_req.binding/index.html | 122 +- .../2.2/manual/cowboy_req.bindings/index.html | 82 +- .../2.2/manual/cowboy_req.body_length/index.html | 86 +- .../cowboy/2.2/manual/cowboy_req.cert/index.html | 108 +- .../cowboy_req.delete_resp_header/index.html | 94 +- .../2.2/manual/cowboy_req.has_body/index.html | 76 +- .../2.2/manual/cowboy_req.has_resp_body/index.html | 83 +- .../manual/cowboy_req.has_resp_header/index.html | 95 +- .../cowboy/2.2/manual/cowboy_req.header/index.html | 129 +- .../2.2/manual/cowboy_req.headers/index.html | 87 +- .../cowboy/2.2/manual/cowboy_req.host/index.html | 88 +- .../2.2/manual/cowboy_req.host_info/index.html | 84 +- .../cowboy/2.2/manual/cowboy_req.inform/index.html | 139 +- .../2.2/manual/cowboy_req.match_cookies/index.html | 134 +- .../2.2/manual/cowboy_req.match_qs/index.html | 134 +- .../cowboy/2.2/manual/cowboy_req.method/index.html | 102 +- .../2.2/manual/cowboy_req.parse_cookies/index.html | 94 +- .../2.2/manual/cowboy_req.parse_header/index.html | 359 +- .../2.2/manual/cowboy_req.parse_qs/index.html | 118 +- .../cowboy/2.2/manual/cowboy_req.path/index.html | 87 +- .../2.2/manual/cowboy_req.path_info/index.html | 84 +- .../cowboy/2.2/manual/cowboy_req.peer/index.html | 97 +- .../cowboy/2.2/manual/cowboy_req.port/index.html | 88 +- .../cowboy/2.2/manual/cowboy_req.push/index.html | 162 +- docs/en/cowboy/2.2/manual/cowboy_req.qs/index.html | 86 +- .../2.2/manual/cowboy_req.read_body/index.html | 165 +- .../2.2/manual/cowboy_req.read_part/index.html | 200 +- .../manual/cowboy_req.read_part_body/index.html | 150 +- .../cowboy_req.read_urlencoded_body/index.html | 140 +- .../cowboy/2.2/manual/cowboy_req.reply/index.html | 190 +- .../2.2/manual/cowboy_req.resp_header/index.html | 119 +- .../2.2/manual/cowboy_req.resp_headers/index.html | 75 +- .../cowboy/2.2/manual/cowboy_req.scheme/index.html | 93 +- .../2.2/manual/cowboy_req.set_resp_body/index.html | 151 +- .../manual/cowboy_req.set_resp_cookie/index.html | 189 +- .../manual/cowboy_req.set_resp_header/index.html | 129 +- .../manual/cowboy_req.set_resp_headers/index.html | 116 +- .../cowboy/2.2/manual/cowboy_req.sock/index.html | 83 +- .../2.2/manual/cowboy_req.stream_body/index.html | 129 +- .../2.2/manual/cowboy_req.stream_reply/index.html | 174 +- .../manual/cowboy_req.stream_trailers/index.html | 118 +- .../en/cowboy/2.2/manual/cowboy_req.uri/index.html | 199 +- .../2.2/manual/cowboy_req.version/index.html | 85 +- docs/en/cowboy/2.2/manual/cowboy_req/index.html | 556 +-- docs/en/cowboy/2.2/manual/cowboy_rest/index.html | 845 ++--- .../2.2/manual/cowboy_router.compile/index.html | 93 +- docs/en/cowboy/2.2/manual/cowboy_router/index.html | 117 +- docs/en/cowboy/2.2/manual/cowboy_static/index.html | 221 +- docs/en/cowboy/2.2/manual/cowboy_stream/index.html | 541 +-- .../cowboy/2.2/manual/cowboy_websocket/index.html | 355 +- .../cowboy/2.2/manual/http_status_codes/index.html | 267 +- docs/en/cowboy/2.2/manual/index.html | 178 +- docs/en/cowboy/2.3/guide/constraints/index.html | 175 +- docs/en/cowboy/2.3/guide/cookies/index.html | 171 +- docs/en/cowboy/2.3/guide/erlang_web/index.html | 218 +- docs/en/cowboy/2.3/guide/flow_diagram/index.html | 121 +- .../en/cowboy/2.3/guide/getting_started/index.html | 181 +- docs/en/cowboy/2.3/guide/handlers/index.html | 106 +- docs/en/cowboy/2.3/guide/index.html | 211 +- docs/en/cowboy/2.3/guide/introduction/index.html | 77 +- docs/en/cowboy/2.3/guide/listeners/index.html | 128 +- docs/en/cowboy/2.3/guide/loop_handlers/index.html | 157 +- docs/en/cowboy/2.3/guide/middlewares/index.html | 100 +- .../cowboy/2.3/guide/migrating_from_1.0/index.html | 480 +-- .../cowboy/2.3/guide/migrating_from_2.0/index.html | 185 +- .../cowboy/2.3/guide/migrating_from_2.1/index.html | 199 +- .../cowboy/2.3/guide/migrating_from_2.2/index.html | 104 +- docs/en/cowboy/2.3/guide/modern_web/index.html | 131 +- docs/en/cowboy/2.3/guide/multipart/index.html | 220 +- docs/en/cowboy/2.3/guide/req/index.html | 484 +-- docs/en/cowboy/2.3/guide/req_body/index.html | 167 +- .../en/cowboy/2.3/guide/resource_design/index.html | 245 +- docs/en/cowboy/2.3/guide/resp/index.html | 476 +-- .../en/cowboy/2.3/guide/rest_flowcharts/index.html | 284 +- docs/en/cowboy/2.3/guide/rest_handlers/index.html | 413 +-- .../en/cowboy/2.3/guide/rest_principles/index.html | 169 +- docs/en/cowboy/2.3/guide/routing/index.html | 304 +- docs/en/cowboy/2.3/guide/specs/index.html | 1172 ++---- docs/en/cowboy/2.3/guide/static_files/index.html | 194 +- docs/en/cowboy/2.3/guide/streams/index.html | 68 +- docs/en/cowboy/2.3/guide/ws_handlers/index.html | 371 +- docs/en/cowboy/2.3/guide/ws_protocol/index.html | 74 +- .../en/cowboy/2.3/manual/cowboy.set_env/index.html | 124 +- .../2.3/manual/cowboy.start_clear/index.html | 159 +- .../cowboy/2.3/manual/cowboy.start_tls/index.html | 165 +- .../2.3/manual/cowboy.stop_listener/index.html | 87 +- docs/en/cowboy/2.3/manual/cowboy/index.html | 135 +- docs/en/cowboy/2.3/manual/cowboy_app/index.html | 178 +- .../2.3/manual/cowboy_constraints.int/index.html | 92 +- .../manual/cowboy_constraints.nonempty/index.html | 90 +- .../2.3/manual/cowboy_constraints/index.html | 85 +- .../2.3/manual/cowboy_handler.terminate/index.html | 115 +- .../en/cowboy/2.3/manual/cowboy_handler/index.html | 108 +- docs/en/cowboy/2.3/manual/cowboy_http/index.html | 321 +- docs/en/cowboy/2.3/manual/cowboy_http2/index.html | 139 +- docs/en/cowboy/2.3/manual/cowboy_loop/index.html | 140 +- .../cowboy/2.3/manual/cowboy_middleware/index.html | 123 +- .../2.3/manual/cowboy_req.binding/index.html | 122 +- .../2.3/manual/cowboy_req.bindings/index.html | 82 +- .../2.3/manual/cowboy_req.body_length/index.html | 86 +- .../cowboy/2.3/manual/cowboy_req.cert/index.html | 108 +- .../cowboy_req.delete_resp_header/index.html | 94 +- .../2.3/manual/cowboy_req.has_body/index.html | 76 +- .../2.3/manual/cowboy_req.has_resp_body/index.html | 83 +- .../manual/cowboy_req.has_resp_header/index.html | 95 +- .../cowboy/2.3/manual/cowboy_req.header/index.html | 129 +- .../2.3/manual/cowboy_req.headers/index.html | 87 +- .../cowboy/2.3/manual/cowboy_req.host/index.html | 88 +- .../2.3/manual/cowboy_req.host_info/index.html | 84 +- .../cowboy/2.3/manual/cowboy_req.inform/index.html | 139 +- .../2.3/manual/cowboy_req.match_cookies/index.html | 134 +- .../2.3/manual/cowboy_req.match_qs/index.html | 134 +- .../cowboy/2.3/manual/cowboy_req.method/index.html | 102 +- .../2.3/manual/cowboy_req.parse_cookies/index.html | 94 +- .../2.3/manual/cowboy_req.parse_header/index.html | 359 +- .../2.3/manual/cowboy_req.parse_qs/index.html | 118 +- .../cowboy/2.3/manual/cowboy_req.path/index.html | 87 +- .../2.3/manual/cowboy_req.path_info/index.html | 84 +- .../cowboy/2.3/manual/cowboy_req.peer/index.html | 97 +- .../cowboy/2.3/manual/cowboy_req.port/index.html | 88 +- .../cowboy/2.3/manual/cowboy_req.push/index.html | 162 +- docs/en/cowboy/2.3/manual/cowboy_req.qs/index.html | 86 +- .../2.3/manual/cowboy_req.read_body/index.html | 165 +- .../2.3/manual/cowboy_req.read_part/index.html | 200 +- .../manual/cowboy_req.read_part_body/index.html | 150 +- .../cowboy_req.read_urlencoded_body/index.html | 140 +- .../cowboy/2.3/manual/cowboy_req.reply/index.html | 190 +- .../2.3/manual/cowboy_req.resp_header/index.html | 119 +- .../2.3/manual/cowboy_req.resp_headers/index.html | 75 +- .../cowboy/2.3/manual/cowboy_req.scheme/index.html | 93 +- .../2.3/manual/cowboy_req.set_resp_body/index.html | 151 +- .../manual/cowboy_req.set_resp_cookie/index.html | 189 +- .../manual/cowboy_req.set_resp_header/index.html | 129 +- .../manual/cowboy_req.set_resp_headers/index.html | 116 +- .../cowboy/2.3/manual/cowboy_req.sock/index.html | 83 +- .../2.3/manual/cowboy_req.stream_body/index.html | 129 +- .../2.3/manual/cowboy_req.stream_reply/index.html | 174 +- .../manual/cowboy_req.stream_trailers/index.html | 118 +- .../en/cowboy/2.3/manual/cowboy_req.uri/index.html | 199 +- .../2.3/manual/cowboy_req.version/index.html | 85 +- docs/en/cowboy/2.3/manual/cowboy_req/index.html | 556 +-- docs/en/cowboy/2.3/manual/cowboy_rest/index.html | 845 ++--- .../2.3/manual/cowboy_router.compile/index.html | 93 +- docs/en/cowboy/2.3/manual/cowboy_router/index.html | 117 +- docs/en/cowboy/2.3/manual/cowboy_static/index.html | 221 +- docs/en/cowboy/2.3/manual/cowboy_stream/index.html | 541 +-- .../cowboy/2.3/manual/cowboy_websocket/index.html | 370 +- .../cowboy/2.3/manual/http_status_codes/index.html | 267 +- docs/en/cowboy/2.3/manual/index.html | 178 +- docs/en/cowboy/2.4/guide/constraints/index.html | 175 +- docs/en/cowboy/2.4/guide/cookies/index.html | 171 +- docs/en/cowboy/2.4/guide/erlang_web/index.html | 218 +- docs/en/cowboy/2.4/guide/flow_diagram/index.html | 121 +- .../en/cowboy/2.4/guide/getting_started/index.html | 181 +- docs/en/cowboy/2.4/guide/handlers/index.html | 106 +- docs/en/cowboy/2.4/guide/index.html | 216 +- docs/en/cowboy/2.4/guide/introduction/index.html | 77 +- docs/en/cowboy/2.4/guide/listeners/index.html | 128 +- docs/en/cowboy/2.4/guide/loop_handlers/index.html | 157 +- docs/en/cowboy/2.4/guide/middlewares/index.html | 100 +- .../cowboy/2.4/guide/migrating_from_1.0/index.html | 480 +-- .../cowboy/2.4/guide/migrating_from_2.0/index.html | 185 +- .../cowboy/2.4/guide/migrating_from_2.1/index.html | 199 +- .../cowboy/2.4/guide/migrating_from_2.2/index.html | 104 +- .../cowboy/2.4/guide/migrating_from_2.3/index.html | 117 +- docs/en/cowboy/2.4/guide/modern_web/index.html | 131 +- docs/en/cowboy/2.4/guide/multipart/index.html | 220 +- docs/en/cowboy/2.4/guide/req/index.html | 483 +-- docs/en/cowboy/2.4/guide/req_body/index.html | 167 +- .../en/cowboy/2.4/guide/resource_design/index.html | 245 +- docs/en/cowboy/2.4/guide/resp/index.html | 476 +-- .../en/cowboy/2.4/guide/rest_flowcharts/index.html | 284 +- docs/en/cowboy/2.4/guide/rest_handlers/index.html | 413 +-- .../en/cowboy/2.4/guide/rest_principles/index.html | 169 +- docs/en/cowboy/2.4/guide/routing/index.html | 304 +- docs/en/cowboy/2.4/guide/specs/index.html | 1172 ++---- docs/en/cowboy/2.4/guide/static_files/index.html | 194 +- docs/en/cowboy/2.4/guide/streams/index.html | 68 +- docs/en/cowboy/2.4/guide/ws_handlers/index.html | 371 +- docs/en/cowboy/2.4/guide/ws_protocol/index.html | 74 +- .../en/cowboy/2.4/manual/cowboy.set_env/index.html | 124 +- .../2.4/manual/cowboy.start_clear/index.html | 159 +- .../cowboy/2.4/manual/cowboy.start_tls/index.html | 165 +- .../2.4/manual/cowboy.stop_listener/index.html | 87 +- docs/en/cowboy/2.4/manual/cowboy/index.html | 135 +- docs/en/cowboy/2.4/manual/cowboy_app/index.html | 178 +- .../2.4/manual/cowboy_constraints.int/index.html | 92 +- .../manual/cowboy_constraints.nonempty/index.html | 90 +- .../2.4/manual/cowboy_constraints/index.html | 85 +- .../2.4/manual/cowboy_handler.terminate/index.html | 115 +- .../en/cowboy/2.4/manual/cowboy_handler/index.html | 108 +- docs/en/cowboy/2.4/manual/cowboy_http/index.html | 321 +- docs/en/cowboy/2.4/manual/cowboy_http2/index.html | 279 +- docs/en/cowboy/2.4/manual/cowboy_loop/index.html | 140 +- .../cowboy/2.4/manual/cowboy_middleware/index.html | 123 +- .../2.4/manual/cowboy_req.binding/index.html | 122 +- .../2.4/manual/cowboy_req.bindings/index.html | 82 +- .../2.4/manual/cowboy_req.body_length/index.html | 86 +- .../cowboy/2.4/manual/cowboy_req.cert/index.html | 108 +- .../cowboy_req.delete_resp_header/index.html | 94 +- .../2.4/manual/cowboy_req.has_body/index.html | 76 +- .../2.4/manual/cowboy_req.has_resp_body/index.html | 83 +- .../manual/cowboy_req.has_resp_header/index.html | 95 +- .../cowboy/2.4/manual/cowboy_req.header/index.html | 129 +- .../2.4/manual/cowboy_req.headers/index.html | 87 +- .../cowboy/2.4/manual/cowboy_req.host/index.html | 88 +- .../2.4/manual/cowboy_req.host_info/index.html | 84 +- .../cowboy/2.4/manual/cowboy_req.inform/index.html | 139 +- .../2.4/manual/cowboy_req.match_cookies/index.html | 134 +- .../2.4/manual/cowboy_req.match_qs/index.html | 134 +- .../cowboy/2.4/manual/cowboy_req.method/index.html | 102 +- .../2.4/manual/cowboy_req.parse_cookies/index.html | 94 +- .../2.4/manual/cowboy_req.parse_header/index.html | 359 +- .../2.4/manual/cowboy_req.parse_qs/index.html | 118 +- .../cowboy/2.4/manual/cowboy_req.path/index.html | 87 +- .../2.4/manual/cowboy_req.path_info/index.html | 84 +- .../cowboy/2.4/manual/cowboy_req.peer/index.html | 97 +- .../cowboy/2.4/manual/cowboy_req.port/index.html | 88 +- .../cowboy/2.4/manual/cowboy_req.push/index.html | 162 +- docs/en/cowboy/2.4/manual/cowboy_req.qs/index.html | 86 +- .../2.4/manual/cowboy_req.read_body/index.html | 165 +- .../2.4/manual/cowboy_req.read_part/index.html | 200 +- .../manual/cowboy_req.read_part_body/index.html | 150 +- .../cowboy_req.read_urlencoded_body/index.html | 140 +- .../cowboy/2.4/manual/cowboy_req.reply/index.html | 190 +- .../2.4/manual/cowboy_req.resp_header/index.html | 119 +- .../2.4/manual/cowboy_req.resp_headers/index.html | 75 +- .../cowboy/2.4/manual/cowboy_req.scheme/index.html | 93 +- .../2.4/manual/cowboy_req.set_resp_body/index.html | 151 +- .../manual/cowboy_req.set_resp_cookie/index.html | 189 +- .../manual/cowboy_req.set_resp_header/index.html | 129 +- .../manual/cowboy_req.set_resp_headers/index.html | 116 +- .../cowboy/2.4/manual/cowboy_req.sock/index.html | 83 +- .../2.4/manual/cowboy_req.stream_body/index.html | 129 +- .../2.4/manual/cowboy_req.stream_reply/index.html | 174 +- .../manual/cowboy_req.stream_trailers/index.html | 118 +- .../en/cowboy/2.4/manual/cowboy_req.uri/index.html | 199 +- .../2.4/manual/cowboy_req.version/index.html | 85 +- docs/en/cowboy/2.4/manual/cowboy_req/index.html | 556 +-- docs/en/cowboy/2.4/manual/cowboy_rest/index.html | 845 ++--- .../2.4/manual/cowboy_router.compile/index.html | 93 +- docs/en/cowboy/2.4/manual/cowboy_router/index.html | 117 +- docs/en/cowboy/2.4/manual/cowboy_static/index.html | 221 +- docs/en/cowboy/2.4/manual/cowboy_stream/index.html | 540 +-- .../cowboy/2.4/manual/cowboy_websocket/index.html | 370 +- .../cowboy/2.4/manual/http_status_codes/index.html | 267 +- docs/en/cowboy/2.4/manual/index.html | 178 +- docs/en/erlang.mk/1/guide/app/index.html | 752 ++-- docs/en/erlang.mk/1/guide/asciidoc/index.html | 107 +- docs/en/erlang.mk/1/guide/ci/index.html | 83 +- docs/en/erlang.mk/1/guide/common_test/index.html | 135 +- docs/en/erlang.mk/1/guide/compat/index.html | 97 +- docs/en/erlang.mk/1/guide/contributing/index.html | 150 +- docs/en/erlang.mk/1/guide/coverage/index.html | 4 +- docs/en/erlang.mk/1/guide/deps/index.html | 815 ++--- docs/en/erlang.mk/1/guide/dialyzer/index.html | 84 +- docs/en/erlang.mk/1/guide/edoc/index.html | 64 +- docs/en/erlang.mk/1/guide/escripts/index.html | 103 +- docs/en/erlang.mk/1/guide/eunit/index.html | 159 +- .../erlang.mk/1/guide/external_plugins/index.html | 178 +- .../1/guide/external_plugins_list/index.html | 83 +- .../erlang.mk/1/guide/getting_started/index.html | 422 +-- docs/en/erlang.mk/1/guide/history/index.html | 69 +- docs/en/erlang.mk/1/guide/index.html | 184 +- docs/en/erlang.mk/1/guide/installation/index.html | 204 +- docs/en/erlang.mk/1/guide/kerl/index.html | 88 +- docs/en/erlang.mk/1/guide/limitations/index.html | 51 +- docs/en/erlang.mk/1/guide/overview/index.html | 102 +- docs/en/erlang.mk/1/guide/ports/index.html | 218 +- docs/en/erlang.mk/1/guide/releases/index.html | 242 +- docs/en/erlang.mk/1/guide/sfx/index.html | 63 +- docs/en/erlang.mk/1/guide/shell/index.html | 68 +- docs/en/erlang.mk/1/guide/sphinx/index.html | 147 +- docs/en/erlang.mk/1/guide/triq/index.html | 45 +- docs/en/erlang.mk/1/guide/updating/index.html | 107 +- docs/en/erlang.mk/1/guide/why/index.html | 92 +- docs/en/erlang.mk/1/guide/xref/index.html | 4 +- docs/en/gun/1.0/guide/connect/index.html | 189 +- docs/en/gun/1.0/guide/http/index.html | 514 +-- docs/en/gun/1.0/guide/index.html | 34 +- docs/en/gun/1.0/guide/introduction/index.html | 54 +- docs/en/gun/1.0/guide/protocols/index.html | 362 +- docs/en/gun/1.0/guide/start/index.html | 55 +- docs/en/gun/1.0/guide/websocket/index.html | 142 +- docs/en/gun/1.0/manual/gun.await/index.html | 210 +- docs/en/gun/1.0/manual/gun.await_body/index.html | 156 +- docs/en/gun/1.0/manual/gun.await_up/index.html | 123 +- docs/en/gun/1.0/manual/gun.cancel/index.html | 107 +- docs/en/gun/1.0/manual/gun.close/index.html | 75 +- docs/en/gun/1.0/manual/gun.data/index.html | 130 +- docs/en/gun/1.0/manual/gun.delete/index.html | 144 +- docs/en/gun/1.0/manual/gun.flush/index.html | 99 +- docs/en/gun/1.0/manual/gun.get/index.html | 150 +- docs/en/gun/1.0/manual/gun.head/index.html | 157 +- docs/en/gun/1.0/manual/gun.info/index.html | 86 +- docs/en/gun/1.0/manual/gun.open/index.html | 123 +- docs/en/gun/1.0/manual/gun.open_unix/index.html | 100 +- docs/en/gun/1.0/manual/gun.options/index.html | 144 +- docs/en/gun/1.0/manual/gun.patch/index.html | 197 +- docs/en/gun/1.0/manual/gun.post/index.html | 193 +- docs/en/gun/1.0/manual/gun.put/index.html | 192 +- docs/en/gun/1.0/manual/gun.request/index.html | 179 +- docs/en/gun/1.0/manual/gun.ws_send/index.html | 107 +- docs/en/gun/1.0/manual/gun.ws_upgrade/index.html | 171 +- docs/en/gun/1.0/manual/gun/index.html | 517 +-- docs/en/gun/1.0/manual/gun_app/index.html | 69 +- docs/en/gun/1.0/manual/gun_data/index.html | 130 +- docs/en/gun/1.0/manual/gun_down/index.html | 145 +- docs/en/gun/1.0/manual/gun_error/index.html | 118 +- docs/en/gun/1.0/manual/gun_inform/index.html | 123 +- docs/en/gun/1.0/manual/gun_push/index.html | 161 +- docs/en/gun/1.0/manual/gun_response/index.html | 134 +- docs/en/gun/1.0/manual/gun_trailers/index.html | 113 +- docs/en/gun/1.0/manual/gun_up/index.html | 101 +- docs/en/gun/1.0/manual/gun_upgrade/index.html | 125 +- docs/en/gun/1.0/manual/gun_ws/index.html | 110 +- docs/en/gun/1.0/manual/index.html | 69 +- docs/en/ranch/1.2/guide/embedded/index.html | 60 +- docs/en/ranch/1.2/guide/index.html | 46 +- docs/en/ranch/1.2/guide/internals/index.html | 105 +- docs/en/ranch/1.2/guide/introduction/index.html | 33 +- docs/en/ranch/1.2/guide/listeners/index.html | 347 +- docs/en/ranch/1.2/guide/parsers/index.html | 140 +- docs/en/ranch/1.2/guide/protocols/index.html | 183 +- docs/en/ranch/1.2/guide/ssl_auth/index.html | 188 +- docs/en/ranch/1.2/guide/transports/index.html | 229 +- docs/en/ranch/1.2/manual/index.html | 36 +- docs/en/ranch/1.2/manual/ranch/index.html | 570 +-- docs/en/ranch/1.2/manual/ranch_app/index.html | 44 +- docs/en/ranch/1.2/manual/ranch_protocol/index.html | 90 +- docs/en/ranch/1.2/manual/ranch_ssl/index.html | 479 +-- docs/en/ranch/1.2/manual/ranch_tcp/index.html | 323 +- .../en/ranch/1.2/manual/ranch_transport/index.html | 672 +--- docs/en/ranch/1.3/guide/embedded/index.html | 60 +- docs/en/ranch/1.3/guide/index.html | 46 +- docs/en/ranch/1.3/guide/internals/index.html | 105 +- docs/en/ranch/1.3/guide/introduction/index.html | 36 +- docs/en/ranch/1.3/guide/listeners/index.html | 416 +-- docs/en/ranch/1.3/guide/parsers/index.html | 140 +- docs/en/ranch/1.3/guide/protocols/index.html | 140 +- docs/en/ranch/1.3/guide/ssl_auth/index.html | 188 +- docs/en/ranch/1.3/guide/transports/index.html | 218 +- docs/en/ranch/1.3/manual/index.html | 36 +- docs/en/ranch/1.3/manual/ranch/index.html | 758 ++-- docs/en/ranch/1.3/manual/ranch_app/index.html | 41 +- docs/en/ranch/1.3/manual/ranch_protocol/index.html | 90 +- docs/en/ranch/1.3/manual/ranch_ssl/index.html | 531 +-- docs/en/ranch/1.3/manual/ranch_tcp/index.html | 334 +- .../en/ranch/1.3/manual/ranch_transport/index.html | 672 +--- docs/en/ranch/1.4/guide/embedded/index.html | 60 +- docs/en/ranch/1.4/guide/index.html | 46 +- docs/en/ranch/1.4/guide/internals/index.html | 105 +- docs/en/ranch/1.4/guide/introduction/index.html | 36 +- docs/en/ranch/1.4/guide/listeners/index.html | 442 +-- docs/en/ranch/1.4/guide/parsers/index.html | 140 +- docs/en/ranch/1.4/guide/protocols/index.html | 140 +- docs/en/ranch/1.4/guide/ssl_auth/index.html | 188 +- docs/en/ranch/1.4/guide/transports/index.html | 218 +- docs/en/ranch/1.4/manual/index.html | 36 +- docs/en/ranch/1.4/manual/ranch/index.html | 771 ++-- docs/en/ranch/1.4/manual/ranch_app/index.html | 41 +- docs/en/ranch/1.4/manual/ranch_protocol/index.html | 90 +- docs/en/ranch/1.4/manual/ranch_ssl/index.html | 531 +-- docs/en/ranch/1.4/manual/ranch_tcp/index.html | 334 +- .../en/ranch/1.4/manual/ranch_transport/index.html | 672 +--- docs/en/ranch/1.5/guide/embedded.asciidoc | 48 + docs/en/ranch/1.5/guide/embedded/index.html | 184 + docs/en/ranch/1.5/guide/index.html | 156 + docs/en/ranch/1.5/guide/internals.asciidoc | 94 + docs/en/ranch/1.5/guide/internals/index.html | 184 + docs/en/ranch/1.5/guide/introduction.asciidoc | 28 + docs/en/ranch/1.5/guide/introduction/index.html | 168 + docs/en/ranch/1.5/guide/listeners.asciidoc | 320 ++ docs/en/ranch/1.5/guide/listeners/index.html | 367 ++ docs/en/ranch/1.5/guide/parsers.asciidoc | 92 + docs/en/ranch/1.5/guide/parsers/index.html | 223 ++ docs/en/ranch/1.5/guide/protocols.asciidoc | 99 + docs/en/ranch/1.5/guide/protocols/index.html | 230 ++ docs/en/ranch/1.5/guide/ssl_auth.asciidoc | 120 + docs/en/ranch/1.5/guide/ssl_auth/index.html | 236 ++ docs/en/ranch/1.5/guide/transports.asciidoc | 161 + docs/en/ranch/1.5/guide/transports/index.html | 261 ++ docs/en/ranch/1.5/manual/index.html | 152 + docs/en/ranch/1.5/manual/ranch/index.html | 364 ++ docs/en/ranch/1.5/manual/ranch_app/index.html | 150 + docs/en/ranch/1.5/manual/ranch_protocol/index.html | 165 + docs/en/ranch/1.5/manual/ranch_ssl/index.html | 306 ++ docs/en/ranch/1.5/manual/ranch_tcp/index.html | 259 ++ .../en/ranch/1.5/manual/ranch_transport/index.html | 363 ++ docs/index.html | 15 +- docs/index.xml | 3634 +++++++++++-------- donate/index.html | 46 +- index.html | 45 +- index.xml | 3799 +++++++++++--------- services/index.html | 159 +- sitemap.xml | 64 + slogan/index.html | 5 +- talks/index.html | 10 +- 664 files changed, 42568 insertions(+), 84089 deletions(-) create mode 100644 docs/en/ranch/1.5/guide/embedded.asciidoc create mode 100644 docs/en/ranch/1.5/guide/embedded/index.html create mode 100644 docs/en/ranch/1.5/guide/index.html create mode 100644 docs/en/ranch/1.5/guide/internals.asciidoc create mode 100644 docs/en/ranch/1.5/guide/internals/index.html create mode 100644 docs/en/ranch/1.5/guide/introduction.asciidoc create mode 100644 docs/en/ranch/1.5/guide/introduction/index.html create mode 100644 docs/en/ranch/1.5/guide/listeners.asciidoc create mode 100644 docs/en/ranch/1.5/guide/listeners/index.html create mode 100644 docs/en/ranch/1.5/guide/parsers.asciidoc create mode 100644 docs/en/ranch/1.5/guide/parsers/index.html create mode 100644 docs/en/ranch/1.5/guide/protocols.asciidoc create mode 100644 docs/en/ranch/1.5/guide/protocols/index.html create mode 100644 docs/en/ranch/1.5/guide/ssl_auth.asciidoc create mode 100644 docs/en/ranch/1.5/guide/ssl_auth/index.html create mode 100644 docs/en/ranch/1.5/guide/transports.asciidoc create mode 100644 docs/en/ranch/1.5/guide/transports/index.html create mode 100644 docs/en/ranch/1.5/manual/index.html create mode 100644 docs/en/ranch/1.5/manual/ranch/index.html create mode 100644 docs/en/ranch/1.5/manual/ranch_app/index.html create mode 100644 docs/en/ranch/1.5/manual/ranch_protocol/index.html create mode 100644 docs/en/ranch/1.5/manual/ranch_ssl/index.html create mode 100644 docs/en/ranch/1.5/manual/ranch_tcp/index.html create mode 100644 docs/en/ranch/1.5/manual/ranch_transport/index.html diff --git a/.gitignore b/.gitignore index 6fd45092..0bcfec03 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ _build/content/docs +_build/deps _build/static/docs _build/tmp diff --git a/_build/Makefile b/_build/Makefile index 0e8d4776..83a9ecf9 100644 --- a/_build/Makefile +++ b/_build/Makefile @@ -2,11 +2,16 @@ PROJECTS = $(sort $(notdir $(basename $(wildcard data/projects/*.toml)))) -all: docs - hugo --theme=ninenines -d .. +all: $(CURDIR)/deps/asciideck docs + PATH=$(CURDIR)/deps/asciideck/scripts:$(PATH) hugo --theme=ninenines -d .. -server: - hugo server --theme=ninenines +server: $(CURDIR)/deps/asciideck + PATH=$(CURDIR)/deps/asciideck/scripts:$(PATH) hugo server --theme=ninenines + +$(CURDIR)/deps/asciideck: + mkdir -p $(CURDIR)/deps + git clone git@github.com:ninenines/asciideck.git $(CURDIR)/deps/asciideck + $(MAKE) -C $(CURDIR)/deps/asciideck clean: DOC_FILES = $(filter-out static/docs/en/cowboy/1.0/guide,$(wildcard static/docs/en/*/*/guide)) clean: OUTPUT_FILES = $(filter-out ../_build,$(wildcard ../*)) diff --git a/_build/themes/ninenines/layouts/index.html b/_build/themes/ninenines/layouts/index.html index e37230a9..ba5a2c4f 100644 --- a/_build/themes/ninenines/layouts/index.html +++ b/_build/themes/ninenines/layouts/index.html @@ -57,13 +57,13 @@
-
+
{{ range $.Site.Pages }} {{ if eq .RelPermalink "/slogan/" }} {{ .Content}} {{ end }} {{ end }} -
+
diff --git a/articles/cowboy-2.0.0-pre.4/index.html b/articles/cowboy-2.0.0-pre.4/index.html index 57e493e3..4eb8dee9 100644 --- a/articles/cowboy-2.0.0-pre.4/index.html +++ b/articles/cowboy-2.0.0-pre.4/index.html @@ -69,105 +69,44 @@

-

Cowboy 2.0.0-pre.4 has been released!

-

This is the new recommended version of Cowboy. -While I would not recommend putting it in production -just yet, I do recommend you start writing new -applications with this Cowboy version.

-

The most significant changes in the pre-release are:

-
-

The manual received a lot of love. It now has one page per -function with a detailed description, arguments list, return -value, changelog and examples. It also links to the other -relevant manual pages: https://ninenines.eu/docs/en/cowboy/2.0/manual/

-

I am quite proud of the manual right now. While more -improvements can be made, what we have now is way better -than before. Feedback for further improvements is welcome!

-

This is a significant step toward Cowboy 2.0. Almost all -the breaking changes are in. A few more pre-releases are -planned and will be released on a weekly basis (with exceptions).

-

Cowboy is now tested and supported with Erlang/OTP 18.0 or above -on Arch Linux, FreeBSD, OSX, Ubuntu and Windows 7. Contact me -if you can provide permanent access to another platform for the -purposes of testing.

-

Cowboy is now available from four locations:

-
+

The manual received a lot of love. It now has one page per function with a detailed description, arguments list, return value, changelog and examples. It also links to the other relevant manual pages: https://ninenines.eu/docs/en/cowboy/2.0/manual/

+

I am quite proud of the manual right now. While more improvements can be made, what we have now is way better than before. Feedback for further improvements is welcome!

+

This is a significant step toward Cowboy 2.0. Almost all the breaking changes are in. A few more pre-releases are planned and will be released on a weekly basis (with exceptions).

+

Cowboy is now tested and supported with Erlang/OTP 18.0 or above on Arch Linux, FreeBSD, OSX, Ubuntu and Windows 7. Contact me if you can provide permanent access to another platform for the purposes of testing.

+

Cowboy is now available from four locations:

+
-

They are updated at the same time so there is no real difference.

-

Cowboy 2.0 will be released once all the breaking changes -are completed and the temporarily removed features are -added back.

-

Thanks for your patience. I know it took a long time.

-
-

Half-price on all donations because I need a new hat:

+ +

They are updated at the same time so there is no real difference.

+

Cowboy 2.0 will be released once all the breaking changes are completed and the temporarily removed features are added back.

+

Thanks for your patience. I know it took a long time.

+

Half-price on all donations because I need a new hat:

diff --git a/articles/cowboy-2.0.0-rc.1/index.html b/articles/cowboy-2.0.0-rc.1/index.html index 03f722c6..d34de49d 100644 --- a/articles/cowboy-2.0.0-rc.1/index.html +++ b/articles/cowboy-2.0.0-rc.1/index.html @@ -69,62 +69,26 @@

-

Cowboy 2.0.0-rc.1 has been released!

-

This is the new recommended version of Cowboy. -Its API should not change before release. While -you probably should not use it in production yet, -many do successfully. Use at your own risk.

-

The plan is to have a new RC version every couple -weeks until the summer ends or later if there are -still blocking issues open. Only issues that can’t -be fixed without making breaking changes to the -interface may block the release.

-

Numerous changes were made since Cowboy 1.0. The -one most people care about is probably HTTP/2, but -it’s most likely not the only one worthwhile. The -full list of changes (excluding types) can be found -in the user guide chapter -Migrating from Cowboy 1.0 to 2.0.

-

As this is not the full release just yet, please pay -extra attention to details and report anything -suspicious you find.

-

There are still some tests failing. Most of those are -related to standards that are not being followed perfectly -just yet. Some of those will probably not be fixed before -Cowboy 2.0 is released. They are edge cases and should not -prevent interoperability.

-

The manual received a lot of love. It now has one page per -function with a detailed description, arguments list, return -value, changelog and examples. It also links to the other -relevant manual pages: https://ninenines.eu/docs/en/cowboy/2.0/manual/

-

Cowboy is now tested and supported with Erlang/OTP 19.0 or above -on Arch Linux, FreeBSD, OSX, Ubuntu and Windows 7. Contact me -if you can provide permanent access to another platform for the -purposes of testing.

-

Cowboy is now available from four locations:

-
    -
  • -

    -https://git.ninenines.eu/cowboy.git -

    +

    Cowboy 2.0.0-rc.1 has been released!

    +

    This is the new recommended version of Cowboy. Its API should not change before release. While you probably should not use it in production yet, many do successfully. Use at your own risk.

    +

    The plan is to have a new RC version every couple weeks until the summer ends or later if there are still blocking issues open. Only issues that can't be fixed without making breaking changes to the interface may block the release.

    +

    Numerous changes were made since Cowboy 1.0. The one most people care about is probably HTTP/2, but it's most likely not the only one worthwhile. The full list of changes (excluding types) can be found in the user guide chapter Migrating from Cowboy 1.0 to 2.0.

    +

    As this is not the full release just yet, please pay extra attention to details and report anything suspicious you find.

    +

    There are still some tests failing. Most of those are related to standards that are not being followed perfectly just yet. Some of those will probably not be fixed before Cowboy 2.0 is released. They are edge cases and should not prevent interoperability.

    +

    The manual received a lot of love. It now has one page per function with a detailed description, arguments list, return value, changelog and examples. It also links to the other relevant manual pages: https://ninenines.eu/docs/en/cowboy/2.0/manual/

    +

    Cowboy is now tested and supported with Erlang/OTP 19.0 or above on Arch Linux, FreeBSD, OSX, Ubuntu and Windows 7. Contact me if you can provide permanent access to another platform for the purposes of testing.

    +

    Cowboy is now available from four locations:

    +
-

They are updated at the same time so there is no real difference.

+ +

They are updated at the same time so there is no real difference.

+ diff --git a/articles/cowboy-2.0.0-rc.2/index.html b/articles/cowboy-2.0.0-rc.2/index.html index 02af2eed..1e009267 100644 --- a/articles/cowboy-2.0.0-rc.2/index.html +++ b/articles/cowboy-2.0.0-rc.2/index.html @@ -69,41 +69,19 @@

-

Cowboy 2.0.0-rc.2 has been released!

-

This is the new recommended version of Cowboy. -Its API should not change before release. While -you probably should not use it in production yet, -many do successfully. Use at your own risk.

-

This new version contains fixes for the following -issues:

-
    -
  • -

    -HTTP/2 server push was using the wrong header - compression context. -

    +

    Cowboy 2.0.0-rc.2 has been released!

    +

    This is the new recommended version of Cowboy. Its API should not change before release. While you probably should not use it in production yet, many do successfully. Use at your own risk.

    +

    This new version contains fixes for the following issues:

    +
    • HTTP/2 server push was using the wrong header compression context.
    • -
    • -

      -HTTP/2 flow control could end up queueing data - in the wrong order when resuming the sending of - data. -

      +
    • HTTP/2 flow control could end up queueing data in the wrong order when resuming the sending of data.
    • -
    • -

      -The shutdown timeout was not implemented - and request processes could be killed too quickly. -

      +
    • The shutdown timeout was not implemented and request processes could be killed too quickly.
    • -
-

What else is new in Cowboy 2.0? Check the -rc.1 announcement.

-

Please test this new release candidate and provide -feedback! The best place to provide feedback is via -tickets. Do not hesitate to open a ticket or bring -an existing ticket to my attention to get it resolved -before 2.0.

+ +

What else is new in Cowboy 2.0? Check the rc.1 announcement.

+

Please test this new release candidate and provide feedback! The best place to provide feedback is via tickets. Do not hesitate to open a ticket or bring an existing ticket to my attention to get it resolved before 2.0.

+ diff --git a/articles/cowboy-2.0.0/index.html b/articles/cowboy-2.0.0/index.html index 61ef2dae..bd4ee760 100644 --- a/articles/cowboy-2.0.0/index.html +++ b/articles/cowboy-2.0.0/index.html @@ -69,54 +69,25 @@

-

Cowboy 2.0.0 has been released!

-

This is the new stable version of Cowboy. There -are no new releases planned for the 1.x version -of Cowboy.

-

The highlights from the release are:

-
    -
  • -

    -HTTP/2 support! -

    +

    Cowboy 2.0.0 has been released!

    +

    This is the new stable version of Cowboy. There are no new releases planned for the 1.x version of Cowboy.

    +

    The highlights from the release are:

    +
    • HTTP/2 support!
    • -
    • -

      -Websocket compression! -

      +
    • Websocket compression!
    • -
    • -

      -Much simpler, cleaner interface. No more weird - errors just because you discard the Req object. -

      +
    • Much simpler, cleaner interface. No more weird errors just because you discard the Req object.
    • -
    • -

      -A new low-level interface that receives all events - from every set of request and response. This - replaces the awkward hooks from 1.0. -

      +
    • A new low-level interface that receives all events from every set of request and response. This replaces the awkward hooks from 1.0.
    • -
    • -

      -A much more detailed manual ! -

      +
    • A much more detailed manual !
    • -
-

A more complete list of changes can be found in the -migration guide: -Migrating from Cowboy 1.0 to 2.0.

-

There are two planned feature releases after 2.0. -Some features were temporarily removed and will be -added back in 2.1. In 2.2 new features will be added -to allow users to support the gRPC protocol. Full -details in tickets.

-

Feeling good about this release? Send money one-time -or monthly via BountySource. -Thanks in advance!

-

As usual, any feedback is appreciated, and any issues -should be reported by opening a ticket. Thanks!

+ +

A more complete list of changes can be found in the migration guide: Migrating from Cowboy 1.0 to 2.0.

+

There are two planned feature releases after 2.0. Some features were temporarily removed and will be added back in 2.1. In 2.2 new features will be added to allow users to support the gRPC protocol. Full details in tickets.

+

Feeling good about this release? Send money one-time or monthly via BountySource. Thanks in advance!

+

As usual, any feedback is appreciated, and any issues should be reported by opening a ticket. Thanks!

+ diff --git a/articles/cowboy-2.1.0/index.html b/articles/cowboy-2.1.0/index.html index 69036c0e..7246b0c3 100644 --- a/articles/cowboy-2.1.0/index.html +++ b/articles/cowboy-2.1.0/index.html @@ -69,48 +69,22 @@

-

Cowboy 2.1.0 has been released!

-

This release focused on adding features that were temporarily -removed during the 2.0 release process:

-
    -
  • -

    -The client TLS certificate can now be obtained. -

    +

    Cowboy 2.1.0 has been released!

    +

    This release focused on adding features that were temporarily removed during the 2.0 release process:

    +
    • The client TLS certificate can now be obtained.
    • -
    • -

      -The 100 Continue response is now sent automatically - again when necessary. -

      +
    • The 100 Continue response is now sent automatically again when necessary.
    • -
    • -

      -NEW: It is now possible to send informational - responses (1XX) directly from user code via the - cowboy_req:inform/2,3 functions. -

      +
    • NEW: It is now possible to send informational responses (1XX) directly from user code via the cowboy_req:inform/2,3 functions.
    • -
    • -

      -NEW: cowboy_rest handlers can now switch to any - other type of handler from almost any callback. This - is especially useful to switch to cowboy_loop to - stream the request or response body. -

      +
    • NEW: cowboy_rest handlers can now switch to any other type of handler from almost any callback. This is especially useful to switch to cowboy_loop to stream the request or response body.
    • -
-

A number of bugs have also been fixed. A more complete -list of changes can be found in the migration guide: -Migrating from Cowboy 2.0 to 2.1.

-

The next release will see the added support for trailers, -which are necessary for implementing the gRPC protocol.

-

You can donate to this project via -BountySource -because I need to eat snacks when I write code. -Thanks in advance!

-

As usual, any feedback is appreciated, and any issues -should be reported by opening a ticket. Thanks!

+ +

A number of bugs have also been fixed. A more complete list of changes can be found in the migration guide: Migrating from Cowboy 2.0 to 2.1.

+

The next release will see the added support for trailers, which are necessary for implementing the gRPC protocol.

+

You can donate to this project via BountySource because I need to eat snacks when I write code. Thanks in advance!

+

As usual, any feedback is appreciated, and any issues should be reported by opening a ticket. Thanks!

+ diff --git a/articles/cowboy-2.2.0/index.html b/articles/cowboy-2.2.0/index.html index 06608ccc..8272096d 100644 --- a/articles/cowboy-2.2.0/index.html +++ b/articles/cowboy-2.2.0/index.html @@ -69,49 +69,20 @@

-

Cowboy 2.2.0 has been released!

-

This release focused on adding features required for writing -gRPC servers and on completing test suites for the core -HTTP RFCs.

-
    -
  • -

    -The cowboy_req:stream_trailers/2 function has been - added. It terminates the streamed response by adding - some trailer field values. This feature is required - for gRPC. -

    +

    Cowboy 2.2.0 has been released!

    +

    This release focused on adding features required for writing gRPC servers and on completing test suites for the core HTTP RFCs.

    +
    • The cowboy_req:stream_trailers/2 function has been added. It terminates the streamed response by adding some trailer field values. This feature is required for gRPC.
    • -
    • -

      -The max_skip_body_length option was added. It controls - how much of the request body we are willing to skip - to get to the next request for HTTP/1.1 keep-alive - connections. -

      +
    • The max_skip_body_length option was added. It controls how much of the request body we are willing to skip to get to the next request for HTTP/1.1 keep-alive connections.
    • -
    • -

      -The CONNECT and TRACE methods have been disabled - entirely. They are currently not implemented and - their behavior is very specific (unlike most other - methods) so it is safer to prevent their use. -

      +
    • The CONNECT and TRACE methods have been disabled entirely. They are currently not implemented and their behavior is very specific (unlike most other methods) so it is safer to prevent their use.
    • -
-

Many bugs have also been fixed. A more complete -list of changes can be found in the migration guide: -Migrating from Cowboy 2.1 to 2.2.

-

The next two releases will tentatively focus on improving -the support for cookies and CORS, but I’m open to suggestions. -If there is a pain point in Cowboy 2.2 I would love to hear -about it.

-

You can donate to this project via -BountySource -because I need to eat snacks when I write code. -Thanks in advance!

-

As usual, any feedback is appreciated, and any issues -should be reported by opening a ticket. Thanks!

+ +

Many bugs have also been fixed. A more complete list of changes can be found in the migration guide: Migrating from Cowboy 2.1 to 2.2.

+

The next two releases will tentatively focus on improving the support for cookies and CORS, but I'm open to suggestions. If there is a pain point in Cowboy 2.2 I would love to hear about it.

+

You can donate to this project via BountySource because I need to eat snacks when I write code. Thanks in advance!

+

As usual, any feedback is appreciated, and any issues should be reported by opening a ticket. Thanks!

+ diff --git a/articles/cowboy-2.3.0/index.html b/articles/cowboy-2.3.0/index.html index 439241cc..91b6e3c3 100644 --- a/articles/cowboy-2.3.0/index.html +++ b/articles/cowboy-2.3.0/index.html @@ -69,18 +69,12 @@

-

Cowboy 2.3.0 has been released!

-

This release focused on adding support for the functions -from the sys module for introspecting Cowboy processes.

-

Many bugs have also been fixed. A more complete -list of changes can be found in the migration guide: -Migrating from Cowboy 2.2 to 2.3.

-

You can donate to this project via -BountySource -because I need to eat snacks when I write code. -Thanks in advance!

-

As usual, feedback is appreciated, and issues -should be reported by opening a ticket. Thanks!

+

Cowboy 2.3.0 has been released!

+

This release focused on adding support for the functions from the sys module for introspecting Cowboy processes.

+

Many bugs have also been fixed. A more complete list of changes can be found in the migration guide: Migrating from Cowboy 2.2 to 2.3.

+

You can donate to this project via BountySource because I need to eat snacks when I write code. Thanks in advance!

+

As usual, feedback is appreciated, and issues should be reported by opening a ticket. Thanks!

+ diff --git a/articles/cowboy-2.4.0/index.html b/articles/cowboy-2.4.0/index.html index cae198b2..2c035ff8 100644 --- a/articles/cowboy-2.4.0/index.html +++ b/articles/cowboy-2.4.0/index.html @@ -69,34 +69,14 @@

-

Cowboy 2.4.0 has been released!

-

Numerous HTTP/2 options have been added to control -the HTTP/2 SETTINGS and general behavior of HTTP/2 -connections. The options for initial window sizes, -maximum frame sizes or compression table sizes -might be of interest for optimizing the performance -of HTTP/2 connections.

-

Experimental support for Websocket over HTTP/2 was -added. Note that browsers do not currently support -it. The only browser with partial support is Google -Chrome 67 (dev build) started with a specific flag. -As a result it’s disabled by default in Cowboy too.

-

All of Cowboy’s RFC7540 tests and all of the h2spec -test suite cases now pass. There are still parts -that are not implemented (the priority mechanisms -for example) and edge cases that are not covered, -however, so the HTTP/2 support can still be improved.

-

A complete -list of changes can be found in the migration guide: -Migrating from Cowboy 2.3 to 2.4.

-

You can donate to this project via -BountySource. -These funds are used to pay for additional servers for -testing. A new server was added this month and allows -me to test with additional Linux distributions Alpine, -CentOS and Debian. Thanks in advance!

-

As usual, feedback is appreciated, and issues or -questions should be sent via Github tickets. Thanks!

+

Cowboy 2.4.0 has been released!

+

Numerous HTTP/2 options have been added to control the HTTP/2 SETTINGS and general behavior of HTTP/2 connections. The options for initial window sizes, maximum frame sizes or compression table sizes might be of interest for optimizing the performance of HTTP/2 connections.

+

Experimental support for Websocket over HTTP/2 was added. Note that browsers do not currently support it. The only browser with partial support is Google Chrome 67 (dev build) started with a specific flag. As a result it's disabled by default in Cowboy too.

+

All of Cowboy's RFC7540 tests and all of the h2spec test suite cases now pass. There are still parts that are not implemented (the priority mechanisms for example) and edge cases that are not covered, however, so the HTTP/2 support can still be improved.

+

A complete list of changes can be found in the migration guide: Migrating from Cowboy 2.3 to 2.4.

+

You can donate to this project via BountySource. These funds are used to pay for additional servers for testing. A new server was added this month and allows me to test with additional Linux distributions Alpine, CentOS and Debian. Thanks in advance!

+

As usual, feedback is appreciated, and issues or questions should be sent via Github tickets. Thanks!

+ diff --git a/articles/cowboy2-qs/index.html b/articles/cowboy2-qs/index.html index d1424cfc..c34acbd9 100644 --- a/articles/cowboy2-qs/index.html +++ b/articles/cowboy2-qs/index.html @@ -69,155 +69,56 @@

-

Now that Cowboy 1.0 is out, I can spend some of my time thinking -about Cowboy 2.0 that will be released soon after Erlang/OTP 18.0. -This entry discusses the proposed changes to query string handling -in Cowboy.

-

Cowboy 2.0 will respond to user wishes by simplifying the interface -of the cowboy_req module. Users want two things: less -juggling with the Req variable, and more maps. Maps is the only -dynamic key/value data structure in Erlang that we can match directly -to extract values, allowing users to greatly simplify their code as -they don’t need to call functions to do everything anymore.

-

Query strings are a good candidate for maps. It’s a list of -key/values, so it’s pretty obvious we can win a lot by using maps. -However query strings have one difference with maps: they can have -duplicate keys.

-

How are we expected to handle duplicate keys? There’s no standard -behavior. It’s up to applications. And looking at what is done in -the wild, there’s no de facto standard either. While some ignore -duplicate keys (keeping the first or the last they find), others -require duplicate keys to end with [] to automatically -put the values in a list, or even worse, languages like PHP even -allow you to do things like key[something][other] and -create a deep structure for it. Finally some allow any key to have -duplicates and just gives you lists of key/values.

-

Cowboy so far had functions to retrieve query string values one -value at a time, and if there were duplicates it would return the -first it finds. It also has a function returning the entire list -with all duplicates, allowing you to filter it to get all of them, -and another function that returns the raw query string.

-

What are duplicates used for? Not that many things actually.

-

One use of duplicate keys is with HTML forms. It is common practice -to give all related checkboxes the same name so you get a list of -what’s been checked. When nothing is checked, nothing is sent at all, -the key is not in the list.

-

Another use of duplicate keys is when generating forms. A good -example of that would be a form that allows uploading any number -of files. When you add a file, client-side code adds another field -to the form. Repeat up to a certain limit.

-

And that’s about it. Of note is that HTML radio elements share -the same name too, but only one key/value is sent, so they are not -relevant here.

-

Normally this would be the part where I tell you how we solve -this elegantly. But I had doubts. Why? Because there’s no good -solutions to solving only this particular problem.

-

I then stopped thinking about duplicate keys for a minute and -started to think about the larger problem.

-

Query strings are input data. They take a particular form, -and may be sent as part of the URI or as part of the request -body. We have other kinds of input data. We have headers and -cookies and the request body in various forms. We also have -path segments in URIs.

-

What do you do with input data? Well you use it to do -something. But there is one thing that you almost always do -(and if you don’t, you really should): you validate it and -you map it into Erlang terms.

-

Cowboy left the user take care of validation and conversion -into Erlang terms so far. Rather, it left the user take care -of it everywhere except one place. Guess where? That’s right, -bindings.

-

If you define routes with bindings then you have the option -to provide constraints. Constraints can be used to do two things: -validate the data and convert it in a more appropriate term. For -example if you use the int constraint, Cowboy will -make sure the binding is an integer, and will replace the value -with the integer representation so that you can use it directly. -In this particular case it not only routes the URI, but also -validates and converts the bindings directly.

-

This is very relevant in the case of our duplicate keys, -because if we have a list with duplicates of a key, chances -are we want to convert that into a list of Erlang terms, and -also make sure that all the elements in this list are expected.

-

The answer to this particular problem is simple. We need a -function that will parse the query string and apply constraints. -But this is not all, there is one other problem to be solved.

-

The other problem is that for the user some keys are mandatory -and some are optional. Optional keys include the ones that -correspond to HTML checkboxes: if the key for one or more -checkbox is missing from the query string, we still want to -have an empty list in our map so we can easily match. Matching -maps is great, but not so much when values might be missing, -so we have to normalize this data a little.

-

This problem is solved by allowing a default value. If the -key is missing and a default exists, set it. If no default -exists, then the key was mandatory and we want to crash.

-

I therefore make a proposal for changing the query string -interface to three functions.

-

The first function already exists, it is cowboy_req:qs(Req) -and it returns only the query string binary. No more Req returned.

-

The second function is a renaming of cowboy_req:qs_vals(Req) -to something more explicit: cowboy_req:parse_qs(Req). -The new name implies that a parsing operation is done. It was implicit -and cached before. It will be explicit and not cached anymore now. -Again, no more Req returned.

-

The third function is the one I mentioned above. I think -the interface cowboy_req:match_qs(Req, Fields) is -most appropriate. It returns a normalized map that is the same -regardless of optional fields being provided with the request, -allowing for easy matching. It crashes if something went wrong. -Still no Req returned.

-

I feel that this three function interface provides everything -one would need to comfortably write applications. You can get -low level and get the query string directly; you can get a list -of key/value binaries without any additional processing and do it -on your own; or you can get a processed map that contains Erlang -terms ready to be used.

-

I strongly believe that by democratizing the constraints to -more than just bindings, but also to query string, cookies and -other key/values in Cowboy, we can allow the developer to quickly -and easily go from HTTP request to Erlang function calls. The -constraints are reusable functions that can serve as guards -against unwanted data, providing convenience in the process.

-

Your handlers will not look like an endless series of calls -to get and convert the input data, they will instead be just -one call at the beginning followed by the actual application -logic, thanks to constraints and maps.

-
-
-
handle(Req, State) ->
-    #{name:=Name, email:=Email, choices:=ChoicesList, remember_me:=RememberMe} =
-        cowboy_req:match_qs(Req, [
-            name, {email, email},
-            {choices, fun check_choices/1, []},
-            {remember_me, boolean, false}]),
-    save_choices(Name, Email, ChoicesList),
-    if RememberMe -> create_account(Name, Email); true -> ok end,
-    {ok, Req, State}.
+
handle(Req, State) ->
+    #{name:=Name, email:=Email, choices:=ChoicesList, remember_me:=RememberMe} =
+        cowboy_req:match_qs(Req, [
+            name, {email, email},
+            {choices, fun check_choices/1, []},
+            {remember_me, boolean, false}]),
+    save_choices(Name, Email, ChoicesList),
+    if RememberMe -> create_account(Name, Email); true -> ok end,
+    {ok, Req, State}.
+
+check_choices(<<"blue">>) -> {true, blue};
+check_choices(<<"red">>) -> {true, red};
+check_choices(_) -> false;
+
+

(Don't look too closely at the structure yet.)

+

As you can see in the above snippet, it becomes really easy to go from query string to values. You can also use the map directly as it is guaranteed to only contain the keys you specified, any extra key is not returned.

+

This would I believe be a huge step up as we can now focus on writing applications instead of translating HTTP calls. Cowboy can now take care of it.

+

And to conclude, this also solves our duplicate keys dilemma, as they now automatically become a list of binaries, and this list is then checked against constraints that will fail if they were not expecting a list. And in the example above, it even converts the values to atoms for easier manipulation.

+

As usual, feedback is more than welcome, and I apologize for the rocky structure of this post as it contains all the thoughts that went into this rather than just the conclusion.

-check_choices(<<"blue">>) -> {true, blue}; -check_choices(<<"red">>) -> {true, red}; -check_choices(_) -> false;
-

(Don’t look too closely at the structure yet.)

-

As you can see in the above snippet, it becomes really easy -to go from query string to values. You can also use the map -directly as it is guaranteed to only contain the keys you -specified, any extra key is not returned.

-

This would I believe be a huge step up as we can now -focus on writing applications instead of translating HTTP -calls. Cowboy can now take care of it.

-

And to conclude, this also solves our duplicate keys -dilemma, as they now automatically become a list of binaries, -and this list is then checked against constraints that -will fail if they were not expecting a list. And in the -example above, it even converts the values to atoms for -easier manipulation.

-

As usual, feedback is more than welcome, and I apologize -for the rocky structure of this post as it contains all the -thoughts that went into this rather than just the conclusion.

diff --git a/articles/dont-let-it-crash/index.html b/articles/dont-let-it-crash/index.html index 53226cc3..95da0f88 100644 --- a/articles/dont-let-it-crash/index.html +++ b/articles/dont-let-it-crash/index.html @@ -69,118 +69,31 @@

-

We have a specific mindset when writing Erlang -programs. We focus on the normal execution of the -program and don’t handle most of the errors that may -occur. We sometimes call this normal execution the -happy path.

-

The general pattern behind writing only for the -happy path, letting the VM catch errors (writing -them to a log for future consumption) and then -having a supervisor restart the processes that -failed from a clean state, has a name. We call it -let it crash; and it drives many of our design -decisions.

-

It’s a really great way to program and the results -are fantastic compared to most other programming -languages. And yet, let it crash barely convinced -anyone that they should use Erlang. Why would that -be?

-

You may already know that Cowboy is capable of -handling at least 2 million Websocket connections -on a single server. This is in large part thanks -to the capabilities of the VM. Still, 2 million -is good, much better than most other servers can -do.

-

Cowboy is not just a Websocket server; it’s also -an HTTP and HTTP/2 server, and it handles many -related features like long polling or the parsing -of most request headers.

-

Can you guess how large the Cowboy codebase is, -without looking at the source?

-

Do make sure you have a clear answer in your mind -before you go check.

-

Good, you are back. Now what were the results? If -I am correct, you overestimated the size of Cowboy. -Cowboy is in fact about five thousand lines of code. -You probably thought it was at least ten thousand. -About eighty percent of readers will have -overestimated the size of Cowboy. And you did only -because I mentioned it can handle millions of -Websocket connections.

-

Numerous studies show this effect. Just mentioning -the large number already prepared your mind to think -in that direction. Repeating the number made you -focus even more on it. Then the question asked for -a number, which ended up larger than the reality.

-

The same effect can be applied to negotiation for -example. You generally want to start by giving your -offer (and not let the other party initiate) and -you want to give a really large number first. You -can also prepare your customer by mentioning an even -larger number in the previous discussion.

-

And it’s not just numbers either. An experiment -showed that just by looking at an image of clouds, -customers of a pillow store were buying pillows -more comfortable (and more expensive) than those -who didn’t see that image.

-

This is the power of associations. It is covered in -much larger detail in the books -Influence -and -Pre-suasion. -I highly recommend reading those and applying what -you learn to your daily life. I’m definitely not -a professional psychologist so take this post with -a grain of salt.

-

When selling Erlang, whether we are selling it to -a customer or trying to convince a developer friend -to start using it, we often talk about how Erlang -lets you sleep at night, that it is auto healing -and always gets fantastic uptimes.

-

And then we talk about let it crash.

-

And we describe what it means.

-

We might as well just say that Erlang crashes a lot -and then take the door. It would have the same effect. -It doesn’t even stop at programs crashing. You know -what else crashes? Cars, planes, trains. Often with -disastrous consequences. Is that really the message -we want to convey?

-

They even printed it on a t-shirt! -Keep calm and let it crash. It’s the kind of t-shirt -you probably shouldn’t wear in an airport, and for good -reasons. A few people did, then realized what they were -wearing and were not too smug about it.

-

And yet this is how we sell Erlang.

-

A better way would be to focus on the positives, of -course, but also to make sure that those positives -are phrased in a way that prevents bad associations -to be formed in people’s minds.

-

Instead of let it crash, you can say that Erlang -has auto healing mechanisms. Healing is a good -thing and accurately describes what happens in the -system.

-

Should you need to go into more details, you will -probably want to avoid recover from crashes and -instead say recover from exceptions. Exceptions -are a pretty neutral word and, should you explain -what you mean by that, you can talk about exceptions -that occur for reasons unrelated to Erlang, like -hardware failure or network instability.

-

The trick is to always use positive words and -phrases to describe Erlang, and to use external -factors to explain how Erlang deals with failures. -Never mention the failures internal to Erlang -systems unless you are asked specifically, in -which case you can say that the auto healing -applies to all exceptions.

-

The let it crash philosophy is great when -learning Erlang or when writing fault-tolerant -systems. But it’s not going to convince anyone -to use it unless they were already looking for -it.

-

Do you like this post? Tell me on Twitter. I might -make more.

+

We have a specific mindset when writing Erlang programs. We focus on the normal execution of the program and don't handle most of the errors that may occur. We sometimes call this normal execution the happy path.

+

The general pattern behind writing only for the happy path, letting the VM catch errors (writing them to a log for future consumption) and then having a supervisor restart the processes that failed from a clean state, has a name. We call it let it crash; and it drives many of our design decisions.

+

It's a really great way to program and the results are fantastic compared to most other programming languages. And yet, let it crash barely convinced anyone that they should use Erlang. Why would that be?

+

You may already know that Cowboy is capable of handling at least 2 million Websocket connections on a single server. This is in large part thanks to the capabilities of the VM. Still, 2 million is good, much better than most other servers can do.

+

Cowboy is not just a Websocket server; it's also an HTTP and HTTP/2 server, and it handles many related features like long polling or the parsing of most request headers.

+

Can you guess how large the Cowboy codebase is, without looking at the source?

+

Do make sure you have a clear answer in your mind before you go check.

+

Good, you are back. Now what were the results? If I am correct, you overestimated the size of Cowboy. Cowboy is in fact about five thousand lines of code. You probably thought it was at least ten thousand. About eighty percent of readers will have overestimated the size of Cowboy. And you did only because I mentioned it can handle millions of Websocket connections.

+

Numerous studies show this effect. Just mentioning the large number already prepared your mind to think in that direction. Repeating the number made you focus even more on it. Then the question asked for a number, which ended up larger than the reality.

+

The same effect can be applied to negotiation for example. You generally want to start by giving your offer (and not let the other party initiate) and you want to give a really large number first. You can also prepare your customer by mentioning an even larger number in the previous discussion.

+

And it's not just numbers either. An experiment showed that just by looking at an image of clouds, customers of a pillow store were buying pillows more comfortable (and more expensive) than those who didn't see that image.

+

This is the power of associations. It is covered in much larger detail in the books Influence and Pre-suasion. I highly recommend reading those and applying what you learn to your daily life. I'm definitely not a professional psychologist so take this post with a grain of salt.

+

When selling Erlang, whether we are selling it to a customer or trying to convince a developer friend to start using it, we often talk about how Erlang lets you sleep at night, that it is auto healing and always gets fantastic uptimes.

+

And then we talk about let it crash.

+

And we describe what it means.

+

We might as well just say that Erlang crashes a lot and then take the door. It would have the same effect. It doesn't even stop at programs crashing. You know what else crashes? Cars, planes, trains. Often with disastrous consequences. Is that really the message we want to convey?

+

They even printed it on a t-shirt! Keep calm and let it crash. It's the kind of t-shirt you probably shouldn't wear in an airport, and for good reasons. A few people did, then realized what they were wearing and were not too smug about it.

+

And yet this is how we sell Erlang.

+

A better way would be to focus on the positives, of course, but also to make sure that those positives are phrased in a way that prevents bad associations to be formed in people's minds.

+

Instead of let it crash, you can say that Erlang has auto healing mechanisms. Healing is a good thing and accurately describes what happens in the system.

+

Should you need to go into more details, you will probably want to avoid recover from crashes and instead say recover from exceptions. Exceptions are a pretty neutral word and, should you explain what you mean by that, you can talk about exceptions that occur for reasons unrelated to Erlang, like hardware failure or network instability.

+

The trick is to always use positive words and phrases to describe Erlang, and to use external factors to explain how Erlang deals with failures. Never mention the failures internal to Erlang systems unless you are asked specifically, in which case you can say that the auto healing applies to all exceptions.

+

The let it crash philosophy is great when learning Erlang or when writing fault-tolerant systems. But it's not going to convince anyone to use it unless they were already looking for it.

+

Do you like this post? Tell me on Twitter. I might make more.

+ diff --git a/articles/erlang-scalability/index.html b/articles/erlang-scalability/index.html index 2df4fd1c..df467034 100644 --- a/articles/erlang-scalability/index.html +++ b/articles/erlang-scalability/index.html @@ -69,140 +69,43 @@

-

I would like to share some experience and theories on -Erlang scalability.

-

This will be in the form of a series of hints, which -may or may not be accompanied with explanations as to why -things are this way, or how they improve or reduce the scalability -of a system. I will try to do my best to avoid giving falsehoods, -even if that means a few things won’t be explained.

-
+

I would like to share some experience and theories on Erlang scalability.

+

This will be in the form of a series of hints, which may or may not be accompanied with explanations as to why things are this way, or how they improve or reduce the scalability of a system. I will try to do my best to avoid giving falsehoods, even if that means a few things won't be explained.

NIFs

-
-

NIFs are considered harmful. I don’t know any single NIF-based -library that I would recommend. That doesn’t mean they should -all be avoided, just that if you’re going to want your system to -scale, you probably shouldn’t use a NIF.

-

A common case for using NIFs is JSON processing. The problem -is that JSON is a highly inefficient data structure (similar -in inefficiency to XML, although perhaps not as bad). If you can -avoid using JSON, you probably should. MessagePack can replace -it in many situations.

-

Long-running NIFs will take over a scheduler and prevent Erlang -from efficiently handling many processes.

-

Short-running NIFs will still confuse the scheduler if they -take more than a few microseconds to run.

-

Threaded NIFs, or the use of the enif_consume_timeslice -might help allievate this problem, but they’re not a silver bullet.

-

And as you already know, a crashing NIF will take down your VM, -destroying any claims you may have at being scalable.

-

Never use a NIF because "C is fast". This is only true in -single-threaded programs.

-
-
-
+

NIFs are considered harmful. I don't know any single NIF-based library that I would recommend. That doesn't mean they should all be avoided, just that if you're going to want your system to scale, you probably shouldn't use a NIF.

+

A common case for using NIFs is JSON processing. The problem is that JSON is a highly inefficient data structure (similar in inefficiency to XML, although perhaps not as bad). If you can avoid using JSON, you probably should. MessagePack can replace it in many situations.

+

Long-running NIFs will take over a scheduler and prevent Erlang from efficiently handling many processes.

+

Short-running NIFs will still confuse the scheduler if they take more than a few microseconds to run.

+

Threaded NIFs, or the use of the enif_consume_timeslice might help allievate this problem, but they're not a silver bullet.

+

And as you already know, a crashing NIF will take down your VM, destroying any claims you may have at being scalable.

+

Never use a NIF because "C is fast". This is only true in single-threaded programs.

BIFs

-
-

BIFs can also be harmful. While they are generally better than -NIFs, they are not perfect and some of them might have harmful -effects on the scheduler.

-

A great example of this is the erlang:decode_packet/3 -BIF, when used for HTTP request or response decoding. Avoiding -its use in Cowboy allowed us to see a big increase in -the number of requests production systems were able to handle, -up to two times the original amount. Incidentally this is something -that is impossible to detect using synthetic benchmarks.

-

BIFs that return immediately are perfectly fine though.

-
-
-
+

BIFs can also be harmful. While they are generally better than NIFs, they are not perfect and some of them might have harmful effects on the scheduler.

+

A great example of this is the erlang:decode_packet/3 BIF, when used for HTTP request or response decoding. Avoiding its use in Cowboy allowed us to see a big increase in the number of requests production systems were able to handle, up to two times the original amount. Incidentally this is something that is impossible to detect using synthetic benchmarks.

+

BIFs that return immediately are perfectly fine though.

Binary strings

-
-

Binary strings use less memory, which means you spend less time -allocating memory compared to list-based strings. They are also -more natural for strings manipulation because they are optimized -for appending (as opposed to prepending for lists).

-

If you can process a binary string using a single match context, -then the code will run incredibly fast. The effects will be much -increased if the code was compiled using HiPE, even if your Erlang -system isn’t compiled natively.

-

Avoid using binary:split or binary:replace -if you can avoid it. They have a certain overhead due to supporting -many options that you probably don’t need for most operations.

-
-
-
+

Binary strings use less memory, which means you spend less time allocating memory compared to list-based strings. They are also more natural for strings manipulation because they are optimized for appending (as opposed to prepending for lists).

+

If you can process a binary string using a single match context, then the code will run incredibly fast. The effects will be much increased if the code was compiled using HiPE, even if your Erlang system isn't compiled natively.

+

Avoid using binary:split or binary:replace if you can avoid it. They have a certain overhead due to supporting many options that you probably don't need for most operations.

Buffering and streaming

-
-

Use binaries. They are great for appending, and it’s a direct copy -from what you receive from a stream (usually a socket or a file).

-

Be careful to not indefinitely receive data, as you might end up -having a single binary taking up huge amounts of memory.

-

If you stream from a socket and know how much data you expect, -then fetch that data in a single recv call.

-

Similarly, if you can use a single send call, then -you should do so, to avoid going back and forth unnecessarily between -your Erlang process and the Erlang port for your socket.

-
-
-
+

Use binaries. They are great for appending, and it's a direct copy from what you receive from a stream (usually a socket or a file).

+

Be careful to not indefinitely receive data, as you might end up having a single binary taking up huge amounts of memory.

+

If you stream from a socket and know how much data you expect, then fetch that data in a single recv call.

+

Similarly, if you can use a single send call, then you should do so, to avoid going back and forth unnecessarily between your Erlang process and the Erlang port for your socket.

List and binary comprehensions

-
-

Prefer list comprehensions over lists:map/2. The -compiler will be able to optimize your code greatly, for example -not creating the result if you don’t need it. As time goes on, -more optimizations will be added to the compiler and you will -automatically benefit from them.

-
-
-
+

Prefer list comprehensions over lists:map/2. The compiler will be able to optimize your code greatly, for example not creating the result if you don't need it. As time goes on, more optimizations will be added to the compiler and you will automatically benefit from them.

gen_server is no silver bullet

-
-

It’s a bad idea to use gen_server for everything. -For two reasons.

-

There is an overhead everytime the gen_server receives -a call, a cast or a simple message. It can be a problem if your -gen_server is in a critical code path where speed -is all that matters. Do not hesitate to create other kinds of -processes where it makes sense. And depending on the kind of process, -you might want to consider making them special processes, which -would essentially behave the same as a gen_server.

-

A common mistake is to have a unique gen_server to -handle queries from many processes. This generally becomes the -biggest bottleneck you’ll want to fix. You should try to avoid -relying on a single process, using a pool if you can.

-
-
-
+

It's a bad idea to use gen_server for everything. For two reasons.

+

There is an overhead everytime the gen_server receives a call, a cast or a simple message. It can be a problem if your gen_server is in a critical code path where speed is all that matters. Do not hesitate to create other kinds of processes where it makes sense. And depending on the kind of process, you might want to consider making them special processes, which would essentially behave the same as a gen_server.

+

A common mistake is to have a unique gen_server to handle queries from many processes. This generally becomes the biggest bottleneck you'll want to fix. You should try to avoid relying on a single process, using a pool if you can.

Supervisor and monitoring

-
-

A supervisor is also a gen_server, -so the previous points also apply to them.

-

Sometimes you’re in a situation where you have supervised -processes but also want to monitor them in one or more other -processes, effectively duplicating the work. The supervisor -already knows when processes die, why not use this to our -advantage?

-

You can create a custom supervisor process that will perform -both the supervision and handle exit and other events, allowing -to avoid the combination of supervising and monitoring which -can prove harmful when many processes die at once, or when you -have many short lived processes.

-
-
-
+

A supervisor is also a gen_server, so the previous points also apply to them.

+

Sometimes you're in a situation where you have supervised processes but also want to monitor them in one or more other processes, effectively duplicating the work. The supervisor already knows when processes die, why not use this to our advantage?

+

You can create a custom supervisor process that will perform both the supervision and handle exit and other events, allowing to avoid the combination of supervising and monitoring which can prove harmful when many processes die at once, or when you have many short lived processes.

ets for LOLSPEED(tm)

-
-

If you have data queried or modified by many processes, then -ets public or protected tables will give you the -performance boost you require. Do not forget to set the -read_concurrency or write_concurrency -options though.

-

You might also be thrilled to know that Erlang R16B will feature -a big performance improvement for accessing ets tables -concurrently.

-
-
+

If you have data queried or modified by many processes, then ets public or protected tables will give you the performance boost you require. Do not forget to set the read_concurrency or write_concurrency options though.

+

You might also be thrilled to know that Erlang R16B will feature a big performance improvement for accessing ets tables concurrently.

+ diff --git a/articles/erlang-validate-utf8/index.html b/articles/erlang-validate-utf8/index.html index e8abf3a7..48df613b 100644 --- a/articles/erlang-validate-utf8/index.html +++ b/articles/erlang-validate-utf8/index.html @@ -69,191 +69,159 @@

-

Yesterday I pushed Websocket permessage-deflate to -Cowboy master. I also pushed -a -change in the way the code validates UTF-8 data -(required for text and close frames as per the spec).

-

When looking into why the permessage-deflate tests -in autobahntestsuite were taking such a long time, I -found that autobahn is using an adaptation of the -algorithm named Flexible -and Economical UTF-8 Decoder. This is the C99 -implementation:

-
-
-
// Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
-// See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details.
+
// Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
+// See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details.
 
-#define UTF8_ACCEPT 0
-#define UTF8_REJECT 1
+#define UTF8_ACCEPT 0
+#define UTF8_REJECT 1
 
-static const uint8_t utf8d[] = {
-  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 00..1f
-  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 20..3f
-  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 40..5f
-  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 60..7f
-  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, // 80..9f
-  7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, // a0..bf
-  8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // c0..df
-  0xa,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x4,0x3,0x3, // e0..ef
-  0xb,0x6,0x6,0x6,0x5,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8, // f0..ff
-  0x0,0x1,0x2,0x3,0x5,0x8,0x7,0x1,0x1,0x1,0x4,0x6,0x1,0x1,0x1,0x1, // s0..s0
-  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,1, // s1..s2
-  1,2,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1, // s3..s4
-  1,2,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,3,1,3,1,1,1,1,1,1, // s5..s6
-  1,3,1,1,1,1,1,3,1,3,1,1,1,1,1,1,1,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // s7..s8
-};
+static const uint8_t utf8d[] = {
+  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 00..1f
+  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 20..3f
+  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 40..5f
+  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 60..7f
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, // 80..9f
+  7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, // a0..bf
+  8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // c0..df
+  0xa,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x4,0x3,0x3, // e0..ef
+  0xb,0x6,0x6,0x6,0x5,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8, // f0..ff
+  0x0,0x1,0x2,0x3,0x5,0x8,0x7,0x1,0x1,0x1,0x4,0x6,0x1,0x1,0x1,0x1, // s0..s0
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,1, // s1..s2
+  1,2,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1, // s3..s4
+  1,2,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,3,1,3,1,1,1,1,1,1, // s5..s6
+  1,3,1,1,1,1,1,3,1,3,1,1,1,1,1,1,1,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // s7..s8
+};
 
 uint32_t inline
-decode(uint32_t* state, uint32_t* codep, uint32_t byte) {
-  uint32_t type = utf8d[byte];
+decode(uint32_t* state, uint32_t* codep, uint32_t byte) {
+  uint32_t type = utf8d[byte];
 
-  *codep = (*state != UTF8_ACCEPT) ?
-    (byte & 0x3fu) | (*codep << 6) :
-    (0xff >> type) & (byte);
+  *codep = (*state != UTF8_ACCEPT) ?
+    (byte & 0x3fu) | (*codep << 6) :
+    (0xff >> type) & (byte);
 
-  *state = utf8d[256 + *state*16 + type];
-  return *state;
-}
-

And this is the Erlang implementation I came up with:

-
-
-
%% This function returns 0 on success, 1 on error, and 2..8 on incomplete data.
-validate_utf8(<<>>, State) -> State;
-validate_utf8(<< C, Rest/bits >>, 0) when C < 128 -> validate_utf8(Rest, 0);
-validate_utf8(<< C, Rest/bits >>, 2) when C >= 128, C < 144 -> validate_utf8(Rest, 0);
-validate_utf8(<< C, Rest/bits >>, 3) when C >= 128, C < 144 -> validate_utf8(Rest, 2);
-validate_utf8(<< C, Rest/bits >>, 5) when C >= 128, C < 144 -> validate_utf8(Rest, 2);
-validate_utf8(<< C, Rest/bits >>, 7) when C >= 128, C < 144 -> validate_utf8(Rest, 3);
-validate_utf8(<< C, Rest/bits >>, 8) when C >= 128, C < 144 -> validate_utf8(Rest, 3);
-validate_utf8(<< C, Rest/bits >>, 2) when C >= 144, C < 160 -> validate_utf8(Rest, 0);
-validate_utf8(<< C, Rest/bits >>, 3) when C >= 144, C < 160 -> validate_utf8(Rest, 2);
-validate_utf8(<< C, Rest/bits >>, 5) when C >= 144, C < 160 -> validate_utf8(Rest, 2);
-validate_utf8(<< C, Rest/bits >>, 6) when C >= 144, C < 160 -> validate_utf8(Rest, 3);
-validate_utf8(<< C, Rest/bits >>, 7) when C >= 144, C < 160 -> validate_utf8(Rest, 3);
-validate_utf8(<< C, Rest/bits >>, 2) when C >= 160, C < 192 -> validate_utf8(Rest, 0);
-validate_utf8(<< C, Rest/bits >>, 3) when C >= 160, C < 192 -> validate_utf8(Rest, 2);
-validate_utf8(<< C, Rest/bits >>, 4) when C >= 160, C < 192 -> validate_utf8(Rest, 2);
-validate_utf8(<< C, Rest/bits >>, 6) when C >= 160, C < 192 -> validate_utf8(Rest, 3);
-validate_utf8(<< C, Rest/bits >>, 7) when C >= 160, C < 192 -> validate_utf8(Rest, 3);
-validate_utf8(<< C, Rest/bits >>, 0) when C >= 194, C < 224 -> validate_utf8(Rest, 2);
-validate_utf8(<< 224, Rest/bits >>, 0) -> validate_utf8(Rest, 4);
-validate_utf8(<< C, Rest/bits >>, 0) when C >= 225, C < 237 -> validate_utf8(Rest, 3);
-validate_utf8(<< 237, Rest/bits >>, 0) -> validate_utf8(Rest, 5);
-validate_utf8(<< C, Rest/bits >>, 0) when C =:= 238; C =:= 239 -> validate_utf8(Rest, 3);
-validate_utf8(<< 240, Rest/bits >>, 0) -> validate_utf8(Rest, 6);
-validate_utf8(<< C, Rest/bits >>, 0) when C =:= 241; C =:= 242; C =:= 243 -> validate_utf8(Rest, 7);
-validate_utf8(<< 244, Rest/bits >>, 0) -> validate_utf8(Rest, 8);
-validate_utf8(_, _) -> 1.
-

Does it look similar to you? So how did we get there?

-

I started with a naive implementation of the original. First, we -don’t need the codepoint calculated and extracted for our validation -function. We just want to know the data is valid, so we only need to -calculate the next state. Then, the only thing we needed to be careful -about was that tuples are 1-based, and that we need to stop processing -the binary when we get the state 1 or when the binary is empty.

-
-
-
validate_utf8(<<>>, State) -> State;
-validate_utf8(_, 1) -> 1;
-validate_utf8(<< C, Rest/bits >>, State) ->
-        validate_utf8(Rest, element(257 + State * 16 + element(1 + C, ?UTF8D), ?UTF8D)).
-

The macro ?UTF8D is the tuple equivalent of the C array -in the original code.

-

Compared to our previous algorithm, this performed about the same. -In some situations a little faster, in some a little slower. In other words, -not good enough. But because this new algorithm allows us to avoid a binary -concatenation this warranted looking further.

-

It was time to step into crazy land.

-

Erlang is very good at pattern matching, even more so than doing some -arithmetic coupled by fetching elements from a tuple. So I decided I was -going to write all possible clauses for all combinations of C -and State. And by write I mean generate.

-

So I opened my Erlang shell, defined the variable D to be -the tuple ?UTF8D with its 400 elements, and then ran the -following expression (after a bit of trial and error):

-
-
-
16> file:write_file("out.txt",
-        [io_lib:format("validate_utf8(<< ~p, Rest/bits >>, ~p) -> ~p;~n",
-                [C, S, element(257 + S * 16 + element(1 + C, D), D)])
-                        || C <- lists:seq(0,255), S <- lists:seq(0,8)]).
-ok
-

The result is a 2304 lines long file, containing 2304 clauses. -People who pay attention to what I say on Twitter will remember -I said something around 3000 clauses, but that was just me not -using the right number of states in my estimate.

-

There was a little more work to be done on this generated -code that I did using regular expressions. We need to recurse -when the resulting state is not 1. We also need to stop when -the binary is empty, making it the 2305th clause.

-

Still, 2305 is a lot. But hey, the code did work, and faster -than the previous implementation too! But hey, perhaps I could -find a way to reduce its size.

-

Removing all the clauses that return 1 and putting a catch-all -clause at the end instead reduced the number to about 500, and -showed that many clauses were similar:

-
-
-
validate_utf8(<< 0, Rest/bits >>, 0) -> validate_utf8(Rest, 0);
-validate_utf8(<< 1, Rest/bits >>, 0) -> validate_utf8(Rest, 0);
-validate_utf8(<< 2, Rest/bits >>, 0) -> validate_utf8(Rest, 0);
-validate_utf8(<< 3, Rest/bits >>, 0) -> validate_utf8(Rest, 0);
-validate_utf8(<< 4, Rest/bits >>, 0) -> validate_utf8(Rest, 0);
-validate_utf8(<< 5, Rest/bits >>, 0) -> validate_utf8(Rest, 0);
-validate_utf8(<< 6, Rest/bits >>, 0) -> validate_utf8(Rest, 0);
-validate_utf8(<< 7, Rest/bits >>, 0) -> validate_utf8(Rest, 0);
-

But also:

-
-
-
validate_utf8(<< 157, Rest/bits >>, 2) -> validate_utf8(Rest, 0);
-validate_utf8(<< 157, Rest/bits >>, 3) -> validate_utf8(Rest, 2);
-validate_utf8(<< 157, Rest/bits >>, 5) -> validate_utf8(Rest, 2);
-validate_utf8(<< 157, Rest/bits >>, 6) -> validate_utf8(Rest, 3);
-validate_utf8(<< 157, Rest/bits >>, 7) -> validate_utf8(Rest, 3);
-validate_utf8(<< 158, Rest/bits >>, 2) -> validate_utf8(Rest, 0);
-validate_utf8(<< 158, Rest/bits >>, 3) -> validate_utf8(Rest, 2);
-validate_utf8(<< 158, Rest/bits >>, 5) -> validate_utf8(Rest, 2);
-validate_utf8(<< 158, Rest/bits >>, 6) -> validate_utf8(Rest, 3);
-validate_utf8(<< 158, Rest/bits >>, 7) -> validate_utf8(Rest, 3);
-

Patterns, my favorites!

-

A little more time was spent to edit the 500 or so clauses into -smaller equivalents, testing that performance was not impacted, and -comitting the result.

-

The patterns above can be found here in the resulting function:

-
-
-
validate_utf8(<< C, Rest/bits >>, 0) when C < 128 -> validate_utf8(Rest, 0);
-...
-validate_utf8(<< C, Rest/bits >>, 2) when C >= 144, C < 160 -> validate_utf8(Rest, 0);
-validate_utf8(<< C, Rest/bits >>, 3) when C >= 144, C < 160 -> validate_utf8(Rest, 2);
-validate_utf8(<< C, Rest/bits >>, 5) when C >= 144, C < 160 -> validate_utf8(Rest, 2);
-validate_utf8(<< C, Rest/bits >>, 6) when C >= 144, C < 160 -> validate_utf8(Rest, 3);
-validate_utf8(<< C, Rest/bits >>, 7) when C >= 144, C < 160 -> validate_utf8(Rest, 3);
-...
-

I hope you enjoyed this post.

+
validate_utf8(<< C, Rest/bits >>, 0) when C < 128 -> validate_utf8(Rest, 0);
+...
+validate_utf8(<< C, Rest/bits >>, 2) when C >= 144, C < 160 -> validate_utf8(Rest, 0);
+validate_utf8(<< C, Rest/bits >>, 3) when C >= 144, C < 160 -> validate_utf8(Rest, 2);
+validate_utf8(<< C, Rest/bits >>, 5) when C >= 144, C < 160 -> validate_utf8(Rest, 2);
+validate_utf8(<< C, Rest/bits >>, 6) when C >= 144, C < 160 -> validate_utf8(Rest, 3);
+validate_utf8(<< C, Rest/bits >>, 7) when C >= 144, C < 160 -> validate_utf8(Rest, 3);
+...
+ +

I hope you enjoyed this post.

+ diff --git a/articles/erlang.mk-and-relx/index.html b/articles/erlang.mk-and-relx/index.html index 4309e0a3..a124ca18 100644 --- a/articles/erlang.mk-and-relx/index.html +++ b/articles/erlang.mk-and-relx/index.html @@ -69,118 +69,69 @@

-

Building OTP releases has always been a difficult task. Tools like -Reltool or Rebar have made this simpler, but -it’s no panacea. This article will show you an alternative and -hopefully much simpler solution.

-

There is two steps to building a release. First you need to build -the various OTP applications you want to include in the release. Once -done, you need to create the release itself, by including the Erlang -runtime system alongside the applications, a boot script to start the -node and all its applications, and some configuration files.

-

Erlang.mk solves -the first step. It is an include file for GNU Make. Just -including it in a Makefile is enough to allow building your project, -fetching and building dependencies, building documentation, performing -static analysis and more.

-

Relx solves the second -step. It is a release creation tool, wrapped into a single executable -file. It doesn’t require a configuration file. And if you do need one, -it will be a pretty small one.

-

Let’s take a look at the smallest Erlang.mk powered -Makefile. There is only one thing required: defining the project -name.

-
-
-
PROJECT = my_project
+
PROJECT = my_project
 
-include erlang.mk
-

Simply doing this allows you to build your application by typing -make, running tests using make tests, and -more. It will even compile your .dtl files found in the -templates/ directory if you are using ErlyDTL!

-

Let’s now take a look at a simplified version of the Makefile for -this website. I only removed a few targets that were off-topic.

-
-
-
PROJECT = ninenines
+
PROJECT = ninenines
 
-DEPS = cowboy erlydtl
-dep_cowboy_commit = 0.8.5
-dep_erlydtl_commit = 4d0dc8fb
+DEPS = cowboy erlydtl
+dep_cowboy_commit = 0.8.5
+dep_erlydtl_commit = 4d0dc8fb
 
-.PHONY: release clean-release
+.PHONY: release clean-release
 
-release: clean-release all projects
-        relx -o rel/$(PROJECT)
+release: clean-release all projects
+	relx -o rel/$(PROJECT)
 
-clean-release: clean-projects
-        rm -rf rel/$(PROJECT)
+clean-release: clean-projects
+	rm -rf rel/$(PROJECT)
 
-include erlang.mk
-

You can see here how to define dependencies. First you list all -the dependency names, then you have one line per dependency, giving -the repository URL and the commit number, tag or branch you want.

-

Then you can see two targets defined, with release -becoming the default target, because it was defined first. You can -override the default target all, which builds the -application and its dependencies, this way.

-

And as you can see, the release target uses -Relx to build a release into the rel/ninenines/ -directory. Let’s take a look at the configuration file for this release.

-
-
-
{release, {ninenines, "1"}, [ninenines]}.
+
{release, {ninenines, "1"}, [ninenines]}.
 
-{extended_start_script, true}.
-{sys_config, "rel/sys.config"}.
+{extended_start_script, true}.
+{sys_config, "rel/sys.config"}.
 
-{overlay, [
-        {mkdir, "log"},
-        {copy, "rel/vm.args",
-                "releases/\{\{release_name\}\}-\{\{release_version\}\}/vm.args"}
-]}.
-

The first line defines a release named ninenines, which -has a version number "1" and includes one application, also -named ninenines, although it doesn’t have to.

-

We then use the extended_start_script option to tell -Relx that we would like to have a start script that allows -us to not only start the release, but do so with the node in the -background, or also to allow us to connect to a running node, and so on. -This start script has the same features as the one tools like -Rebar generates.

-

The rest of the file just makes sure our configuration files are -where we expect them. Relx will automatically take care -of your sys.config file as long as you tell it where to -find it. The vm.args file used by the extended start script -needs to be handled more explicitly by using an overlay however.

-

How does Relx find what applications to include? -By looking at the application dependencies in the .app -file of each OTP application. Make sure you put all dependencies in -there, including library applications, and Relx -will find everything for you.

-

For example, this release includes the following applications. -Only what’s strictly required.

-
-
-
compiler-4.9.1  crypto-2.3     kernel-2.16.1    ranch-0.8.3    syntax_tools-1.6.11
-cowboy-0.8.5    erlydtl-0.7.0  ninenines-0.2.0  stdlib-1.19.1
+{overlay, [ + {mkdir, "log"}, + {copy, "rel/vm.args", + "releases/\{\{release_name\}\}-\{\{release_version\}\}/vm.args"} +]}.
-

The sys.config file is standard and -well documented. -The vm.args file is just an optionally multiline file -containing all the flags to pass to the Erlang VM, for example --name ninenines@127.0.0.1 -heart.

-

Building OTP releases has always been a difficult task. Until now.

+

The first line defines a release named ninenines, which has a version number "1" and includes one application, also named ninenines, although it doesn't have to.

+

We then use the extended_start_script option to tell Relx that we would like to have a start script that allows us to not only start the release, but do so with the node in the background, or also to allow us to connect to a running node, and so on. This start script has the same features as the one tools like Rebar generates.

+

The rest of the file just makes sure our configuration files are where we expect them. Relx will automatically take care of your sys.config file as long as you tell it where to find it. The vm.args file used by the extended start script needs to be handled more explicitly by using an overlay however.

+

How does Relx find what applications to include? By looking at the application dependencies in the .app file of each OTP application. Make sure you put all dependencies in there, including library applications, and Relx will find everything for you.

+

For example, this release includes the following applications. Only what's strictly required.

+
compiler-4.9.1	crypto-2.3     kernel-2.16.1	ranch-0.8.3    syntax_tools-1.6.11
+cowboy-0.8.5	erlydtl-0.7.0  ninenines-0.2.0	stdlib-1.19.1
+

The sys.config file is standard and well documented. The vm.args file is just an optionally multiline file containing all the flags to pass to the Erlang VM, for example -name ninenines@127.0.0.1 -heart.

+

Building OTP releases has always been a difficult task. Until now.

+ diff --git a/articles/erlanger-playbook-september-2015-update/index.html b/articles/erlanger-playbook-september-2015-update/index.html index 4aa732b7..54949c1b 100644 --- a/articles/erlanger-playbook-september-2015-update/index.html +++ b/articles/erlanger-playbook-september-2015-update/index.html @@ -69,19 +69,14 @@

-

An update to The Erlanger Playbook is now available!

-

The Erlanger Playbook is a book about software development using -Erlang. It currently covers all areas from the conception, design, -the writing of code, documentation and tests.

-

The book is still a work in progress. Future topics will include -refactoring, debugging and tracing, benchmarking, releases, community -management (for open source projects).

-

This update fixes a number of things and adds two chapters: IOlists -and Erlang building blocks.

-

Learn more about The Erlanger Playbook!

-

This is a self-published ebook. The base price is 50€. All proceeds -will be used to allow me to work on open source full time.

-

Thank you for helping me helping you help us all!

+

An update to The Erlanger Playbook is now available!

+

The Erlanger Playbook is a book about software development using Erlang. It currently covers all areas from the conception, design, the writing of code, documentation and tests.

+

The book is still a work in progress. Future topics will include refactoring, debugging and tracing, benchmarking, releases, community management (for open source projects).

+

This update fixes a number of things and adds two chapters: IOlists and Erlang building blocks.

+

Learn more about The Erlanger Playbook!

+

This is a self-published ebook. The base price is 50€. All proceeds will be used to allow me to work on open source full time.

+

Thank you for helping me helping you help us all!

+ diff --git a/articles/erlanger-playbook/index.html b/articles/erlanger-playbook/index.html index 490f06e5..c02c7fc9 100644 --- a/articles/erlanger-playbook/index.html +++ b/articles/erlanger-playbook/index.html @@ -69,87 +69,47 @@

-

I am proud to announce the pre-release of The Erlanger Playbook.

-

The Erlanger Playbook is a book about software development using -Erlang. It currently covers all areas from the conception, design, -the writing of code, documentation and tests.

-

The book is still a work in progress. Future topics will include -refactoring, debugging and tracing, benchmarking, releases, community -management (for open source projects).

-

The following sections are currently available:

-
    -
  • -

    -About this book; Changelog; Future additions -

    +

    I am proud to announce the pre-release of The Erlanger Playbook.

    +

    The Erlanger Playbook is a book about software development using Erlang. It currently covers all areas from the conception, design, the writing of code, documentation and tests.

    +

    The book is still a work in progress. Future topics will include refactoring, debugging and tracing, benchmarking, releases, community management (for open source projects).

    +

    The following sections are currently available:

    +
    • About this book; Changelog; Future additions
    • -
    • -

      -Erlang: Building blocks; Patterns -

      +
    • Erlang: Building blocks; Patterns
    • -
    • -

      -Workflow: Think; Write; Stay productive -

      +
    • Workflow: Think; Write; Stay productive
    • -
    • -

      -Documentation: On documentation; Tutorials; User guide; Manual; README files -

      +
    • Documentation: On documentation; Tutorials; User guide; Manual; README files
    • -
    • -

      -Design: RESTful APIs; Lessons learned -

      +
    • Design: RESTful APIs; Lessons learned
    • -
    • -

      -Code: Starting a project; Version control; Project structure; Code style; Best practices; Special processes; IOLists; The process dictionary -

      +
    • Code: Starting a project; Version control; Project structure; Code style; Best practices; Special processes; IOLists; The process dictionary
    • -
    • -

      -Tests: On testing; Success typing analysis; Manual testing; Unit testing; Functional testing -

      +
    • Tests: On testing; Success typing analysis; Manual testing; Unit testing; Functional testing
    • -
    • -

      -Selling Erlang: On persuasion; Don’t let it crash -

      +
    • Selling Erlang: On persuasion; Don't let it crash
    • -
-

Read a preview: Special processes

-

The book is currently 180 pages long. The final version -of the book is planned to be between 200 and 250 pages. -A print version of the book will be considered once the final -version gets released. The printed book is not included -in the price.

-

This is a self-published book. The base price is 50€. All proceeds -will be used to allow me to work on open source full time.

+ +

Read a preview: Special processes

+

The book is currently 180 pages long. The final version of the book is planned to be between 200 and 250 pages. A print version of the book will be considered once the final version gets released. The printed book is not included in the price.

+

This is a self-published book. The base price is 50€. All proceeds will be used to allow me to work on open source full time.

- -

You are more than welcome to pay extra by using this second button. -It allows you to set the price you want. Make sure to set it to at least -50€ to receive the book.

+

You are more than welcome to pay extra by using this second button. It allows you to set the price you want. Make sure to set it to at least 50€ to receive the book.

-
-

Make sure to provide a valid email address.

-

There will be a delay between payment and sending of the book. -This process is currently manual.

-

As the book is a pre-release, feedback is more than welcome. You can -send your comments to erlanger@ this website.

-

The plan is to add content regularly until I run out of things to say. -You will receive updates to the book for free as soon as they are available.

-

Huge thanks for your interest in buying this book!

+

Make sure to provide a valid email address.

+

There will be a delay between payment and sending of the book. This process is currently manual.

+

As the book is a pre-release, feedback is more than welcome. You can send your comments to erlanger@ this website.

+

The plan is to add content regularly until I run out of things to say. You will receive updates to the book for free as soon as they are available.

+

Huge thanks for your interest in buying this book!

+ diff --git a/articles/farwest-funded/index.html b/articles/farwest-funded/index.html index 584858a2..2a60af86 100644 --- a/articles/farwest-funded/index.html +++ b/articles/farwest-funded/index.html @@ -69,27 +69,15 @@

-

This was a triumph! I’m making a note here: HUGE SUCCESS!!

- -

It’s hard to overstate my satisfaction. Thanks to everyone who -made this possible.

-

If you have backed this fundraiser, and haven’t provided your -personal details yet, please do so quickly so that your rewards -can be sent!

-

I am hoping that we will be able to make good use of all that -money. The details of the expenses will be published regularly -on the 2013 Fundraiser wiki page, -giving you full disclosure as to how your money is used.

-

It will take a little time to get things started, we are in -summer after all! We will however act quickly to make the -prototype easy enough to use so that the paid UI work can -begin. This is also when user contributions will be welcome.

-

You can see the Roadmap -to get more information on the current plans. This document will -get updated as time goes on so check again later to see if you -can help!

-

Look at me: still talking when there’s open source to do!

-

Thanks again for all your support. I really appreciate it.

+

This was a triumph! I'm making a note here: HUGE SUCCESS!!

+

It's hard to overstate my satisfaction. Thanks to everyone who made this possible.

+

If you have backed this fundraiser, and haven't provided your personal details yet, please do so quickly so that your rewards can be sent!

+

I am hoping that we will be able to make good use of all that money. The details of the expenses will be published regularly on the 2013 Fundraiser wiki page, giving you full disclosure as to how your money is used.

+

It will take a little time to get things started, we are in summer after all! We will however act quickly to make the prototype easy enough to use so that the paid UI work can begin. This is also when user contributions will be welcome.

+

You can see the Roadmap to get more information on the current plans. This document will get updated as time goes on so check again later to see if you can help!

+

Look at me: still talking when there's open source to do!

+

Thanks again for all your support. I really appreciate it.

+ diff --git a/articles/gun-1.0.0-rc.1/index.html b/articles/gun-1.0.0-rc.1/index.html index f0b4664b..9521c7ea 100644 --- a/articles/gun-1.0.0-rc.1/index.html +++ b/articles/gun-1.0.0-rc.1/index.html @@ -69,41 +69,16 @@

-

Gun 1.0.0-rc.1 has been released!

-

Gun is an HTTP/1.1, HTTP/2 and Websocket client -for Erlang/OTP.

-

Gun provides an asynchronous interface and will -keep the connection open to the server, reconnecting -as necessary.

-

Gun has existed for many years as the test client -for Cowboy and is now mature enough to receive a -proper version. Gun is battle tested by customers -and other users but is not the most well tested -client there is.

-

This release candidate differs from previous tags -in the way Websocket-related messages are handled: -the gun_ws_upgrade message is now gun_upgrade, -and the gun_ws message has an extra element. The -dependency on Ranch has also been removed. In -addition some undocumented features have been -modified; they will be documented in future -releases.

-

I have given the Cowboy treatment to the Gun manual: -a separate page per function call with all kind -of useful information, including examples. Since -Gun provides an asynchronous interface, each message -also has a separate manual page. Check it out: -https://ninenines.eu/docs/en/gun/1.0/manual/

-

Gun 1.0 will be released once customers projects -are updated and I confirm everything works as intended.

-

You can donate to this project via -BountySource. -These funds are used to pay for additional servers for -testing. A new server was added last month and allows -me to test with additional Linux distributions Alpine, -CentOS and Debian. Thanks in advance!

-

As usual, feedback is appreciated, and issues or -questions should be sent via Github tickets. Thanks!

+

Gun 1.0.0-rc.1 has been released!

+

Gun is an HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP.

+

Gun provides an asynchronous interface and will keep the connection open to the server, reconnecting as necessary.

+

Gun has existed for many years as the test client for Cowboy and is now mature enough to receive a proper version. Gun is battle tested by customers and other users but is not the most well tested client there is.

+

This release candidate differs from previous tags in the way Websocket-related messages are handled: the gun_ws_upgrade message is now gun_upgrade, and the gun_ws message has an extra element. The dependency on Ranch has also been removed. In addition some undocumented features have been modified; they will be documented in future releases.

+

I have given the Cowboy treatment to the Gun manual: a separate page per function call with all kind of useful information, including examples. Since Gun provides an asynchronous interface, each message also has a separate manual page. Check it out: https://ninenines.eu/docs/en/gun/1.0/manual/

+

Gun 1.0 will be released once customers projects are updated and I confirm everything works as intended.

+

You can donate to this project via BountySource. These funds are used to pay for additional servers for testing. A new server was added last month and allows me to test with additional Linux distributions Alpine, CentOS and Debian. Thanks in advance!

+

As usual, feedback is appreciated, and issues or questions should be sent via Github tickets. Thanks!

+ diff --git a/articles/index.html b/articles/index.html index 4df97ede..b3128c02 100644 --- a/articles/index.html +++ b/articles/index.html @@ -75,9 +75,9 @@

Gun 1.0.0-rc.1 has been released! - Gun is an HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP. - Gun provides an asynchronous interface and will keep the connection open to the server, reconnecting as necessary. - Gun has existed for many years as the test client for Cowboy and is now mature enough to receive a proper version. Gun is battle tested by customers and other users but is not the most well tested client there is.

+Gun is an HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP. +Gun provides an asynchronous interface and will keep the connection open to the server, reconnecting as necessary. +Gun has existed for many years as the test client for Cowboy and is now mature enough to receive a proper version. Gun is battle tested by customers and other users but is not the most well tested client there is.

Read More @@ -94,8 +94,8 @@

Cowboy 2.4.0 has been released! - Numerous HTTP/2 options have been added to control the HTTP/2 SETTINGS and general behavior of HTTP/2 connections. The options for initial window sizes, maximum frame sizes or compression table sizes might be of interest for optimizing the performance of HTTP/2 connections. - Experimental support for Websocket over HTTP/2 was added. Note that browsers do not currently support it. The only browser with partial support is Google Chrome 67 (dev build) started with a specific flag.

+Numerous HTTP/2 options have been added to control the HTTP/2 SETTINGS and general behavior of HTTP/2 connections. The options for initial window sizes, maximum frame sizes or compression table sizes might be of interest for optimizing the performance of HTTP/2 connections. +Experimental support for Websocket over HTTP/2 was added. Note that browsers do not currently support it. The only browser with partial support is Google Chrome 67 (dev build) started with a specific flag.

Read More @@ -112,9 +112,10 @@

Cowboy 2.3.0 has been released! - This release focused on adding support for the functions from the sys module for introspecting Cowboy processes. - Many bugs have also been fixed. A more complete list of changes can be found in the migration guide: Migrating from Cowboy 2.2 to 2.3. - You can donate to this project via BountySource because I need to eat snacks when I write code. Thanks in advance!

+This release focused on adding support for the functions from the sys module for introspecting Cowboy processes. +Many bugs have also been fixed. A more complete list of changes can be found in the migration guide: Migrating from Cowboy 2.2 to 2.3. +You can donate to this project via BountySource because I need to eat snacks when I write code. Thanks in advance! +As usual, feedback is appreciated, and issues should be reported by opening a ticket.

Read More @@ -131,8 +132,8 @@

Cowboy 2.2.0 has been released! - This release focused on adding features required for writing gRPC servers and on completing test suites for the core HTTP RFCs. - The cowboy_req:stream_trailers/2 function has been added. It terminates the streamed response by adding some trailer field values. This feature is required for gRPC. The max_skip_body_length option was added. It controls how much of the request body we are willing to skip to get to the next request for HTTP/1.

+This release focused on adding features required for writing gRPC servers and on completing test suites for the core HTTP RFCs. +The cowboy_req:stream_trailers/2 function has been added. It terminates the streamed response by adding some trailer field values. This feature is required for gRPC. The max_skip_body_length option was added. It controls how much of the request body we are willing to skip to get to the next request for HTTP/1.

Read More @@ -149,8 +150,8 @@

Cowboy 2.1.0 has been released! - This release focused on adding features that were temporarily removed during the 2.0 release process: - The client TLS certificate can now be obtained. The 100 Continue response is now sent automatically again when necessary. NEW: It is now possible to send informational responses (1XX) directly from user code via the cowboy_req:inform/2,3 functions. NEW: cowboy_rest handlers can now switch to any other type of handler from almost any callback.

+This release focused on adding features that were temporarily removed during the 2.0 release process: +The client TLS certificate can now be obtained. The 100 Continue response is now sent automatically again when necessary. NEW: It is now possible to send informational responses (1XX) directly from user code via the cowboy_req:inform/2,3 functions. NEW: cowboy_rest handlers can now switch to any other type of handler from almost any callback.

Read More @@ -167,9 +168,9 @@

Cowboy 2.0.0 has been released! - This is the new stable version of Cowboy. There are no new releases planned for the 1.x version of Cowboy. - The highlights from the release are: - HTTP/2 support! Websocket compression! Much simpler, cleaner interface. No more weird errors just because you discard the Req object. A new low-level interface that receives all events from every set of request and response.

+This is the new stable version of Cowboy. There are no new releases planned for the 1.x version of Cowboy. +The highlights from the release are: +HTTP/2 support! Websocket compression! Much simpler, cleaner interface. No more weird errors just because you discard the Req object. A new low-level interface that receives all events from every set of request and response. This replaces the awkward hooks from 1.

Read More @@ -186,9 +187,9 @@

Cowboy 2.0.0-rc.2 has been released! - This is the new recommended version of Cowboy. Its API should not change before release. While you probably should not use it in production yet, many do successfully. Use at your own risk. - This new version contains fixes for the following issues: - HTTP/2 server push was using the wrong header compression context. HTTP/2 flow control could end up queueing data in the wrong order when resuming the sending of data.

+This is the new recommended version of Cowboy. Its API should not change before release. While you probably should not use it in production yet, many do successfully. Use at your own risk. +This new version contains fixes for the following issues: +HTTP/2 server push was using the wrong header compression context. HTTP/2 flow control could end up queueing data in the wrong order when resuming the sending of data.

Read More @@ -205,8 +206,8 @@

Cowboy 2.0.0-rc.1 has been released! - This is the new recommended version of Cowboy. Its API should not change before release. While you probably should not use it in production yet, many do successfully. Use at your own risk. - The plan is to have a new RC version every couple weeks until the summer ends or later if there are still blocking issues open. Only issues that can’t be fixed without making breaking changes to the interface may block the release.

+This is the new recommended version of Cowboy. Its API should not change before release. While you probably should not use it in production yet, many do successfully. Use at your own risk. +The plan is to have a new RC version every couple weeks until the summer ends or later if there are still blocking issues open. Only issues that can't be fixed without making breaking changes to the interface may block the release.

Read More @@ -223,7 +224,7 @@

Have you ever tried telling someone why they should use Erlang? You boast the smaller code size, the auto healing mechanisms, the distribution and they seem really excited. They wonder why they never heard about Erlang before. And then you show them what the code looks like. All excitement goes away. The smiles disappear. Their face starts becoming really serious. - You lost them. You know you lost them. They comment on the syntax, or perhaps you do, already admitting defeat.

+You lost them. You know you lost them. They comment on the syntax, or perhaps you do, already admitting defeat.

Read More @@ -239,8 +240,8 @@

-

We have a specific mindset when writing Erlang programs. We focus on the normal execution of the program and don’t handle most of the errors that may occur. We sometimes call this normal execution the happy path. - The general pattern behind writing only for the happy path, letting the VM catch errors (writing them to a log for future consumption) and then having a supervisor restart the processes that failed from a clean state, has a name.

+

We have a specific mindset when writing Erlang programs. We focus on the normal execution of the program and don't handle most of the errors that may occur. We sometimes call this normal execution the happy path. +The general pattern behind writing only for the happy path, letting the VM catch errors (writing them to a log for future consumption) and then having a supervisor restart the processes that failed from a clean state, has a name.

Read More @@ -257,9 +258,9 @@

Cowboy 2.0.0-pre.4 has been released! - This is the new recommended version of Cowboy. While I would not recommend putting it in production just yet, I do recommend you start writing new applications with this Cowboy version. - The most significant changes in the pre-release are: - A new architecture: there now is one process per connection and one process per request. This was done because HTTP/2 allows running requests concurrently.

+This is the new recommended version of Cowboy. While I would not recommend putting it in production just yet, I do recommend you start writing new applications with this Cowboy version. +The most significant changes in the pre-release are: +A new architecture: there now is one process per connection and one process per request. This was done because HTTP/2 allows running requests concurrently. Stream handlers.

Read More @@ -276,8 +277,9 @@

Ranch 1.3.0 has been released! - This release fixes a number of long standing issues and adds a small number of features: - The ssl application has been added to the list of dependencies. If you don’t need it, you can remove it automatically when fetching Ranch or when building the release. If you do need it, you will no longer have issues shutting down a node because of Ranch.

+This release fixes a number of long standing issues and adds a small number of features: +The ssl application has been added to the list of dependencies. If you don't need it, you can remove it automatically when fetching Ranch or when building the release. If you do need it, you will no longer have issues shutting down a node because of Ranch. +The ranch:info/0 and ranch:procs/2 can be used to retrieve information about Ranch's state.

Read More @@ -294,9 +296,9 @@

The old mailing list archives have been added to the site, mainly for referencing purposes. - The mailing list has been shut down and all personal information has been deleted. - If you need help with a project, consider either opening a ticket on that project’s issues tracker or going through the community channels (erlang-questions, #ninenines or #erlang on Freenode). - Prefer tickets; often when people have issues it highlights an underlying problem in the project or its documentation.

+The mailing list has been shut down and all personal information has been deleted. +If you need help with a project, consider either opening a ticket on that project's issues tracker or going through the community channels (erlang-questions, #ninenines or #erlang on Freenode). +Prefer tickets; often when people have issues it highlights an underlying problem in the project or its documentation.

Read More @@ -313,8 +315,8 @@

Last week-end I updated the Nine Nines website. - I switched to Hugo. The site is now built from Asciidoc documents. You probably saw me switch to Asciidoc for documentation this past year. This is the natural conclusion to that story. The great thing is that with a little bit of Makefile magic I can just copy the documentation files into Hugo and poof, they appear on the website. - I am very happy with that new setup.

+I switched to Hugo. The site is now built from Asciidoc documents. You probably saw me switch to Asciidoc for documentation this past year. This is the natural conclusion to that story. The great thing is that with a little bit of Makefile magic I can just copy the documentation files into Hugo and poof, they appear on the website. +I am very happy with that new setup.

Read More @@ -331,9 +333,9 @@

An update to The Erlanger Playbook is now available! - The Erlanger Playbook is a book about software development using Erlang. It currently covers all areas from the conception, design, the writing of code, documentation and tests. - The book is still a work in progress. Future topics will include refactoring, debugging and tracing, benchmarking, releases, community management (for open source projects). - This update fixes a number of things and adds two chapters: IOlists and Erlang building blocks.

+The Erlanger Playbook is a book about software development using Erlang. It currently covers all areas from the conception, design, the writing of code, documentation and tests. +The book is still a work in progress. Future topics will include refactoring, debugging and tracing, benchmarking, releases, community management (for open source projects). +This update fixes a number of things and adds two chapters: IOlists and Erlang building blocks.

Read More @@ -350,9 +352,10 @@

I am proud to announce the pre-release of The Erlanger Playbook. - The Erlanger Playbook is a book about software development using Erlang. It currently covers all areas from the conception, design, the writing of code, documentation and tests. - The book is still a work in progress. Future topics will include refactoring, debugging and tracing, benchmarking, releases, community management (for open source projects). - The following sections are currently available:

+The Erlanger Playbook is a book about software development using Erlang. It currently covers all areas from the conception, design, the writing of code, documentation and tests. +The book is still a work in progress. Future topics will include refactoring, debugging and tracing, benchmarking, releases, community management (for open source projects). +The following sections are currently available: +About this book; Changelog; Future additions Erlang: Building blocks; Patterns Workflow: Think; Write; Stay productive Documentation: On documentation; Tutorials; User guide; Manual; README files Design: RESTful APIs; Lessons learned Code: Starting a project; Version control; Project structure; Code style; Best practices; Special processes; IOLists; The process dictionary Tests: On testing; Success typing analysis; Manual testing; Unit testing; Functional testing Selling Erlang: On persuasion; Don't let it crash Read a preview: Special processes

Read More @@ -369,8 +372,8 @@

Yesterday I pushed Websocket permessage-deflate to Cowboy master. I also pushed a change in the way the code validates UTF-8 data (required for text and close frames as per the spec). - When looking into why the permessage-deflate tests in autobahntestsuite were taking such a long time, I found that autobahn is using an adaptation of the algorithm named Flexible and Economical UTF-8 Decoder. This is the C99 implementation: - // Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.

+When looking into why the permessage-deflate tests in autobahntestsuite were taking such a long time, I found that autobahn is using an adaptation of the algorithm named Flexible and Economical UTF-8 Decoder. This is the C99 implementation: +// Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.

Read More @@ -402,7 +405,7 @@

-

As I am away from home with little to do (some call this a vacation) I wanted to reflect a little on the story so far, or how I arrived to Erlang and got to where I am now. The raw personal experience. It’ll be an article that’s more about social aspect, communities and marketing a project than technical considerations. As a period piece, it will also allow me to reflect on the evolution of Erlang in recent years.

+

As I am away from home with little to do (some call this a vacation) I wanted to reflect a little on the story so far, or how I arrived to Erlang and got to where I am now. The raw personal experience. It'll be an article that's more about social aspect, communities and marketing a project than technical considerations. As a period piece, it will also allow me to reflect on the evolution of Erlang in recent years.

Read More @@ -419,7 +422,7 @@

Now that Cowboy 1.0 is out, I can spend some of my time thinking about Cowboy 2.0 that will be released soon after Erlang/OTP 18.0. This entry discusses the proposed changes to query string handling in Cowboy. - Cowboy 2.0 will respond to user wishes by simplifying the interface of the cowboy_req module. Users want two things: less juggling with the Req variable, and more maps. Maps is the only dynamic key/value data structure in Erlang that we can match directly to extract values, allowing users to greatly simplify their code as they don’t need to call functions to do everything anymore.

+Cowboy 2.0 will respond to user wishes by simplifying the interface of the cowboy_req module. Users want two things: less juggling with the Req variable, and more maps. Maps is the only dynamic key/value data structure in Erlang that we can match directly to extract values, allowing users to greatly simplify their code as they don't need to call functions to do everything anymore.

Read More diff --git a/articles/index.xml b/articles/index.xml index 23e4a6f1..ddd42bf6 100644 --- a/articles/index.xml +++ b/articles/index.xml @@ -18,9 +18,9 @@ https://ninenines.eu/articles/gun-1.0.0-rc.1/ Gun 1.0.0-rc.1 has been released! - Gun is an HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP. - Gun provides an asynchronous interface and will keep the connection open to the server, reconnecting as necessary. - Gun has existed for many years as the test client for Cowboy and is now mature enough to receive a proper version. Gun is battle tested by customers and other users but is not the most well tested client there is. +Gun is an HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP. +Gun provides an asynchronous interface and will keep the connection open to the server, reconnecting as necessary. +Gun has existed for many years as the test client for Cowboy and is now mature enough to receive a proper version. Gun is battle tested by customers and other users but is not the most well tested client there is. @@ -30,8 +30,8 @@ https://ninenines.eu/articles/cowboy-2.4.0/ Cowboy 2.4.0 has been released! - Numerous HTTP/2 options have been added to control the HTTP/2 SETTINGS and general behavior of HTTP/2 connections. The options for initial window sizes, maximum frame sizes or compression table sizes might be of interest for optimizing the performance of HTTP/2 connections. - Experimental support for Websocket over HTTP/2 was added. Note that browsers do not currently support it. The only browser with partial support is Google Chrome 67 (dev build) started with a specific flag. +Numerous HTTP/2 options have been added to control the HTTP/2 SETTINGS and general behavior of HTTP/2 connections. The options for initial window sizes, maximum frame sizes or compression table sizes might be of interest for optimizing the performance of HTTP/2 connections. +Experimental support for Websocket over HTTP/2 was added. Note that browsers do not currently support it. The only browser with partial support is Google Chrome 67 (dev build) started with a specific flag. @@ -41,9 +41,10 @@ https://ninenines.eu/articles/cowboy-2.3.0/ Cowboy 2.3.0 has been released! - This release focused on adding support for the functions from the sys module for introspecting Cowboy processes. - Many bugs have also been fixed. A more complete list of changes can be found in the migration guide: Migrating from Cowboy 2.2 to 2.3. - You can donate to this project via BountySource because I need to eat snacks when I write code. Thanks in advance! +This release focused on adding support for the functions from the sys module for introspecting Cowboy processes. +Many bugs have also been fixed. A more complete list of changes can be found in the migration guide: Migrating from Cowboy 2.2 to 2.3. +You can donate to this project via BountySource because I need to eat snacks when I write code. Thanks in advance! +As usual, feedback is appreciated, and issues should be reported by opening a ticket. @@ -53,8 +54,8 @@ https://ninenines.eu/articles/cowboy-2.2.0/ Cowboy 2.2.0 has been released! - This release focused on adding features required for writing gRPC servers and on completing test suites for the core HTTP RFCs. - The cowboy_req:stream_trailers/2 function has been added. It terminates the streamed response by adding some trailer field values. This feature is required for gRPC. The max_skip_body_length option was added. It controls how much of the request body we are willing to skip to get to the next request for HTTP/1. +This release focused on adding features required for writing gRPC servers and on completing test suites for the core HTTP RFCs. +The cowboy_req:stream_trailers/2 function has been added. It terminates the streamed response by adding some trailer field values. This feature is required for gRPC. The max_skip_body_length option was added. It controls how much of the request body we are willing to skip to get to the next request for HTTP/1. @@ -64,8 +65,8 @@ https://ninenines.eu/articles/cowboy-2.1.0/ Cowboy 2.1.0 has been released! - This release focused on adding features that were temporarily removed during the 2.0 release process: - The client TLS certificate can now be obtained. The 100 Continue response is now sent automatically again when necessary. NEW: It is now possible to send informational responses (1XX) directly from user code via the cowboy_req:inform/2,3 functions. NEW: cowboy_rest handlers can now switch to any other type of handler from almost any callback. +This release focused on adding features that were temporarily removed during the 2.0 release process: +The client TLS certificate can now be obtained. The 100 Continue response is now sent automatically again when necessary. NEW: It is now possible to send informational responses (1XX) directly from user code via the cowboy_req:inform/2,3 functions. NEW: cowboy_rest handlers can now switch to any other type of handler from almost any callback. @@ -75,9 +76,9 @@ https://ninenines.eu/articles/cowboy-2.0.0/ Cowboy 2.0.0 has been released! - This is the new stable version of Cowboy. There are no new releases planned for the 1.x version of Cowboy. - The highlights from the release are: - HTTP/2 support! Websocket compression! Much simpler, cleaner interface. No more weird errors just because you discard the Req object. A new low-level interface that receives all events from every set of request and response. +This is the new stable version of Cowboy. There are no new releases planned for the 1.x version of Cowboy. +The highlights from the release are: +HTTP/2 support! Websocket compression! Much simpler, cleaner interface. No more weird errors just because you discard the Req object. A new low-level interface that receives all events from every set of request and response. This replaces the awkward hooks from 1. @@ -87,9 +88,9 @@ https://ninenines.eu/articles/cowboy-2.0.0-rc.2/ Cowboy 2.0.0-rc.2 has been released! - This is the new recommended version of Cowboy. Its API should not change before release. While you probably should not use it in production yet, many do successfully. Use at your own risk. - This new version contains fixes for the following issues: - HTTP/2 server push was using the wrong header compression context. HTTP/2 flow control could end up queueing data in the wrong order when resuming the sending of data. +This is the new recommended version of Cowboy. Its API should not change before release. While you probably should not use it in production yet, many do successfully. Use at your own risk. +This new version contains fixes for the following issues: +HTTP/2 server push was using the wrong header compression context. HTTP/2 flow control could end up queueing data in the wrong order when resuming the sending of data. @@ -99,8 +100,8 @@ https://ninenines.eu/articles/cowboy-2.0.0-rc.1/ Cowboy 2.0.0-rc.1 has been released! - This is the new recommended version of Cowboy. Its API should not change before release. While you probably should not use it in production yet, many do successfully. Use at your own risk. - The plan is to have a new RC version every couple weeks until the summer ends or later if there are still blocking issues open. Only issues that can&#8217;t be fixed without making breaking changes to the interface may block the release. +This is the new recommended version of Cowboy. Its API should not change before release. While you probably should not use it in production yet, many do successfully. Use at your own risk. +The plan is to have a new RC version every couple weeks until the summer ends or later if there are still blocking issues open. Only issues that can&apos;t be fixed without making breaking changes to the interface may block the release. @@ -110,7 +111,7 @@ https://ninenines.eu/articles/the-elephant-in-the-room/ Have you ever tried telling someone why they should use Erlang? You boast the smaller code size, the auto healing mechanisms, the distribution and they seem really excited. They wonder why they never heard about Erlang before. And then you show them what the code looks like. All excitement goes away. The smiles disappear. Their face starts becoming really serious. - You lost them. You know you lost them. They comment on the syntax, or perhaps you do, already admitting defeat. +You lost them. You know you lost them. They comment on the syntax, or perhaps you do, already admitting defeat. @@ -119,8 +120,8 @@ Sun, 22 Jan 2017 00:00:00 +0100 https://ninenines.eu/articles/dont-let-it-crash/ - We have a specific mindset when writing Erlang programs. We focus on the normal execution of the program and don&#8217;t handle most of the errors that may occur. We sometimes call this normal execution the happy path. - The general pattern behind writing only for the happy path, letting the VM catch errors (writing them to a log for future consumption) and then having a supervisor restart the processes that failed from a clean state, has a name. + We have a specific mindset when writing Erlang programs. We focus on the normal execution of the program and don&apos;t handle most of the errors that may occur. We sometimes call this normal execution the happy path. +The general pattern behind writing only for the happy path, letting the VM catch errors (writing them to a log for future consumption) and then having a supervisor restart the processes that failed from a clean state, has a name. @@ -130,9 +131,9 @@ https://ninenines.eu/articles/cowboy-2.0.0-pre.4/ Cowboy 2.0.0-pre.4 has been released! - This is the new recommended version of Cowboy. While I would not recommend putting it in production just yet, I do recommend you start writing new applications with this Cowboy version. - The most significant changes in the pre-release are: - A new architecture: there now is one process per connection and one process per request. This was done because HTTP/2 allows running requests concurrently. +This is the new recommended version of Cowboy. While I would not recommend putting it in production just yet, I do recommend you start writing new applications with this Cowboy version. +The most significant changes in the pre-release are: +A new architecture: there now is one process per connection and one process per request. This was done because HTTP/2 allows running requests concurrently. Stream handlers. @@ -142,8 +143,9 @@ https://ninenines.eu/articles/ranch-1.3/ Ranch 1.3.0 has been released! - This release fixes a number of long standing issues and adds a small number of features: - The ssl application has been added to the list of dependencies. If you don&#8217;t need it, you can remove it automatically when fetching Ranch or when building the release. If you do need it, you will no longer have issues shutting down a node because of Ranch. +This release fixes a number of long standing issues and adds a small number of features: +The ssl application has been added to the list of dependencies. If you don&apos;t need it, you can remove it automatically when fetching Ranch or when building the release. If you do need it, you will no longer have issues shutting down a node because of Ranch. +The ranch:info/0 and ranch:procs/2 can be used to retrieve information about Ranch&apos;s state. @@ -153,9 +155,9 @@ https://ninenines.eu/articles/ml-archives/ The old mailing list archives have been added to the site, mainly for referencing purposes. - The mailing list has been shut down and all personal information has been deleted. - If you need help with a project, consider either opening a ticket on that project&#8217;s issues tracker or going through the community channels (erlang-questions, #ninenines or #erlang on Freenode). - Prefer tickets; often when people have issues it highlights an underlying problem in the project or its documentation. +The mailing list has been shut down and all personal information has been deleted. +If you need help with a project, consider either opening a ticket on that project&apos;s issues tracker or going through the community channels (erlang-questions, #ninenines or #erlang on Freenode). +Prefer tickets; often when people have issues it highlights an underlying problem in the project or its documentation. @@ -165,8 +167,8 @@ https://ninenines.eu/articles/website-update/ Last week-end I updated the Nine Nines website. - I switched to Hugo. The site is now built from Asciidoc documents. You probably saw me switch to Asciidoc for documentation this past year. This is the natural conclusion to that story. The great thing is that with a little bit of Makefile magic I can just copy the documentation files into Hugo and poof, they appear on the website. - I am very happy with that new setup. +I switched to Hugo. The site is now built from Asciidoc documents. You probably saw me switch to Asciidoc for documentation this past year. This is the natural conclusion to that story. The great thing is that with a little bit of Makefile magic I can just copy the documentation files into Hugo and poof, they appear on the website. +I am very happy with that new setup. @@ -176,9 +178,9 @@ https://ninenines.eu/articles/erlanger-playbook-september-2015-update/ An update to The Erlanger Playbook is now available! - The Erlanger Playbook is a book about software development using Erlang. It currently covers all areas from the conception, design, the writing of code, documentation and tests. - The book is still a work in progress. Future topics will include refactoring, debugging and tracing, benchmarking, releases, community management (for open source projects). - This update fixes a number of things and adds two chapters: IOlists and Erlang building blocks. +The Erlanger Playbook is a book about software development using Erlang. It currently covers all areas from the conception, design, the writing of code, documentation and tests. +The book is still a work in progress. Future topics will include refactoring, debugging and tracing, benchmarking, releases, community management (for open source projects). +This update fixes a number of things and adds two chapters: IOlists and Erlang building blocks. @@ -188,9 +190,10 @@ https://ninenines.eu/articles/erlanger-playbook/ I am proud to announce the pre-release of The Erlanger Playbook. - The Erlanger Playbook is a book about software development using Erlang. It currently covers all areas from the conception, design, the writing of code, documentation and tests. - The book is still a work in progress. Future topics will include refactoring, debugging and tracing, benchmarking, releases, community management (for open source projects). - The following sections are currently available: +The Erlanger Playbook is a book about software development using Erlang. It currently covers all areas from the conception, design, the writing of code, documentation and tests. +The book is still a work in progress. Future topics will include refactoring, debugging and tracing, benchmarking, releases, community management (for open source projects). +The following sections are currently available: +About this book; Changelog; Future additions Erlang: Building blocks; Patterns Workflow: Think; Write; Stay productive Documentation: On documentation; Tutorials; User guide; Manual; README files Design: RESTful APIs; Lessons learned Code: Starting a project; Version control; Project structure; Code style; Best practices; Special processes; IOLists; The process dictionary Tests: On testing; Success typing analysis; Manual testing; Unit testing; Functional testing Selling Erlang: On persuasion; Don&apos;t let it crash Read a preview: Special processes @@ -200,8 +203,8 @@ https://ninenines.eu/articles/erlang-validate-utf8/ Yesterday I pushed Websocket permessage-deflate to Cowboy master. I also pushed a change in the way the code validates UTF-8 data (required for text and close frames as per the spec). - When looking into why the permessage-deflate tests in autobahntestsuite were taking such a long time, I found that autobahn is using an adaptation of the algorithm named Flexible and Economical UTF-8 Decoder. This is the C99 implementation: - // Copyright (c) 2008-2009 Bjoern Hoehrmann &lt;bjoern@hoehrmann. +When looking into why the permessage-deflate tests in autobahntestsuite were taking such a long time, I found that autobahn is using an adaptation of the algorithm named Flexible and Economical UTF-8 Decoder. This is the C99 implementation: +// Copyright (c) 2008-2009 Bjoern Hoehrmann &lt;bjoern@hoehrmann. @@ -219,7 +222,7 @@ Sat, 23 Aug 2014 00:00:00 +0100 https://ninenines.eu/articles/the-story-so-far/ - As I am away from home with little to do (some call this a vacation) I wanted to reflect a little on the story so far, or how I arrived to Erlang and got to where I am now. The raw personal experience. It&#8217;ll be an article that&#8217;s more about social aspect, communities and marketing a project than technical considerations. As a period piece, it will also allow me to reflect on the evolution of Erlang in recent years. + As I am away from home with little to do (some call this a vacation) I wanted to reflect a little on the story so far, or how I arrived to Erlang and got to where I am now. The raw personal experience. It&apos;ll be an article that&apos;s more about social aspect, communities and marketing a project than technical considerations. As a period piece, it will also allow me to reflect on the evolution of Erlang in recent years. @@ -229,7 +232,7 @@ https://ninenines.eu/articles/cowboy2-qs/ Now that Cowboy 1.0 is out, I can spend some of my time thinking about Cowboy 2.0 that will be released soon after Erlang/OTP 18.0. This entry discusses the proposed changes to query string handling in Cowboy. - Cowboy 2.0 will respond to user wishes by simplifying the interface of the cowboy_req module. Users want two things: less juggling with the Req variable, and more maps. Maps is the only dynamic key/value data structure in Erlang that we can match directly to extract values, allowing users to greatly simplify their code as they don&#8217;t need to call functions to do everything anymore. +Cowboy 2.0 will respond to user wishes by simplifying the interface of the cowboy_req module. Users want two things: less juggling with the Req variable, and more maps. Maps is the only dynamic key/value data structure in Erlang that we can match directly to extract values, allowing users to greatly simplify their code as they don&apos;t need to call functions to do everything anymore. @@ -239,8 +242,8 @@ https://ninenines.eu/articles/january-2014-status/ I will now be regularly writing posts about project status, plans and hopes for the future. - Before that though, there&#8217;s one important news to share. - Until a year ago all development was financed through consulting and development services. This worked alright but too much time was spent doing things that didn&#8217;t benefit the open source projects. And that didn&#8217;t make me happy at all. Because I like being happy I stopped that for the most part and spent the year figuring things out, experimenting and discussing with people about it. +Before that though, there&apos;s one important news to share. +Until a year ago all development was financed through consulting and development services. This worked alright but too much time was spent doing things that didn&apos;t benefit the open source projects. And that didn&apos;t make me happy at all. Because I like being happy I stopped that for the most part and spent the year figuring things out, experimenting and discussing with people about it. @@ -249,10 +252,10 @@ Thu, 27 Jun 2013 00:00:00 +0100 https://ninenines.eu/articles/farwest-funded/ - This was a triumph! I&#8217;m making a note here: HUGE SUCCESS!! - It&#8217;s hard to overstate my satisfaction. Thanks to everyone who made this possible. - If you have backed this fundraiser, and haven&#8217;t provided your personal details yet, please do so quickly so that your rewards can be sent! - I am hoping that we will be able to make good use of all that money. The details of the expenses will be published regularly on the 2013 Fundraiser wiki page, giving you full disclosure as to how your money is used. + This was a triumph! I&apos;m making a note here: HUGE SUCCESS!! +It&apos;s hard to overstate my satisfaction. Thanks to everyone who made this possible. +If you have backed this fundraiser, and haven&apos;t provided your personal details yet, please do so quickly so that your rewards can be sent! +I am hoping that we will be able to make good use of all that money. The details of the expenses will be published regularly on the 2013 Fundraiser wiki page, giving you full disclosure as to how your money is used. @@ -261,8 +264,8 @@ Tue, 28 May 2013 00:00:00 +0100 https://ninenines.eu/articles/erlang.mk-and-relx/ - Building OTP releases has always been a difficult task. Tools like Reltool or Rebar have made this simpler, but it&#8217;s no panacea. This article will show you an alternative and hopefully much simpler solution. - There is two steps to building a release. First you need to build the various OTP applications you want to include in the release. Once done, you need to create the release itself, by including the Erlang runtime system alongside the applications, a boot script to start the node and all its applications, and some configuration files. + Building OTP releases has always been a difficult task. Tools like Reltool or Rebar have made this simpler, but it&apos;s no panacea. This article will show you an alternative and hopefully much simpler solution. +There is two steps to building a release. First you need to build the various OTP applications you want to include in the release. Once done, you need to create the release itself, by including the Erlang runtime system alongside the applications, a boot script to start the node and all its applications, and some configuration files. @@ -271,9 +274,9 @@ Mon, 25 Mar 2013 00:00:00 +0100 https://ninenines.eu/articles/xerl-0.5-intermediate-module/ - Today we will start the work on the intermediate module that will be used to run the code for the expressions found in our file&#8217;s body, replacing our interpreter. - This is what we want to have when all the work is done: - xerl -&gt; tokens -&gt; AST -&gt; intermediate -&gt; cerl Today we will perform this work only on the atomic integer expression however, so we will not build any module at the end. + Today we will start the work on the intermediate module that will be used to run the code for the expressions found in our file&apos;s body, replacing our interpreter. +This is what we want to have when all the work is done: +xerl -&gt; tokens -&gt; AST -&gt; intermediate -&gt; cerl Today we will perform this work only on the atomic integer expression however, so we will not build any module at the end. @@ -283,9 +286,9 @@ https://ninenines.eu/articles/xerl-0.4-expression-separator/ As promised we are adding an expression separator this time. This will be short and easy. - In the tokenizer we only need to add a line recognizing the comma as a valid token. - , : {token, {',', TokenLine}}. Then we need to change the following lines in the parser: - exprs -&gt; expr : ['$1']. exprs -&gt; expr exprs : ['$1' | '$2']. And add a comma between the expressions on the second line: +In the tokenizer we only need to add a line recognizing the comma as a valid token. +, : {token, {',', TokenLine}}. Then we need to change the following lines in the parser: +exprs -&gt; expr : ['$1']. exprs -&gt; expr exprs : ['$1' | '$2']. And add a comma between the expressions on the second line: @@ -295,7 +298,7 @@ https://ninenines.eu/articles/erlang-scalability/ I would like to share some experience and theories on Erlang scalability. - This will be in the form of a series of hints, which may or may not be accompanied with explanations as to why things are this way, or how they improve or reduce the scalability of a system. I will try to do my best to avoid giving falsehoods, even if that means a few things won&#8217;t be explained. +This will be in the form of a series of hints, which may or may not be accompanied with explanations as to why things are this way, or how they improve or reduce the scalability of a system. I will try to do my best to avoid giving falsehoods, even if that means a few things won&apos;t be explained. @@ -305,8 +308,8 @@ https://ninenines.eu/articles/xerl-0.3-atomic-expressions/ We will be adding atomic integer expressions to our language. These look as follow in Erlang: - 42. And the result of this expression is of course 42. - We will be running this expression at compile time, since we don&#8217;t have the means to run code at runtime yet. This will of course result in no module being compiled, but that&#8217;s OK, it will allow us to discuss a few important things we&#8217;ll have to plan for later on. +42. And the result of this expression is of course 42. +We will be running this expression at compile time, since we don&apos;t have the means to run code at runtime yet. This will of course result in no module being compiled, but that&apos;s OK, it will allow us to discuss a few important things we&apos;ll have to plan for later on. @@ -316,10 +319,10 @@ https://ninenines.eu/articles/xerl-0.2-two-modules/ Everything is an expression. - This sentence carries profound meaning. We will invoke it many times over the course of these articles. - If everything is an expression, then the language shouldn&#8217;t have any problem with me defining two modules in the same source file. - mod first_module begin end mod second_module begin end Likewise, it shouldn&#8217;t have any problem with me defining a module inside another module. - mod out_module begin mod in_module begin end end Of course, in the context of the Erlang VM, these two snippets are equivalent; there is nothing preventing you from calling the in_module module from any other module. +This sentence carries profound meaning. We will invoke it many times over the course of these articles. +If everything is an expression, then the language shouldn&apos;t have any problem with me defining two modules in the same source file. +mod first_module begin end mod second_module begin end Likewise, it shouldn&apos;t have any problem with me defining a module inside another module. +mod out_module begin mod in_module begin end end Of course, in the context of the Erlang VM, these two snippets are equivalent; there is nothing preventing you from calling the in_module module from any other module. @@ -328,9 +331,9 @@ Wed, 30 Jan 2013 00:00:00 +0100 https://ninenines.eu/articles/xerl-0.1-empty-modules/ - Let&#8217;s build a programming language. I call it Xerl: eXtended ERLang. It&#8217;ll be an occasion for us to learn a few things, especially me. - Unlike in Erlang, in this language, everything is an expression. This means that modules and functions are expression, and indeed that you can have more than one module per file. - We are just starting, so let&#8217;s no go ahead of ourselves here. We&#8217;ll begin with writing the code allowing us to compile an empty module. + Let&apos;s build a programming language. I call it Xerl: eXtended ERLang. It&apos;ll be an occasion for us to learn a few things, especially me. +Unlike in Erlang, in this language, everything is an expression. This means that modules and functions are expression, and indeed that you can have more than one module per file. +We are just starting, so let&apos;s no go ahead of ourselves here. We&apos;ll begin with writing the code allowing us to compile an empty module. @@ -340,7 +343,7 @@ https://ninenines.eu/articles/ranch-ftp/ Last week I was speaking at the London Erlang Factory Lite where I presented a live demonstration of building an FTP server using Ranch. As there was no slide, you should use this article as a reference instead. - The goal of this article is to showcase how to use Ranch for writing a network protocol implementation, how Ranch gets out of the way to let you write the code that matters, and the common techniques used when writing servers. +The goal of this article is to showcase how to use Ranch for writing a network protocol implementation, how Ranch gets out of the way to let you write the code that matters, and the common techniques used when writing servers. @@ -350,9 +353,9 @@ https://ninenines.eu/articles/tictactoe/ Everyone knows Tic Tac Toe, right? - Players choose either to be the Xs or the Os, then place their symbol on a 3x3 board one after another, trying to create a line of 3 of them. - Writing an algorithm to check for victory sounds easy, right? It&#8217;s easily tested, considering there&#8217;s only 8 possible winning rows (3 horizontal, 3 vertical and 2 diagonal). - In Erlang though, you probably wouldn&#8217;t want an algorithm. +Players choose either to be the Xs or the Os, then place their symbol on a 3x3 board one after another, trying to create a line of 3 of them. +Writing an algorithm to check for victory sounds easy, right? It&apos;s easily tested, considering there&apos;s only 8 possible winning rows (3 horizontal, 3 vertical and 2 diagonal). +In Erlang though, you probably wouldn&apos;t want an algorithm. diff --git a/articles/january-2014-status/index.html b/articles/january-2014-status/index.html index 2c489556..6548a920 100644 --- a/articles/january-2014-status/index.html +++ b/articles/january-2014-status/index.html @@ -69,146 +69,41 @@

-

I will now be regularly writing posts about project status, plans -and hopes for the future.

-

Before that though, there’s one important news to share.

-

Until a year ago all development was financed through consulting -and development services. This worked alright but too much time was -spent doing things that didn’t benefit the open source projects. -And that didn’t make me happy at all. Because I like being happy -I stopped that for the most part and spent the year figuring things -out, experimenting and discussing with people about it.

-

What makes me happy is answering these "what if" questions. -Ranch and Cowboy are a direct product of that, as they originate -from the "what if we could have a server running different protocols -on different ports but all part of the same application?"; Erlang.mk -is a bit different: "this works great for me, what if it could -become the standard solution for building Erlang applications?".

-

When I successfully answer the question, this becomes a project -that may end up largely benefiting the Erlang community. I love -Erlang and I love enabling people to build awesome products based -on my projects. It’s a lot more rewarding than activities like -consulting where you only help one company at a time. And it’s -also a much better use of my time as this has a bigger impact on -the community.

-

The hard part is to figure out how to be able to spend 100% -of the time on projects that you basically give away for free, -and still be able to afford living.

-

The immediate solution was getting work sponsored by the -LeoFS project. LeoFS is a great -distributed file storage that I can only recommend to anyone who -needs to store files or large pieces of data. The sponsorship -works pretty great, and spurred development of the SPDY code in -Cowboy amongst other things, plus a couple upcoming projects -done more recently and getting a final touch before release.

-

It turns out sponsoring works great. So I’m thinking of -expanding on it and hopefully get enough sponsoring for fulltime -open source development. So I figured out a few things that -can give incentive to companies willing to sponsor.

-

Sponsors can request that a particular version of Cowboy -be maintained indefinitely (as long as they’re sponsoring). -This means fixes will be backported. This doesn’t include -features although I can take requests depending on feasability.

-

Sponsors can have a direct, private line of communication, -useful when they need help debugging or optimizing their product.

-

Sponsors can get their name associated with one of the -project and get a good standing in the community thanks -to this. They would be featured in the README of the project -which is viewed by hundreds of developers daily.

-

Sponsors can be listed on this website. I will modify -the front page when we get a few more sponsors, they will be -featured below the carousel of projects.

-

Please contact us if -you are interested in sponsoring, and say how much you are willing -to sponsor. The goal here is only to have enough money to make a -living and attend a few conferences. There’s an upper limit in the -amount needed per year, so the more sponsors there are the cheaper -it becomes to everyone.

-

The upper limit stems from the new legal entity that will replace -the current Nine Nines. This is mostly to lower the legal costs and -simplify the administrative stuff and allow me to dedicate all my -time on what’s important. From your point of view it’s business as -usual.

-

Now on to project statuses and future works.

-
+

I will now be regularly writing posts about project status, plans and hopes for the future.

+

Before that though, there's one important news to share.

+

Until a year ago all development was financed through consulting and development services. This worked alright but too much time was spent doing things that didn't benefit the open source projects. And that didn't make me happy at all. Because I like being happy I stopped that for the most part and spent the year figuring things out, experimenting and discussing with people about it.

+

What makes me happy is answering these "what if" questions. Ranch and Cowboy are a direct product of that, as they originate from the "what if we could have a server running different protocols on different ports but all part of the same application?"; Erlang.mk is a bit different: "this works great for me, what if it could become the standard solution for building Erlang applications?".

+

When I successfully answer the question, this becomes a project that may end up largely benefiting the Erlang community. I love Erlang and I love enabling people to build awesome products based on my projects. It's a lot more rewarding than activities like consulting where you only help one company at a time. And it's also a much better use of my time as this has a bigger impact on the community.

+

The hard part is to figure out how to be able to spend 100% of the time on projects that you basically give away for free, and still be able to afford living.

+

The immediate solution was getting work sponsored by the LeoFS project. LeoFS is a great distributed file storage that I can only recommend to anyone who needs to store files or large pieces of data. The sponsorship works pretty great, and spurred development of the SPDY code in Cowboy amongst other things, plus a couple upcoming projects done more recently and getting a final touch before release.

+

It turns out sponsoring works great. So I'm thinking of expanding on it and hopefully get enough sponsoring for fulltime open source development. So I figured out a few things that can give incentive to companies willing to sponsor.

+

Sponsors can request that a particular version of Cowboy be maintained indefinitely (as long as they're sponsoring). This means fixes will be backported. This doesn't include features although I can take requests depending on feasability.

+

Sponsors can have a direct, private line of communication, useful when they need help debugging or optimizing their product.

+

Sponsors can get their name associated with one of the project and get a good standing in the community thanks to this. They would be featured in the README of the project which is viewed by hundreds of developers daily.

+

Sponsors can be listed on this website. I will modify the front page when we get a few more sponsors, they will be featured below the carousel of projects.

+

Please contact us if you are interested in sponsoring, and say how much you are willing to sponsor. The goal here is only to have enough money to make a living and attend a few conferences. There's an upper limit in the amount needed per year, so the more sponsors there are the cheaper it becomes to everyone.

+

The upper limit stems from the new legal entity that will replace the current Nine Nines. This is mostly to lower the legal costs and simplify the administrative stuff and allow me to dedicate all my time on what's important. From your point of view it's business as usual.

+

Now on to project statuses and future works.

Cowboy

-
-

Cowboy is getting ready for a 1.0 release. Once multipart support -is in, all that’s left is finishing the guide, improving tests and -finishing moving code to the cowlib project. I hope everything will -be ready around the time R17B is released.

-

I already dream of some API breaking changes after 1.0, which -would essentially become 2.0 when they’re done. An extensive survey -will be setup after the 1.0 release to get more information on what -people like and don’t like about the API.

-

And of course, when clients start implementing HTTP/2.0 then we -will too.

-
-
-
+

Cowboy is getting ready for a 1.0 release. Once multipart support is in, all that's left is finishing the guide, improving tests and finishing moving code to the cowlib project. I hope everything will be ready around the time R17B is released.

+

I already dream of some API breaking changes after 1.0, which would essentially become 2.0 when they're done. An extensive survey will be setup after the 1.0 release to get more information on what people like and don't like about the API.

+

And of course, when clients start implementing HTTP/2.0 then we will too.

Ranch

-
-

Ranch is also getting close to 1.0. I am currently writing a -test suite for upgrades. After that I also would like to write -a chaos_monkey test suite and add a getting started chapter to the -guide.

-

Ranch is pretty solid otherwise, it’s hard to foresee new -features at this point.

-
-
-
+

Ranch is also getting close to 1.0. I am currently writing a test suite for upgrades. After that I also would like to write a chaos_monkey test suite and add a getting started chapter to the guide.

+

Ranch is pretty solid otherwise, it's hard to foresee new features at this point.

Erlang.mk

-
-

I didn’t expect this project to become popular. Glad it did though.

-

Windows support is planned, but will require GNU Make 4. -Thankfully, it’s available at least through cygwin. Make, -Git and Erlang will be the only required dependencies -because the rest of the external calls will be converted to -using Guile, a Scheme included since GNU Make 4. So it is -Guile that will download the needed files, magically fill -the list of modules in the .app file and so on, allowing -us to provide a truly cross-platform solution without -losing on the performance we benefit from using Make.

-

Also note that it is possible to check whether Guile -is available so we will be able to fallback to the current -code for older systems.

-

I am also thinking about adding an extra column to the package -index, indicating the preferred tag or commit number to be used. -This would allow us to skip the individual dep lines -entirely if the information in the package index is good enough. -And committing that file to your project would be the only thing -needed to lock the dependencies. Of course if a dep -line is specified this would instead override the file.

-
-
-
+

I didn't expect this project to become popular. Glad it did though.

+

Windows support is planned, but will require GNU Make 4. Thankfully, it's available at least through cygwin. Make, Git and Erlang will be the only required dependencies because the rest of the external calls will be converted to using Guile, a Scheme included since GNU Make 4. So it is Guile that will download the needed files, magically fill the list of modules in the .app file and so on, allowing us to provide a truly cross-platform solution without losing on the performance we benefit from using Make.

+

Also note that it is possible to check whether Guile is available so we will be able to fallback to the current code for older systems.

+

I am also thinking about adding an extra column to the package index, indicating the preferred tag or commit number to be used. This would allow us to skip the individual dep lines entirely if the information in the package index is good enough. And committing that file to your project would be the only thing needed to lock the dependencies. Of course if a dep line is specified this would instead override the file.

Alien Shaman

-
-

This is the two-parts project requested by the LeoFS team. -This is essentially a "distributed bigwig". I am hoping to -have a prototype up in a few days.

-

Alien is the part that allows writing and enabling probes -in your nodes. Probes send events which may get filtered before -being forwarded to their destination. The events may be sent -to a local process, a remote process, over UDP, TCP or SSL. -Events may also be received by a process called a relay, which -may be used to group or aggregate data before it is being sent -over the network, reducing the footprint overall.

-

Shaman is the UI for it. It will ultimately be able to display -any event as long as it’s configured to do so. Events may be logs, -numeric values displayed on graphs updated in real time, lists of -items like processes and so on.

-
-
-
+

This is the two-parts project requested by the LeoFS team. This is essentially a "distributed bigwig". I am hoping to have a prototype up in a few days.

+

Alien is the part that allows writing and enabling probes in your nodes. Probes send events which may get filtered before being forwarded to their destination. The events may be sent to a local process, a remote process, over UDP, TCP or SSL. Events may also be received by a process called a relay, which may be used to group or aggregate data before it is being sent over the network, reducing the footprint overall.

+

Shaman is the UI for it. It will ultimately be able to display any event as long as it's configured to do so. Events may be logs, numeric values displayed on graphs updated in real time, lists of items like processes and so on.

Feedback

-
-

That’s it for today! There will be another status update once -Shaman is out. But for now I have to focus on it.

-

As always, please send feedback on the projects, this post, -the sponsoring idea, anything really! Thanks.

-
-
+

That's it for today! There will be another status update once Shaman is out. But for now I have to focus on it.

+

As always, please send feedback on the projects, this post, the sponsoring idea, anything really! Thanks.

+ diff --git a/articles/ml-archives/index.html b/articles/ml-archives/index.html index fd96cbc1..1d0862fc 100644 --- a/articles/ml-archives/index.html +++ b/articles/ml-archives/index.html @@ -69,16 +69,12 @@

-

The old mailing list archives have been -added to the site, mainly for referencing purposes.

-

The mailing list has been shut down and all personal information -has been deleted.

-

If you need help with a project, consider either opening a ticket -on that project’s issues tracker or going through the community -channels (erlang-questions, #ninenines or #erlang on Freenode).

-

Prefer tickets; often when people have issues it highlights an -underlying problem in the project or its documentation.

-

Thanks.

+

The old mailing list archives have been added to the site, mainly for referencing purposes.

+

The mailing list has been shut down and all personal information has been deleted.

+

If you need help with a project, consider either opening a ticket on that project's issues tracker or going through the community channels (erlang-questions, #ninenines or #erlang on Freenode).

+

Prefer tickets; often when people have issues it highlights an underlying problem in the project or its documentation.

+

Thanks.

+ diff --git a/articles/on-open-source/index.html b/articles/on-open-source/index.html index 08340dfc..e3c476e0 100644 --- a/articles/on-open-source/index.html +++ b/articles/on-open-source/index.html @@ -69,123 +69,24 @@

-

Last week I read a great article -on -contributing to open source by Alvaro Videla. He makes -many great points and I am in agreement with most of it. -This made me want to properly explain my point of view with -regard to open source and contributions. Unlike most open -source evangelism articles I will not talk about ideals or -any of that crap, but rather my personal feelings and -experience.

-

I have been doing open source work for quite some time. -My very first open source project was a graphics driver -for (the very early version of) the PCSX2 emulator. That -was more than ten years ago, and there -isn’t -much left to look at today. This was followed by a -PHP framework -(started long before Zend Framework was even a thing) and -a few other small projects. None of them really took off. -It’s alright, that’s pretty much the fate of most open -source projects. You spend a lot of work and sweat and -get very little in return from others.

-

This sounds harsh but this is the reality of all open -source projects. If you are thinking of building a project -and releasing it as open source, you should be prepared -for that. This is how most of your projects will feel like. -Don’t release a project as open source thinking everyone -will pat you on the back and cheer, this won’t happen. In -fact if your project is a too small improvement over existing -software, what many people will do is say you have NIH -syndrome, regardless of the improvement you bring. So you -need not to rely on other people in order to get your -enjoyment out of building open source software.

-

In my case I get enjoyment from thinking about problems -that need solving. Often times the problems are already -solved, but nevermind that, I still think about them and -sometimes come up with something I feel is better and then -write code for it. Writing code is also fun, but not as -fun as using my brain to imagine solutions.

-

You don’t need thousands of users to do that. So are -users worthless to me then? No, of course not. In fact -they are an important component: they bring me problems -that need solving. So users are very important to me. -But that’s not the only reason.

-

I got lucky that the Cowboy project became popular. -And seeing it be this popular, and some of my other projects -also do quite well, made me believe I could perhaps work -full time on open source. If I can work full time then -I can produce better software. What I had one hour to -work on before I can now spend a day on, and experiment -until I am satisfied. This is very useful because that -means I can get it almost right from the beginning, and -avoid the million API breaking changes that occured -before Cowboy 1.0 was released.

-

To be able to work full time on open source however, -I need money. This is a largely unspoken topic of open -source work. The work is never free. You can download the -product for free, but someone has to pay for the work -itself. Life is unfortunately not free.

-

Large projects and some lucky people have their work -sponsored by their employers. Everyone else has to deal -with it differently. In my case I was sponsored for a -while by the LeoFS -project, but that ended. I also had the Farwest fundraiser, -which was a success, although the project stalled after that. -(Fear not, as Farwest will make a comeback as a conglomerate -of Web development projects in the future.) After that I set -up the sponsoring scheme, -which I can proudly say today brings in enough money to -cover my food and shelter. Great!

-

This is a start, but it’s of course not enough. Life -is a little more than food and shelter, and so I am still -looking for sponsors. This is not a very glorious experience, -as I am essentially looking for scraps that companies can -throw away. Still, if a handful more companies were doing -that, not only would I be able to live comfortably, but I -would also be able to stop worrying about the future as I -could put money on the side for when it gets rough.

-

A few companies giving me some scrap money so I could -live and work independently is by far the most important -thing anyone can do to help my projects, including Cowboy. -Yes, they’re even more important than code contributions, -bug reports and feedback. Because this money gives me the -time I need to handle the code contributions, bug reports -and feedback.

-

If Cowboy or another project is a large part of your -product or infrastructure, then the best thing you can do -is become a sponsor. The second best is opening tickets -and/or providing feedback. The third best is providing -good code contributions.

-

I will not expand on the feedback part. Feedback is -very important, and even just a high five or a retweet -is already good feedback. It’s not very complicated.

-

I want to expand a little on code contributions -however. Not long ago I ran across the term "patch bomb" -which means dropping patches and expecting the project -maintainers to merge them and maintain them. I receive -a lot of patches, and often have to refuse them. Causes -for refusal vary. Some patches only benefit the people -who submitted them (or a very small number of people). -Some patches are not refined enough to be included. -Others are out of scope of the project. These are some -of the reasons why I refuse patches. Having limited -time and resources, I have to focus my efforts on the -code used by the larger number of users. I have to -prioritize patches from submitters who are reactive -and address the issues pointed out. And I have to plainly -refuse other patches.

-

I believe this wraps up my thoughts on open source. -Overall I had a great experience, the Erlang community -being nice and understanding of the issues at hand in -general. And if the money problem could be solved soon, -then I would be one of the luckiest and happiest open -source developer on Earth.

-

Think about it the next time you see a donation button -or a request for funds or sponsoring. You can considerably -improve an open source developer’s life with very little -of your company’s money.

+

Last week I read a great article on +contributing to open source by Alvaro Videla. He makes many great points and I am in agreement with most of it. This made me want to properly explain my point of view with regard to open source and contributions. Unlike most open source evangelism articles I will not talk about ideals or any of that crap, but rather my personal feelings and experience.

+

I have been doing open source work for quite some time. My very first open source project was a graphics driver for (the very early version of) the PCSX2 emulator. That was more than ten years ago, and there isn't +much left to look at today. This was followed by a PHP framework (started long before Zend Framework was even a thing) and a few other small projects. None of them really took off. It's alright, that's pretty much the fate of most open source projects. You spend a lot of work and sweat and get very little in return from others.

+

This sounds harsh but this is the reality of all open source projects. If you are thinking of building a project and releasing it as open source, you should be prepared for that. This is how most of your projects will feel like. Don't release a project as open source thinking everyone will pat you on the back and cheer, this won't happen. In fact if your project is a too small improvement over existing software, what many people will do is say you have NIH syndrome, regardless of the improvement you bring. So you need not to rely on other people in order to get your enjoyment out of building open source software.

+

In my case I get enjoyment from thinking about problems that need solving. Often times the problems are already solved, but nevermind that, I still think about them and sometimes come up with something I feel is better and then write code for it. Writing code is also fun, but not as fun as using my brain to imagine solutions.

+

You don't need thousands of users to do that. So are users worthless to me then? No, of course not. In fact they are an important component: they bring me problems that need solving. So users are very important to me. But that's not the only reason.

+

I got lucky that the Cowboy project became popular. And seeing it be this popular, and some of my other projects also do quite well, made me believe I could perhaps work full time on open source. If I can work full time then I can produce better software. What I had one hour to work on before I can now spend a day on, and experiment until I am satisfied. This is very useful because that means I can get it almost right from the beginning, and avoid the million API breaking changes that occured before Cowboy 1.0 was released.

+

To be able to work full time on open source however, I need money. This is a largely unspoken topic of open source work. The work is never free. You can download the product for free, but someone has to pay for the work itself. Life is unfortunately not free.

+

Large projects and some lucky people have their work sponsored by their employers. Everyone else has to deal with it differently. In my case I was sponsored for a while by the LeoFS project, but that ended. I also had the Farwest fundraiser, which was a success, although the project stalled after that. (Fear not, as Farwest will make a comeback as a conglomerate of Web development projects in the future.) After that I set up the sponsoring scheme, which I can proudly say today brings in enough money to cover my food and shelter. Great!

+

This is a start, but it's of course not enough. Life is a little more than food and shelter, and so I am still looking for sponsors. This is not a very glorious experience, as I am essentially looking for scraps that companies can throw away. Still, if a handful more companies were doing that, not only would I be able to live comfortably, but I would also be able to stop worrying about the future as I could put money on the side for when it gets rough.

+

A few companies giving me some scrap money so I could live and work independently is by far the most important thing anyone can do to help my projects, including Cowboy. Yes, they're even more important than code contributions, bug reports and feedback. Because this money gives me the time I need to handle the code contributions, bug reports and feedback.

+

If Cowboy or another project is a large part of your product or infrastructure, then the best thing you can do is become a sponsor. The second best is opening tickets and/or providing feedback. The third best is providing good code contributions.

+

I will not expand on the feedback part. Feedback is very important, and even just a high five or a retweet is already good feedback. It's not very complicated.

+

I want to expand a little on code contributions however. Not long ago I ran across the term "patch bomb" which means dropping patches and expecting the project maintainers to merge them and maintain them. I receive a lot of patches, and often have to refuse them. Causes for refusal vary. Some patches only benefit the people who submitted them (or a very small number of people). Some patches are not refined enough to be included. Others are out of scope of the project. These are some of the reasons why I refuse patches. Having limited time and resources, I have to focus my efforts on the code used by the larger number of users. I have to prioritize patches from submitters who are reactive and address the issues pointed out. And I have to plainly refuse other patches.

+

I believe this wraps up my thoughts on open source. Overall I had a great experience, the Erlang community being nice and understanding of the issues at hand in general. And if the money problem could be solved soon, then I would be one of the luckiest and happiest open source developer on Earth.

+

Think about it the next time you see a donation button or a request for funds or sponsoring. You can considerably improve an open source developer's life with very little of your company's money.

+ diff --git a/articles/page/2/index.html b/articles/page/2/index.html index 194f9243..c8629fe5 100644 --- a/articles/page/2/index.html +++ b/articles/page/2/index.html @@ -75,8 +75,8 @@

I will now be regularly writing posts about project status, plans and hopes for the future. - Before that though, there’s one important news to share. - Until a year ago all development was financed through consulting and development services. This worked alright but too much time was spent doing things that didn’t benefit the open source projects. And that didn’t make me happy at all. Because I like being happy I stopped that for the most part and spent the year figuring things out, experimenting and discussing with people about it.

+Before that though, there's one important news to share. +Until a year ago all development was financed through consulting and development services. This worked alright but too much time was spent doing things that didn't benefit the open source projects. And that didn't make me happy at all. Because I like being happy I stopped that for the most part and spent the year figuring things out, experimenting and discussing with people about it.

Read More @@ -92,10 +92,10 @@

-

This was a triumph! I’m making a note here: HUGE SUCCESS!! - It’s hard to overstate my satisfaction. Thanks to everyone who made this possible. - If you have backed this fundraiser, and haven’t provided your personal details yet, please do so quickly so that your rewards can be sent! - I am hoping that we will be able to make good use of all that money. The details of the expenses will be published regularly on the 2013 Fundraiser wiki page, giving you full disclosure as to how your money is used.

+

This was a triumph! I'm making a note here: HUGE SUCCESS!! +It's hard to overstate my satisfaction. Thanks to everyone who made this possible. +If you have backed this fundraiser, and haven't provided your personal details yet, please do so quickly so that your rewards can be sent! +I am hoping that we will be able to make good use of all that money. The details of the expenses will be published regularly on the 2013 Fundraiser wiki page, giving you full disclosure as to how your money is used.

Read More @@ -111,8 +111,8 @@

-

Building OTP releases has always been a difficult task. Tools like Reltool or Rebar have made this simpler, but it’s no panacea. This article will show you an alternative and hopefully much simpler solution. - There is two steps to building a release. First you need to build the various OTP applications you want to include in the release. Once done, you need to create the release itself, by including the Erlang runtime system alongside the applications, a boot script to start the node and all its applications, and some configuration files.

+

Building OTP releases has always been a difficult task. Tools like Reltool or Rebar have made this simpler, but it's no panacea. This article will show you an alternative and hopefully much simpler solution. +There is two steps to building a release. First you need to build the various OTP applications you want to include in the release. Once done, you need to create the release itself, by including the Erlang runtime system alongside the applications, a boot script to start the node and all its applications, and some configuration files.

Read More @@ -128,9 +128,9 @@

-

Today we will start the work on the intermediate module that will be used to run the code for the expressions found in our file’s body, replacing our interpreter. - This is what we want to have when all the work is done: - xerl -> tokens -> AST -> intermediate -> cerl Today we will perform this work only on the atomic integer expression however, so we will not build any module at the end.

+

Today we will start the work on the intermediate module that will be used to run the code for the expressions found in our file's body, replacing our interpreter. +This is what we want to have when all the work is done: +xerl -> tokens -> AST -> intermediate -> cerl Today we will perform this work only on the atomic integer expression however, so we will not build any module at the end.

Read More @@ -147,9 +147,9 @@

As promised we are adding an expression separator this time. This will be short and easy. - In the tokenizer we only need to add a line recognizing the comma as a valid token. - , : {token, {',', TokenLine}}. Then we need to change the following lines in the parser: - exprs -> expr : ['$1']. exprs -> expr exprs : ['$1' | '$2']. And add a comma between the expressions on the second line:

+In the tokenizer we only need to add a line recognizing the comma as a valid token. +, : {token, {',', TokenLine}}. Then we need to change the following lines in the parser: +exprs -> expr : ['$1']. exprs -> expr exprs : ['$1' | '$2']. And add a comma between the expressions on the second line:

Read More @@ -166,7 +166,7 @@

I would like to share some experience and theories on Erlang scalability. - This will be in the form of a series of hints, which may or may not be accompanied with explanations as to why things are this way, or how they improve or reduce the scalability of a system. I will try to do my best to avoid giving falsehoods, even if that means a few things won’t be explained.

+This will be in the form of a series of hints, which may or may not be accompanied with explanations as to why things are this way, or how they improve or reduce the scalability of a system. I will try to do my best to avoid giving falsehoods, even if that means a few things won't be explained.

Read More @@ -183,8 +183,8 @@

We will be adding atomic integer expressions to our language. These look as follow in Erlang: - 42. And the result of this expression is of course 42. - We will be running this expression at compile time, since we don’t have the means to run code at runtime yet. This will of course result in no module being compiled, but that’s OK, it will allow us to discuss a few important things we’ll have to plan for later on.

+42. And the result of this expression is of course 42. +We will be running this expression at compile time, since we don't have the means to run code at runtime yet. This will of course result in no module being compiled, but that's OK, it will allow us to discuss a few important things we'll have to plan for later on.

Read More @@ -201,10 +201,10 @@

Everything is an expression. - This sentence carries profound meaning. We will invoke it many times over the course of these articles. - If everything is an expression, then the language shouldn’t have any problem with me defining two modules in the same source file. - mod first_module begin end mod second_module begin end Likewise, it shouldn’t have any problem with me defining a module inside another module. - mod out_module begin mod in_module begin end end Of course, in the context of the Erlang VM, these two snippets are equivalent; there is nothing preventing you from calling the in_module module from any other module.

+This sentence carries profound meaning. We will invoke it many times over the course of these articles. +If everything is an expression, then the language shouldn't have any problem with me defining two modules in the same source file. +mod first_module begin end mod second_module begin end Likewise, it shouldn't have any problem with me defining a module inside another module. +mod out_module begin mod in_module begin end end Of course, in the context of the Erlang VM, these two snippets are equivalent; there is nothing preventing you from calling the in_module module from any other module.

Read More @@ -220,9 +220,9 @@

-

Let’s build a programming language. I call it Xerl: eXtended ERLang. It’ll be an occasion for us to learn a few things, especially me. - Unlike in Erlang, in this language, everything is an expression. This means that modules and functions are expression, and indeed that you can have more than one module per file. - We are just starting, so let’s no go ahead of ourselves here. We’ll begin with writing the code allowing us to compile an empty module.

+

Let's build a programming language. I call it Xerl: eXtended ERLang. It'll be an occasion for us to learn a few things, especially me. +Unlike in Erlang, in this language, everything is an expression. This means that modules and functions are expression, and indeed that you can have more than one module per file. +We are just starting, so let's no go ahead of ourselves here. We'll begin with writing the code allowing us to compile an empty module.

Read More @@ -239,7 +239,7 @@

Last week I was speaking at the London Erlang Factory Lite where I presented a live demonstration of building an FTP server using Ranch. As there was no slide, you should use this article as a reference instead. - The goal of this article is to showcase how to use Ranch for writing a network protocol implementation, how Ranch gets out of the way to let you write the code that matters, and the common techniques used when writing servers.

+The goal of this article is to showcase how to use Ranch for writing a network protocol implementation, how Ranch gets out of the way to let you write the code that matters, and the common techniques used when writing servers.

Read More @@ -256,9 +256,9 @@

Everyone knows Tic Tac Toe, right? - Players choose either to be the Xs or the Os, then place their symbol on a 3x3 board one after another, trying to create a line of 3 of them. - Writing an algorithm to check for victory sounds easy, right? It’s easily tested, considering there’s only 8 possible winning rows (3 horizontal, 3 vertical and 2 diagonal). - In Erlang though, you probably wouldn’t want an algorithm.

+Players choose either to be the Xs or the Os, then place their symbol on a 3x3 board one after another, trying to create a line of 3 of them. +Writing an algorithm to check for victory sounds easy, right? It's easily tested, considering there's only 8 possible winning rows (3 horizontal, 3 vertical and 2 diagonal). +In Erlang though, you probably wouldn't want an algorithm.

Read More diff --git a/articles/ranch-1.3/index.html b/articles/ranch-1.3/index.html index 914259e4..43d90a8c 100644 --- a/articles/ranch-1.3/index.html +++ b/articles/ranch-1.3/index.html @@ -69,88 +69,53 @@

-

Ranch 1.3.0 has been released!

-

This release fixes a number of long standing issues and adds -a small number of features:

-

The ssl application has been added to the list of dependencies. -If you don’t need it, you can remove it automatically when fetching -Ranch or when building the release. If you do need it, you will no -longer have issues shutting down a node because of Ranch.

-

The ranch:info/0 and ranch:procs/2 can be used to retrieve -information about Ranch’s state. Use it for diagnostic and -discovery purposes.

-

SSL listeners can now be configured without a certificate, for setups -that make use of the SNI extension.

-

Transport options are now a blacklist, meaning all unknown options -will be accepted. However Dialyzer will warn if said option is not -defined in Ranch’s type specifications. Please send a patch when that -happens!

-

Various bugs have been fixed, including the bug where the -number of active connections could become negative. Common -errors at listener startup should be easier to read (for -example when the port is already in use).

-

See the CHANGELOG -for more details.

-

Ranch is now tested and supported with Erlang/OTP R16B or above -on Arch Linux, FreeBSD, OSX, Ubuntu and Windows 7. Contact me -if you can provide permanent access to another platform for the -purposes of testing.

-

Ranch is now available from four locations:

-
    -
  • -

    -https://git.ninenines.eu/ranch.git -

    +

    Ranch 1.3.0 has been released!

    +

    This release fixes a number of long standing issues and adds a small number of features:

    +

    The ssl application has been added to the list of dependencies. If you don't need it, you can remove it automatically when fetching Ranch or when building the release. If you do need it, you will no longer have issues shutting down a node because of Ranch.

    +

    The ranch:info/0 and ranch:procs/2 can be used to retrieve information about Ranch's state. Use it for diagnostic and discovery purposes.

    +

    SSL listeners can now be configured without a certificate, for setups that make use of the SNI extension.

    +

    Transport options are now a blacklist, meaning all unknown options will be accepted. However Dialyzer will warn if said option is not defined in Ranch's type specifications. Please send a patch when that happens!

    +

    Various bugs have been fixed, including the bug where the number of active connections could become negative. Common errors at listener startup should be easier to read (for example when the port is already in use).

    +

    See the CHANGELOG for more details.

    +

    Ranch is now tested and supported with Erlang/OTP R16B or above on Arch Linux, FreeBSD, OSX, Ubuntu and Windows 7. Contact me if you can provide permanent access to another platform for the purposes of testing.

    +

    Ranch is now available from four locations:

    +
-

They are updated at the same time so there is no real difference.

-

The most recent Ranch commit is now always signed. You can import the -signing key for Loïc Hoguin with:

-
-
-
$ gpg --keyserver hkp://keys.gnupg.net --recv-key 66CCCC8A
-

The primary key fingerprint is F19F 189C ECC7 4396 99CE DD7A 6EF7 A770 66CC CC8A.

-

When verifying signatures in git, the following should appear:

-
-
-
gpg: Signature made Sat 26 Nov 2016 12:58:35 PM CET
-gpg:                using RSA key 71366FF21851DF03
-gpg: Good signature from "Loïc Hoguin <essen@ninenines.eu>" [unknown]
-gpg: WARNING: This key is not certified with a trusted signature!
-gpg:          There is no indication that the signature belongs to the owner.
-Primary key fingerprint: F19F 189C ECC7 4396 99CE  DD7A 6EF7 A770 66CC CC8A
-     Subkey fingerprint: FEDA 6E41 B390 F745 A385  5CDC 7136 6FF2 1851 DF03
-

You can safely ignore the warning if you don’t know what it -means, as long as everything else is correct.

-

Mirrors and signature verification will soon be implemented -directly in Erlang.mk. In the meantime, you will need to -set them up manually.

-

Most of this work was done to fix issues in RabbitMQ. Paid -customers get priority; contact me if you have some issues -that need fixing sooner rather than later.

-

Expect future releases to be announced in this space.

-

Thanks for reading!

+
gpg: Signature made Sat 26 Nov 2016 12:58:35 PM CET
+gpg:                using RSA key 71366FF21851DF03
+gpg: Good signature from "Loïc Hoguin <essen@ninenines.eu>" [unknown]
+gpg: WARNING: This key is not certified with a trusted signature!
+gpg:          There is no indication that the signature belongs to the owner.
+Primary key fingerprint: F19F 189C ECC7 4396 99CE  DD7A 6EF7 A770 66CC CC8A
+     Subkey fingerprint: FEDA 6E41 B390 F745 A385  5CDC 7136 6FF2 1851 DF03
+ +

You can safely ignore the warning if you don't know what it means, as long as everything else is correct.

+

Mirrors and signature verification will soon be implemented directly in Erlang.mk. In the meantime, you will need to set them up manually.

+

Most of this work was done to fix issues in RabbitMQ. Paid customers get priority; contact me if you have some issues that need fixing sooner rather than later.

+

Expect future releases to be announced in this space.

+

Thanks for reading!

+ diff --git a/articles/ranch-ftp/index.html b/articles/ranch-ftp/index.html index f5a30f51..58d4b220 100644 --- a/articles/ranch-ftp/index.html +++ b/articles/ranch-ftp/index.html @@ -69,216 +69,155 @@

-

Last week I was speaking at the -London Erlang Factory Lite -where I presented a live demonstration of building an FTP server using -Ranch. -As there was no slide, you should use this article as a reference instead.

-

The goal of this article is to showcase how to use Ranch for writing -a network protocol implementation, how Ranch gets out of the way to let -you write the code that matters, and the common techniques used when -writing servers.

-

Let’s start by creating an empty project. Create a new directory and -then open a terminal into that directory. The first step is to add Ranch -as a dependency. Create the rebar.config file and add the -following 3 lines.

-
-
-
{deps, [
-    {ranch, ".*", {git, "git://github.com/extend/ranch.git", "master"}}
-]}.
-

This makes your application depend on the last Ranch version available -on the master branch. This is fine for development, however when -you start pushing your application to production you will want to revisit -this file to hardcode the exact version you are using, to make sure you -run the same version of dependencies in production.

-

You can now fetch the dependencies.

-
-
$ rebar get-deps
-==> ranch_ftp (get-deps)
-Pulling ranch from {git,"git://github.com/extend/ranch.git","master"}
-Cloning into 'ranch'...
-==> ranch (get-deps)
-

This will create a deps/ folder containing Ranch.

-

We don’t actually need anything else to write the protocol code. -We could make an application for it, but this isn’t the purpose of this -article so let’s just move on to writing the protocol itself. Create -the file ranch_ftp_protocol.erl and open it in your favorite -editor.

-
-
-
$ vim ranch_ftp_protocol.erl
-

Let’s start with a blank protocol module.

-
-
-
-module(ranch_ftp_protocol).
--export([start_link/4, init/3]).
+
-module(ranch_ftp_protocol).
+-export([start_link/4, init/3]).
 
-start_link(ListenerPid, Socket, Transport, Opts) ->
-    Pid = spawn_link(?MODULE, init, [ListenerPid, Socket, Transport]),
-    {ok, Pid}.
+start_link(ListenerPid, Socket, Transport, Opts) ->
+    Pid = spawn_link(?MODULE, init, [ListenerPid, Socket, Transport]),
+    {ok, Pid}.
 
-init(ListenerPid, Socket, Transport) ->
-    io:format("Got a connection!~n"),
-    ok.
-

When Ranch receives a connection, it will call the <code>start_link/4</code> -function with the listener’s pid, socket, transport module to be used, -and the options we define when starting the listener. We don’t need options -for the purpose of this article, so we don’t pass them to the process we are -creating.

-

Let’s open a shell and start a Ranch listener to begin accepting -connections. We only need to call one function. You should probably open -it in another terminal and keep it open for convenience. If you quit -the shell you will have to repeat the commands to proceed.

-

Also note that you need to type c(ranch_ftp_protocol). -to recompile and reload the code for the protocol. You do not need to -restart any process however.

-
-
-
$ erl -pa ebin deps/*/ebin
-Erlang R15B02 (erts-5.9.2) [source] [64-bit] [smp:4:4] [async-threads:0] [hipe] [kernel-poll:false]
+
$ erl -pa ebin deps/*/ebin
+Erlang R15B02 (erts-5.9.2) [source] [64-bit] [smp:4:4] [async-threads:0] [hipe] [kernel-poll:false]
 
-Eshell V5.9.2  (abort with ^G)
-
-
-
1> application:start(ranch).
-ok
-2> ranch:start_listener(my_ftp, 10,
-       ranch_tcp, [{port, 2121}],
-       ranch_ftp_protocol, []).
-{ok,<0.40.0>}
-

This starts a listener named my_ftp that runs your very own -ranch_ftp_protocol over TCP, listening on port 2121. -The last argument is the options given to the protocol that we ignored -earlier.

-

To try your code, you can use the following command. It should be able -to connect, the server will print a message in the console, and then -the client will print an error.

-
-
-
$ ftp localhost 2121
-

Let’s move on to actually writing the protocol.

-

Once you have created the new process and returned the pid, Ranch will -give ownership of the socket to you. This requires a synchronization -step though.

-
-
-
init(ListenerPid, Socket, Transport) ->
-    ok = ranch:accept_ack(ListenerPid),
-    ok.
-

Now that you acknowledged the new connection, you can use it safely.

-

When an FTP server accepts a connection, it starts by sending a -welcome message which can be one or more lines starting with the -code 200. Then the server will wait for the client -to authenticate the user, and if the authentication went successfully, -which it will always do for the purpose of this article, it will reply -with a 230 code.

-
-
-
init(ListenerPid, Socket, Transport) ->
-    ok = ranch:accept_ack(ListenerPid),
-    Transport:send(Socket, <<"200 My cool FTP server welcomes you!\r\n">>),
-    {ok, Data} = Transport:recv(Socket, 0, 30000),
-    auth(Socket, Transport, Data).
+
init(ListenerPid, Socket, Transport) ->
+    ok = ranch:accept_ack(ListenerPid),
+    Transport:send(Socket, <<"200 My cool FTP server welcomes you!\r\n">>),
+    {ok, Data} = Transport:recv(Socket, 0, 30000),
+    auth(Socket, Transport, Data).
 
-auth(Socket, Transport, <<"USER ", Rest/bits>>) ->
-    io:format("User authenticated! ~p~n", [Rest]),
-    Transport:send(Socket, <<"230 Auth OK\r\n">>),
-    ok.
-

As you can see we don’t need complex parsing code. We can simply -match on the binary in the argument!

-

Next we need to loop receiving data commands and optionally -execute them, if we want our server to become useful.

-

We will replace the <code>ok.</code> line with the call to -the following function. The new function is recursive, each call -receiving data from the socket and sending a response. For now -we will send an error response for all commands the client sends.

-
-
-
loop(Socket, Transport) ->
-    case Transport:recv(Socket, 0, 30000) of
-        {ok, Data} ->
-            handle(Socket, Transport, Data),
-            loop(Socket, Transport);
-        {error, _} ->
-            io:format("The client disconnected~n")
-    end.
+
loop(Socket, Transport) ->
+    case Transport:recv(Socket, 0, 30000) of
+        {ok, Data} ->
+            handle(Socket, Transport, Data),
+            loop(Socket, Transport);
+        {error, _} ->
+            io:format("The client disconnected~n")
+    end.
 
-handle(Socket, Transport, Data) ->
-    io:format("Command received ~p~n", [Data]),
-    Transport:send(Socket, <<"500 Bad command\r\n">>).
-

With this we are almost ready to start implementing commands. -But with code like this we might have errors if the client doesn’t -send just one command per packet, or if the packets arrive too fast, -or if a command is split over multiple packets.

-

To solve this, we need to use a buffer. Each time we receive data, -we will append to the buffer, and then check if we have received a -command fully before running it. The code could look similar to the -following.

-
-
-
loop(Socket, Transport, Buffer) ->
-    case Transport:recv(Socket, 0, 30000) of
-        {ok, Data} ->
-                        Buffer2 = << Buffer/binary, Data/binary >>,
-                        {Commands, Rest} = split(Buffer2),
-                        [handle(Socket, Transport, C) || C <- Commands],
-            loop(Socket, Transport, Rest);
-        {error, _} ->
-            io:format("The client disconnected~n")
-    end.
-

The implementation of split/1 is left as an exercice -to the reader. You will also probably want to handle the QUIT -command, which must stop any processing and close the connection.

-

The attentive reader will also take note that in the case of text- -based protocols where commands are separated by line breaks, you can -set an option using Transport:setopts/2 and have all the -buffering done for you for free by Erlang itself.

-

As you can surely notice by now, Ranch allows us to build network -applications by getting out of our way entirely past the initial setup. -It lets you use the power of binary pattern matching to write text and -binary protocol implementations in just a few lines of code.

-
    -
  • -

    -Watch the talk -

    +
    loop(Socket, Transport, Buffer) ->
    +    case Transport:recv(Socket, 0, 30000) of
    +        {ok, Data} ->
    +			Buffer2 = << Buffer/binary, Data/binary >>,
    +			{Commands, Rest} = split(Buffer2),
    +			[handle(Socket, Transport, C) || C <- Commands],
    +            loop(Socket, Transport, Rest);
    +        {error, _} ->
    +            io:format("The client disconnected~n")
    +    end.
    +
+

The implementation of split/1 is left as an exercice to the reader. You will also probably want to handle the QUIT command, which must stop any processing and close the connection.

+

The attentive reader will also take note that in the case of text- based protocols where commands are separated by line breaks, you can set an option using Transport:setopts/2 and have all the buffering done for you for free by Erlang itself.

+

As you can surely notice by now, Ranch allows us to build network applications by getting out of our way entirely past the initial setup. It lets you use the power of binary pattern matching to write text and binary protocol implementations in just a few lines of code.

+ + + diff --git a/articles/the-elephant-in-the-room/index.html b/articles/the-elephant-in-the-room/index.html index 8123f821..4a57b018 100644 --- a/articles/the-elephant-in-the-room/index.html +++ b/articles/the-elephant-in-the-room/index.html @@ -69,139 +69,37 @@

-

Have you ever tried telling someone why they should use -Erlang? You boast the smaller code size, the auto healing -mechanisms, the distribution and they seem really excited. -They wonder why they never heard about Erlang before. And -then you show them what the code looks like. All excitement -goes away. The smiles disappear. Their face starts -becoming really serious.

-

You lost them. You know you lost them. They comment on the -syntax, or perhaps you do, already admitting defeat. It’s -unlike anything they have ever used before. And they will -most likely end up not using it.

-

What about people who already know what the syntax looks -like? As soon as you mention Erlang, the topic of the syntax -comes in. It’s like nothing else matters.

-

Perhaps the topic of syntax didn’t come up. But they’re -still not going to try Erlang because of it.

-

You’re probably not having these kinds of interactions at -Erlang conferences. This doesn’t happen with people who are -already somewhat interested in, or need, the features that -Erlang provides. With them the syntax is at worst a minor -inconvenience.

-

This happens because most developers are familiar with -syntaxes that look nothing like Erlang. To be clear, I -include language features and other concepts like objects -as part of "syntax" here. Familiarity is a very important -factor to drive adoption.

-

You can see an example of that in the Elixir world, where -the majority of people come from Ruby or already knew and -liked Ruby. The 2016 survey tells us that 59% of Elixir -developers were using Ruby primarily before. That’s in -large part because of the syntax. They will deny it of -course and find other reasons. And yet, we don’t see such -a strong adoption of Erlang from Ruby developers, before -or after Elixir appeared.

-

Side note: have you ever wondered why the Elixir community -is, I quote, much friendlier than the Ruby community? -Despite having much of the same people?

-

Before we continue, let me be clear. I love the Erlang -syntax. It is simple and explicit. It is powerful, especially -when dealing with binary data. It has very few quirks. -It has little to no ambiguity. It’s great. Except for -persuading people to use it.

-

Over the years I have been writing Erlang, I have seen -very few people point out that the syntax slows down -adoption. We have no problem with it, so why would others? -At the same time, people coming to Erlang come to solve -a real problem they’re having, so the syntax is fairly -secondary. Even if they hate it at first, they know they -can solve their problems despite the syntax.

-

You don’t build a popular product or language by solving -people’s problems though. In general you end up solving -some problems and creating new problems. No, you build -a popular product by convincing people to use it. And -you make them stay with your product by making them -commit to using it.

-

Take MongoDB for example. It didn’t become popular by -working, or even by being practical. It wasn’t performing -its primary function and was losing people’s data. That -didn’t stop it from becoming popular. Smart people would -knowingly use a database that was losing data. Think about -that for a minute.

-

MongoDB of course had a huge marketing machine, and they -focused on that. They helped organize many meetups all -over the world, complete with various swag items given -for free, including a small handbook about MongoDB. All -people had to do was show up.

-

They didn’t go tell people to look at all the weaknesses -their product had. They focused on the strengths. On -what would convince people to try it. They would go -to meetups, discuss with others, commit to try it (or -try it at meetups directly), and by doing so sell MongoDB -to themselves.

-

How do we get people to meetups though? That’d be the -first step: you need to catch their attention. -I believe MongoDB did this using benchmark results. -Ironic isn’t it? MongoDB gets fast benchmark results -because they lose data, and this gets everyone to buy -into the product.

-

The key points to remember about this are:

-
    -
  • -

    -catch people’s attention -

    +

    Have you ever tried telling someone why they should use Erlang? You boast the smaller code size, the auto healing mechanisms, the distribution and they seem really excited. They wonder why they never heard about Erlang before. And then you show them what the code looks like. All excitement goes away. The smiles disappear. Their face starts becoming really serious.

    +

    You lost them. You know you lost them. They comment on the syntax, or perhaps you do, already admitting defeat. It's unlike anything they have ever used before. And they will most likely end up not using it.

    +

    What about people who already know what the syntax looks like? As soon as you mention Erlang, the topic of the syntax comes in. It's like nothing else matters.

    +

    Perhaps the topic of syntax didn't come up. But they're still not going to try Erlang because of it.

    +

    You're probably not having these kinds of interactions at Erlang conferences. This doesn't happen with people who are already somewhat interested in, or need, the features that Erlang provides. With them the syntax is at worst a minor inconvenience.

    +

    This happens because most developers are familiar with syntaxes that look nothing like Erlang. To be clear, I include language features and other concepts like objects as part of "syntax" here. Familiarity is a very important factor to drive adoption.

    +

    You can see an example of that in the Elixir world, where the majority of people come from Ruby or already knew and liked Ruby. The 2016 survey tells us that 59% of Elixir developers were using Ruby primarily before. That's in large part because of the syntax. They will deny it of course and find other reasons. And yet, we don't see such a strong adoption of Erlang from Ruby developers, before or after Elixir appeared.

    +

    Side note: have you ever wondered why the Elixir community is, I quote, much friendlier than the Ruby community? Despite having much of the same people?

    +

    Before we continue, let me be clear. I love the Erlang syntax. It is simple and explicit. It is powerful, especially when dealing with binary data. It has very few quirks. It has little to no ambiguity. It's great. Except for persuading people to use it.

    +

    Over the years I have been writing Erlang, I have seen very few people point out that the syntax slows down adoption. We have no problem with it, so why would others? At the same time, people coming to Erlang come to solve a real problem they're having, so the syntax is fairly secondary. Even if they hate it at first, they know they can solve their problems despite the syntax.

    +

    You don't build a popular product or language by solving people's problems though. In general you end up solving some problems and creating new problems. No, you build a popular product by convincing people to use it. And you make them stay with your product by making them commit to using it.

    +

    Take MongoDB for example. It didn't become popular by working, or even by being practical. It wasn't performing its primary function and was losing people's data. That didn't stop it from becoming popular. Smart people would knowingly use a database that was losing data. Think about that for a minute.

    +

    MongoDB of course had a huge marketing machine, and they focused on that. They helped organize many meetups all over the world, complete with various swag items given for free, including a small handbook about MongoDB. All people had to do was show up.

    +

    They didn't go tell people to look at all the weaknesses their product had. They focused on the strengths. On what would convince people to try it. They would go to meetups, discuss with others, commit to try it (or try it at meetups directly), and by doing so sell MongoDB to themselves.

    +

    How do we get people to meetups though? That'd be the first step: you need to catch their attention. I believe MongoDB did this using benchmark results. Ironic isn't it? MongoDB gets fast benchmark results because they lose data, and this gets everyone to buy into the product.

    +

    The key points to remember about this are:

    +
    • catch people's attention
    • -
    • -

      -show your product’s strengths -

      +
    • show your product's strengths
    • -
    • -

      -make people take a commitment -

      +
    • make people take a commitment
    • -
-

Once they commit to something, you win. Everyone will not -end up ultimately using your product of course, but it’s -at the very least become a consideration. It’s on their -mind. Their resolve will be stronger when they ultimately -try it and inevitably run into issues.

-

Erlang’s syntax is a weakness. Almost nobody looks at the -Erlang syntax and falls in love with it at first sight. -No, it takes time to learn it and understand how good it -is. You need to sell Erlang to people without showing -the Erlang syntax. If you do show it, then you need to -hide the parts that feel alien. Function calls are OK. -Recursion, not so much. Maps are OK. Records, not.

-

Avoiding code is not always possible when you try -to sell it, especially to developers. You can however -prepare them to accept the alien syntax by admitting -that the syntax is not perfect before you show it. -You can do this while praising it at the same time. -For example, "the syntax is a little out there, but -it matches the concepts perfectly, it will all make -sense when you start learning".

-

This might not be the best introduction. Someone will -need to A/B test it to find the one that gives the -best results. But that should give you ideas.

-

When something terrible happens, mentioning that this -isn’t the end of the world before you tell others what -happened will soften their reaction. When someone -breaks your favorite item and cries over it calling -themselves stupid, it’s harder to get mad at them, -compared to the same event with no emotional reaction.

-

Our behavior is largely dependent on what’s at the -top of our mind, so it’s up to you to take advantage -of this to make your case in the best conditions.

-

Next time you try to make someone use Erlang, remember -that you should aim for getting a spoken commitment -out of them, if possible before you show the syntax. -If that’s not possible, then prepare them to accept -the flaws or the weirdness before they see them.

+ +

Once they commit to something, you win. Everyone will not end up ultimately using your product of course, but it's at the very least become a consideration. It's on their mind. Their resolve will be stronger when they ultimately try it and inevitably run into issues.

+

Erlang's syntax is a weakness. Almost nobody looks at the Erlang syntax and falls in love with it at first sight. No, it takes time to learn it and understand how good it is. You need to sell Erlang to people without showing the Erlang syntax. If you do show it, then you need to hide the parts that feel alien. Function calls are OK. Recursion, not so much. Maps are OK. Records, not.

+

Avoiding code is not always possible when you try to sell it, especially to developers. You can however prepare them to accept the alien syntax by admitting that the syntax is not perfect before you show it. You can do this while praising it at the same time. For example, "the syntax is a little out there, but it matches the concepts perfectly, it will all make sense when you start learning".

+

This might not be the best introduction. Someone will need to A/B test it to find the one that gives the best results. But that should give you ideas.

+

When something terrible happens, mentioning that this isn't the end of the world before you tell others what happened will soften their reaction. When someone breaks your favorite item and cries over it calling themselves stupid, it's harder to get mad at them, compared to the same event with no emotional reaction.

+

Our behavior is largely dependent on what's at the top of our mind, so it's up to you to take advantage of this to make your case in the best conditions.

+

Next time you try to make someone use Erlang, remember that you should aim for getting a spoken commitment out of them, if possible before you show the syntax. If that's not possible, then prepare them to accept the flaws or the weirdness before they see them.

+ diff --git a/articles/the-story-so-far/index.html b/articles/the-story-so-far/index.html index 8750d6db..4b749e7f 100644 --- a/articles/the-story-so-far/index.html +++ b/articles/the-story-so-far/index.html @@ -69,230 +69,28 @@

-

As I am away from home with little to do (some call this -a vacation) I wanted to reflect a little on the story so far, -or how I arrived to Erlang and got to where I am now. The -raw personal experience. It’ll be an article that’s more -about social aspect, communities and marketing a project than -technical considerations. As a period piece, it will also -allow me to reflect on the evolution of Erlang in recent -years.

-

Once upon a time-- Okay this isn’t a fairy tale. The story -begins with a short chapter in 2010. The year 2010 started -with a fairly major event in my life: the US servers for the -online game I stopped playing a few months before, but was -still involved with through its community, were closing. OMG! -Someone found a way to log packets and started working on a -private server; meanwhile the JP servers were still up. And -that’s pretty much it.

-

Fast forward a few months and it became pretty clear that -the private server was going nowhere considering all the drama -surrounding it-- which is actually not unusual, but it was -more entertaining than average and the technical abilities of -people running the project were obviously lacking so I decided -to obtain those logged packets and look at things myself. I -didn’t want to do a private server yet, I only wanted to take -a peek to see how things worked, and perhaps organize some -effort to document the protocol.

-

There was 10GB of logs. I didn’t have an easy to use -language to analyze them, and hex editors wouldn’t cut it for -most purposes, so I had to look elsewhere. This was a good -opportunity to start learning this PHP killer I read about -before, which also happens to feature syntax for matching -binaries, called Erlang. To be perfectly honest I wouldn’t -have touched the logs if I didn’t have the added motivation -to play with and learn a new language.

-

At the time it was pretty hard to learn Erlang. In my -experience there was Joe’s book (which I always recommend -first as I believe it is the best to learn the Erlang side -of things; but falls a little short on OTP), and there was -about 5 chapters of LYSE. There were a couple other books -I never managed to get into (sorry guys), and there was also -a few interesting blogs, some of which I can’t find anymore. -Finally the #erlang IRC community was there but I was strictly -lurking at the time.

-

What a difference compared to 4 years later! (That’s -today, by the way!) Now we have more books than I can -remember, tons of articles covering various aspects of the -language and platform, many targeting beginners but a good -number of them also about advanced topics. We even have a -free online book, LYSE, with more than 30 chapters covering -pretty much everything. Needless to say I never finished -reading LYSE as it got written slower than I learnt.

-

Back to 2010. I wrote a parser for the logs, and -aggregated those results into one CSV file per packet type -so I could open them in Gnumeric and aggregate some more, -but manually this time, and draw conclusions on the packet -structures. That was pretty easy. Even for a beginner. -Anyone can go from zero to that level in a day or two. -Then, having mastered binary pattern matching, I wanted -to learn some more Erlang, by making this aggregation -faster. What I had done before worked, but I wasn’t going -to wait forever to process everything sequentially. So I -looked and found a project called plists (still exists, -but not maintained AFAIK). I downloaded that project and -replaced my lists: calls to plists:. -Boom. In just a few minutes all logs were processed, and -I had learnt something new.

-

It is particularly interesting to note that the lack of -a package manager or index never bothered me. Neither before -nor after learning Erlang. My experience with package -managers was mostly related to Ubuntu, a little Perl and -Python, and PHP’s Pear. Let’s just stay polite and say it -was always a terrible experience. So searching on the Web -didn’t feel awkward, because even if I used a tool or -website I would have ended up doing a search or two anyway. -This is in contrast to the package index feature in -Erlang.mk, -which is meant to simplify specifying dependencies more -than anything: DEPS = cowboy. It does not -attempt to solve any other problem, and will only attempt -to solve one extra problem in the near future, which is -the discovery of packages. So expect some kind of website -listing packages soon enough.

-

I want to use this parenthese to also point out that at -the time there was a very small number of projects out there, -at least compared to today. While you sometimes hear people -complain about lack of certain libraries, it is so much -better now than it was before! The situation improves very -quickly, so much that it’s not going to be that big an issue -soon enough.

-

Wanting to know more about that game’s protocol, in the -year 2010, I ended up starting to write more Erlang code to -simulate a server and use the server to query the client and -see what was happening, documenting the packets and so on. -This eventually lead to a larger project implementing more -and more until people got their hopes up for a revival of -the game, all the while the now competing original server -project died in a stream of drama and technical incompetence. -Of course, I ended up doing what any good Internet citizen -would do, I crushed people’s hopes, but that’s not important -to our story. The important part is that before giving up -on this project, I not only learnt a good deal of Erlang -and a little deal of OTP (which I did not touch until 6 -months after I started with Erlang; see the paragraph -about learning material above), but I also had an intriguing -idea pop into my mind for what would become my greatest -success yet.

-

The giving up part was not easy. Having had financial -difficulties all year 2010 and part of 2009, I resolved -to travel back to Paris to try and make it. I ended up -sleeping in offices for 6 months, being hosted by a shady -person, and hearing my fair share of stories about -the dark side of business. While there I also worked for -another company with someone who would end up becoming -another high profile Erlang developer. The situation -slowly improved, I started taking part in the #erlang -IRC discussions, giving up my status of lurker and, a -few months into 2011, started working on the Apache killer -project: Cowboy.

-

This is the part where I probably should get accused of -racism and other fun things, but I never did. And I think -that speaks lots about the Erlang community. In all my time -writing Erlang code, I can count the number of conflicts I -had with other people on a single hand. This is the nicest -programming community I have ever seen, by far. And the -humblest too. The Erlang community feels like Japan. And -I love Japan. So I love the Erlang community. I can’t say -this enough. This is something that stayed true for all -my time using Erlang, and despite the rise of alternative -languages that are not Japan the Erlang community has -remained very Japan.

-

The first published version of Cowboy was written in -two weeks. A little before those two weeks, during, and -a while after, pretty much everything I said on the -Internets was that Cowboy was going to be the greatest -HTTP server ever, that the other servers were problematic -(and just to be clear, Yaws was rarely if ever mentioned, -due to being in a perceived different league of "full -featured servers" while Cowboy was a "lightweight server"), -and that Cowboy will be the best replacement to a Mochiweb -or Misultin application. This, alongside a lot of time -spent on IRC telling people to use Cowboy when they were -asking for an HTTP server to use, probably made me sound -very annoying. But it worked, and Cowboy started getting -its first users, despite being only a few weeks old. Of -course, as soon as I got my very first user, I started -claiming Cowboy had "a lot of users".

-

Looking back today I would definitely find myself annoying, -this wasn’t just an idle comment there. For about a year, -maybe a little more, all I ever said was that Cowboy was -the best. This probably made me a little dumber in the -process (as if I wasn’t enough! I know). Being French, I -sometimes would also say things quite abruptly. To stay -polite, I probably sounded like an asshole. I learnt to -stop being so French over time thankfully.

-

I think what was most important to Cowboy at the time, -was three things. First, it felt fresh. It was new, had new -ideas, tried to do things differently and followed "new" old -best practices (the OTP way-- which was simply too obscure -for most people at the time). Second, it had me spending -all my time telling people to use it whenever they were -looking for an HTTP server. Third, it had me helping people -get started with it and guide them all the steps of the way. -Mostly because it didn’t have a very good documentation, but -still, hand holding does wonders.

-

To be able to help people every time they had a problem, -I did not spend all my days reading IRC. Instead I simply -made sure to be notified when someone said cowboy. -The same way many people subscribe to alerts when their -company is mentioned in the news. Nothing fancy.

-

Time went on, Cowboy grew, or as some like to say, -completely destroyed the competition, and many people -eventually moved from Mochiweb and Misultin to Cowboy. -And then Roberto Ostinelli stopped Misultin development -and told everyone to move to Cowboy. This is the most -humble and selfless act I have ever seen in the programming -sphere, and I only have one thing to say about it: GG. -Thanks for the fish. He left me with the tasks of improving -Cowboy examples, documentation and strongly believed that -the Misultin interface was more user friendly out of all -the servers. So I added many examples, as many lines of -documentation as we have of code, and strongly believe -that Cowboy 2.0 will be the most user friendly interface -out of all servers. But only time will tell.

-

With the rise of the project and the rise in the number -of users, my previous strategy (completely incidental, by -the way, and definitely not a well thought out plan to -become popular) stopped working. It was taking me too much -time. The important aspects slowly drifted. If I wanted to -support more users, I would have to spend less time with -each individual user. This was actually a hard problem. -You basically have to make people understand they can’t -just come to you directly when they have a problem, they -have to follow proper channels. It becomes less personal, -and might be felt like you don’t care about them anymore. -You have to hurt some people’s feelings at this point. It -is quite unfortunate, and also quite difficult to do. There -is some unwritten rule that says early adopters deserve -more, but in the real world it never works like this. So -I probably hurt some people’s feelings at some point. But -that’s okay. Because even if you make sure to be as nice -as possible when you tell people to go through proper -channels from now on, some people will still get offended. -There’s nothing you can do about it.

-

From that point onward the important points about the -project was getting the documentation done, making sure -people knew about the proper channels to get help and -report issues, etc. Basically making myself less needed. -This is quite a contrast with the first days, but I believe -Cowboy made that transition successfully.

-

Not only did I win time by not having to hold hands with -everyone all the time (not that I didn’t like it, but you -know, the sweat), but I also won time thanks to the increased -project popularity. Indeed, the more users you have, the more -annoying guys there are to tell people to use your project -and that it’s the best and everything. Which is great. At -least, it’s great if you don’t pay too much attention to it. -Sometimes people will give an advice that is, in your opinion, -a bad advice. And that’s okay. Don’t intervene every time -someone gives a bad advice, learn to let it go. People will -figure it out. You learn by making mistakes, after all. Use -this extra time to make sure other people don’t end up -giving the same bad advice instead. Fix the code or the -documentation that led to this mistake. Slowly improve the -project and make sure it doesn’t happen again.

-

This is my story. So far, anyway.

+

As I am away from home with little to do (some call this a vacation) I wanted to reflect a little on the story so far, or how I arrived to Erlang and got to where I am now. The raw personal experience. It'll be an article that's more about social aspect, communities and marketing a project than technical considerations. As a period piece, it will also allow me to reflect on the evolution of Erlang in recent years.

+

Once upon a time-- Okay this isn't a fairy tale. The story begins with a short chapter in 2010. The year 2010 started with a fairly major event in my life: the US servers for the online game I stopped playing a few months before, but was still involved with through its community, were closing. OMG! Someone found a way to log packets and started working on a private server; meanwhile the JP servers were still up. And that's pretty much it.

+

Fast forward a few months and it became pretty clear that the private server was going nowhere considering all the drama surrounding it-- which is actually not unusual, but it was more entertaining than average and the technical abilities of people running the project were obviously lacking so I decided to obtain those logged packets and look at things myself. I didn't want to do a private server yet, I only wanted to take a peek to see how things worked, and perhaps organize some effort to document the protocol.

+

There was 10GB of logs. I didn't have an easy to use language to analyze them, and hex editors wouldn't cut it for most purposes, so I had to look elsewhere. This was a good opportunity to start learning this PHP killer I read about before, which also happens to feature syntax for matching binaries, called Erlang. To be perfectly honest I wouldn't have touched the logs if I didn't have the added motivation to play with and learn a new language.

+

At the time it was pretty hard to learn Erlang. In my experience there was Joe's book (which I always recommend first as I believe it is the best to learn the Erlang side of things; but falls a little short on OTP), and there was about 5 chapters of LYSE. There were a couple other books I never managed to get into (sorry guys), and there was also a few interesting blogs, some of which I can't find anymore. Finally the #erlang IRC community was there but I was strictly lurking at the time.

+

What a difference compared to 4 years later! (That's today, by the way!) Now we have more books than I can remember, tons of articles covering various aspects of the language and platform, many targeting beginners but a good number of them also about advanced topics. We even have a free online book, LYSE, with more than 30 chapters covering pretty much everything. Needless to say I never finished reading LYSE as it got written slower than I learnt.

+

Back to 2010. I wrote a parser for the logs, and aggregated those results into one CSV file per packet type so I could open them in Gnumeric and aggregate some more, but manually this time, and draw conclusions on the packet structures. That was pretty easy. Even for a beginner. Anyone can go from zero to that level in a day or two. Then, having mastered binary pattern matching, I wanted to learn some more Erlang, by making this aggregation faster. What I had done before worked, but I wasn't going to wait forever to process everything sequentially. So I looked and found a project called plists (still exists, but not maintained AFAIK). I downloaded that project and replaced my lists: calls to plists:. Boom. In just a few minutes all logs were processed, and I had learnt something new.

+

It is particularly interesting to note that the lack of a package manager or index never bothered me. Neither before nor after learning Erlang. My experience with package managers was mostly related to Ubuntu, a little Perl and Python, and PHP's Pear. Let's just stay polite and say it was always a terrible experience. So searching on the Web didn't feel awkward, because even if I used a tool or website I would have ended up doing a search or two anyway. This is in contrast to the package index feature in Erlang.mk, which is meant to simplify specifying dependencies more than anything: DEPS = cowboy. It does not attempt to solve any other problem, and will only attempt to solve one extra problem in the near future, which is the discovery of packages. So expect some kind of website listing packages soon enough.

+

I want to use this parenthese to also point out that at the time there was a very small number of projects out there, at least compared to today. While you sometimes hear people complain about lack of certain libraries, it is so much better now than it was before! The situation improves very quickly, so much that it's not going to be that big an issue soon enough.

+

Wanting to know more about that game's protocol, in the year 2010, I ended up starting to write more Erlang code to simulate a server and use the server to query the client and see what was happening, documenting the packets and so on. This eventually lead to a larger project implementing more and more until people got their hopes up for a revival of the game, all the while the now competing original server project died in a stream of drama and technical incompetence. Of course, I ended up doing what any good Internet citizen would do, I crushed people's hopes, but that's not important to our story. The important part is that before giving up on this project, I not only learnt a good deal of Erlang and a little deal of OTP (which I did not touch until 6 months after I started with Erlang; see the paragraph about learning material above), but I also had an intriguing idea pop into my mind for what would become my greatest success yet.

+

The giving up part was not easy. Having had financial difficulties all year 2010 and part of 2009, I resolved to travel back to Paris to try and make it. I ended up sleeping in offices for 6 months, being hosted by a shady person, and hearing my fair share of stories about the dark side of business. While there I also worked for another company with someone who would end up becoming another high profile Erlang developer. The situation slowly improved, I started taking part in the #erlang IRC discussions, giving up my status of lurker and, a few months into 2011, started working on the Apache killer project: Cowboy.

+

This is the part where I probably should get accused of racism and other fun things, but I never did. And I think that speaks lots about the Erlang community. In all my time writing Erlang code, I can count the number of conflicts I had with other people on a single hand. This is the nicest programming community I have ever seen, by far. And the humblest too. The Erlang community feels like Japan. And I love Japan. So I love the Erlang community. I can't say this enough. This is something that stayed true for all my time using Erlang, and despite the rise of alternative languages that are not Japan the Erlang community has remained very Japan.

+

The first published version of Cowboy was written in two weeks. A little before those two weeks, during, and a while after, pretty much everything I said on the Internets was that Cowboy was going to be the greatest HTTP server ever, that the other servers were problematic (and just to be clear, Yaws was rarely if ever mentioned, due to being in a perceived different league of "full featured servers" while Cowboy was a "lightweight server"), and that Cowboy will be the best replacement to a Mochiweb or Misultin application. This, alongside a lot of time spent on IRC telling people to use Cowboy when they were asking for an HTTP server to use, probably made me sound very annoying. But it worked, and Cowboy started getting its first users, despite being only a few weeks old. Of course, as soon as I got my very first user, I started claiming Cowboy had "a lot of users".

+

Looking back today I would definitely find myself annoying, this wasn't just an idle comment there. For about a year, maybe a little more, all I ever said was that Cowboy was the best. This probably made me a little dumber in the process (as if I wasn't enough! I know). Being French, I sometimes would also say things quite abruptly. To stay polite, I probably sounded like an asshole. I learnt to stop being so French over time thankfully.

+

I think what was most important to Cowboy at the time, was three things. First, it felt fresh. It was new, had new ideas, tried to do things differently and followed "new" old best practices (the OTP way-- which was simply too obscure for most people at the time). Second, it had me spending all my time telling people to use it whenever they were looking for an HTTP server. Third, it had me helping people get started with it and guide them all the steps of the way. Mostly because it didn't have a very good documentation, but still, hand holding does wonders.

+

To be able to help people every time they had a problem, I did not spend all my days reading IRC. Instead I simply made sure to be notified when someone said cowboy. The same way many people subscribe to alerts when their company is mentioned in the news. Nothing fancy.

+

Time went on, Cowboy grew, or as some like to say, completely destroyed the competition, and many people eventually moved from Mochiweb and Misultin to Cowboy. And then Roberto Ostinelli stopped Misultin development and told everyone to move to Cowboy. This is the most humble and selfless act I have ever seen in the programming sphere, and I only have one thing to say about it: GG. Thanks for the fish. He left me with the tasks of improving Cowboy examples, documentation and strongly believed that the Misultin interface was more user friendly out of all the servers. So I added many examples, as many lines of documentation as we have of code, and strongly believe that Cowboy 2.0 will be the most user friendly interface out of all servers. But only time will tell.

+

With the rise of the project and the rise in the number of users, my previous strategy (completely incidental, by the way, and definitely not a well thought out plan to become popular) stopped working. It was taking me too much time. The important aspects slowly drifted. If I wanted to support more users, I would have to spend less time with each individual user. This was actually a hard problem. You basically have to make people understand they can't just come to you directly when they have a problem, they have to follow proper channels. It becomes less personal, and might be felt like you don't care about them anymore. You have to hurt some people's feelings at this point. It is quite unfortunate, and also quite difficult to do. There is some unwritten rule that says early adopters deserve more, but in the real world it never works like this. So I probably hurt some people's feelings at some point. But that's okay. Because even if you make sure to be as nice as possible when you tell people to go through proper channels from now on, some people will still get offended. There's nothing you can do about it.

+

From that point onward the important points about the project was getting the documentation done, making sure people knew about the proper channels to get help and report issues, etc. Basically making myself less needed. This is quite a contrast with the first days, but I believe Cowboy made that transition successfully.

+

Not only did I win time by not having to hold hands with everyone all the time (not that I didn't like it, but you know, the sweat), but I also won time thanks to the increased project popularity. Indeed, the more users you have, the more annoying guys there are to tell people to use your project and that it's the best and everything. Which is great. At least, it's great if you don't pay too much attention to it. Sometimes people will give an advice that is, in your opinion, a bad advice. And that's okay. Don't intervene every time someone gives a bad advice, learn to let it go. People will figure it out. You learn by making mistakes, after all. Use this extra time to make sure other people don't end up giving the same bad advice instead. Fix the code or the documentation that led to this mistake. Slowly improve the project and make sure it doesn't happen again.

+

This is my story. So far, anyway.

+ diff --git a/articles/tictactoe/index.html b/articles/tictactoe/index.html index 3fd8e6e3..33cc169b 100644 --- a/articles/tictactoe/index.html +++ b/articles/tictactoe/index.html @@ -69,89 +69,60 @@

-

Everyone knows Tic Tac Toe, -right?

-

Players choose either to be the Xs or the Os, then place their symbol -on a 3x3 board one after another, trying to create a line of 3 of them.

-

Writing an algorithm to check for victory sounds easy, right? It’s -easily tested, considering there’s only 8 possible winning rows (3 horizontal, -3 vertical and 2 diagonal).

-

In Erlang though, you probably wouldn’t want an algorithm. Erlang has -this cool feature called pattern matching which will allow us to completely -avoid writing the algorithm by instead letting us match directly on the -solutions.

-

Let’s first create a board. A board is a list of 3 rows each containing -3 columns. It can also be thought of as a tuple containing 9 elements. -A tuple is easier to manipulate so this is what we are going to use. -Each position can either contain an x, an o, -or be undefined.

-
-
-
new() ->
-    {undefined, undefined, undefined,
-     undefined, undefined, undefined,
-     undefined, undefined, undefined}.
-

Now that we have a board, if we want to play, we need a function that -will allow players to, you know, actually play their moves. Rows and -columns are numbered 1 to 3 so we need a little math to correctly -deduce the element’s position.

-
-
-
play(Who, X, Y, Board) ->
-    setelement((Y - 1) * 3 + X, Board, Who).
-

This function returns the board with the element modified. Of course, -as you probably noticed, we aren’t checking that the arguments are correct, -or that the element was already set. This is left as an exercise to the -reader.

-

After playing the move, we need to check whether someone won. That’s -where you’d write an algorithm, and that’s where I wouldn’t. Let’s just -pattern match all of them!

-
-
-
check(Board) ->
-    case Board of
-        {x, x, x,
-         _, _, _,
-         _, _, _} -> {victory, x};
+
check(Board) ->
+    case Board of
+        {x, x, x,
+         _, _, _,
+         _, _, _} -> {victory, x};
 
-        {x, _, _,
-         _, x, _,
-         _, _, x} -> {victory, x};
+        {x, _, _,
+         _, x, _,
+         _, _, x} -> {victory, x};
 
-        {x, _, _,
-         x, _, _,
-         x, _, _} -> {victory, x};
+        {x, _, _,
+         x, _, _,
+         x, _, _} -> {victory, x};
 
-        %% [snip]
+        %% [snip]
 
-        _ -> ok
-    end.
-

Pattern matching allows us to simply draw the solutions -directly inside our code, and if the board matches any of them, then we -have a victory or a draw, otherwise the game can continue.

-

The _ variable is special in that it always matches, -allowing us to focus strictly on the winning row. And because it’s very -graphical, if we were to have messed up somewhere, then we’d only need -take a quick glance to be sure the winning solutions are the right ones.

-

Erlang allows us to transform algorithms into very graphical code thanks -to its pattern matching feature, and let us focus on doing things instead -of writing algorithms to do things.

-
+

Pattern matching allows us to simply draw the solutions directly inside our code, and if the board matches any of them, then we have a victory or a draw, otherwise the game can continue.

+

The _ variable is special in that it always matches, allowing us to focus strictly on the winning row. And because it's very graphical, if we were to have messed up somewhere, then we'd only need take a quick glance to be sure the winning solutions are the right ones.

+

Erlang allows us to transform algorithms into very graphical code thanks to its pattern matching feature, and let us focus on doing things instead of writing algorithms to do things.

+ + + diff --git a/articles/website-update/index.html b/articles/website-update/index.html index bc871131..7730c1e3 100644 --- a/articles/website-update/index.html +++ b/articles/website-update/index.html @@ -69,63 +69,17 @@

-

Last week-end I updated the Nine Nines website.

-

I switched to Hugo. The site is -now built from Asciidoc -documents. You probably saw me switch to Asciidoc -for documentation this past year. This is the -natural conclusion to that story. The great thing -is that with a little bit of Makefile magic I can -just copy the documentation files into Hugo and -poof, they appear on the website.

-

I am very happy with that new setup. I can now -post my thoughts again. Woo! Expect regular posts -from now on. I will try to replace my long series -of tweets with posts.

-

The sections have been rearranged. There used to -be a separate training section; now -all my services are described in -one page. I have also clarified my areas of -expertise. There used to be confusion in the past, -so now it should be clearer that I am not a -distributed systems expert.

-

On that note, if you are looking for my -services right now, I’m not available. I’ll have -to work 7 days a week for a while. Try again in a -couple months. More on that in a future post.

-

The documentation becomes a first class -citizen. Bullet and Cowlib don’t have proper -documentation… yet. I have started working on the -Cowlib documentation, and Bullet shouldn’t take too -long. All these projects will be documented when -Cowboy gets to 2.0, and will all be supported -equally. Note that the Cowboy 1.0 documentation -still has the old website templates and links. -Don’t worry about it.

-

The mailing lists link has been removed. I did -announce a few months back that mailing lists were -going to go. They’re still up right now, but not -for long. I am planning to put the archives -read-only, link to them from a future post and -be done with it. If you have a question, open a -ticket on Github. Then I can just decide to leave -the ticket open if I want to do improvements based -on your feedback.

-

I have replaced most of the "we" by "I". I am -a one-man company right now. Have been for a while. -Doesn’t make sense to keep a facade. I want to be -close to users, not put a barrier between us.

-

The RSS changed. The old link doesn’t work anymore. -The new link is at /index.xml, -or /articles/index.xml -if you only care about my posts. I guess that’s the -one most people want.

-

I still have some tweaks to do, but it will take a -while. My long term plan is to remove Bootstrap, use -vanilla CSS and as little JS as possible. The reason -for that is that it’s cheaper than upgrading libraries -every few years. Life is too short to spend it -upgrading JS libraries.

+

Last week-end I updated the Nine Nines website.

+

I switched to Hugo. The site is now built from Asciidoc documents. You probably saw me switch to Asciidoc for documentation this past year. This is the natural conclusion to that story. The great thing is that with a little bit of Makefile magic I can just copy the documentation files into Hugo and poof, they appear on the website.

+

I am very happy with that new setup. I can now post my thoughts again. Woo! Expect regular posts from now on. I will try to replace my long series of tweets with posts.

+

The sections have been rearranged. There used to be a separate training section; now all my services are described in one page. I have also clarified my areas of expertise. There used to be confusion in the past, so now it should be clearer that I am not a distributed systems expert.

+

On that note, if you are looking for my services right now, I'm not available. I'll have to work 7 days a week for a while. Try again in a couple months. More on that in a future post.

+

The documentation becomes a first class citizen. Bullet and Cowlib don't have proper documentation... yet. I have started working on the Cowlib documentation, and Bullet shouldn't take too long. All these projects will be documented when Cowboy gets to 2.0, and will all be supported equally. Note that the Cowboy 1.0 documentation still has the old website templates and links. Don't worry about it.

+

The mailing lists link has been removed. I did announce a few months back that mailing lists were going to go. They're still up right now, but not for long. I am planning to put the archives read-only, link to them from a future post and be done with it. If you have a question, open a ticket on Github. Then I can just decide to leave the ticket open if I want to do improvements based on your feedback.

+

I have replaced most of the "we" by "I". I am a one-man company right now. Have been for a while. Doesn't make sense to keep a facade. I want to be close to users, not put a barrier between us.

+

The RSS changed. The old link doesn't work anymore. The new link is at /index.xml, or /articles/index.xml if you only care about my posts. I guess that's the one most people want.

+

I still have some tweaks to do, but it will take a while. My long term plan is to remove Bootstrap, use vanilla CSS and as little JS as possible. The reason for that is that it's cheaper than upgrading libraries every few years. Life is too short to spend it upgrading JS libraries.

+ diff --git a/articles/xerl-0.1-empty-modules/index.html b/articles/xerl-0.1-empty-modules/index.html index 86d54924..281c134a 100644 --- a/articles/xerl-0.1-empty-modules/index.html +++ b/articles/xerl-0.1-empty-modules/index.html @@ -69,144 +69,95 @@

-

Let’s build a programming language. I call it Xerl: eXtended ERLang. -It’ll be an occasion for us to learn a few things, especially me.

-

Unlike in Erlang, in this language, everything is an expression. -This means that modules and functions are expression, and indeed that -you can have more than one module per file.

-

We are just starting, so let’s no go ahead of ourselves here. We’ll -begin with writing the code allowing us to compile an empty module.

-

We will compile to Core Erlang: this is one of the many intermediate -step your Erlang code compiles to before it becomes BEAM machine code. -Core Erlang is a very neat language for machine generated code, and we -will learn many things about it.

-

Today we will only focus on compiling the following code:

-
-
-
mod my_module
-begin
-end
-

Compilation will be done in a few steps. First, the source file will -be transformed in a tree of tokens by the lexer. Then, the parser will -use that tree of tokens and convert it to the AST, bringing semantical -meaning to our representation. Finally, the code generator will transform -this AST to Core Erlang AST, which will then be compiled.

-

We will use leex for the lexer. This lexer uses .xrl files -which are then compiled to .erl files that you can then compile to BEAM. -The file is divided in three parts: definitions, rules and Erlang code. -Definitions and Erlang code are obvious; rules are what concerns us.

-

We only need two things: atoms and whitespaces. Atoms are a lowercase -letter followed by any letter, number, _ or @. Whitespace is either a -space, an horizontal tab, \r or \n. There exists other kinds of whitespaces -but we simply do not allow them in the Xerl language.

-

Rules consist of a regular expression followed by Erlang code. The -latter must return a token representation or the atom skip_token.

-
-
-
{L}{A}* :
-    Atom = list_to_atom(TokenChars),
-    {token, case reserved_word(Atom) of
-        true -> {Atom, TokenLine};
-        false -> {atom, TokenLine, Atom}
-    end}.
+
{L}{A}* :
+    Atom = list_to_atom(TokenChars),
+    {token, case reserved_word(Atom) of
+        true -> {Atom, TokenLine};
+        false -> {atom, TokenLine, Atom}
+    end}.
 
-{WS}+ : skip_token.
-

The first rule matches an atom, which is converted to either a special -representation for reserved words, or an atom tuple. The -TokenChars variable represents the match as a string, and -the TokenLine variable contains the line number. -View the complete file.

-

We obtain the following result from the lexer:

-
-
-
[{mod,1},{atom,1,my_module},{'begin',2},{'end',3}]
-

The second step is to parse this list of tokens to add semantic meaning -and generate what is called an abstract syntax tree. We will be -using the yecc parser generator for this. This time it will take -.yrl files but the process is the same as before. The file is a little -more complex than for the lexer, we need to define at the very least -terminals, nonterminals and root symbols, the grammar itself, and -optionally some Erlang code.

-

To compile our module, we need a few things. First, everything is an -expression. We thus need list of expressions and individual expressions. -We will support a single expression for now, the mod -expression which defines a module. And that’s it! We end up with the -following grammar:

-
-
-
exprs -> expr : ['$1'].
-exprs -> expr exprs : ['$1' | '$2'].
+
exprs -> expr : ['$1'].
+exprs -> expr exprs : ['$1' | '$2'].
 
-expr -> module : '$1'.
+expr -> module : '$1'.
 
-module -> 'mod' atom 'begin' 'end' :
-        {'mod', ?line('$1'), '$2', []}.
- -

We obtain the following result from the parser:

-
-
-
[{mod,1,{atom,1,my_module},[]}]
-

We obtain a list of a single mod expression. Just like -we wanted. Last step is generating the Core Erlang code from it.

-

Code generation generally is comprised of several steps. We will -discuss these in more details later on. For now, we will focus on the -minimal needed for successful compilation.

-

We can use the cerl module to generate Core Erlang AST. -We will simply be using functions, which allows us to avoid learning -and keeping up to date with the internal representation.

-

There’s one important thing to do when generating Core Erlang AST -for a module: create the module_info/{0,1} functions. -Indeed, these are added to Erlang before it becomes Core Erlang, and -so we need to replicate this ourselves. Do not be concerned however, -as this only takes a few lines of extra code.

-

As you can see by -looking at the complete file, -the code generator echoes the grammar we defined in the parser, and -simply applies the appropriate Core Erlang functions for each expressions.

-

We obtain the following pretty-printed Core Erlang generated code:

-
-
-
module 'my_module' ['module_info'/0,
-                       'module_info'/1]
-    attributes []
-'module_info'/0 =
-    fun () ->
-        call 'erlang':'get_module_info'
-            ('empty_module')
-'module_info'/1 =
-    fun (Key) ->
-        call 'erlang':'get_module_info'
-            ('empty_module', Key)
-end
-

For convenience I added all the steps in a xerl:compile/1 -function that you can use against your own .xerl files.

-

That’s it for today! We will go into more details over each steps in -the next few articles.

-
    -
  • -

    -View the source -

    +
    module 'my_module' ['module_info'/0,
    +                       'module_info'/1]
    +    attributes []
    +'module_info'/0 =
    +    fun () ->
    +        call 'erlang':'get_module_info'
    +            ('empty_module')
    +'module_info'/1 =
    +    fun (Key) ->
    +        call 'erlang':'get_module_info'
    +            ('empty_module', Key)
    +end
    +
+

For convenience I added all the steps in a xerl:compile/1 function that you can use against your own .xerl files.

+

That's it for today! We will go into more details over each steps in the next few articles.

+ + + diff --git a/articles/xerl-0.2-two-modules/index.html b/articles/xerl-0.2-two-modules/index.html index 2dd5f828..f37b899f 100644 --- a/articles/xerl-0.2-two-modules/index.html +++ b/articles/xerl-0.2-two-modules/index.html @@ -69,149 +69,123 @@

-

Everything is an expression.

-

This sentence carries profound meaning. We will invoke it many -times over the course of these articles.

-

If everything is an expression, then the language shouldn’t have -any problem with me defining two modules in the same source file.

-
-
-
mod first_module
-begin
-end
+
mod first_module
+begin
+end
 
-mod second_module
-begin
-end
-

Likewise, it shouldn’t have any problem with me defining a -module inside another module.

-
-
-
mod out_module
-begin
-    mod in_module
-    begin
-    end
-end
-

Of course, in the context of the Erlang VM, these two snippets -are equivalent; there is nothing preventing you from calling the -in_module module from any other module. The mod -instruction means a module should be created in the Erlang VM, -with no concept of scope attached.

-

Still we need to handle both. To do this we will add a step -between the parser and the code generator that will walk over the -abstract syntax tree, from here onward shortened as AST, -and transform the AST by executing it where applicable.

-

What happens when you execute a mod instruction? -A module is created. Since we are compiling, that simply means -the compiler will branch out and create a module.

-

If everything is an expression, does that mean this will allow -me to create modules at runtime using the same syntax? Yes, but -let’s not get ahead of ourselves yet.

-

For now we will just iterate over the AST, and will compile -a module for each mod found. Modules cannot contain -expressions yet, so there’s no need to recurse over it at this -point. This should solve the compilation of our first snippet.

-

The compile/1 function becomes:

-
-
-
compile(Filename) ->
-        io:format("Compiling ~s...~n", [Filename]),
-        {ok, Src} = file:read_file(Filename),
-        {ok, Tokens, _} = xerl_lexer:string(binary_to_list(Src)),
-        {ok, Exprs} = xerl_parser:parse(Tokens),
-        execute(Filename, Exprs, []).
+
compile(Filename) ->
+	io:format("Compiling ~s...~n", [Filename]),
+	{ok, Src} = file:read_file(Filename),
+	{ok, Tokens, _} = xerl_lexer:string(binary_to_list(Src)),
+	{ok, Exprs} = xerl_parser:parse(Tokens),
+	execute(Filename, Exprs, []).
 
-execute(_, [], Modules) ->
-        io:format("Done...~n"),
-        {ok, lists:reverse(Modules)};
-execute(Filename, [Expr = {mod, _, {atom, _, Name}, []}|Tail], Modules) ->
-        {ok, [Core]} = xerl_codegen:exprs([Expr]),
-        {ok, [{Name, []}]} = core_lint:module(Core),
-        io:format("~s~n", [core_pp:format(Core)]),
-        {ok, _, Beam} = compile:forms(Core,
-                [binary, from_core, return_errors, {source, Filename}]),
-        {module, Name} = code:load_binary(Name, Filename, Beam),
-        execute(Filename, Tail, [Name|Modules]).
-

Running this compiler over the first snippet yields the following -result:

-
-
-
Compiling test/mod_SUITE_data/two_modules.xerl...
-module 'first_module' ['module_info'/0,
-                       'module_info'/1]
-    attributes []
-'module_info'/0 =
-    fun () ->
-        call 'erlang':'get_module_info'
-            ('first_module')
-'module_info'/1 =
-    fun (Key) ->
-        call 'erlang':'get_module_info'
-            ('first_module', Key)
-end
-module 'second_module' ['module_info'/0,
-                        'module_info'/1]
-    attributes []
-'module_info'/0 =
-    fun () ->
-        call 'erlang':'get_module_info'
-            ('second_module')
-'module_info'/1 =
-    fun (Key) ->
-        call 'erlang':'get_module_info'
-            ('second_module', Key)
-end
-Done...
-{ok,[first_module,second_module]}
-

Everything looks fine. And we can check that the two modules have -been loaded into the VM:

-
-
-
9> m(first_module).
-Module first_module compiled: Date: February 2 2013, Time: 14.56
-Compiler options:  [from_core]
-Object file: test/mod_SUITE_data/two_modules.xerl
-Exports:
-         module_info/0
-         module_info/1
-ok
-10> m(second_module).
-Module second_module compiled: Date: February 2 2013, Time: 14.56
-Compiler options:  [from_core]
-Object file: test/mod_SUITE_data/two_modules.xerl
-Exports:
-         module_info/0
-         module_info/1
-ok
-

So far so good!

-

What about the second snippet? It brings up many questions. What -happens once a mod expression has been executed at -compile time? If it’s an expression then it has to have a result, -right? Right. We are still a bit lacking with expressions for now, -though, so let’s get back to it after we add more.

-
    -
  • -

    -View the source -

    +
    9> m(first_module).
    +Module first_module compiled: Date: February 2 2013, Time: 14.56
    +Compiler options:  [from_core]
    +Object file: test/mod_SUITE_data/two_modules.xerl
    +Exports: 
    +         module_info/0
    +         module_info/1
    +ok
    +10> m(second_module).
    +Module second_module compiled: Date: February 2 2013, Time: 14.56
    +Compiler options:  [from_core]
    +Object file: test/mod_SUITE_data/two_modules.xerl
    +Exports: 
    +         module_info/0
    +         module_info/1
    +ok
    +
+

So far so good!

+

What about the second snippet? It brings up many questions. What happens once a mod expression has been executed at compile time? If it's an expression then it has to have a result, right? Right. We are still a bit lacking with expressions for now, though, so let's get back to it after we add more.

+ + + diff --git a/articles/xerl-0.3-atomic-expressions/index.html b/articles/xerl-0.3-atomic-expressions/index.html index 5ed954e2..861caedb 100644 --- a/articles/xerl-0.3-atomic-expressions/index.html +++ b/articles/xerl-0.3-atomic-expressions/index.html @@ -69,153 +69,92 @@

-

We will be adding atomic integer expressions to our language. -These look as follow in Erlang:

-
-
-
42.
-

And the result of this expression is of course 42.

-

We will be running this expression at compile time, since we -don’t have the means to run code at runtime yet. This will of -course result in no module being compiled, but that’s OK, it will -allow us to discuss a few important things we’ll have to plan for -later on.

-

First, we must of course accept integers in the tokenizer.

-
-
-
{D}+ : {token, {integer, TokenLine, list_to_integer(TokenChars)}}.
-

We must then accept atomic integer expressions in the parser. -This is a simple change. The integer token is terminal so we need -to add it to the list of terminals, and then we only need to add -it as a possible expression.

-
-
-
expr -> integer : '$1'.
-

A file containing only the number 42 (with no terminating dot) -will give the following result when parsing it. This is incidentally -the same result as when tokenizing.

-
-
-
[{integer,1,42}]
-

We must then evaluate it. We’re going to interpret it for now. -Since the result of this expression is not stored in a variable, -we are going to simply print it on the screen and discard it.

-
-
-
execute(Filename, [{integer, _, Int}|Tail], Modules) ->
-    io:format("integer ~p~n", [Int]),
-    execute(Filename, Tail, Modules).
-

You might think by now that what we’ve done so far this time -is useless. It brings up many interesting questions though.

-
    -
  • -

    -What happens if a file contains two integers? -

    +
    execute(Filename, [{integer, _, Int}|Tail], Modules) ->
    +    io:format("integer ~p~n", [Int]),
    +    execute(Filename, Tail, Modules).
    +
+

You might think by now that what we've done so far this time is useless. It brings up many interesting questions though.

+
  • What happens if a file contains two integers?
  • -
  • -

    -Can we live without expression separators? -

    +
  • Can we live without expression separators?
  • -
  • -

    -Do we need an interpreter for the compile step? -

    +
  • Do we need an interpreter for the compile step?
  • -
-

This is what happens when we create a file that contains two -integers on two separate lines:

-
-
-
[{integer,1,42},{integer,2,43}]
-

And on the same lines:

-
-
-
[{integer,1,42},{integer,1,43}]
-

Does this mean we do not need separators between expressions? -Not quite. The + and - operators are an -example of why we can’t have nice things. They are ambiguous. They -have two different meanings: make an atomic integer positive or -negative, or perform an addition or a substraction between two -integers. Without a separator you won’t be able to know if the -following snippet is one or two expressions:

-
-
-
42 - 12
-

Can we use the line ending as an expression separator then? -Some languages make whitespace important, often the line -separator becomes the expression separator. I do not think this -is the best idea, it can lead to errors. For example the following -snippet would be two expressions:

-
-
-
Var = some_module:some_function() + some_module:other_function()
-    + another_module:another_function()
-

It is not obvious what would happen unless you are a veteran -of the language, and so we will not go down that road. We will use -an expression separator just like in Erlang: the comma. We will -however allow a trailing comma to make copy pasting code easier, -even if this means some old academics guy will go nuts about it -later on. This trailing comma will be optional and simply discarded -by the parser when encountered. We will implement this next.

-

The question as to how we will handle running expressions -remains. We have two choices here: we can write an interpreter, -or we can compile the code and run it. Writing an interpreter -would require us to do twice the work, and we are lazy, so we will -not do that.

-

You might already know that Erlang does not use the same code -for compiling and for evaluating commands in the shell. The main -reason for this is that in Erlang everything isn’t an expression. -Indeed, the compiler compiles forms which contain expressions, -but you can’t have forms in the shell.

-

How are we going to compile the code that isn’t part of a module -then? What do we need to run at compile-time, anyway? The body of -the file itself, of course. The body of module declarations. That’s -about it.

-

For the file itself, we can simply compile it as a big function -that will be executed. Then, everytime we encounter a module -declaration, we will run the compiler on its body, making its body -essentially a big function that will be executed. The same mechanism -will be applied when we encounter a module declaration at runtime.

-

At runtime there’s nothing else for us to do, the result of this -operation will load all the compiled modules. At compile time we -will also want to save them to a file. We’ll see later how we can -do that.

-
    -
  • -

    -View the source -

    +
    Var = some_module:some_function() + some_module:other_function()
    +    + another_module:another_function()
    +
+

It is not obvious what would happen unless you are a veteran of the language, and so we will not go down that road. We will use an expression separator just like in Erlang: the comma. We will however allow a trailing comma to make copy pasting code easier, even if this means some old academics guy will go nuts about it later on. This trailing comma will be optional and simply discarded by the parser when encountered. We will implement this next.

+

The question as to how we will handle running expressions remains. We have two choices here: we can write an interpreter, or we can compile the code and run it. Writing an interpreter would require us to do twice the work, and we are lazy, so we will not do that.

+

You might already know that Erlang does not use the same code for compiling and for evaluating commands in the shell. The main reason for this is that in Erlang everything isn't an expression. Indeed, the compiler compiles forms which contain expressions, but you can't have forms in the shell.

+

How are we going to compile the code that isn't part of a module then? What do we need to run at compile-time, anyway? The body of the file itself, of course. The body of module declarations. That's about it.

+

For the file itself, we can simply compile it as a big function that will be executed. Then, everytime we encounter a module declaration, we will run the compiler on its body, making its body essentially a big function that will be executed. The same mechanism will be applied when we encounter a module declaration at runtime.

+

At runtime there's nothing else for us to do, the result of this operation will load all the compiled modules. At compile time we will also want to save them to a file. We'll see later how we can do that.

+ + + diff --git a/articles/xerl-0.4-expression-separator/index.html b/articles/xerl-0.4-expression-separator/index.html index 1f434d6c..e4dccec9 100644 --- a/articles/xerl-0.4-expression-separator/index.html +++ b/articles/xerl-0.4-expression-separator/index.html @@ -69,58 +69,44 @@

-

As promised we are adding an expression separator this time. -This will be short and easy.

-

In the tokenizer we only need to add a line recognizing the -comma as a valid token.

-
-
-
, : {token, {',', TokenLine}}.
-

Then we need to change the following lines in the parser:

-
-
-
exprs -> expr : ['$1'].
-exprs -> expr exprs : ['$1' | '$2'].
-

And add a comma between the expressions on the second line:

-
-
-
exprs -> expr : ['$1'].
-exprs -> expr ',' exprs : ['$1' | '$3'].
-

That takes care of everything except the optional trailing -comma at the end of our lists of expressions. We just need an -additional rule to take care of this.

-
-
-
exprs -> expr ',' : ['$1'].
-

That’s it.

-

Wondering why we don’t have this optional trailing comma in -Erlang considering how easy it was and the number of people -complaining about it? Yeah, me too. But that’s for someone else -to answer.

-

Another change I want to talk about is a simple modification -of the compiler code to use an #env{} record for -tracking state instead of passing around individual variables. -This will be required later on when we make modules into proper -expressions so I thought it was a good idea to anticipate.

-
+

That's it.

+

Wondering why we don't have this optional trailing comma in Erlang considering how easy it was and the number of people complaining about it? Yeah, me too. But that's for someone else to answer.

+

Another change I want to talk about is a simple modification of the compiler code to use an #env{} record for tracking state instead of passing around individual variables. This will be required later on when we make modules into proper expressions so I thought it was a good idea to anticipate.

+ + + diff --git a/articles/xerl-0.5-intermediate-module/index.html b/articles/xerl-0.5-intermediate-module/index.html index 7bb94d5b..09d6b2d8 100644 --- a/articles/xerl-0.5-intermediate-module/index.html +++ b/articles/xerl-0.5-intermediate-module/index.html @@ -69,136 +69,88 @@

-

Today we will start the work on the intermediate module -that will be used to run the code for the expressions found -in our file’s body, replacing our interpreter.

-

This is what we want to have when all the work is done:

-
-
-
xerl -> tokens -> AST -> intermediate -> cerl
-
-

Today we will perform this work only on the atomic integer -expression however, so we will not build any module at the end. -We have a few more things to take care of before getting there. -This does mean that we completely break compilation of modules -though, so hopefully we can resolve that soon.

-

This intermediate representation is in the form of a module -which contains a single function: run/0. This function -contains all the expressions from our Xerl source file.

-

In the case of a Xerl source file only containing the integer -42, we will obtain the following module ready to -be executed:

-
-
-
-module('$xerl_intermediate').
--export([run/0]).
+
-module('$xerl_intermediate').
+-export([run/0]).
 
-run() ->
-    42.
-

Running it will of course give us a result of 42, -the same we had when interpreting expressions.

-

The resulting Core Erlang code looks like this:

-
-
-
module '$xerl_intermediate' ['run'/0]
-    attributes []
-'run'/0 =
-    fun () ->
-        42
-end
-

The nice thing about doing it like this is that other than the -definition of the intermediate module and its run/0 -function, we can use the same code we are using for generating -the final Beam file. It may also be faster than interpreting -if you have complex modules.

-

Of course this here only works for the simplest cases, as you -cannot declare a module or a function inside another Erlang function. -We will need to wrap these into function calls to the Xerl compiler -that will take care of compiling them, making them available for -any subsequent expression. We will also need to pass the environment -to the run function to keep track of all this.

-

This does mean that we will have different code for compiling -fun and mod expressions when creating -the intermediate module. But the many other expressions don’t need -any special care.

-

Right now we’ve used the '$xerl_intermediate' atom -for the intermediate module name because we only have one, but we -will need to have a more random name later on when we’ll implement -modules this way.

-

The attentive mind will know by now that when compiling a Xerl -file containing one module, we will need to compile two intermediate -modules: one for the file body, and one for the module’s body. Worry -not though, if we only detect mod instructions in the file -body, we can just skip this phase.

-

While we’re at it, we’ll modify our code generator to handle lists -of expressions, which didn’t actually work with integer literals -before.

-

We’re going to use Core Erlang sequences for running the many -expressions. Sequences work like let, except no value -is actually bound. Perfect for our case, since we don’t support -binding values at this time anyway.

-

Sequences have an argument and a body, both being Core Erlang -expressions. The simplest way to have many expressions is to use -a simple expression for the argument and a sequence for the rest -of the expressions. When we encounter the last expression in the -list, we do not create a sequence.

-

The result is this very simple function:

-
-
-
comp_body([Expr]) ->
-    expr(Expr);
-comp_body([Expr|Exprs]) ->
-    Arg = expr(Expr),
-    Body = comp_body(Exprs),
-    cerl:c_seq(Arg, Body).
-

In the case of our example above, a sequence will not be created, -we only have one expression. If we were to have 42, 43, 44 -in our Xerl source file, we would have a result equivalent to the -following before optimization:

-
-
-
-module('$xerl_intermediate').
--export([run/0]).
+
-module('$xerl_intermediate').
+-export([run/0]).
 
-run() ->
-    42,
-    43,
-    44.
-

And the result is of course 44.

-

The resulting Core Erlang code looks like this:

-
-
-
module '$xerl_intermediate' ['run'/0]
-    attributes []
-'run'/0 =
-    fun () ->
-        do  42
-            do  43
-                44
-end
-

Feels very lisp-y, right? Yep.

-
    -
  • -

    -View the source -

    +
    module '$xerl_intermediate' ['run'/0]
    +    attributes []
    +'run'/0 =
    +    fun () ->
    +        do  42
    +            do  43
    +                44
    +end
    +
+

Feels very lisp-y, right? Yep.

+ + + diff --git a/docs/en/cowboy/2.0/guide/constraints/index.html b/docs/en/cowboy/2.0/guide/constraints/index.html index d89fe6a6..60c1ec6d 100644 --- a/docs/en/cowboy/2.0/guide/constraints/index.html +++ b/docs/en/cowboy/2.0/guide/constraints/index.html @@ -62,141 +62,86 @@

Constraints

-

Constraints are validation and conversion functions applied -to user input.

-

They are used in various places in Cowboy, including the -router and the cowboy_req match functions.

-
+

Constraints are validation and conversion functions applied to user input.

+

They are used in various places in Cowboy, including the router and the cowboy_req match functions.

Syntax

-
-

Constraints are provided as a list of fields. For each field -in the list, specific constraints can be applied, as well as -a default value if the field is missing.

-

A field can take the form of an atom field, a tuple with -constraints {field, Constraints} or a tuple with constraints -and a default value {field, Constraints, Default}. -The field form indicates the field is mandatory.

-

Note that when used with the router, only the second form -makes sense, as it does not use the default and the field -is always defined.

-

Constraints for each field are provided as an ordered list -of atoms or funs to apply. Built-in constraints are provided -as atoms, while custom constraints are provided as funs.

-

When multiple constraints are provided, they are applied in -the order given. If the value has been modified by a constraint -then the next one receives the new value.

-

For example, the following constraints will first validate -and convert the field my_value to an integer, and then -check that the integer is positive:

-
-
-
PositiveFun = fun
-    (_, V) when V > 0 ->
-        {ok, V};
-    (_, _) ->
-        {error, not_positive}
-end,
-{my_value, [int, PositiveFun]}.
-

We ignore the first fun argument in this snippet. We shouldn’t. -We will simply learn what it is later in this chapter.

-

When there’s only one constraint, it can be provided directly -without wrapping it into a list:

-
-
-
{my_value, int}
-
-
-
+
{my_value, int}
+

Built-in constraints

-
-

Built-in constraints are specified as an atom:

-
- --- - - - - - - - - - +

Built-in constraints are specified as an atom:

+
Constraint Description

int

Converts binary value to integer.

+ + + + - - - + + - -
ConstraintDescription
intConverts binary value to integer.

nonempty

Ensures the binary value is non-empty.

nonemptyEnsures the binary value is non-empty.
-
-
- -
+

Custom constraints

-
-

Custom constraints are specified as a fun. This fun takes -two arguments. The first argument indicates the operation -to be performed, and the second is the value. What the -value is and what must be returned depends on the operation.

-

Cowboy currently defines three operations. The operation -used for validating and converting user input is the forward -operation.

-
-
-
int(forward, Value) ->
-    try
-        {ok, binary_to_integer(Value)}
-    catch _:_ ->
-        {error, not_an_integer}
-    end;
-

The value must be returned even if it is not converted -by the constraint.

-

The reverse operation does the opposite: it -takes a converted value and changes it back to what the -user input would have been.

-
-
-
int(reverse, Value) ->
-        try
-                {ok, integer_to_binary(Value)}
-        catch _:_ ->
-                {error, not_an_integer}
-        end;
-

Finally, the format_error operation takes an error -returned by any other operation and returns a formatted -human-readable error message.

-
-
-
int(format_error, {not_an_integer, Value}) ->
-        io_lib:format("The value ~p is not an integer.", [Value]).
-

Notice that for this case you get both the error and -the value that was given to the constraint that produced -this error.

-

Cowboy will not catch exceptions coming from constraint -functions. They should be written to not emit any exceptions.

-
-
+
int(format_error, {not_an_integer, Value}) ->
+	io_lib:format("The value ~p is not an integer.", [Value]).
+ +

Notice that for this case you get both the error and the value that was given to the constraint that produced this error.

+

Cowboy will not catch exceptions coming from constraint functions. They should be written to not emit any exceptions.

+ diff --git a/docs/en/cowboy/2.0/guide/cookies/index.html b/docs/en/cowboy/2.0/guide/cookies/index.html index 646c79de..dd764e82 100644 --- a/docs/en/cowboy/2.0/guide/cookies/index.html +++ b/docs/en/cowboy/2.0/guide/cookies/index.html @@ -62,144 +62,103 @@

Using cookies

-

Cookies are a mechanism allowing applications to maintain -state on top of the stateless HTTP protocol.

-

Cookies are a name/value store where the names and values are -stored in plain text. They expire either after a delay -or when the browser closes. They can be configured on a -specific domain name or path, and restricted to secure -resources (sent or downloaded over HTTPS), or restricted -to the server (disallowing access from client-side scripts).

-

Cookie names are de facto case sensitive.

-

Cookies are stored client-side and sent with every subsequent -request that matches the domain and path for which they were -stored, until they expire. This can create a non-negligible -cost.

-

Cookies should not be considered secure. They are stored on -the user’s computer in plain text, and can be read by any -program. They can also be read by proxies when using clear -connections. Always validate the value before using it, -and never store any sensitive information inside it.

-

Cookies set by the server are only available in requests -following the client reception of the response containing -them.

-

Cookies may be sent repeatedly. This is often useful to -update the expiration time and avoid losing a cookie.

-
+

Cookies are a mechanism allowing applications to maintain state on top of the stateless HTTP protocol.

+

Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts).

+

Cookie names are de facto case sensitive.

+

Cookies are stored client-side and sent with every subsequent request that matches the domain and path for which they were stored, until they expire. This can create a non-negligible cost.

+

Cookies should not be considered secure. They are stored on the user's computer in plain text, and can be read by any program. They can also be read by proxies when using clear connections. Always validate the value before using it, and never store any sensitive information inside it.

+

Cookies set by the server are only available in requests following the client reception of the response containing them.

+

Cookies may be sent repeatedly. This is often useful to update the expiration time and avoid losing a cookie.

Setting cookies

-
-

By default cookies are defined for the duration of the session:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0).
-

They can also be set for a duration in seconds:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{max_age => 3600}).
-

To delete cookies, set max_age to 0:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{max_age => 0}).
-

To restrict cookies to a specific domain and path, the options -of the same name can be used:

-
-
-
Req = cowboy_req:set_resp_cookie(<<"inaccount">>, <<"1">>, Req0,
-    #{domain => "my.example.org", path => "/account"}).
-

Cookies will be sent with requests to this domain and all -its subdomains, and to resources on this path or deeper -in the path hierarchy.

-

To restrict cookies to secure channels (typically resources -available over HTTPS):

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{secure => true}).
-

To prevent client-side scripts from accessing a cookie:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{http_only => true}).
-

Cookies may also be set client-side, for example using -Javascript.

-
-
-
+
SessionID = generate_session_id(),
+Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
+    #{http_only => true}).
+
+

Cookies may also be set client-side, for example using Javascript.

Reading cookies

-
-

The client only ever sends back the cookie name and value. -All other options that can be set are never sent back.

-

Cowboy provides two functions for reading cookies. Both -involve parsing the cookie header(s) and so should not -be called repeatedly.

-

You can get all cookies as a key/value list:

-
-
-
Cookies = cowboy_req:parse_cookies(Req),
-{_, Lang} = lists:keyfind(<<"lang">>, 1, Cookies).
-

Or you can perform a match against cookies and retrieve -only the ones you need, while at the same time doing -any required post processing using constraints. -This function returns a map:

-
-
-
#{id := ID, lang := Lang} = cowboy_req:match_cookies([id, lang], Req).
-

You can use constraints to validate the values while matching -them. The following snippet will crash if the id cookie is -not an integer number or if the lang cookie is empty. Additionally -the id cookie value will be converted to an integer term:

-
-
-
CookiesMap = cowboy_req:match_cookies([{id, int}, {lang, nonempty}], Req).
-

Note that if two cookies share the same name, then the map value -will be a list of the two cookie values.

-

A default value can be provided. The default will be used -if the lang cookie is not found. It will not be used if -the cookie is found but has an empty value:

-
-
-
#{lang := Lang} = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
-

If no default is provided and the value is missing, an -exception is thrown.

-
- +
#{lang := Lang} = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
+ +

If no default is provided and the value is missing, an exception is thrown.

+ diff --git a/docs/en/cowboy/2.0/guide/erlang_web/index.html b/docs/en/cowboy/2.0/guide/erlang_web/index.html index 9d5a0518..128647f7 100644 --- a/docs/en/cowboy/2.0/guide/erlang_web/index.html +++ b/docs/en/cowboy/2.0/guide/erlang_web/index.html @@ -62,194 +62,52 @@

Erlang and the Web

-

Erlang is the ideal platform for writing Web applications. -Its features are a perfect match for the requirements of -modern Web applications.

-
+

Erlang is the ideal platform for writing Web applications. Its features are a perfect match for the requirements of modern Web applications.

The Web is concurrent

-
-

When you access a website there is little concurrency -involved. A few connections are opened and requests -are sent through these connections. Then the web page -is displayed on your screen. Your browser will only -open up to 4 or 8 connections to the server, depending -on your settings. This isn’t much.

-

But think about it. You are not the only one accessing -the server at the same time. There can be hundreds, if -not thousands, if not millions of connections to the -same server at the same time.

-

Even today a lot of systems used in production haven’t -solved the C10K problem (ten thousand concurrent connections). -And the ones who did are trying hard to get to the next -step, C100K, and are pretty far from it.

-

Erlang meanwhile has no problem handling millions of -connections. At the time of writing there are application -servers written in Erlang that can handle more than two -million connections on a single server in a real production -application, with spare memory and CPU!

-

The Web is concurrent, and Erlang is a language designed -for concurrency, so it is a perfect match.

-

Of course, various platforms need to scale beyond a few -million connections. This is where Erlang’s built-in -distribution mechanisms come in. If one server isn’t -enough, add more! Erlang allows you to use the same code -for talking to local processes or to processes in other -parts of your cluster, which means you can scale very -quickly if the need arises.

-

The Web has large userbases, and the Erlang platform was -designed to work in a distributed setting, so it is a -perfect match.

-

Or is it? Surely you can find solutions to handle that many -concurrent connections with your favorite language… But all -these solutions will break down in the next few years. Why? -Firstly because servers don’t get any more powerful, they -instead get a lot more cores and memory. This is only useful -if your application can use them properly, and Erlang is -light-years away from anything else in that area. Secondly, -today your computer and your phone are online, tomorrow your -watch, goggles, bike, car, fridge and tons of other devices -will also connect to various applications on the Internet.

-

Only Erlang is prepared to deal with what’s coming.

-
-
-
+

When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. This isn't much.

+

But think about it. You are not the only one accessing the server at the same time. There can be hundreds, if not thousands, if not millions of connections to the same server at the same time.

+

Even today a lot of systems used in production haven't solved the C10K problem (ten thousand concurrent connections). And the ones who did are trying hard to get to the next step, C100K, and are pretty far from it.

+

Erlang meanwhile has no problem handling millions of connections. At the time of writing there are application servers written in Erlang that can handle more than two million connections on a single server in a real production application, with spare memory and CPU!

+

The Web is concurrent, and Erlang is a language designed for concurrency, so it is a perfect match.

+

Of course, various platforms need to scale beyond a few million connections. This is where Erlang's built-in distribution mechanisms come in. If one server isn't enough, add more! Erlang allows you to use the same code for talking to local processes or to processes in other parts of your cluster, which means you can scale very quickly if the need arises.

+

The Web has large userbases, and the Erlang platform was designed to work in a distributed setting, so it is a perfect match.

+

Or is it? Surely you can find solutions to handle that many concurrent connections with your favorite language... But all these solutions will break down in the next few years. Why? Firstly because servers don't get any more powerful, they instead get a lot more cores and memory. This is only useful if your application can use them properly, and Erlang is light-years away from anything else in that area. Secondly, today your computer and your phone are online, tomorrow your watch, goggles, bike, car, fridge and tons of other devices will also connect to various applications on the Internet.

+

Only Erlang is prepared to deal with what's coming.

The Web is soft real time

-
-

What does soft real time mean, you ask? It means we want the -operations done as quickly as possible, and in the case of -web applications, it means we want the data propagated fast.

-

In comparison, hard real time has a similar meaning, but also -has a hard time constraint, for example an operation needs to -be done in under N milliseconds otherwise the system fails -entirely.

-

Users aren’t that needy yet, they just want to get access -to their content in a reasonable delay, and they want the -actions they make to register at most a few seconds after -they submitted them, otherwise they’ll start worrying about -whether it successfully went through.

-

The Web is soft real time because taking longer to perform an -operation would be seen as bad quality of service.

-

Erlang is a soft real time system. It will always run -processes fairly, a little at a time, switching to another -process after a while and preventing a single process to -steal resources from all others. This means that Erlang -can guarantee stable low latency of operations.

-

Erlang provides the guarantees that the soft real time Web -requires.

-
-
-
+

What does soft real time mean, you ask? It means we want the operations done as quickly as possible, and in the case of web applications, it means we want the data propagated fast.

+

In comparison, hard real time has a similar meaning, but also has a hard time constraint, for example an operation needs to be done in under N milliseconds otherwise the system fails entirely.

+

Users aren't that needy yet, they just want to get access to their content in a reasonable delay, and they want the actions they make to register at most a few seconds after they submitted them, otherwise they'll start worrying about whether it successfully went through.

+

The Web is soft real time because taking longer to perform an operation would be seen as bad quality of service.

+

Erlang is a soft real time system. It will always run processes fairly, a little at a time, switching to another process after a while and preventing a single process to steal resources from all others. This means that Erlang can guarantee stable low latency of operations.

+

Erlang provides the guarantees that the soft real time Web requires.

The Web is asynchronous

-
-

Long ago, the Web was synchronous because HTTP was synchronous. -You fired a request, and then waited for a response. Not anymore. -It all began when XmlHttpRequest started being used. It allowed -the client to perform asynchronous calls to the server.

-

Then Websocket appeared and allowed both the server and the client -to send data to the other endpoint completely asynchronously. The -data is contained within frames and no response is necessary.

-

Erlang processes work the same. They send each other data contained -within messages and then continue running without needing a response. -They tend to spend most of their time inactive, waiting for a new -message, and the Erlang VM happily activate them when one is received.

-

It is therefore quite easy to imagine Erlang being good at receiving -Websocket frames, which may come in at unpredictable times, pass the -data to the responsible processes which are always ready waiting for -new messages, and perform the operations required by only activating -the required parts of the system.

-

The more recent Web technologies, like Websocket of course, but also -HTTP/2.0, are all fully asynchronous protocols. The concept -of requests and responses is retained of course, but anything could -be sent in between, by both the client or the browser, and the -responses could also be received in a completely different order.

-

Erlang is by nature asynchronous and really good at it thanks to the -great engineering that has been done in the VM over the years. It’s -only natural that it’s so good at dealing with the asynchronous Web.

-
-
-
+

Long ago, the Web was synchronous because HTTP was synchronous. You fired a request, and then waited for a response. Not anymore. It all began when XmlHttpRequest started being used. It allowed the client to perform asynchronous calls to the server.

+

Then Websocket appeared and allowed both the server and the client to send data to the other endpoint completely asynchronously. The data is contained within frames and no response is necessary.

+

Erlang processes work the same. They send each other data contained within messages and then continue running without needing a response. They tend to spend most of their time inactive, waiting for a new message, and the Erlang VM happily activate them when one is received.

+

It is therefore quite easy to imagine Erlang being good at receiving Websocket frames, which may come in at unpredictable times, pass the data to the responsible processes which are always ready waiting for new messages, and perform the operations required by only activating the required parts of the system.

+

The more recent Web technologies, like Websocket of course, but also HTTP/2.0, are all fully asynchronous protocols. The concept of requests and responses is retained of course, but anything could be sent in between, by both the client or the browser, and the responses could also be received in a completely different order.

+

Erlang is by nature asynchronous and really good at it thanks to the great engineering that has been done in the VM over the years. It's only natural that it's so good at dealing with the asynchronous Web.

The Web is omnipresent

-
-

The Web has taken a very important part of our lives. We’re -connected at all times, when we’re on our phone, using our computer, -passing time using a tablet while in the bathroom… And this -isn’t going to slow down, every single device at home or on us -will be connected.

-

All these devices are always connected. And with the number of -alternatives to give you access to the content you seek, users -tend to not stick around when problems arise. Users today want -their applications to be always available and if it’s having -too many issues they just move on.

-

Despite this, when developers choose a product to use for building -web applications, their only concern seems to be "Is it fast?", -and they look around for synthetic benchmarks showing which one -is the fastest at sending "Hello world" with only a handful -concurrent connections. Web benchmarks haven’t been representative -of reality in a long time, and are drifting further away as -time goes on.

-

What developers should really ask themselves is "Can I service -all my users with no interruption?" and they’d find that they have -two choices. They can either hope for the best, or they can use -Erlang.

-

Erlang is built for fault tolerance. When writing code in any other -language, you have to check all the return values and act accordingly -to avoid any unforeseen issues. If you’re lucky, you won’t miss -anything important. When writing Erlang code, you can just check -the success condition and ignore all errors. If an error happens, -the Erlang process crashes and is then restarted by a special -process called a supervisor.

-

Erlang developers thus have no need to fear unhandled -errors, and can focus on handling only the errors that should -give some feedback to the user and let the system take care of -the rest. This also has the advantage of allowing them to write -a lot less code, and let them sleep at night.

-

Erlang’s fault tolerance oriented design is the first piece of -what makes it the best choice for the omnipresent, always available -Web.

-

The second piece is Erlang’s built-in distribution. Distribution -is a key part of building a fault tolerant system, because it -allows you to handle bigger failures, like a whole server going -down, or even a data center entirely.

-

Fault tolerance and distribution are important today, and will be -vital in the future of the Web. Erlang is ready.

-
-
-
+

The Web has taken a very important part of our lives. We're connected at all times, when we're on our phone, using our computer, passing time using a tablet while in the bathroom... And this isn't going to slow down, every single device at home or on us will be connected.

+

All these devices are always connected. And with the number of alternatives to give you access to the content you seek, users tend to not stick around when problems arise. Users today want their applications to be always available and if it's having too many issues they just move on.

+

Despite this, when developers choose a product to use for building web applications, their only concern seems to be "Is it fast?", and they look around for synthetic benchmarks showing which one is the fastest at sending "Hello world" with only a handful concurrent connections. Web benchmarks haven't been representative of reality in a long time, and are drifting further away as time goes on.

+

What developers should really ask themselves is "Can I service all my users with no interruption?" and they'd find that they have two choices. They can either hope for the best, or they can use Erlang.

+

Erlang is built for fault tolerance. When writing code in any other language, you have to check all the return values and act accordingly to avoid any unforeseen issues. If you're lucky, you won't miss anything important. When writing Erlang code, you can just check the success condition and ignore all errors. If an error happens, the Erlang process crashes and is then restarted by a special process called a supervisor.

+

Erlang developers thus have no need to fear unhandled errors, and can focus on handling only the errors that should give some feedback to the user and let the system take care of the rest. This also has the advantage of allowing them to write a lot less code, and let them sleep at night.

+

Erlang's fault tolerance oriented design is the first piece of what makes it the best choice for the omnipresent, always available Web.

+

The second piece is Erlang's built-in distribution. Distribution is a key part of building a fault tolerant system, because it allows you to handle bigger failures, like a whole server going down, or even a data center entirely.

+

Fault tolerance and distribution are important today, and will be vital in the future of the Web. Erlang is ready.

Learn Erlang

-
-

If you are new to Erlang, you may want to grab a book or -two to get started. Those are my recommendations as the -author of Cowboy.

-
+

If you are new to Erlang, you may want to grab a book or two to get started. Those are my recommendations as the author of Cowboy.

The Erlanger Playbook

-

The Erlanger Playbook is an ebook I am currently writing, -which covers a number of different topics from code to -documentation to testing Erlang applications. It also has -an Erlang section where it covers directly the building -blocks and patterns, rather than details like the syntax.

-

You can most likely read it as a complete beginner, but -you will need a companion book to make the most of it. -Buy it from the Nine Nines website.

-
-
+

The Erlanger Playbook is an ebook I am currently writing, which covers a number of different topics from code to documentation to testing Erlang applications. It also has an Erlang section where it covers directly the building blocks and patterns, rather than details like the syntax.

+

You can most likely read it as a complete beginner, but you will need a companion book to make the most of it. Buy it from the Nine Nines website.

Programming Erlang

-

This book is from one of the creator of Erlang, Joe -Armstrong. It provides a very good explanation of what -Erlang is and why it is so. It serves as a very good -introduction to the language and platform.

-

The book is Programming Erlang, -and it also features a chapter on Cowboy.

-
-
+

This book is from one of the creator of Erlang, Joe Armstrong. It provides a very good explanation of what Erlang is and why it is so. It serves as a very good introduction to the language and platform.

+

The book is Programming Erlang, and it also features a chapter on Cowboy.

Learn You Some Erlang for Great Good!

-

LYSE is a much more complete -book covering many aspects of Erlang, while also providing -stories and humor. Be warned: it’s pretty verbose. It comes -with a free online version and a more refined paper and -ebook version.

-
-
-
+

LYSE is a much more complete book covering many aspects of Erlang, while also providing stories and humor. Be warned: it's pretty verbose. It comes with a free online version and a more refined paper and ebook version.

+ diff --git a/docs/en/cowboy/2.0/guide/flow_diagram/index.html b/docs/en/cowboy/2.0/guide/flow_diagram/index.html index 65fe9305..d518183a 100644 --- a/docs/en/cowboy/2.0/guide/flow_diagram/index.html +++ b/docs/en/cowboy/2.0/guide/flow_diagram/index.html @@ -62,113 +62,30 @@

Flow diagram

-

Cowboy is a lightweight HTTP server with support for HTTP/1.1, -HTTP/2 and Websocket.

-

It is built on top of Ranch. Please see the Ranch guide for more -information about how the network connections are handled.

-
+

Cowboy is a lightweight HTTP server with support for HTTP/1.1, HTTP/2 and Websocket.

+

It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled.

Overview

-
-
-
-HTTP request/response flowchart -
-
-

As you can see on the diagram, the client -begins by connecting to the server. This step is handled -by a Ranch acceptor, which is a process dedicated to -accepting new connections.

-

After Ranch accepts a new connection, whether it is an -HTTP/1.1 or HTTP/2 connection, Cowboy starts receiving -requests and handling them.

-

In HTTP/1.1 all requests come sequentially. In HTTP/2 -the requests may arrive and be processed concurrently.

-

When a request comes in, Cowboy creates a stream, which -is a set of request/response and all the events associated -with them. The protocol code in Cowboy defers the handling -of these streams to stream handler modules. When you -configure Cowboy you may define one or more module that -will receive all events associated with a stream, including -the request, response, bodies, Erlang messages and more.

-

By default Cowboy comes configured with a stream handler -called cowboy_stream_h. This stream handler will create -a new process for every request coming in, and then -communicate with this process to read the body or send -a response back. The request process executes middlewares -which, by default, including the router and then the -execution of handlers. Like stream handlers, middlewares -may also be customized.

-

A response may be sent at almost any point in this -diagram. If the response must be sent before the stream -is initialized (because an error occurred early, for -example) then stream handlers receive a special event -indicating this error.

-
-
-
+HTTP request/response flowchart

As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections.

+

After Ranch accepts a new connection, whether it is an HTTP/1.1 or HTTP/2 connection, Cowboy starts receiving requests and handling them.

+

In HTTP/1.1 all requests come sequentially. In HTTP/2 the requests may arrive and be processed concurrently.

+

When a request comes in, Cowboy creates a stream, which is a set of request/response and all the events associated with them. The protocol code in Cowboy defers the handling of these streams to stream handler modules. When you configure Cowboy you may define one or more module that will receive all events associated with a stream, including the request, response, bodies, Erlang messages and more.

+

By default Cowboy comes configured with a stream handler called cowboy_stream_h. This stream handler will create a new process for every request coming in, and then communicate with this process to read the body or send a response back. The request process executes middlewares which, by default, including the router and then the execution of handlers. Like stream handlers, middlewares may also be customized.

+

A response may be sent at almost any point in this diagram. If the response must be sent before the stream is initialized (because an error occurred early, for example) then stream handlers receive a special event indicating this error.

Protocol-specific headers

-
-

Cowboy takes care of protocol-specific headers and prevents -you from sending them manually. For HTTP/1.1 this includes -the transfer-encoding and connection headers. For HTTP/2 -this includes the colon headers like :status.

-

Cowboy will also remove protocol-specific headers from -requests before passing them to stream handlers. Cowboy -tries to hide the implementation details of all protocols -as well as possible.

-
-
-
+

Cowboy takes care of protocol-specific headers and prevents you from sending them manually. For HTTP/1.1 this includes the transfer-encoding and connection headers. For HTTP/2 this includes the colon headers like :status.

+

Cowboy will also remove protocol-specific headers from requests before passing them to stream handlers. Cowboy tries to hide the implementation details of all protocols as well as possible.

Number of processes per connection

-
-

By default, Cowboy will use one process per connection, -plus one process per set of request/response (called a -stream, internally).

-

The reason it creates a new process for every request is due -to the requirements of HTTP/2 where requests are executed -concurrently and independently from the connection. The -frames from the different requests end up interleaved on -the single TCP connection.

-

The request processes are never reused. There is therefore -no need to perform any cleanup after the response has been -sent. The process will terminate and Erlang/OTP will reclaim -all memory at once.

-

Cowboy ultimately does not require more than one process -per connection. It is possible to interact with the connection -directly from a stream handler, a low level interface to Cowboy. -They are executed from within the connection process, and can -handle the incoming requests and send responses. This is however -not recommended in normal circumstances, as a stream handler -taking too long to execute could have a negative impact on -concurrent requests or the state of the connection itself.

-
-
-
+

By default, Cowboy will use one process per connection, plus one process per set of request/response (called a stream, internally).

+

The reason it creates a new process for every request is due to the requirements of HTTP/2 where requests are executed concurrently and independently from the connection. The frames from the different requests end up interleaved on the single TCP connection.

+

The request processes are never reused. There is therefore no need to perform any cleanup after the response has been sent. The process will terminate and Erlang/OTP will reclaim all memory at once.

+

Cowboy ultimately does not require more than one process per connection. It is possible to interact with the connection directly from a stream handler, a low level interface to Cowboy. They are executed from within the connection process, and can handle the incoming requests and send responses. This is however not recommended in normal circumstances, as a stream handler taking too long to execute could have a negative impact on concurrent requests or the state of the connection itself.

Date header

-
-

Because querying for the current date and time can be expensive, -Cowboy generates one Date header value every second, shares it -to all other processes, which then simply copy it in the response. -This allows compliance with HTTP/1.1 with no actual performance loss.

-
-
-
+

Because querying for the current date and time can be expensive, Cowboy generates one Date header value every second, shares it to all other processes, which then simply copy it in the response. This allows compliance with HTTP/1.1 with no actual performance loss.

Binaries

-
-

Cowboy makes extensive use of binaries.

-

Binaries are more efficient than lists for representing -strings because they take less memory space. Processing -performance can vary depending on the operation. Binaries -are known for generally getting a great boost if the code -is compiled natively. Please see the HiPE documentation -for more details.

-

Binaries may end up being shared between processes. This -can lead to some large memory usage when one process keeps -the binary data around forever without freeing it. If you -see some weird memory usage in your application, this might -be the cause.

-
-
+

Cowboy makes extensive use of binaries.

+

Binaries are more efficient than lists for representing strings because they take less memory space. Processing performance can vary depending on the operation. Binaries are known for generally getting a great boost if the code is compiled natively. Please see the HiPE documentation for more details.

+

Binaries may end up being shared between processes. This can lead to some large memory usage when one process keeps the binary data around forever without freeing it. If you see some weird memory usage in your application, this might be the cause.

+ diff --git a/docs/en/cowboy/2.0/guide/getting_started/index.html b/docs/en/cowboy/2.0/guide/getting_started/index.html index 4b6c7c33..6c156e4e 100644 --- a/docs/en/cowboy/2.0/guide/getting_started/index.html +++ b/docs/en/cowboy/2.0/guide/getting_started/index.html @@ -62,161 +62,104 @@

Getting started

-

Erlang is more than a language, it is also an operating system -for your applications. Erlang developers rarely write standalone -modules, they write libraries or applications, and then bundle -those into what is called a release. A release contains the -Erlang VM plus all applications required to run the node, so -it can be pushed to production directly.

-

This chapter walks you through all the steps of setting up -Cowboy, writing your first application and generating your first -release. At the end of this chapter you should know everything -you need to push your first Cowboy application to production.

-
+

Erlang is more than a language, it is also an operating system for your applications. Erlang developers rarely write standalone modules, they write libraries or applications, and then bundle those into what is called a release. A release contains the Erlang VM plus all applications required to run the node, so it can be pushed to production directly.

+

This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. At the end of this chapter you should know everything you need to push your first Cowboy application to production.

Prerequisites

-
-

We are going to use the Erlang.mk -build system. If you are using Windows, please check the -Installation instructions -to get your environment setup before you continue.

-
-
-
+

We are going to use the Erlang.mk build system. If you are using Windows, please check the Installation instructions to get your environment setup before you continue.

Bootstrap

-
-

First, let’s create the directory for our application.

-
-
$ mkdir hello_erlang
-$ cd hello_erlang
-

Then we need to download Erlang.mk. Either use the following -command or download it manually.

-
-
-
$ wget https://erlang.mk/erlang.mk
-

We can now bootstrap our application. Since we are going to generate -a release, we will also bootstrap it at the same time.

-
-
-
$ make -f erlang.mk bootstrap bootstrap-rel
-

This creates a Makefile, a base application, and the release files -necessary for creating the release. We can already build and start -this release.

-
-
$ make run
-...
-(hello_erlang@127.0.0.1)1>
-

Entering the command i(). will show the running processes, including -one called hello_erlang_sup. This is the supervisor for our -application.

-

The release currently does nothing. In the rest of this chapter we -will add Cowboy as a dependency and write a simple "Hello world!" -handler.

-
-
-
+... +(hello_erlang@127.0.0.1)1> +
+

Entering the command i(). will show the running processes, including one called hello_erlang_sup. This is the supervisor for our application.

+

The release currently does nothing. In the rest of this chapter we will add Cowboy as a dependency and write a simple "Hello world!" handler.

Cowboy setup

-
-

We will modify the Makefile to tell the build system it needs to -fetch and compile Cowboy:

-
-
-
PROJECT = hello_erlang
+
PROJECT = hello_erlang
 
-DEPS = cowboy
-dep_cowboy_commit = master
+DEPS = cowboy
+dep_cowboy_commit = master
 
-DEP_PLUGINS = cowboy
+DEP_PLUGINS = cowboy
 
-include erlang.mk
-

We also tell the build system to load the plugins Cowboy provides. -These include predefined templates that we will use soon.

-

If you do make run now, Cowboy will be included in the release -and started automatically. This is not enough however, as Cowboy -doesn’t do anything by default. We still need to tell Cowboy to -listen for connections.

-
- -
+include erlang.mk +
+

We also tell the build system to load the plugins Cowboy provides. These include predefined templates that we will use soon.

+

If you do make run now, Cowboy will be included in the release and started automatically. This is not enough however, as Cowboy doesn't do anything by default. We still need to tell Cowboy to listen for connections.

Listening for connections

-
-

First we define the routes that Cowboy will use to map requests -to handler modules, and then we start the listener. This is best -done at application startup.

-

Open the src/hello_erlang_app.erl file and add the necessary -code to the start/2 function to make it look like this:

-
-
-
start(_Type, _Args) ->
-    Dispatch = cowboy_router:compile([
-        {'_', [{"/", hello_handler, []}]}
+
start(_Type, _Args) ->
+    Dispatch = cowboy_router:compile([
+        {'_', [{"/", hello_handler, []}]}
     ]),
-    {ok, _} = cowboy:start_clear(my_http_listener,
-        [{port, 8080}],
-        #{env => #{dispatch => Dispatch}}
+    {ok, _} = cowboy:start_clear(my_http_listener,
+        [{port, 8080}],
+        #{env => #{dispatch => Dispatch}}
     ),
-    hello_erlang_sup:start_link().
-

Routes are explained in details in the Routing -chapter. For this tutorial we map the path / to the handler -module hello_handler. This module doesn’t exist yet.

-

Build and start the release, then open http://localhost:8080 -in your browser. You will get a 500 error because the module is missing. -Any other URL, like http://localhost:8080/test, will result in a -404 error.

-
- -
+ hello_erlang_sup:start_link(). +
+

Routes are explained in details in the Routing chapter. For this tutorial we map the path / to the handler module hello_handler. This module doesn't exist yet.

+

Build and start the release, then open http://localhost:8080 in your browser. You will get a 500 error because the module is missing. Any other URL, like http://localhost:8080/test, will result in a 404 error.

Handling requests

-
-

Cowboy features different kinds of handlers, including REST -and Websocket handlers. For this tutorial we will use a plain -HTTP handler.

-

Generate a handler from a template:

-
-
-
$ make new t=cowboy.http n=hello_handler
-

Then, open the src/hello_handler.erl file and modify -the init/2 function like this to send a reply.

-
-
-
init(Req0, State) ->
-    Req = cowboy_req:reply(200,
-        #{<<"content-type">> => <<"text/plain">>},
-        <<"Hello Erlang!">>,
-        Req0),
-    {ok, Req, State}.
-

What the above code does is send a 200 OK reply, with the -Content-type header set to text/plain and the response -body set to Hello Erlang!.

-

If you run the release and open http://localhost:8080 -in your browser, you should get a nice Hello Erlang! displayed!

-
- +
init(Req0, State) ->
+    Req = cowboy_req:reply(200,
+        #{<<"content-type">> => <<"text/plain">>},
+        <<"Hello Erlang!">>,
+        Req0),
+    {ok, Req, State}.
+ +

What the above code does is send a 200 OK reply, with the Content-type header set to text/plain and the response body set to Hello Erlang!.

+

If you run the release and open http://localhost:8080 in your browser, you should get a nice Hello Erlang! displayed!

+ diff --git a/docs/en/cowboy/2.0/guide/handlers/index.html b/docs/en/cowboy/2.0/guide/handlers/index.html index 28a6c5ec..dccd2faf 100644 --- a/docs/en/cowboy/2.0/guide/handlers/index.html +++ b/docs/en/cowboy/2.0/guide/handlers/index.html @@ -62,91 +62,57 @@

Handlers

-

Handlers are Erlang modules that handle HTTP requests.

-
+

Handlers are Erlang modules that handle HTTP requests.

Plain HTTP handlers

-
-

The most basic handler in Cowboy implements the mandatory -init/2 callback, manipulates the request, optionally -sends a response and then returns.

-

This callback receives the Req object and the initial -state defined in the router configuration.

-

A handler that does nothing would look like this:

-
-
-
init(Req, State) ->
-    {ok, Req, State}.
-

Despite sending no reply, a 204 No Content response will be -sent to the client, as Cowboy makes sure that a response is -sent for every request.

-

We need to use the Req object to reply.

-
-
-
init(Req0, State) ->
-    Req = cowboy_req:reply(200, #{
-        <<"content-type">> => <<"text/plain">>
-    }, <<"Hello World!">>, Req0),
-    {ok, Req, State}.
-

Cowboy will immediately send a response when cowboy:reply/4 -is called.

-

We then return a 3-tuple. ok means that the handler ran -successfully. We also give the modified Req back to Cowboy.

-

The last value of the tuple is a state that will be used -in every subsequent callbacks to this handler. Plain HTTP -handlers only have one additional callback, the optional -and rarely used terminate/3.

-
-
-
+
init(Req0, State) ->
+    Req = cowboy_req:reply(200, #{
+        <<"content-type">> => <<"text/plain">>
+    }, <<"Hello World!">>, Req0),
+    {ok, Req, State}.
+
+

Cowboy will immediately send a response when cowboy:reply/4 is called.

+

We then return a 3-tuple. ok means that the handler ran successfully. We also give the modified Req back to Cowboy.

+

The last value of the tuple is a state that will be used in every subsequent callbacks to this handler. Plain HTTP handlers only have one additional callback, the optional and rarely used terminate/3.

Other handlers

-
-

The init/2 callback can also be used to inform Cowboy -that this is a different kind of handler and that Cowboy -should switch to it. To do this you simply need to return -the module name of the handler type you want to switch to.

-

Cowboy comes with three handler types you can switch to: -cowboy_rest, cowboy_websocket -and cowboy_loop. In addition to those you -can define your own handler types.

-

Switching is simple. Instead of returning ok, you simply -return the name of the handler type you want to use. The -following snippet switches to a Websocket handler:

-
-
-
init(Req, State) ->
-    {cowboy_websocket, Req, State}.
-
- -
+
init(Req, State) ->
+    {cowboy_websocket, Req, State}.
+

Cleaning up

-
-

All handler types provide the optional terminate/3 callback.

-
-
-
terminate(_Reason, _Req, _State) ->
-    ok.
-

This callback is strictly reserved for any required cleanup. -You cannot send a response from this function. There is no -other return value.

-

This callback is optional because it is rarely necessary. -Cleanup should be done in separate processes directly (by -monitoring the handler process to detect when it exits).

-

Cowboy does not reuse processes for different requests. The -process will terminate soon after this call returns.

-
- +
terminate(_Reason, _Req, _State) ->
+    ok.
+ +

This callback is strictly reserved for any required cleanup. You cannot send a response from this function. There is no other return value.

+

This callback is optional because it is rarely necessary. Cleanup should be done in separate processes directly (by monitoring the handler process to detect when it exits).

+

Cowboy does not reuse processes for different requests. The process will terminate soon after this call returns.

+ diff --git a/docs/en/cowboy/2.0/guide/index.html b/docs/en/cowboy/2.0/guide/index.html index 7bbe1815..2fe39e6b 100644 --- a/docs/en/cowboy/2.0/guide/index.html +++ b/docs/en/cowboy/2.0/guide/index.html @@ -62,199 +62,79 @@

Cowboy User Guide

-
+ +

Rationale

- -
-
+

Introduction

- -
-
+

Configuration

-
- -
-
-
+

Handlers

- -
- - - -
+

Advanced

-
- -
-
- + + diff --git a/docs/en/cowboy/2.0/guide/introduction/index.html b/docs/en/cowboy/2.0/guide/introduction/index.html index 0b8a47e4..6c0d681e 100644 --- a/docs/en/cowboy/2.0/guide/introduction/index.html +++ b/docs/en/cowboy/2.0/guide/introduction/index.html @@ -62,79 +62,40 @@

Introduction

-

Cowboy is a small, fast and modern HTTP server for Erlang/OTP.

-

Cowboy aims to provide a complete modern Web stack. -This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and -Webmachine-based REST.

-

Cowboy comes with functions for introspection and tracing, enabling -developers to know precisely what is happening at any time. Its modular -design also easily enable developers to add instrumentation.

-

Cowboy is a high quality project. It has a small code base, is very -efficient (both in latency and memory use) and can easily be embedded -in another application.

-

Cowboy is clean Erlang code. It includes hundreds of tests and its code -is fully compliant with the Dialyzer. It is also well documented and -features a Function Reference, a User Guide and numerous Tutorials.

-
+

Cowboy is a small, fast and modern HTTP server for Erlang/OTP.

+

Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST.

+

Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation.

+

Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application.

+

Cowboy is clean Erlang code. It includes hundreds of tests and its code is fully compliant with the Dialyzer. It is also well documented and features a Function Reference, a User Guide and numerous Tutorials.

Prerequisites

-
-

Beginner Erlang knowledge is recommended for reading this guide.

-

Knowledge of the HTTP protocol is recommended but not required, as it -will be detailed throughout the guide.

-
-
-
+

Beginner Erlang knowledge is recommended for reading this guide.

+

Knowledge of the HTTP protocol is recommended but not required, as it will be detailed throughout the guide.

Supported platforms

-
-

Cowboy is tested and supported on Linux, FreeBSD, Windows and OSX.

-

Cowboy has been reported to work on other platforms, but we make no -guarantee that the experience will be safe and smooth. You are advised -to perform the necessary testing and security audits prior to deploying -on other platforms.

-

Cowboy is developed for Erlang/OTP 19.0 and newer.

-
-
-
+

Cowboy is tested and supported on Linux, FreeBSD, Windows and OSX.

+

Cowboy has been reported to work on other platforms, but we make no guarantee that the experience will be safe and smooth. You are advised to perform the necessary testing and security audits prior to deploying on other platforms.

+

Cowboy is developed for Erlang/OTP 19.0 and newer.

License

-
-

Cowboy uses the ISC License.

-
-
-
Copyright (c) 2011-2017, Loïc Hoguin <essen@ninenines.eu>
+

Cowboy uses the ISC License.

+
Copyright (c) 2011-2017, Loïc Hoguin <essen@ninenines.eu>
 
 Permission to use, copy, modify, and/or distribute this software for any
 purpose with or without fee is hereby granted, provided that the above
 copyright notice and this permission notice appear in all copies.
 
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-
-
-
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Versioning

-
- -
-
-
+

Cowboy uses Semantic Versioning 2.0.0.

Conventions

-
-

In the HTTP protocol, the method name is case sensitive. All standard -method names are uppercase.

-

Header names are case insensitive. When using HTTP/1.1, Cowboy converts -all the request header names to lowercase. HTTP/2 requires clients to -send them as lowercase. Any other header name is expected to be provided -lowercased, including when querying information about the request or -when sending responses.

-

The same applies to any other case insensitive value.

-
-
+

In the HTTP protocol, the method name is case sensitive. All standard method names are uppercase.

+

Header names are case insensitive. When using HTTP/1.1, Cowboy converts all the request header names to lowercase. HTTP/2 requires clients to send them as lowercase. Any other header name is expected to be provided lowercased, including when querying information about the request or when sending responses.

+

The same applies to any other case insensitive value.

+ diff --git a/docs/en/cowboy/2.0/guide/listeners/index.html b/docs/en/cowboy/2.0/guide/listeners/index.html index bd477809..920cbdc7 100644 --- a/docs/en/cowboy/2.0/guide/listeners/index.html +++ b/docs/en/cowboy/2.0/guide/listeners/index.html @@ -62,109 +62,61 @@

Listeners

-

A listener is a set of processes that listens on a port for -new connections. Incoming connections get handled by Cowboy. -Depending on the connection handshake, one or another protocol -may be used.

-

This chapter is specific to Cowboy. Please refer to the -Ranch User Guide -for more information about listeners.

-

Cowboy provides two types of listeners: one listening for -clear TCP connections, and one listening for secure TLS -connections. Both of them support the HTTP/1.1 and HTTP/2 -protocols.

-
+

A listener is a set of processes that listens on a port for new connections. Incoming connections get handled by Cowboy. Depending on the connection handshake, one or another protocol may be used.

+

This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners.

+

Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. Both of them support the HTTP/1.1 and HTTP/2 protocols.

Clear TCP listener

-
-

The clear TCP listener will accept connections on the -given port. A typical HTTP server would listen on port 80. -Port 80 requires special permissions on most platforms -however so a common alternative is port 8080.

-

The following snippet starts listening for connections -on port 8080:

-
-
-
start(_Type, _Args) ->
-    Dispatch = cowboy_router:compile([
-        {'_', [{"/", hello_handler, []}]}
+
start(_Type, _Args) ->
+    Dispatch = cowboy_router:compile([
+        {'_', [{"/", hello_handler, []}]}
     ]),
-    {ok, _} = cowboy:start_clear(my_http_listener,
-        [{port, 8080}],
-        #{env => #{dispatch => Dispatch}}
+    {ok, _} = cowboy:start_clear(my_http_listener,
+        [{port, 8080}],
+        #{env => #{dispatch => Dispatch}}
     ),
-    hello_erlang_sup:start_link().
-

The Getting Started chapter uses a -clear TCP listener.

-

Clients connecting to Cowboy on the clear listener port are -expected to use either HTTP/1.1 or HTTP/2.

-

Cowboy supports both methods of initiating a clear -HTTP/2 connection: through the Upgrade mechanism -(RFC 7540 3.2) -or by sending the preface directly -(RFC 7540 3.4).

-

Compatibility with HTTP/1.0 is provided by Cowboy’s HTTP/1.1 -implementation.

-
-
-
+ hello_erlang_sup:start_link(). +
+

The Getting Started chapter uses a clear TCP listener.

+

Clients connecting to Cowboy on the clear listener port are expected to use either HTTP/1.1 or HTTP/2.

+

Cowboy supports both methods of initiating a clear HTTP/2 connection: through the Upgrade mechanism (RFC 7540 3.2) or by sending the preface directly (RFC 7540 3.4).

+

Compatibility with HTTP/1.0 is provided by Cowboy's HTTP/1.1 implementation.

Secure TLS listener

-
-

The secure TLS listener will accept connections on the -given port. A typical HTTPS server would listen on port 443. -Port 443 requires special permissions on most platforms -however so a common alternative is port 8443.

-

The function provided by Cowboy will ensure that the TLS -options given are following the HTTP/2 RFC with regards -to security. For example some TLS extensions or ciphers -may be disabled. This also applies to HTTP/1.1 connections -on this listener. If this is not desirable, Ranch can be -used directly to setup a custom listener.

-
-
+

The function provided by Cowboy will ensure that the TLS options given are following the HTTP/2 RFC with regards to security. For example some TLS extensions or ciphers may be disabled. This also applies to HTTP/1.1 connections on this listener. If this is not desirable, Ranch can be used directly to setup a custom listener.

+
-
start(_Type, _Args) ->
-    Dispatch = cowboy_router:compile([
-        {'_', [{"/", hello_handler, []}]}
+
start(_Type, _Args) ->
+    Dispatch = cowboy_router:compile([
+        {'_', [{"/", hello_handler, []}]}
     ]),
-    {ok, _} = cowboy:start_tls(my_http_listener,
+    {ok, _} = cowboy:start_tls(my_http_listener,
         [
-            {port, 8443},
-            {certfile, "/path/to/certfile"},
-            {keyfile, "/path/to/keyfile"}
+            {port, 8443},
+            {certfile, "/path/to/certfile"},
+            {keyfile, "/path/to/keyfile"}
         ],
-        #{env => #{dispatch => Dispatch}}
+        #{env => #{dispatch => Dispatch}}
     ),
-    hello_erlang_sup:start_link().
-

Clients connecting to Cowboy on the secure listener are -expected to use the ALPN TLS extension to indicate what -protocols they understand. Cowboy always prefers HTTP/2 -over HTTP/1.1 when both are supported. When neither are -supported by the client, or when the ALPN extension was -missing, Cowboy expects HTTP/1.1 to be used.

-

Cowboy also advertises HTTP/2 support through the older -NPN TLS extension for compatibility. Note however that -this support will likely not be enabled by default when -Cowboy 2.0 gets released.

-

Compatibility with HTTP/1.0 is provided by Cowboy’s HTTP/1.1 -implementation.

-
-
-
+ hello_erlang_sup:start_link(). +
+

Clients connecting to Cowboy on the secure listener are expected to use the ALPN TLS extension to indicate what protocols they understand. Cowboy always prefers HTTP/2 over HTTP/1.1 when both are supported. When neither are supported by the client, or when the ALPN extension was missing, Cowboy expects HTTP/1.1 to be used.

+

Cowboy also advertises HTTP/2 support through the older NPN TLS extension for compatibility. Note however that this support will likely not be enabled by default when Cowboy 2.0 gets released.

+

Compatibility with HTTP/1.0 is provided by Cowboy's HTTP/1.1 implementation.

Protocol configuration

-
-

The HTTP/1.1 and HTTP/2 protocols share the same semantics; -only their framing differs. The first is a text protocol and -the second a binary protocol.

-

Cowboy doesn’t separate the configuration for HTTP/1.1 and -HTTP/2. Everything goes into the same map. Many options are -shared.

-
- +

The HTTP/1.1 and HTTP/2 protocols share the same semantics; only their framing differs. The first is a text protocol and the second a binary protocol.

+

Cowboy doesn't separate the configuration for HTTP/1.1 and HTTP/2. Everything goes into the same map. Many options are shared.

+ + + diff --git a/docs/en/cowboy/2.0/guide/loop_handlers/index.html b/docs/en/cowboy/2.0/guide/loop_handlers/index.html index a5507761..02ff7a4b 100644 --- a/docs/en/cowboy/2.0/guide/loop_handlers/index.html +++ b/docs/en/cowboy/2.0/guide/loop_handlers/index.html @@ -62,131 +62,72 @@

Loop handlers

-

Loop handlers are a special kind of HTTP handlers used when the -response can not be sent right away. The handler enters instead -a receive loop waiting for the right message before it can send -a response.

-

Loop handlers are used for requests where a response might not -be immediately available, but where you would like to keep the -connection open for a while in case the response arrives. The -most known example of such practice is known as long polling.

-

Loop handlers can also be used for requests where a response is -partially available and you need to stream the response body -while the connection is open. The most known example of such -practice is server-sent events.

-

While the same can be accomplished using plain HTTP handlers, -it is recommended to use loop handlers because they are well-tested -and allow using built-in features like hibernation and timeouts.

-

Loop handlers essentially wait for one or more Erlang messages -and feed these messages to the info/3 callback. It also features -the init/2 and terminate/3 callbacks which work the same as -for plain HTTP handlers.

-
+

Loop handlers are a special kind of HTTP handlers used when the response can not be sent right away. The handler enters instead a receive loop waiting for the right message before it can send a response.

+

Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling.

+

Loop handlers can also be used for requests where a response is partially available and you need to stream the response body while the connection is open. The most known example of such practice is server-sent events.

+

While the same can be accomplished using plain HTTP handlers, it is recommended to use loop handlers because they are well-tested and allow using built-in features like hibernation and timeouts.

+

Loop handlers essentially wait for one or more Erlang messages and feed these messages to the info/3 callback. It also features the init/2 and terminate/3 callbacks which work the same as for plain HTTP handlers.

Initialization

-
-

The init/2 function must return a cowboy_loop tuple to enable -loop handler behavior. This tuple may optionally contain -a timeout value and/or the atom hibernate to make the -process enter hibernation until a message is received.

-

This snippet enables the loop handler:

-
-
-
init(Req, State) ->
-    {cowboy_loop, Req, State}.
-

This also makes the process hibernate:

-
-
-
init(Req, State) ->
-    {cowboy_loop, Req, State, hibernate}.
-
-
-
+
init(Req, State) ->
+    {cowboy_loop, Req, State, hibernate}.
+

Receive loop

-
-

Once initialized, Cowboy will wait for messages to arrive -in the process' mailbox. When a message arrives, Cowboy -calls the info/3 function with the message, the Req object -and the handler’s state.

-

The following snippet sends a reply when it receives a -reply message from another process, or waits for another -message otherwise.

-
-
-
info({reply, Body}, Req, State) ->
-    cowboy_req:reply(200, #{}, Body, Req),
-    {stop, Req, State};
-info(_Msg, Req, State) ->
-    {ok, Req, State, hibernate}.
-

Do note that the reply tuple here may be any message -and is simply an example.

-

This callback may perform any necessary operation including -sending all or parts of a reply, and will subsequently -return a tuple indicating if more messages are to be expected.

-

The callback may also choose to do nothing at all and just -skip the message received.

-

If a reply is sent, then the stop tuple should be returned. -This will instruct Cowboy to end the request.

-

Otherwise an ok tuple should be returned.

-
- -
+
info({reply, Body}, Req, State) ->
+    cowboy_req:reply(200, #{}, Body, Req),
+    {stop, Req, State};
+info(_Msg, Req, State) ->
+    {ok, Req, State, hibernate}.
+
+

Do note that the reply tuple here may be any message and is simply an example.

+

This callback may perform any necessary operation including sending all or parts of a reply, and will subsequently return a tuple indicating if more messages are to be expected.

+

The callback may also choose to do nothing at all and just skip the message received.

+

If a reply is sent, then the stop tuple should be returned. This will instruct Cowboy to end the request.

+

Otherwise an ok tuple should be returned.

Streaming loop

-
-

Another common case well suited for loop handlers is -streaming data received in the form of Erlang messages. -This can be done by initiating a chunked reply in the -init/2 callback and then using cowboy_req:chunk/2 -every time a message is received.

-

The following snippet does exactly that. As you can see -a chunk is sent every time an event message is received, -and the loop is stopped by sending an eof message.

-
-
-
init(Req, State) ->
-    Req2 = cowboy_req:stream_reply(200, Req),
-    {cowboy_loop, Req2, State}.
-
-info(eof, Req, State) ->
-    {stop, Req, State};
-info({event, Data}, Req, State) ->
-    cowboy_req:stream_body(Data, nofin, Req),
-    {ok, Req, State};
-info(_Msg, Req, State) ->
-    {ok, Req, State}.
-
- -
+
init(Req, State) ->
+    Req2 = cowboy_req:stream_reply(200, Req),
+    {cowboy_loop, Req2, State}.
+
+info(eof, Req, State) ->
+    {stop, Req, State};
+info({event, Data}, Req, State) ->
+    cowboy_req:stream_body(Data, nofin, Req),
+    {ok, Req, State};
+info(_Msg, Req, State) ->
+    {ok, Req, State}.
+

Cleaning up

-
-

It is recommended that you set the connection header to -close when replying, as this process may be reused for -a subsequent request.

-

Please refer to the Handlers chapter -for general instructions about cleaning up.

-
- -
+

It is recommended that you set the connection header to close when replying, as this process may be reused for a subsequent request.

+

Please refer to the Handlers chapter for general instructions about cleaning up.

Hibernate

-
-

To save memory, you may hibernate the process in between -messages received. This is done by returning the atom -hibernate as part of the loop tuple callbacks normally -return. Just add the atom at the end and Cowboy will hibernate -accordingly.

-
-
+

To save memory, you may hibernate the process in between messages received. This is done by returning the atom hibernate as part of the loop tuple callbacks normally return. Just add the atom at the end and Cowboy will hibernate accordingly.

+ diff --git a/docs/en/cowboy/2.0/guide/middlewares/index.html b/docs/en/cowboy/2.0/guide/middlewares/index.html index 518bf7c3..35a3bbcc 100644 --- a/docs/en/cowboy/2.0/guide/middlewares/index.html +++ b/docs/en/cowboy/2.0/guide/middlewares/index.html @@ -62,92 +62,38 @@

Middlewares

-

Cowboy delegates the request processing to middleware components. -By default, two middlewares are defined, for the routing and handling -of the request, as is detailed in most of this guide.

-

Middlewares give you complete control over how requests are to be -processed. You can add your own middlewares to the mix or completely -change the chain of middlewares as needed.

-

Cowboy will execute all middlewares in the given order, unless one -of them decides to stop processing.

-
+

Cowboy delegates the request processing to middleware components. By default, two middlewares are defined, for the routing and handling of the request, as is detailed in most of this guide.

+

Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed.

+

Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing.

Usage

-
-

Middlewares only need to implement a single callback: execute/2. -It is defined in the cowboy_middleware behavior.

-

This callback has two arguments. The first is the Req object. -The second is the environment.

-

Middlewares can return one of three different values:

-
    -
  • -

    -{ok, Req, Env} to continue the request processing -

    +

    Middlewares only need to implement a single callback: execute/2. It is defined in the cowboy_middleware behavior.

    +

    This callback has two arguments. The first is the Req object. The second is the environment.

    +

    Middlewares can return one of three different values:

    +
    • {ok, Req, Env} to continue the request processing
    • -
    • -

      -{suspend, Module, Function, Args} to hibernate -

      +
    • {suspend, Module, Function, Args} to hibernate
    • -
    • -

      -{stop, Req} to stop processing and move on to the next request -

      +
    • {stop, Req} to stop processing and move on to the next request
    • -
-

Of note is that when hibernating, processing will resume on the given -MFA, discarding all previous stacktrace. Make sure you keep the Req -and Env in the arguments of this MFA for later use.

-

If an error happens during middleware processing, Cowboy will not try -to send an error back to the socket, the process will just crash. It -is up to the middleware to make sure that a reply is sent if something -goes wrong.

-
-
-
+ +

Of note is that when hibernating, processing will resume on the given MFA, discarding all previous stacktrace. Make sure you keep the Req and Env in the arguments of this MFA for later use.

+

If an error happens during middleware processing, Cowboy will not try to send an error back to the socket, the process will just crash. It is up to the middleware to make sure that a reply is sent if something goes wrong.

Configuration

-
-

The middleware environment is defined as the env protocol option. -In the previous chapters we saw it briefly when we needed to pass -the routing information. It is a list of tuples with the first -element being an atom and the second any Erlang term.

-

Two values in the environment are reserved:

-
    -
  • -

    -listener contains the name of the listener -

    +

    The middleware environment is defined as the env protocol option. In the previous chapters we saw it briefly when we needed to pass the routing information. It is a list of tuples with the first element being an atom and the second any Erlang term.

    +

    Two values in the environment are reserved:

    +
    • listener contains the name of the listener
    • -
    • -

      -result contains the result of the processing -

      +
    • result contains the result of the processing
    • -
-

The listener value is always defined. The result value can be -set by any middleware. If set to anything other than ok, Cowboy -will not process any subsequent requests on this connection.

-

The middlewares that come with Cowboy may define or require other -environment values to perform.

-

You can update the environment by calling the cowboy:set_env/3 -convenience function, adding or replacing a value in the environment.

-
-
-
+ +

The listener value is always defined. The result value can be set by any middleware. If set to anything other than ok, Cowboy will not process any subsequent requests on this connection.

+

The middlewares that come with Cowboy may define or require other environment values to perform.

+

You can update the environment by calling the cowboy:set_env/3 convenience function, adding or replacing a value in the environment.

Routing middleware

-
-

The routing middleware requires the dispatch value. If routing -succeeds, it will put the handler name and options in the handler -and handler_opts values of the environment, respectively.

-
-
-
+

The routing middleware requires the dispatch value. If routing succeeds, it will put the handler name and options in the handler and handler_opts values of the environment, respectively.

Handler middleware

-
-

The handler middleware requires the handler and handler_opts -values. It puts the result of the request handling into result.

-
-
+

The handler middleware requires the handler and handler_opts values. It puts the result of the request handling into result.

+ diff --git a/docs/en/cowboy/2.0/guide/migrating_from_1.0/index.html b/docs/en/cowboy/2.0/guide/migrating_from_1.0/index.html index 96402bf8..924ef215 100644 --- a/docs/en/cowboy/2.0/guide/migrating_from_1.0/index.html +++ b/docs/en/cowboy/2.0/guide/migrating_from_1.0/index.html @@ -62,378 +62,118 @@

Migrating from Cowboy 1.0 to 2.0

-

A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req -interface in particular has seen a massive revamp. Hooks are -gone, their functionality can now be achieved via stream -handlers.

-

The documentation has seen great work, in particular the -manual. Each module and each function now has its own dedicated -manual page with full details and examples.

-
+

A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req interface in particular has seen a massive revamp. Hooks are gone, their functionality can now be achieved via stream handlers.

+

The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples.

Compatibility

-
-

Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. -Erlang/OTP 19.0 or above is required. It is non-trivial to -make Cowboy 2.0 work with older Erlang/OTP versions.

-

Cowboy 2.0 is not compatible with Cowlib versions older than -2.0. It should be compatible with Ranch 1.0 or above, however -it has not been tested with Ranch versions older than 1.4.

-

Cowboy 2.0 is tested on Arch Linux, Ubuntu, FreeBSD, Windows -and OSX. It is tested with every point release (latest patch -release) and also with HiPE on the most recent release.

-

Cowboy 2.0 now comes with Erlang.mk templates.

-
-
-
+

Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. Erlang/OTP 19.0 or above is required. It is non-trivial to make Cowboy 2.0 work with older Erlang/OTP versions.

+

Cowboy 2.0 is not compatible with Cowlib versions older than 2.0. It should be compatible with Ranch 1.0 or above, however it has not been tested with Ranch versions older than 1.4.

+

Cowboy 2.0 is tested on Arch Linux, Ubuntu, FreeBSD, Windows and OSX. It is tested with every point release (latest patch release) and also with HiPE on the most recent release.

+

Cowboy 2.0 now comes with Erlang.mk templates.

Features added

-
-
    -
  • -

    -The HTTP/2 protocol is now supported. -

    -
  • -
  • -

    -Cowboy no longer uses only one process per connection. - It now uses one process per connection plus one process - per request by default. This is necessary for HTTP/2. - There might be a slight drop in performance for HTTP/1.1 - connections due to this change. -

    -
  • -
  • -

    -Cowboy internals have largely been reworked in order to - support HTTP/2. This opened the way to stream handlers, - which are a chain of modules that are called whenever - something happens relating to a request/response. -

    -
  • -
  • -

    -The cowboy_stream_h stream handler has been added. - It provides most of Cowboy’s default behavior. -

    -
  • -
  • -

    -The cowboy_compress_h stream handler has been added. - It compresses responses when possible. It’s worth noting - that it compresses in more cases than Cowboy 1.0 ever did. -

    -
  • -
  • -

    -Because of the many changes in the internals of Cowboy, - many options have been added or modified. Of note is that - the Websocket options are now given per handler rather - than for the entire listener. -

    -
  • -
  • -

    -Websocket permessage-deflate compression is now supported - via the compress option. -

    -
  • -
  • -

    -Static file handlers will now correctly find files found - in .ez archives. -

    -
  • -
  • -

    -Constraints have been generalized and are now used not only - in the router but also in some cowboy_req functions. Their - interface has also been modified to allow for reverse - operations and formatting of errors. -

    -
  • -
-
-
-
+
  • The HTTP/2 protocol is now supported. +
  • +
  • Cowboy no longer uses only one process per connection. It now uses one process per connection plus one process per request by default. This is necessary for HTTP/2. There might be a slight drop in performance for HTTP/1.1 connections due to this change. +
  • +
  • Cowboy internals have largely been reworked in order to support HTTP/2. This opened the way to stream handlers, which are a chain of modules that are called whenever something happens relating to a request/response. +
  • +
  • The cowboy_stream_h stream handler has been added. It provides most of Cowboy's default behavior. +
  • +
  • The cowboy_compress_h stream handler has been added. It compresses responses when possible. It's worth noting that it compresses in more cases than Cowboy 1.0 ever did. +
  • +
  • Because of the many changes in the internals of Cowboy, many options have been added or modified. Of note is that the Websocket options are now given per handler rather than for the entire listener. +
  • +
  • Websocket permessage-deflate compression is now supported via the compress option. +
  • +
  • Static file handlers will now correctly find files found in .ez archives. +
  • +
  • Constraints have been generalized and are now used not only in the router but also in some cowboy_req functions. Their interface has also been modified to allow for reverse operations and formatting of errors. +
  • +

Features removed

-
-
    -
  • -

    -SPDY support has been removed. Use HTTP/2 instead. -

    -
  • -
  • -

    -Hooks have been removed. Use stream handlers instead. -

    -
  • -
  • -

    -The undocumented waiting_stream hack has been removed. - It allowed disabling chunked transfer-encoding for HTTP/1.1. - It has no equivalent in Cowboy 2.0. Open a ticket if necessary. -

    -
  • -
  • -

    -Sub protocols still exist, but their interface has largely changed - and they are no longer documented for the time being. -

    -
  • -
-
-
-
+
  • SPDY support has been removed. Use HTTP/2 instead. +
  • +
  • Hooks have been removed. Use stream handlers instead. +
  • +
  • The undocumented waiting_stream hack has been removed. It allowed disabling chunked transfer-encoding for HTTP/1.1. It has no equivalent in Cowboy 2.0. Open a ticket if necessary. +
  • +
  • Sub protocols still exist, but their interface has largely changed and they are no longer documented for the time being. +
  • +

Changed behaviors

-
-
    -
  • -

    -The handler behaviors have been renamed and are now cowboy_handler, - cowboy_loop, cowboy_rest and cowboy_websocket. -

    -
  • -
  • -

    -Plain HTTP, loop, REST and Websocket handlers have had their - init and terminate callbacks unified. They now all use the - init/2 and terminate/3 callbacks. The latter is now optional. - The terminate reason has now been documented for all handlers. -

    -
  • -
  • -

    -The tuple returned to switch to a different handler type has - changed. It now takes the form {Module, Req, State} or - {Module, Req, State, Opts}, where Opts is a map of options - to configure the handler. The timeout and hibernate options - must now be specified using this map, where applicable. -

    -
  • -
  • -

    -All behaviors that used to accept halt or shutdown tuples - as a return value no longer do so. The return value is now - a stop tuple, consistent across Cowboy. -

    -
  • -
  • -

    -Middlewares can no longer return an error tuple. They have - to send the response and return a stop tuple instead. -

    -
  • -
  • -

    -The known_content_type REST handler callback has been removed - as it was found unnecessary. -

    -
  • -
  • -

    -Websocket handlers have both the normal init/2 and - an optional websocket_init/1 function. The reason for - that exception is that the websocket_* callbacks execute - in a separate process from the init/2 callback, and it - was therefore not obvious how timers or monitors should - be setup properly. They are effectively initializing the - handler before and after the HTTP/1.1 upgrade. -

    -
  • -
  • -

    -Websocket handlers can now send frames directly from - websocket_init/1. The frames will be sent immediately - after the handshake. -

    -
  • -
  • -

    -Websocket handler callbacks no longer receive the Req - argument. The init/2 callback still receives it and - can be used to extract relevant information. The terminate/3 - callback, if implemented, may still receive the Req - (see next bullet point). -

    -
  • -
  • -

    -Websocket handlers have a new req_filter option that - can be used to customize how much information should be - discarded from the Req object after the handshake. Note - that the Req object is only available in terminate/3 - past that point. -

    -
  • -
  • -

    -Websocket handlers have their timeout default changed - from infinity to 60 seconds. -

    -
  • -
-
-
-
+
  • The handler behaviors have been renamed and are now cowboy_handler, cowboy_loop, cowboy_rest and cowboy_websocket. +
  • +
  • Plain HTTP, loop, REST and Websocket handlers have had their init and terminate callbacks unified. They now all use the init/2 and terminate/3 callbacks. The latter is now optional. The terminate reason has now been documented for all handlers. +
  • +
  • The tuple returned to switch to a different handler type has changed. It now takes the form {Module, Req, State} or {Module, Req, State, Opts}, where Opts is a map of options to configure the handler. The timeout and hibernate options must now be specified using this map, where applicable. +
  • +
  • All behaviors that used to accept halt or shutdown tuples as a return value no longer do so. The return value is now a stop tuple, consistent across Cowboy. +
  • +
  • Middlewares can no longer return an error tuple. They have to send the response and return a stop tuple instead. +
  • +
  • The known_content_type REST handler callback has been removed as it was found unnecessary. +
  • +
  • Websocket handlers have both the normal init/2 and an optional websocket_init/1 function. The reason for that exception is that the websocket_* callbacks execute in a separate process from the init/2 callback, and it was therefore not obvious how timers or monitors should be setup properly. They are effectively initializing the handler before and after the HTTP/1.1 upgrade. +
  • +
  • Websocket handlers can now send frames directly from websocket_init/1. The frames will be sent immediately after the handshake. +
  • +
  • Websocket handler callbacks no longer receive the Req argument. The init/2 callback still receives it and can be used to extract relevant information. The terminate/3 callback, if implemented, may still receive the Req (see next bullet point). +
  • +
  • Websocket handlers have a new req_filter option that can be used to customize how much information should be discarded from the Req object after the handshake. Note that the Req object is only available in terminate/3 past that point. +
  • +
  • Websocket handlers have their timeout default changed from infinity to 60 seconds. +
  • +

New functions

-
-
    -
  • -

    -The cowboy_req:scheme/1 function has been added. -

    -
  • -
  • -

    -The cowboy_req:uri/1,2 function has been added, replacing the - less powerful functions cowboy_req:url/1 and cowboy_req:host_url/1. -

    -
  • -
  • -

    -The functions cowboy_req:match_qs/2 and cowboy_req:match_cookies/2 - allow matching query string and cookies against constraints. -

    -
  • -
  • -

    -The function cowboy_req:set_resp_cookie/3 has been added to - complement cowboy_req:set_resp_cookie/4. -

    -
  • -
  • -

    -The functions cowboy_req:resp_header/2,3 and cowboy_req:resp_headers/1 - have been added. They can be used to retrieve response headers - that were previously set. -

    -
  • -
  • -

    -The function cowboy_req:set_resp_headers/2 has been added. It - allows setting many response headers at once. -

    -
  • -
  • -

    -The functions cowboy_req:push/3,4 can be used to push resources - for protocols that support it (by default only HTTP/2). -

    -
  • -
-
-
-
+
  • The cowboy_req:scheme/1 function has been added. +
  • +
  • The cowboy_req:uri/1,2 function has been added, replacing the less powerful functions cowboy_req:url/1 and cowboy_req:host_url/1. +
  • +
  • The functions cowboy_req:match_qs/2 and cowboy_req:match_cookies/2 allow matching query string and cookies against constraints. +
  • +
  • The function cowboy_req:set_resp_cookie/3 has been added to complement cowboy_req:set_resp_cookie/4. +
  • +
  • The functions cowboy_req:resp_header/2,3 and cowboy_req:resp_headers/1 have been added. They can be used to retrieve response headers that were previously set. +
  • +
  • The function cowboy_req:set_resp_headers/2 has been added. It allows setting many response headers at once. +
  • +
  • The functions cowboy_req:push/3,4 can be used to push resources for protocols that support it (by default only HTTP/2). +
  • +

Changed functions

-
-
    -
  • -

    -The cowboy:start_http/4 function was renamed to cowboy:start_clear/3. -

    -
  • -
  • -

    -The cowboy:start_https/4 function was renamed to cowboy:start_tls/3. -

    -
  • -
  • -

    -Most, if not all, functions in the cowboy_req module have been modified. - Please consult the changelog of each individual functions. The changes - are mainly about simplifying and clarifying the interface. The Req is no - longer returned when not necessary, maps are used wherever possible, - and some functions have been renamed. -

    -
  • -
  • -

    -The position of the Opts argument for cowboy_req:set_resp_cookie/4 - has changed to improve consistency. It is now the last argument. -

    -
  • -
-
-
-
+
  • The cowboy:start_http/4 function was renamed to cowboy:start_clear/3. +
  • +
  • The cowboy:start_https/4 function was renamed to cowboy:start_tls/3. +
  • +
  • Most, if not all, functions in the cowboy_req module have been modified. Please consult the changelog of each individual functions. The changes are mainly about simplifying and clarifying the interface. The Req is no longer returned when not necessary, maps are used wherever possible, and some functions have been renamed. +
  • +
  • The position of the Opts argument for cowboy_req:set_resp_cookie/4 has changed to improve consistency. It is now the last argument. +
  • +

Removed functions

-
-
    -
  • -

    -The functions cowboy_req:url/1 and cowboy_req:host_url/1 have been - removed in favor of the new function cowboy_req:uri/1,2. -

    -
  • -
  • -

    -The functions cowboy_req:meta/2,3 and cowboy_req:set_meta/3 have - been removed. The Req object is now a public map, therefore they became - unnecessary. -

    -
  • -
  • -

    -The functions cowboy_req:set_resp_body_fun/2,3 have been removed. - For sending files, the function cowboy_req:set_resp_body/2 can now - take a sendfile tuple. -

    -
  • -
  • -

    -Remove many undocumented functions from cowboy_req, including the - functions cowboy_req:get/2 and cowboy_req:set/3. -

    -
  • -
-
-
-
+
  • The functions cowboy_req:url/1 and cowboy_req:host_url/1 have been removed in favor of the new function cowboy_req:uri/1,2. +
  • +
  • The functions cowboy_req:meta/2,3 and cowboy_req:set_meta/3 have been removed. The Req object is now a public map, therefore they became unnecessary. +
  • +
  • The functions cowboy_req:set_resp_body_fun/2,3 have been removed. For sending files, the function cowboy_req:set_resp_body/2 can now take a sendfile tuple. +
  • +
  • Remove many undocumented functions from cowboy_req, including the functions cowboy_req:get/2 and cowboy_req:set/3. +
  • +

Other changes

-
-
    -
  • -

    -The correct percent-decoding algorithm is now used for path elements - during routing. It will no longer decode + characters. -

    -
  • -
  • -

    -The router will now properly handle path segments . and ... -

    -
  • -
  • -

    -Routing behavior has changed for URIs containing latin1 characters. - They are no longer allowed. URIs are expected to be in UTF-8 once - they are percent-decoded. -

    -
  • -
  • -

    -Etag comparison in REST handlers has been fixed. Some requests may - now fail when they succeeded in the past. -

    -
  • -
  • -

    -The If-*-Since headers are now ignored in REST handlers if - the corresponding If*-Match header exist. The former is - largely a backward compatible header and this shouldn’t create - any issue. The new behavior follows the current RFCs more closely. -

    -
  • -
  • -

    -The static file handler has been improved to handle more special - characters on systems that accept them. -

    -
  • -
-
-
+
  • The correct percent-decoding algorithm is now used for path elements during routing. It will no longer decode + characters. +
  • +
  • The router will now properly handle path segments . and ... +
  • +
  • Routing behavior has changed for URIs containing latin1 characters. They are no longer allowed. URIs are expected to be in UTF-8 once they are percent-decoded. +
  • +
  • Etag comparison in REST handlers has been fixed. Some requests may now fail when they succeeded in the past. +
  • +
  • The If-*-Since headers are now ignored in REST handlers if the corresponding If*-Match header exist. The former is largely a backward compatible header and this shouldn't create any issue. The new behavior follows the current RFCs more closely. +
  • +
  • The static file handler has been improved to handle more special characters on systems that accept them. +
  • +
+ diff --git a/docs/en/cowboy/2.0/guide/modern_web/index.html b/docs/en/cowboy/2.0/guide/modern_web/index.html index 6614a734..df02e1b5 100644 --- a/docs/en/cowboy/2.0/guide/modern_web/index.html +++ b/docs/en/cowboy/2.0/guide/modern_web/index.html @@ -62,115 +62,38 @@

The modern Web

-

Cowboy is a server for the modern Web. This chapter explains -what it means and details all the standards involved.

-

Cowboy supports all the standards listed in this document.

-
+

Cowboy is a server for the modern Web. This chapter explains what it means and details all the standards involved.

+

Cowboy supports all the standards listed in this document.

HTTP/2

-
-

HTTP/2 is the most efficient protocol for consuming Web -services. It enables clients to keep a connection open -for long periods of time; to send requests concurrently; -to reduce the size of requests through HTTP headers -compression; and more. The protocol is binary, greatly -reducing the resources needed to parse it.

-

HTTP/2 also enables the server to push messages to the -client. This can be used for various purposes, including -the sending of related resources before the client requests -them, in an effort to reduce latency. This can also be used -to enable bidirectional communication.

-

Cowboy provides transparent support for HTTP/2. Clients -that know it can use it; others fall back to HTTP/1.1 -automatically.

-

HTTP/2 is compatible with the HTTP/1.1 semantics.

-

HTTP/2 is defined by RFC 7540 and RFC 7541.

-
-
-
+

HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. The protocol is binary, greatly reducing the resources needed to parse it.

+

HTTP/2 also enables the server to push messages to the client. This can be used for various purposes, including the sending of related resources before the client requests them, in an effort to reduce latency. This can also be used to enable bidirectional communication.

+

Cowboy provides transparent support for HTTP/2. Clients that know it can use it; others fall back to HTTP/1.1 automatically.

+

HTTP/2 is compatible with the HTTP/1.1 semantics.

+

HTTP/2 is defined by RFC 7540 and RFC 7541.

HTTP/1.1

-
-

HTTP/1.1 is the previous version of the HTTP protocol. -The protocol itself is text-based and suffers from numerous -issues and limitations. In particular it is not possible -to execute requests concurrently (though pipelining is -sometimes possible), and it’s also sometimes difficult -to detect that a client disconnected.

-

HTTP/1.1 does provide very good semantics for interacting -with Web services. It defines the standard methods, headers -and status codes used by HTTP/1.1 and HTTP/2 clients and -servers.

-

HTTP/1.1 also defines compatibility with an older version -of the protocol, HTTP/1.0, which was never really standardized -across implementations.

-

The core of HTTP/1.1 is defined by RFC 7230, RFC 7231, -RFC 7232, RFC 7233, RFC 7234 and RFC 7235. Numerous RFCs -and other specifications exist defining additional HTTP -methods, status codes, headers or semantics.

-
-
-
+

HTTP/1.1 is the previous version of the HTTP protocol. The protocol itself is text-based and suffers from numerous issues and limitations. In particular it is not possible to execute requests concurrently (though pipelining is sometimes possible), and it's also sometimes difficult to detect that a client disconnected.

+

HTTP/1.1 does provide very good semantics for interacting with Web services. It defines the standard methods, headers and status codes used by HTTP/1.1 and HTTP/2 clients and servers.

+

HTTP/1.1 also defines compatibility with an older version of the protocol, HTTP/1.0, which was never really standardized across implementations.

+

The core of HTTP/1.1 is defined by RFC 7230, RFC 7231, RFC 7232, RFC 7233, RFC 7234 and RFC 7235. Numerous RFCs and other specifications exist defining additional HTTP methods, status codes, headers or semantics.

Websocket

-
-

Websocket is a protocol built on top of HTTP/1.1 -that provides a two-ways communication channel between the client and -the server. Communication is asynchronous and can occur concurrently.

-

It consists of a Javascript object allowing setting up a -Websocket connection to the server, and a binary based -protocol for sending data to the server or the client.

-

Websocket connections can transfer either UTF-8 encoded text -data or binary data. The protocol also includes support for -implementing a ping/pong mechanism, allowing the server and -the client to have more confidence that the connection is still -alive.

-

A Websocket connection can be used to transfer any kind of data, -small or big, text or binary. Because of this Websocket is -sometimes used for communication between systems.

-

Websocket messages have no semantics on their own. Websocket -is closer to TCP in that aspect, and requires you to design -and implement your own protocol on top of it; or adapt an -existing protocol to Websocket.

-

Cowboy provides an interface known as Websocket handlers -that gives complete control over a Websocket connection.

-

The Websocket protocol is defined by RFC 6455.

-
-
-
+

Websocket is a protocol built on top of HTTP/1.1 that provides a two-ways communication channel between the client and the server. Communication is asynchronous and can occur concurrently.

+

It consists of a Javascript object allowing setting up a Websocket connection to the server, and a binary based protocol for sending data to the server or the client.

+

Websocket connections can transfer either UTF-8 encoded text data or binary data. The protocol also includes support for implementing a ping/pong mechanism, allowing the server and the client to have more confidence that the connection is still alive.

+

A Websocket connection can be used to transfer any kind of data, small or big, text or binary. Because of this Websocket is sometimes used for communication between systems.

+

Websocket messages have no semantics on their own. Websocket is closer to TCP in that aspect, and requires you to design and implement your own protocol on top of it; or adapt an existing protocol to Websocket.

+

Cowboy provides an interface known as Websocket handlers that gives complete control over a Websocket connection.

+

The Websocket protocol is defined by RFC 6455.

Long-lived requests

-
-

Cowboy provides an interface that can be used to support -long-polling or to stream large amounts of data reliably, -including using Server-Sent Events.

-

Long-polling is a mechanism in which the client performs -a request which may not be immediately answered by the -server. It allows clients to request resources that may -not currently exist, but are expected to be created soon, -and which will be returned as soon as they are.

-

Long-polling is essentially a hack, but it is widely used -to overcome limitations on older clients and servers.

-

Server-Sent Events is a small protocol defined as a media -type, text/event-stream, along with a new HTTP header, -Last-Event-ID. It is defined in the EventSource W3C -specification.

-

Cowboy provides an interface known as loop handlers -that facilitates the implementation of long-polling or stream -mechanisms. It works regardless of the underlying protocol.

-
-
-
+

Cowboy provides an interface that can be used to support long-polling or to stream large amounts of data reliably, including using Server-Sent Events.

+

Long-polling is a mechanism in which the client performs a request which may not be immediately answered by the server. It allows clients to request resources that may not currently exist, but are expected to be created soon, and which will be returned as soon as they are.

+

Long-polling is essentially a hack, but it is widely used to overcome limitations on older clients and servers.

+

Server-Sent Events is a small protocol defined as a media type, text/event-stream, along with a new HTTP header, Last-Event-ID. It is defined in the EventSource W3C specification.

+

Cowboy provides an interface known as loop handlers that facilitates the implementation of long-polling or stream mechanisms. It works regardless of the underlying protocol.

REST

-
-

REST, or REpresentational State Transfer, -is a style of architecture for loosely connected distributed -systems. It can easily be implemented on top of HTTP.

-

REST is essentially a set of constraints to be followed. -Many of these constraints are purely architectural and -solved by simply using HTTP. Some constraints must be -explicitly followed by the developer.

-

Cowboy provides an interface known as REST handlers -that simplifies the implementation of a REST API on top of -the HTTP protocol.

-
-
+

REST, or REpresentational State Transfer, is a style of architecture for loosely connected distributed systems. It can easily be implemented on top of HTTP.

+

REST is essentially a set of constraints to be followed. Many of these constraints are purely architectural and solved by simply using HTTP. Some constraints must be explicitly followed by the developer.

+

Cowboy provides an interface known as REST handlers that simplifies the implementation of a REST API on top of the HTTP protocol.

+ diff --git a/docs/en/cowboy/2.0/guide/multipart/index.html b/docs/en/cowboy/2.0/guide/multipart/index.html index 73525df2..7157eab1 100644 --- a/docs/en/cowboy/2.0/guide/multipart/index.html +++ b/docs/en/cowboy/2.0/guide/multipart/index.html @@ -62,169 +62,107 @@

Multipart requests

-

Multipart originates from MIME, an Internet standard that -extends the format of emails.

-

A multipart message is a list of parts. A part contains -headers and a body. The body of the parts may be -of any media type, and contain text or binary data. -It is possible for parts to contain a multipart media -type.

-

In the context of HTTP, multipart is most often used -with the multipart/form-data media type. It is what -browsers use to upload files through HTML forms.

-

The multipart/byteranges is also common. It is the -media type used to send arbitrary bytes from a resource, -enabling clients to resume downloads.

-
+

Multipart originates from MIME, an Internet standard that extends the format of emails.

+

A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type.

+

In the context of HTTP, multipart is most often used with the multipart/form-data media type. It is what browsers use to upload files through HTML forms.

+

The multipart/byteranges is also common. It is the media type used to send arbitrary bytes from a resource, enabling clients to resume downloads.

Form-data

-
-

In the normal case, when a form is submitted, the -browser will use the application/x-www-form-urlencoded -content-type. This type is just a list of keys and -values and is therefore not fit for uploading files.

-

That’s where the multipart/form-data content-type -comes in. When the form is configured to use this -content-type, the browser will create a multipart -message where each part corresponds to a field on -the form. For files, it also adds some metadata in -the part headers, like the file name.

-

A form with a text input, a file input and a select -choice box will result in a multipart message with -three parts, one for each field.

-

The browser does its best to determine the media type -of the files it sends this way, but you should not -rely on it for determining the contents of the file. -Proper investigation of the contents is recommended.

-
-
-
+

In the normal case, when a form is submitted, the browser will use the application/x-www-form-urlencoded content-type. This type is just a list of keys and values and is therefore not fit for uploading files.

+

That's where the multipart/form-data content-type comes in. When the form is configured to use this content-type, the browser will create a multipart message where each part corresponds to a field on the form. For files, it also adds some metadata in the part headers, like the file name.

+

A form with a text input, a file input and a select choice box will result in a multipart message with three parts, one for each field.

+

The browser does its best to determine the media type of the files it sends this way, but you should not rely on it for determining the contents of the file. Proper investigation of the contents is recommended.

Checking for multipart messages

-
-

The content-type header indicates the presence of -a multipart message:

-
-
-
{<<"multipart">>, <<"form-data">>, _}
-    = cowboy_req:parse_header(<<"content-type">>, Req).
-
-
-
+
{<<"multipart">>, <<"form-data">>, _}
+    = cowboy_req:parse_header(<<"content-type">>, Req).
+

Reading a multipart message

-
-

Cowboy provides two sets of functions for reading -request bodies as multipart messages.

-

The cowboy_req:read_part/1,2 functions return the -next part’s headers, if any.

-

The cowboy_req:read_part_body/1,2 functions return -the current part’s body. For large bodies you may -need to call the function multiple times.

-

To read a multipart message you need to iterate over -all its parts:

-
-
-
multipart(Req0) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, _Headers, Req1} ->
-            {ok, _Body, Req} = cowboy_req:read_part_body(Req1),
-            multipart(Req);
-        {done, Req} ->
-            Req
-    end.
-

When part bodies are too large, Cowboy will return -a more tuple, and allow you to loop until the part -body has been fully read.

-

The function cow_multipart:form_data/1 can be used -to quickly obtain information about a part from a -multipart/form-data message. The function returns -a data or a file tuple depending on whether this -is a normal field or a file being uploaded.

-

The following snippet will use this function and -use different strategies depending on whether the -part is a file:

-
-
-
multipart(Req0) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, Headers, Req1} ->
-            Req = case cow_multipart:form_data(Headers) of
-                {data, _FieldName} ->
-                    {ok, _Body, Req2} = cowboy_req:read_part_body(Req1),
-                    Req2;
-                {file, _FieldName, _Filename, _CType} ->
-                    stream_file(Req1)
-            end,
-            multipart(Req);
-        {done, Req} ->
-            Req
-    end.
-
-stream_file(Req0) ->
-    case cowboy_req:read_part_body(Req0) of
-        {ok, _LastBodyChunk, Req} ->
-            Req;
-        {more, _BodyChunk, Req} ->
-            stream_file(Req)
-    end.
-

Both the part header and body reading functions can take -options that will be given to the request body reading -functions. By default, cowboy_req:read_part/1 reads -up to 64KB for up to 5 seconds. cowboy_req:read_part_body/1 -has the same defaults as cowboy_req:read_body/1.

-

To change the defaults for part headers:

-
-
-
cowboy_req:read_part(Req, #{length => 128000}).
-

And for part bodies:

-
-
-
cowboy_req:read_part_body(Req, #{length => 1000000, period => 7000}).
-
- -
+
cowboy_req:read_part_body(Req, #{length => 1000000, period => 7000}).
+

Skipping unwanted parts

-
-

Part bodies do not have to be read. Cowboy will automatically -skip it when you request the next part’s body.

-

The following snippet reads all part headers and skips -all bodies:

-
-
-
multipart(Req0) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, _Headers, Req} ->
-            multipart(Req);
-        {done, Req} ->
-            Req
-    end.
-

Similarly, if you start reading the body and it ends up -being too big, you can simply continue with the next part. -Cowboy will automatically skip what remains.

-

While Cowboy can skip part bodies automatically, the read -rate is not configurable. Depending on your application -you may want to skip manually, in particular if you observe -poor performance while skipping.

-

You do not have to read all parts either. You can stop -reading as soon as you find the data you need.

-
- +
multipart(Req0) ->
+    case cowboy_req:read_part(Req0) of
+        {ok, _Headers, Req} ->
+            multipart(Req);
+        {done, Req} ->
+            Req
+    end.
+ +

Similarly, if you start reading the body and it ends up being too big, you can simply continue with the next part. Cowboy will automatically skip what remains.

+

While Cowboy can skip part bodies automatically, the read rate is not configurable. Depending on your application you may want to skip manually, in particular if you observe poor performance while skipping.

+

You do not have to read all parts either. You can stop reading as soon as you find the data you need.

+ + diff --git a/docs/en/cowboy/2.0/guide/req/index.html b/docs/en/cowboy/2.0/guide/req/index.html index baf17ce4..938c3e01 100644 --- a/docs/en/cowboy/2.0/guide/req/index.html +++ b/docs/en/cowboy/2.0/guide/req/index.html @@ -62,407 +62,283 @@

The Req object

-

The Req object is a variable used for obtaining information -about a request, read its body or send a response.

-

It is not really an object in the object-oriented sense. -It is a simple map that can be directly accessed or -used when calling functions from the cowboy_req module.

-

The Req object is the subject of a few different chapters. -In this chapter we will learn about the Req object and -look at how to retrieve information about the request.

-
+

The Req object is a variable used for obtaining information about a request, read its body or send a response.

+

It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module.

+

The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request.

Direct access

-
-

The Req map contains a number of fields which are documented -and can be accessed directly. They are the fields that have -a direct mapping to HTTP: the request method; the HTTP -version used; the effective URI components scheme, -host, port, path and qs; the request headers; -and the connection peer address and port.

-

Note that the version field can be used to determine -whether a connection is using HTTP/2.

-

To access a field, you can simply match in the function -head. The following example sends a simple "Hello world!" -response when the method is GET, and a 405 error -otherwise.

-
-
-
init(Req0=#{method := <<"GET">>}, State) ->
-    Req = cowboy_req:reply(200, #{
-        <<"content-type">> => <<"text/plain">>
-    }, <<"Hello world!">>, Req0),
-    {ok, Req, State};
-init(Req0, State) ->
-    Req = cowboy_req:reply(405, #{
-        <<"allow">> => <<"GET">>
-    }, Req0),
-    {ok, Req, State}.
-

Any other field is internal and should not be accessed. -They may change in future releases, including maintenance -releases, without notice.

-

Modifying the Req object, while allowed, is not recommended -unless strictly necessary. If adding new fields, make sure -to namespace the field names so that no conflict can occur -with future Cowboy updates or third party projects.

-
-
-
+
init(Req0=#{method := <<"GET">>}, State) ->
+    Req = cowboy_req:reply(200, #{
+        <<"content-type">> => <<"text/plain">>
+    }, <<"Hello world!">>, Req0),
+    {ok, Req, State};
+init(Req0, State) ->
+    Req = cowboy_req:reply(405, #{
+        <<"allow">> => <<"GET">>
+    }, Req0),
+    {ok, Req, State}.
+
+

Any other field is internal and should not be accessed. They may change in future releases, including maintenance releases, without notice.

+

Modifying the Req object, while allowed, is not recommended unless strictly necessary. If adding new fields, make sure to namespace the field names so that no conflict can occur with future Cowboy updates or third party projects.

+

Introduction to the cowboy_req interface

-
-

Functions in the cowboy_req module provide access to -the request information but also various operations that -are common when dealing with HTTP requests.

-

All the functions that begin with a verb indicate an action. -Other functions simply return the corresponding value -(sometimes that value does need to be built, but the -cost of the operation is equivalent to retrieving a value).

-

Some of the cowboy_req functions return an updated Req -object. They are the read, reply, set and delete functions. -While ignoring the returned Req will not cause incorrect -behavior for some of them, it is highly recommended to -always keep and use the last returned Req object. The -manual for cowboy_req details these functions and what -modifications are done to the Req object.

-

Some of the calls to cowboy_req have side effects. This -is the case of the read and reply functions. Cowboy reads -the request body or replies immediately when the function -is called.

-

All functions will crash if something goes wrong. There -is usually no need to catch these errors, Cowboy will -send the appropriate 4xx or 5xx response depending on -where the crash occurred.

-
- -
+ +

Functions in the cowboy_req module provide access to the request information but also various operations that are common when dealing with HTTP requests.

+

All the functions that begin with a verb indicate an action. Other functions simply return the corresponding value (sometimes that value does need to be built, but the cost of the operation is equivalent to retrieving a value).

+

Some of the cowboy_req functions return an updated Req object. They are the read, reply, set and delete functions. While ignoring the returned Req will not cause incorrect behavior for some of them, it is highly recommended to always keep and use the last returned Req object. The manual for cowboy_req details these functions and what modifications are done to the Req object.

+

Some of the calls to cowboy_req have side effects. This is the case of the read and reply functions. Cowboy reads the request body or replies immediately when the function is called.

+

All functions will crash if something goes wrong. There is usually no need to catch these errors, Cowboy will send the appropriate 4xx or 5xx response depending on where the crash occurred.

Request method

-
-

The request method can be retrieved directly:

-
-
-
#{method := Method} = Req.
-

Or using a function:

-
-
-
Method = cowboy_req:method(Req).
-

The method is a case sensitive binary string. Standard -methods include GET, HEAD, OPTIONS, PATCH, POST, PUT -or DELETE.

-
-
-
+
Method = cowboy_req:method(Req).
+
+

The method is a case sensitive binary string. Standard methods include GET, HEAD, OPTIONS, PATCH, POST, PUT or DELETE.

HTTP version

-
-

The HTTP version is informational. It does not indicate that -the client implements the protocol well or fully.

-

There is typically no need to change behavior based on the -HTTP version: Cowboy already does it for you.

-

It can be useful in some cases, though. For example, one may -want to redirect HTTP/1.1 clients to use Websocket, while HTTP/2 -clients keep using HTTP/2.

-

The HTTP version can be retrieved directly:

-
-
-
#{version := Version} = Req.
-

Or using a function:

-
-
-
Version = cowboy_req:version(Req).
-

Cowboy defines the 'HTTP/1.0', 'HTTP/1.1' and 'HTTP/2' -versions. Custom protocols can define their own values as -atoms.

-
- -
+
Version = cowboy_req:version(Req).
+
+

Cowboy defines the 'HTTP/1.0', 'HTTP/1.1' and 'HTTP/2' versions. Custom protocols can define their own values as atoms.

Effective request URI

-
-

The scheme, host, port, path and query string components -of the effective request URI can all be retrieved directly:

-
-
#{
-    scheme := Scheme,
-    host := Host,
-    port := Port,
-    path := Path,
-    qs := Qs
-} = Req.
-

Or using the related functions:

-
-
-
Scheme = cowboy_req:scheme(Req),
-Host = cowboy_req:host(Req),
-Port = cowboy_req:port(Req),
-Path = cowboy_req:path(Req).
-Qs = cowboy_req:qs(Req).
-

The scheme and host are lowercased case insensitive binary -strings. The port is an integer representing the port number. -The path and query string are case sensitive binary strings.

-

Cowboy defines only the <<"http">> and <<"https">> schemes. -They are chosen so that the scheme will only be <<"https">> -for requests on secure HTTP/1.1 or HTTP/2 connections.

-

The effective request URI itself can be reconstructed with -the cowboy_req:uri/1,2 function. By default, an absolute -URI is returned:

-
-
+

The effective request URI itself can be reconstructed with the cowboy_req:uri/1,2 function. By default, an absolute URI is returned:

+
-
%% scheme://host[:port]/path[?qs]
-URI = cowboy_req:uri(Req).
-

Options are available to either disable or replace some -or all of the components. Various URIs or URI formats can -be generated this way, including the origin form:

-
-
-
%% /path[?qs]
-URI = cowboy_req:uri(Req, #{host => undefined}).
-

The protocol relative form:

-
-
-
%% //host[:port]/path[?qs]
-URI = cowboy_req:uri(Req, #{scheme => undefined}).
-

The absolute URI without a query string:

-
-
-
URI = cowboy_req:uri(Req, #{qs => undefined}).
-

A different host:

-
-
-
URI = cowboy_req:uri(Req, #{host => <<"example.org">>}).
-

And any other combination.

-
-
-
+
URI = cowboy_req:uri(Req, #{host => <<"example.org">>}).
+
+

And any other combination.

Bindings

-
-

Bindings are the host and path components that you chose -to extract when defining the routes of your application. -They are only available after the routing.

-

Cowboy provides functions to retrieve one or all bindings.

-

To retrieve a single value:

-
-
-
Value = cowboy_req:binding(userid, Req).
-

When attempting to retrieve a value that was not bound, -undefined will be returned. A different default value -can be provided:

-
-
-
Value = cowboy_req:binding(userid, Req, 42).
-

To retrieve everything that was bound:

-
-
-
Bindings = cowboy_req:bindings(Req).
-

They are returned as a map, with keys being atoms.

-

The Cowboy router also allows you to capture many host -or path segments at once using the ... qualifier.

-

To retrieve the segments captured from the host name:

-
-
-
HostInfo = cowboy_req:host_info(Req).
-

And the path segments:

-
-
-
PathInfo = cowboy_req:path_info(Req).
-

Cowboy will return undefined if ... was not used -in the route.

-
- -
+
PathInfo = cowboy_req:path_info(Req).
+
+

Cowboy will return undefined if ... was not used in the route.

Query parameters

-
-

Cowboy provides two functions to access query parameters. -You can use the first to get the entire list of parameters.

-
-
-
QsVals = cowboy_req:parse_qs(Req),
-{_, Lang} = lists:keyfind(<<"lang">>, 1, QsVals).
-

Cowboy will only parse the query string, and not do any -transformation. This function may therefore return duplicates, -or parameter names without an associated value. The order of -the list returned is undefined.

-

When a query string is key=1&key=2, the list returned will -contain two parameters of name key.

-

The same is true when trying to use the PHP-style suffix []. -When a query string is key[]=1&key[]=2, the list returned will -contain two parameters of name key[].

-

When a query string is simply key, Cowboy will return the -list [{<<"key">>, true}], using true to indicate that the -parameter key was defined, but with no value.

-

The second function Cowboy provides allows you to match out -only the parameters you are interested in, and at the same -time do any post processing you require using constraints. -This function returns a map.

-
-
-
#{id := ID, lang := Lang} = cowboy_req:match_qs([id, lang], Req).
-

Constraints can be applied automatically. The following -snippet will crash when the id parameter is not an integer, -or when the lang parameter is empty. At the same time, the -value for id will be converted to an integer term:

-
-
-
QsMap = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req).
-

A default value may also be provided. The default will be used -if the lang key is not found. It will not be used if -the key is found but has an empty value.

-
-
-
#{lang := Lang} = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
-

If no default is provided and the value is missing, the -query string is deemed invalid and the process will crash.

-

When the query string is key=1&key=2, the value for key -will be the list [1, 2]. Parameter names do not need to -include the PHP-style suffix. Constraints may be used to -ensure that only one value was passed through.

-
- -
+
#{lang := Lang} = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
+
+

If no default is provided and the value is missing, the query string is deemed invalid and the process will crash.

+

When the query string is key=1&key=2, the value for key will be the list [1, 2]. Parameter names do not need to include the PHP-style suffix. Constraints may be used to ensure that only one value was passed through.

Headers

-
-

Header values can be retrieved either as a binary string -or parsed into a more meaningful representation.

-

The get the raw value:

-
-
-
HeaderVal = cowboy_req:header(<<"content-type">>, Req).
-

Cowboy expects all header names to be provided as lowercase -binary strings. This is true for both requests and responses, -regardless of the underlying protocol.

-

When the header is missing from the request, undefined -will be returned. A different default can be provided:

-
-
-
HeaderVal = cowboy_req:header(<<"content-type">>, Req, <<"text/plain">>).
-

All headers can be retrieved at once, either directly:

-
-
-
#{headers := AllHeaders} = Req.
-

Or using a function:

-
-
-
AllHeaders = cowboy_req:headers(Req).
-

Cowboy provides equivalent functions to parse individual -headers. There is no function to parse all headers at once.

-

To parse a specific header:

-
-
-
ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req).
-

An exception will be thrown if it doesn’t know how to parse the -given header, or if the value is invalid. The list of known headers -and default values can be found in the manual.

-

When the header is missing, undefined is returned. You can -change the default value. Note that it should be the parsed value -directly:

-
-
-
ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req,
-    {<<"text">>, <<"plain">>, []}).
-
- -
+
ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req,
+    {<<"text">>, <<"plain">>, []}).
+

Peer

-
-

The peer address and port number for the connection can be -retrieved either directly or using a function.

-

To retrieve the peer directly:

-
-
-
#{peer := {IP, Port}} = Req.
-

And using a function:

-
-
-
{IP, Port} = cowboy_req:peer(Req).
-

Note that the peer corresponds to the remote end of the -connection to the server, which may or may not be the -client itself. It may also be a proxy or a gateway.

-
- +
{IP, Port} = cowboy_req:peer(Req).
+ +

Note that the peer corresponds to the remote end of the connection to the server, which may or may not be the client itself. It may also be a proxy or a gateway.

+ diff --git a/docs/en/cowboy/2.0/guide/req_body/index.html b/docs/en/cowboy/2.0/guide/req_body/index.html index dd3143c6..ace18a44 100644 --- a/docs/en/cowboy/2.0/guide/req_body/index.html +++ b/docs/en/cowboy/2.0/guide/req_body/index.html @@ -62,144 +62,93 @@

Reading the request body

-

The request body can be read using the Req object.

-

Cowboy will not attempt to read the body until requested. -You need to call the body reading functions in order to -retrieve it.

-

Cowboy will not cache the body, it is therefore only -possible to read it once.

-

You are not required to read it, however. If a body is -present and was not read, Cowboy will either cancel or -skip its download, depending on the protocol.

-

Cowboy provides functions for reading the body raw, -and read and parse form urlencoded or multipart bodies. -The latter is covered in its own chapter.

-
+

The request body can be read using the Req object.

+

Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it.

+

Cowboy will not cache the body, it is therefore only possible to read it once.

+

You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol.

+

Cowboy provides functions for reading the body raw, and read and parse form urlencoded or multipart bodies. The latter is covered in its own chapter.

Request body presence

-
-

Not all requests come with a body. You can check for -the presence of a request body with this function:

-
-
-
cowboy_req:has_body(Req).
-

It returns true if there is a body; false otherwise.

-

In practice, this function is rarely used. When the -method is POST, PUT or PATCH, the request body -is often required by the application, which should -just attempt to read it directly.

-
-
-
+
cowboy_req:has_body(Req).
+
+

It returns true if there is a body; false otherwise.

+

In practice, this function is rarely used. When the method is POST, PUT or PATCH, the request body is often required by the application, which should just attempt to read it directly.

Request body length

-
-

You can obtain the length of the body:

-
-
-
Length = cowboy_req:body_length(Req).
-

Note that the length may not be known in advance. In -that case undefined will be returned. This can happen -with HTTP/1.1’s chunked transfer-encoding, or HTTP/2 -when no content-length was provided.

-

Cowboy will update the body length in the Req object -once the body has been read completely. A length will -always be returned when attempting to call this function -after reading the body completely.

-
- -
+
Length = cowboy_req:body_length(Req).
+
+

Note that the length may not be known in advance. In that case undefined will be returned. This can happen with HTTP/1.1's chunked transfer-encoding, or HTTP/2 when no content-length was provided.

+

Cowboy will update the body length in the Req object once the body has been read completely. A length will always be returned when attempting to call this function after reading the body completely.

Reading the body

-
-

You can read the entire body with one function call:

-
-
-
{ok, Data, Req} = cowboy_req:read_body(Req0).
-

Cowboy returns an ok tuple when the body has been -read fully.

-

By default, Cowboy will attempt to read up to 8MB -of data, for up to 15 seconds. The call will return -once Cowboy has read at least 8MB of data, or at -the end of the 15 seconds period.

-

These values can be customized. For example, to read -only up to 1MB for up to 5 seconds:

-
-
-
{ok, Data, Req} = cowboy_req:read_body(Req0,
-    #{length => 1000000, period => 5000}).
-

You may also disable the length limit:

-
-
-
{ok, Data, Req} = cowboy_req:read_body(Req0, #{length => infinity}).
-

This makes the function wait 15 seconds and return with -whatever arrived during that period. This is not -recommended for public facing applications.

-

These two options can effectively be used to control -the rate of transmission of the request body.

-
- -
+
{ok, Data, Req} = cowboy_req:read_body(Req0, #{length => infinity}).
+
+

This makes the function wait 15 seconds and return with whatever arrived during that period. This is not recommended for public facing applications.

+

These two options can effectively be used to control the rate of transmission of the request body.

Streaming the body

-
-

When the body is too large, the first call will return -a more tuple instead of ok. You can call the -function again to read more of the body, reading -it one chunk at a time.

-
-
-
read_body_to_console(Req0) ->
-    case cowboy_req:read_body(Req0) of
-        {ok, Data, Req} ->
-            io:format("~s", [Data]),
-            Req;
-        {more, Data, Req} ->
-            io:format("~s", [Data]),
-            read_body_to_console(Req)
-    end.
-

The length and period options can also be used. -They need to be passed for every call.

-
- -
+
read_body_to_console(Req0) ->
+    case cowboy_req:read_body(Req0) of
+        {ok, Data, Req} ->
+            io:format("~s", [Data]),
+            Req;
+        {more, Data, Req} ->
+            io:format("~s", [Data]),
+            read_body_to_console(Req)
+    end.
+
+

The length and period options can also be used. They need to be passed for every call.

Reading a form urlencoded body

-
-

Cowboy provides a convenient function for reading and -parsing bodies sent as application/x-www-form-urlencoded.

-
-
-
{ok, KeyValues, Req} = cowboy_req:read_urlencoded_body(Req0).
-

This function returns a list of key/values, exactly like -the function cowboy_req:parse_qs/1.

-

The defaults for this function are different. Cowboy will -read for up to 64KB and up to 5 seconds. They can be modified:

-
-
-
{ok, KeyValues, Req} = cowboy_req:read_urlencoded_body(Req0,
-    #{length => 4096, period => 3000}).
-
- +
{ok, KeyValues, Req} = cowboy_req:read_urlencoded_body(Req0,
+    #{length => 4096, period => 3000}).
+ + diff --git a/docs/en/cowboy/2.0/guide/resource_design/index.html b/docs/en/cowboy/2.0/guide/resource_design/index.html index 31c9286a..dec626fa 100644 --- a/docs/en/cowboy/2.0/guide/resource_design/index.html +++ b/docs/en/cowboy/2.0/guide/resource_design/index.html @@ -62,213 +62,66 @@

Designing a resource handler

-

This chapter aims to provide you with a list of questions -you must answer in order to write a good resource handler. -It is meant to be usable as a step by step guide.

-
+

This chapter aims to provide you with a list of questions you must answer in order to write a good resource handler. It is meant to be usable as a step by step guide.

The service

-
-

Can the service become unavailable, and when it does, can -we detect it? For example, database connectivity problems -may be detected early. We may also have planned outages -of all or parts of the system. Implement the -service_available callback.

-

What HTTP methods does the service implement? Do we need -more than the standard OPTIONS, HEAD, GET, PUT, POST, -PATCH and DELETE? Are we not using one of those at all? -Implement the known_methods callback.

-
-
-
+

Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. Implement the service_available callback.

+

What HTTP methods does the service implement? Do we need more than the standard OPTIONS, HEAD, GET, PUT, POST, PATCH and DELETE? Are we not using one of those at all? Implement the known_methods callback.

Type of resource handler

-
-

Am I writing a handler for a collection of resources, -or for a single resource?

-

The semantics for each of these are quite different. -You should not mix collection and single resource in -the same handler.

-
-
-
+

Am I writing a handler for a collection of resources, or for a single resource?

+

The semantics for each of these are quite different. You should not mix collection and single resource in the same handler.

Collection handler

-
-

Skip this section if you are not doing a collection.

-

Is the collection hardcoded or dynamic? For example, -if you use the route /users for the collection of -users then the collection is hardcoded; if you use -/forums/:category for the collection of threads -then it isn’t. When the collection is hardcoded you -can safely assume the resource always exists.

-

What methods should I implement?

-

OPTIONS is used to get some information about the -collection. It is recommended to allow it even if you -do not implement it, as Cowboy has a default -implementation built-in.

-

HEAD and GET are used to retrieve the collection. -If you allow GET, also allow HEAD as there’s no extra -work required to make it work.

-

POST is used to create a new resource inside the -collection. Creating a resource by using POST on -the collection is useful when resources may be -created before knowing their URI, usually because -parts of it are generated dynamically. A common -case is some kind of auto incremented integer -identifier.

-

The next methods are more rarely allowed.

-

PUT is used to create a new collection (when -the collection isn’t hardcoded), or replace -the entire collection.

-

DELETE is used to delete the entire collection.

-

PATCH is used to modify the collection using -instructions given in the request body. A PATCH -operation is atomic. The PATCH operation may -be used for such things as reordering; adding, -modifying or deleting parts of the collection.

-
-
-
+

Skip this section if you are not doing a collection.

+

Is the collection hardcoded or dynamic? For example, if you use the route /users for the collection of users then the collection is hardcoded; if you use /forums/:category for the collection of threads then it isn't. When the collection is hardcoded you can safely assume the resource always exists.

+

What methods should I implement?

+

OPTIONS is used to get some information about the collection. It is recommended to allow it even if you do not implement it, as Cowboy has a default implementation built-in.

+

HEAD and GET are used to retrieve the collection. If you allow GET, also allow HEAD as there's no extra work required to make it work.

+

POST is used to create a new resource inside the collection. Creating a resource by using POST on the collection is useful when resources may be created before knowing their URI, usually because parts of it are generated dynamically. A common case is some kind of auto incremented integer identifier.

+

The next methods are more rarely allowed.

+

PUT is used to create a new collection (when the collection isn't hardcoded), or replace the entire collection.

+

DELETE is used to delete the entire collection.

+

PATCH is used to modify the collection using instructions given in the request body. A PATCH operation is atomic. The PATCH operation may be used for such things as reordering; adding, modifying or deleting parts of the collection.

Single resource handler

-
-

Skip this section if you are doing a collection.

-

What methods should I implement?

-

OPTIONS is used to get some information about the -resource. It is recommended to allow it even if you -do not implement it, as Cowboy has a default -implementation built-in.

-

HEAD and GET are used to retrieve the resource. -If you allow GET, also allow HEAD as there’s no extra -work required to make it work.

-

POST is used to update the resource.

-

PUT is used to create a new resource (when it doesn’t -already exist) or replace the resource.

-

DELETE is used to delete the resource.

-

PATCH is used to modify the resource using -instructions given in the request body. A PATCH -operation is atomic. The PATCH operation may -be used for adding, removing or modifying specific -values in the resource.

-
-
-
+

Skip this section if you are doing a collection.

+

What methods should I implement?

+

OPTIONS is used to get some information about the resource. It is recommended to allow it even if you do not implement it, as Cowboy has a default implementation built-in.

+

HEAD and GET are used to retrieve the resource. If you allow GET, also allow HEAD as there's no extra work required to make it work.

+

POST is used to update the resource.

+

PUT is used to create a new resource (when it doesn't already exist) or replace the resource.

+

DELETE is used to delete the resource.

+

PATCH is used to modify the resource using instructions given in the request body. A PATCH operation is atomic. The PATCH operation may be used for adding, removing or modifying specific values in the resource.

The resource

-
-

Following the above discussion, implement the -allowed_methods callback.

-

Does the resource always exist? If it may not, implement -the resource_exists callback.

-

Do I need to authenticate the client before they can -access the resource? What authentication mechanisms -should I provide? This may include form-based, token-based -(in the URL or a cookie), HTTP basic, HTTP digest, -SSL certificate or any other form of authentication. -Implement the is_authorized callback.

-

Do I need fine-grained access control? How do I determine -that they are authorized access? Handle that in your -is_authorized callback.

-

Can access to a resource be forbidden regardless of access -being authorized? A simple example of that is censorship -of a resource. Implement the forbidden callback.

-

Are there any constraints on the length of the resource URI? -For example, the URI may be used as a key in storage and may -have a limit in length. Implement uri_too_long.

-
-
-
+

Following the above discussion, implement the allowed_methods callback.

+

Does the resource always exist? If it may not, implement the resource_exists callback.

+

Do I need to authenticate the client before they can access the resource? What authentication mechanisms should I provide? This may include form-based, token-based (in the URL or a cookie), HTTP basic, HTTP digest, SSL certificate or any other form of authentication. Implement the is_authorized callback.

+

Do I need fine-grained access control? How do I determine that they are authorized access? Handle that in your is_authorized callback.

+

Can access to a resource be forbidden regardless of access being authorized? A simple example of that is censorship of a resource. Implement the forbidden callback.

+

Are there any constraints on the length of the resource URI? For example, the URI may be used as a key in storage and may have a limit in length. Implement uri_too_long.

Representations

-
-

What media types do I provide? If text based, what charsets -are provided? What languages do I provide?

-

Implement the mandatory content_types_provided. Prefix -the callbacks with to_ for clarity. For example, to_html -or to_text.

-

Implement the languages_provided or charsets_provided -callbacks if applicable.

-

Is there any other header that may make the representation -of the resource vary? Implement the variances callback.

-

Depending on your choices for caching content, you may -want to implement one or more of the generate_etag, -last_modified and expires callbacks.

-

Do I want the user or user agent to actively choose a -representation available? Send a list of available -representations in the response body and implement -the multiple_choices callback.

-
-
-
+

What media types do I provide? If text based, what charsets are provided? What languages do I provide?

+

Implement the mandatory content_types_provided. Prefix the callbacks with to_ for clarity. For example, to_html or to_text.

+

Implement the languages_provided or charsets_provided callbacks if applicable.

+

Is there any other header that may make the representation of the resource vary? Implement the variances callback.

+

Depending on your choices for caching content, you may want to implement one or more of the generate_etag, last_modified and expires callbacks.

+

Do I want the user or user agent to actively choose a representation available? Send a list of available representations in the response body and implement the multiple_choices callback.

Redirections

-
-

Do I need to keep track of what resources were deleted? -For example, you may have a mechanism where moving a -resource leaves a redirect link to its new location. -Implement the previously_existed callback.

-

Was the resource moved, and is the move temporary? If -it is explicitly temporary, for example due to maintenance, -implement the moved_temporarily callback. Otherwise, -implement the moved_permanently callback.

-
-
-
+

Do I need to keep track of what resources were deleted? For example, you may have a mechanism where moving a resource leaves a redirect link to its new location. Implement the previously_existed callback.

+

Was the resource moved, and is the move temporary? If it is explicitly temporary, for example due to maintenance, implement the moved_temporarily callback. Otherwise, implement the moved_permanently callback.

The request

-
-

Do you need to read the query string? Individual headers? -Implement malformed_request and do all the parsing and -validation in this function. Note that the body should not -be read at this point.

-

May there be a request body? Will I know its size? -What’s the maximum size of the request body I’m willing -to accept? Implement valid_entity_length.

-

Finally, take a look at the sections corresponding to the -methods you are implementing.

-
-
-
+

Do you need to read the query string? Individual headers? Implement malformed_request and do all the parsing and validation in this function. Note that the body should not be read at this point.

+

May there be a request body? Will I know its size? What's the maximum size of the request body I'm willing to accept? Implement valid_entity_length.

+

Finally, take a look at the sections corresponding to the methods you are implementing.

OPTIONS method

-
-

Cowboy by default will send back a list of allowed methods. -Do I need to add more information to the response? Implement -the options method.

-
-
-
+

Cowboy by default will send back a list of allowed methods. Do I need to add more information to the response? Implement the options method.

GET and HEAD methods

-
-

If you implement the methods GET and/or HEAD, you must -implement one ProvideResource callback for each -content-type returned by the content_types_provided -callback.

-
-
-
-

PUT, POST and PATCH methods

-
-

If you implement the methods PUT, POST and/or PATCH, -you must implement the content_types_accepted callback, -and one AcceptResource callback for each content-type -it returns. Prefix the AcceptResource callback names -with from_ for clarity. For example, from_html or -from_json.

-

Do we want to allow the POST method to create individual -resources directly through their URI (like PUT)? Implement -the allow_missing_post callback. It is recommended to -explicitly use PUT in these cases instead.

-

May there be conflicts when using PUT to create or replace -a resource? Do we want to make sure that two updates around -the same time are not cancelling one another? Implement the -is_conflict callback.

-
-
-
+

If you implement the methods GET and/or HEAD, you must implement one ProvideResource callback for each content-type returned by the content_types_provided callback.

+

PUT, POST and PATCH methods

+

If you implement the methods PUT, POST and/or PATCH, you must implement the content_types_accepted callback, and one AcceptResource callback for each content-type it returns. Prefix the AcceptResource callback names with from_ for clarity. For example, from_html or from_json.

+

Do we want to allow the POST method to create individual resources directly through their URI (like PUT)? Implement the allow_missing_post callback. It is recommended to explicitly use PUT in these cases instead.

+

May there be conflicts when using PUT to create or replace a resource? Do we want to make sure that two updates around the same time are not cancelling one another? Implement the is_conflict callback.

DELETE methods

-
-

If you implement the method DELETE, you must implement -the delete_resource callback.

-

When delete_resource returns, is the resource completely -removed from the server, including from any caching service? -If not, and/or if the deletion is asynchronous and we have -no way of knowing it has been completed yet, implement the -delete_completed callback.

-
-
+

If you implement the method DELETE, you must implement the delete_resource callback.

+

When delete_resource returns, is the resource completely removed from the server, including from any caching service? If not, and/or if the deletion is asynchronous and we have no way of knowing it has been completed yet, implement the delete_completed callback.

+ diff --git a/docs/en/cowboy/2.0/guide/resp/index.html b/docs/en/cowboy/2.0/guide/resp/index.html index 97aff988..20a6f487 100644 --- a/docs/en/cowboy/2.0/guide/resp/index.html +++ b/docs/en/cowboy/2.0/guide/resp/index.html @@ -62,322 +62,218 @@

Sending a response

-

The response must be sent using the Req object.

-

Cowboy provides two different ways of sending responses: -either directly or by streaming the body. Response headers -and body may be set in advance. The response is sent as -soon as one of the reply or stream reply function is -called.

-

Cowboy also provides a simplified interface for sending -files. It can also send only specific parts of a file.

-

While only one response is allowed for every request, -HTTP/2 introduced a mechanism that allows the server -to push additional resources related to the response. -This chapter also describes how this feature works in -Cowboy.

-
+

The response must be sent using the Req object.

+

Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called.

+

Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file.

+

While only one response is allowed for every request, HTTP/2 introduced a mechanism that allows the server to push additional resources related to the response. This chapter also describes how this feature works in Cowboy.

Reply

-
-

Cowboy provides three functions for sending the entire reply, -depending on whether you need to set headers and body. In all -cases, Cowboy will add any headers required by the protocol -(for example the date header will always be sent).

-

When you need to set only the status code, -use cowboy_req:reply/2:

-
-
-
Req = cowboy_req:reply(200, Req0).
-

When you need to set response headers at the same time, -use cowboy_req:reply/3:

-
-
-
Req = cowboy_req:reply(303, #{
-    <<"location">> => <<"https://ninenines.eu">>
-}, Req0).
-

Note that the header name must always be a lowercase -binary.

-

When you also need to set the response body, -use cowboy_req:reply/4:

-
-
-
Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, "Hello world!", Req0).
-

You should always set the content-type header when the -response has a body. There is however no need to set -the content-length header; Cowboy does it automatically.

-

The response body and the header values must be either -a binary or an iolist. An iolist is a list containing -binaries, characters, strings or other iolists. This -allows you to build a response from different parts -without having to do any concatenation:

-
-
-
Title = "Hello world!",
-Body = <<"Hats off!">>,
-Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/html">>
-}, ["<html><head><title>", Title, "</title></head>",
-    "<body><p>", Body, "</p></body></html>"], Req0).
-

This method of building responses is more efficient than -concatenating. Behind the scenes, each element of the list -is simply a pointer, and those pointers are used directly -when writing to the socket.

-
-
-
+
Title = "Hello world!",
+Body = <<"Hats off!">>,
+Req = cowboy_req:reply(200, #{
+    <<"content-type">> => <<"text/html">>
+}, ["<html><head><title>", Title, "</title></head>",
+    "<body><p>", Body, "</p></body></html>"], Req0).
+
+

This method of building responses is more efficient than concatenating. Behind the scenes, each element of the list is simply a pointer, and those pointers are used directly when writing to the socket.

Stream reply

-
-

Cowboy provides two functions for initiating a response, -and an additional function for streaming the response body. -Cowboy will add any required headers to the response.

-

When you need to set only the status code, -use cowboy_req:stream_reply/2:

-
-
+

When you need to set only the status code, use cowboy_req:stream_reply/2:

+
-
Req = cowboy_req:stream_reply(200, Req0),
-
-cowboy_req:stream_body("Hello...", nofin, Req),
-cowboy_req:stream_body("chunked...", nofin, Req),
-cowboy_req:stream_body("world!!", fin, Req).
-

The second argument to cowboy_req:stream_body/3 indicates -whether this data terminates the body. Use fin for the -final flag, and nofin otherwise.

-

This snippet does not set a content-type header. This is -not recommended. All responses with a body should have -a content-type. The header can be set beforehand, or -using the cowboy_req:stream_reply/3:

-
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/html">>
-}, Req0),
-
-cowboy_req:stream_body("<html><head>Hello world!</head>", nofin, Req),
-cowboy_req:stream_body("<body><p>Hats off!</p></body></html>", fin, Req).
-

HTTP provides a few different ways to stream response bodies. -Cowboy will select the most appropriate one based on the HTTP -version and the request and response headers.

-

While not required by any means, it is recommended that you -set the content-length header in the response if you know it -in advance. This will ensure that the best response method -is selected and help clients understand when the response -is fully received.

-
-
-
+
Req = cowboy_req:stream_reply(200, #{
+    <<"content-type">> => <<"text/html">>
+}, Req0),
+
+cowboy_req:stream_body("<html><head>Hello world!</head>", nofin, Req),
+cowboy_req:stream_body("<body><p>Hats off!</p></body></html>", fin, Req).
+
+

HTTP provides a few different ways to stream response bodies. Cowboy will select the most appropriate one based on the HTTP version and the request and response headers.

+

While not required by any means, it is recommended that you set the content-length header in the response if you know it in advance. This will ensure that the best response method is selected and help clients understand when the response is fully received.

+

Preset response headers

-
-

Cowboy provides functions to set response headers without -immediately sending them. They are stored in the Req object -and sent as part of the response when a reply function is -called.

-

To set response headers:

-
-
-
Req = cowboy_req:set_resp_header(<<"allow">>, "GET", Req0).
-

Header names must be a lowercase binary.

-

Do not use this function for setting cookies. Refer to -the Cookies chapter for more information.

-

To check if a response header has already been set:

-
-
-
cowboy_req:has_resp_header(<<"allow">>, Req).
-

It returns true if the header was set, false otherwise.

-

To delete a response header that was set previously:

-
-
-
Req = cowboy_req:delete_resp_header(<<"allow">>, Req0).
-
- -
+
Req = cowboy_req:delete_resp_header(<<"allow">>, Req0).
+

Overriding headers

-
-

As Cowboy provides different ways of setting response -headers and body, clashes may occur, so it’s important -to understand what happens when a header is set twice.

-

Headers come from five different origins:

-
    -
  • -

    -Protocol-specific headers (for example HTTP/1.1’s connection header) -

    +

    As Cowboy provides different ways of setting response headers and body, clashes may occur, so it's important to understand what happens when a header is set twice.

    +

    Headers come from five different origins:

    +
    • Protocol-specific headers (for example HTTP/1.1's connection header)
    • -
    • -

      -Other required headers (for example the date header) -

      +
    • Other required headers (for example the date header)
    • -
    • -

      -Preset headers -

      +
    • Preset headers
    • -
    • -

      -Headers given to the reply function -

      +
    • Headers given to the reply function
    • -
    • -

      -Set-cookie headers -

      +
    • Set-cookie headers
    • -
-

Cowboy does not allow overriding protocol-specific headers.

-

Set-cookie headers will always be appended at the end of -the list of headers before sending the response.

-

Headers given to the reply function will always override -preset headers and required headers. If a header is found -in two or three of these, then the one in the reply function -is picked and the others are dropped.

-

Similarly, preset headers will always override required -headers.

-

To illustrate, look at the following snippet. Cowboy by -default sends the server header with the value "Cowboy". -We can override it:

-
-
-
Req = cowboy_req:reply(200, #{
-    <<"server">> => <<"yaws">>
-}, Req0).
-
- -
+
Req = cowboy_req:reply(200, #{
+    <<"server">> => <<"yaws">>
+}, Req0).
+

Preset response body

-
-

Cowboy provides functions to set the response body without -immediately sending it. It is stored in the Req object and -sent when the reply function is called.

-

To set the response body:

-
-
-
Req = cowboy_req:set_resp_body("Hello world!", Req0).
-

To check if a response body has already been set:

-
-
+ +

To check if a response body has already been set:

+
-
cowboy_req:has_resp_body(Req).
-

It returns true if the body was set and is non-empty, -false otherwise.

-

The preset response body is only sent if the reply function -used is cowboy_req:reply/2 or cowboy_req:reply/3.

-
-
-
+
cowboy_req:has_resp_body(Req).
+
+

It returns true if the body was set and is non-empty, false otherwise.

+ + + +

The preset response body is only sent if the reply function used is cowboy_req:reply/2 or cowboy_req:reply/3.

Sending files

-
-

Cowboy provides a shortcut for sending files. When -using cowboy_req:reply/4, or when presetting the -response header, you can give a sendfile tuple to -Cowboy:

-
-
-
{sendfile, Offset, Length, Filename}
-

Depending on the values for Offset or Length, the -entire file may be sent, or just a part of it.

-

The length is required even for sending the entire file. -Cowboy sends it in the content-length header.

-

To send a file while replying:

-
-
-
Req = cowboy_req:reply(200, #{
-    <<"content-type">> => "image/png"
-}, {sendfile, 0, 12345, "path/to/logo.png"}, Req0).
-
- -
+
Req = cowboy_req:reply(200, #{
+    <<"content-type">> => "image/png"
+}, {sendfile, 0, 12345, "path/to/logo.png"}, Req0).
+
+ + + + + + + + +

Push

-
-

The HTTP/2 protocol introduced the ability to push resources -related to the one sent in the response. Cowboy provides two -functions for that purpose: cowboy_req:push/3,4.

-

Push is only available for HTTP/2. Cowboy will automatically -ignore push requests if the protocol doesn’t support it.

-

The push function must be called before any of the reply -functions. Doing otherwise will result in a crash.

-

To push a resource, you need to provide the same information -as a client performing a request would. This includes the -HTTP method, the URI and any necessary request headers.

-

Cowboy by default only requires you to give the path to -the resource and the request headers. The rest of the URI -is taken from the current request (excluding the query -string, set to empty) and the method is GET by default.

-

The following snippet pushes a CSS file that is linked to -in the response:

-
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, Req0),
-Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/html">>
-}, ["<html><head><title>My web page</title>",
-    "<link rel='stylesheet' type='text/css' href='/static/style.css'>",
-    "<body><p>Welcome to Erlang!</p></body></html>"], Req0).
-

To override the method, scheme, host, port or query string, -simply pass in a fourth argument. The following snippet -uses a different host name:

-
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, #{host => <<"cdn.example.org">>}, Req),
-

Pushed resources don’t have to be files. As long as the push -request is cacheable, safe and does not include a body, the -resource can be pushed.

-

Under the hood, Cowboy handles pushed requests the same as -normal requests: a different process is created which will -ultimately send a response to the client.

-
- +
cowboy_req:push("/static/style.css", #{
+    <<"accept">> => <<"text/css">>
+}, #{host => <<"cdn.example.org">>}, Req),
+ +

Pushed resources don't have to be files. As long as the push request is cacheable, safe and does not include a body, the resource can be pushed.

+

Under the hood, Cowboy handles pushed requests the same as normal requests: a different process is created which will ultimately send a response to the client.

+ diff --git a/docs/en/cowboy/2.0/guide/rest_flowcharts/index.html b/docs/en/cowboy/2.0/guide/rest_flowcharts/index.html index 2bed5190..01817463 100644 --- a/docs/en/cowboy/2.0/guide/rest_flowcharts/index.html +++ b/docs/en/cowboy/2.0/guide/rest_flowcharts/index.html @@ -62,244 +62,64 @@

REST flowcharts

-

This chapter will explain the REST handler state machine through -a number of different diagrams.

-

There are four main paths that requests may follow. One for the -method OPTIONS; one for the methods GET and HEAD; one for the -methods PUT, POST and PATCH; and one for the method DELETE.

-

All paths start with the "Start" diagram, and all paths excluding -the OPTIONS path go through the "Content negotiation" diagram -and optionally the "Conditional requests" diagram if the resource -exists.

-

The red squares refer to another diagram. The light green squares -indicate a response. Other squares may be either a callback or a -question answered by Cowboy itself. Green arrows tend to indicate -the default behavior if the callback is undefined.

-
+

This chapter will explain the REST handler state machine through a number of different diagrams.

+

There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE.

+

All paths start with the "Start" diagram, and all paths excluding the OPTIONS path go through the "Content negotiation" diagram and optionally the "Conditional requests" diagram if the resource exists.

+

The red squares refer to another diagram. The light green squares indicate a response. Other squares may be either a callback or a question answered by Cowboy itself. Green arrows tend to indicate the default behavior if the callback is undefined.

Start

-
-

All requests start from here.

-
-
-REST starting flowchart -
-
-

A series of callbacks are called in succession to perform -a general checkup of the service, the request line and -request headers.

-

The request body, if any, is not expected to have been -received for any of these steps. It is only processed -at the end of the "PUT, POST and PATCH methods" diagram, -when all conditions have been met.

-

The known_methods and allowed_methods callbacks -return a list of methods. Cowboy then checks if the request -method is in the list, and stops otherwise.

-

The is_authorized callback may be used to check that -access to the resource is authorized. Authentication -may also be performed as needed. When authorization is -denied, the return value from the callback must include -a challenge applicable to the requested resource, which -will be sent back to the client in the www-authenticate -header.

-

This diagram is immediately followed by either the -"OPTIONS method" diagram when the request method is -OPTIONS, or the "Content negotiation" diagram otherwise.

-
-
-
+

All requests start from here.

+REST starting flowchart

A series of callbacks are called in succession to perform a general checkup of the service, the request line and request headers.

+

The request body, if any, is not expected to have been received for any of these steps. It is only processed at the end of the "PUT, POST and PATCH methods" diagram, when all conditions have been met.

+

The known_methods and allowed_methods callbacks return a list of methods. Cowboy then checks if the request method is in the list, and stops otherwise.

+

The is_authorized callback may be used to check that access to the resource is authorized. Authentication may also be performed as needed. When authorization is denied, the return value from the callback must include a challenge applicable to the requested resource, which will be sent back to the client in the www-authenticate header.

+

This diagram is immediately followed by either the "OPTIONS method" diagram when the request method is OPTIONS, or the "Content negotiation" diagram otherwise.

OPTIONS method

-
-

This diagram only applies to OPTIONS requests.

-
-
-REST OPTIONS method flowchart -
-
-

The options callback may be used to add information -about the resource, such as media types or languages -provided; allowed methods; any extra information. A -response body may also be set, although clients should -not be expected to read it.

-

If the options callback is not defined, Cowboy will -send a response containing the list of allowed methods -by default.

-
-
-
+

This diagram only applies to OPTIONS requests.

+REST OPTIONS method flowchart

The options callback may be used to add information about the resource, such as media types or languages provided; allowed methods; any extra information. A response body may also be set, although clients should not be expected to read it.

+

If the options callback is not defined, Cowboy will send a response containing the list of allowed methods by default.

Content negotiation

-
-

This diagram applies to all request methods other than -OPTIONS. It is executed right after the "Start" diagram -is completed.

-
-
-REST content negotiation flowchart -
-
-

The purpose of these steps is to determine an appropriate -representation to be sent back to the client.

-

The request may contain any of the accept header; the -accept-language header; or the accept-charset header. -When present, Cowboy will parse the headers and then -call the corresponding callback to obtain the list -of provided content-type, language or charset for this -resource. It then automatically select the best match -based on the request.

-

If a callback is not defined, Cowboy will select the -content-type, language or charset that the client -prefers.

-

The content_types_provided also returns the name of -a callback for every content-type it accepts. This -callback will only be called at the end of the -"GET and HEAD methods" diagram, when all conditions -have been met.

-

The selected content-type, language and charset are -saved as meta values in the Req object. You should -use the appropriate representation if you set a -response body manually (alongside an error code, -for example).

-

This diagram is immediately followed by -the "GET and HEAD methods" diagram, -the "PUT, POST and PATCH methods" diagram, -or the "DELETE method" diagram, depending on the -method.

-
-
-
+

This diagram applies to all request methods other than OPTIONS. It is executed right after the "Start" diagram is completed.

+REST content negotiation flowchart

The purpose of these steps is to determine an appropriate representation to be sent back to the client.

+

The request may contain any of the accept header; the accept-language header; or the accept-charset header. When present, Cowboy will parse the headers and then call the corresponding callback to obtain the list of provided content-type, language or charset for this resource. It then automatically select the best match based on the request.

+

If a callback is not defined, Cowboy will select the content-type, language or charset that the client prefers.

+

The content_types_provided also returns the name of a callback for every content-type it accepts. This callback will only be called at the end of the "GET and HEAD methods" diagram, when all conditions have been met.

+

The selected content-type, language and charset are saved as meta values in the Req object. You should use the appropriate representation if you set a response body manually (alongside an error code, for example).

+

This diagram is immediately followed by the "GET and HEAD methods" diagram, the "PUT, POST and PATCH methods" diagram, or the "DELETE method" diagram, depending on the method.

GET and HEAD methods

-
-

This diagram only applies to GET and HEAD requests.

-

For a description of the cond step, please see -the "Conditional requests" diagram.

-
-
-REST GET/HEAD methods flowchart -
-
-

When the resource exists, and the conditional steps -succeed, the resource can be retrieved.

-

Cowboy prepares the response by first retrieving -metadata about the representation, then by calling -the ProvideResource callback. This is the callback -you defined for each content-types you returned from -content_types_provided. This callback returns the body -that will be sent back to the client, or a fun if the -body must be streamed.

-

When the resource does not exist, Cowboy will figure out -whether the resource existed previously, and if so whether -it was moved elsewhere in order to redirect the client to -the new URI.

-

The moved_permanently and moved_temporarily callbacks -must return the new location of the resource if it was in -fact moved.

-
-
-
-

PUT, POST and PATCH methods

-
-

This diagram only applies to PUT, POST and PATCH requests.

-

For a description of the cond step, please see -the "Conditional requests" diagram.

-
-
-REST PUT/POST/PATCH methods flowchart -
-
-

When the resource exists, first the conditional steps -are executed. When that succeeds, and the method is PUT, -Cowboy will call the is_conflict callback. This function -can be used to prevent potential race conditions, by locking -the resource for example.

-

Then all three methods reach the content_types_accepted -step that we will describe in a few paragraphs.

-

When the resource does not exist, and the method is PUT, -Cowboy will check for conflicts and then move on to the -content_types_accepted step. For other methods, Cowboy -will figure out whether the resource existed previously, -and if so whether it was moved elsewhere. If the resource -is truly non-existent, the method is POST and the call -for allow_missing_post returns true, then Cowboy will -move on to the content_types_accepted step. Otherwise -the request processing ends there.

-

The moved_permanently and moved_temporarily callbacks -must return the new location of the resource if it was in -fact moved.

-

The content_types_accepted returns a list of -content-types it accepts, but also the name of a callback -for each of them. Cowboy will select the appropriate -callback for processing the request body and call it.

-

This callback may return one of three different return -values.

-

If an error occurred while processing the request body, -it must return false and Cowboy will send an -appropriate error response.

-

If the method is POST, then you may return true with -an URI of where the resource has been created. This is -especially useful for writing handlers for collections.

-

Otherwise, return true to indicate success. Cowboy -will select the appropriate response to be sent depending -on whether a resource has been created, rather than -modified, and on the availability of a location header -or a body in the response.

-
-
-
+

This diagram only applies to GET and HEAD requests.

+

For a description of the cond step, please see the "Conditional requests" diagram.

+REST GET/HEAD methods flowchart

When the resource exists, and the conditional steps succeed, the resource can be retrieved.

+

Cowboy prepares the response by first retrieving metadata about the representation, then by calling the ProvideResource callback. This is the callback you defined for each content-types you returned from content_types_provided. This callback returns the body that will be sent back to the client, or a fun if the body must be streamed.

+

When the resource does not exist, Cowboy will figure out whether the resource existed previously, and if so whether it was moved elsewhere in order to redirect the client to the new URI.

+

The moved_permanently and moved_temporarily callbacks must return the new location of the resource if it was in fact moved.

+

PUT, POST and PATCH methods

+

This diagram only applies to PUT, POST and PATCH requests.

+

For a description of the cond step, please see the "Conditional requests" diagram.

+REST PUT/POST/PATCH methods flowchart

When the resource exists, first the conditional steps are executed. When that succeeds, and the method is PUT, Cowboy will call the is_conflict callback. This function can be used to prevent potential race conditions, by locking the resource for example.

+

Then all three methods reach the content_types_accepted step that we will describe in a few paragraphs.

+

When the resource does not exist, and the method is PUT, Cowboy will check for conflicts and then move on to the content_types_accepted step. For other methods, Cowboy will figure out whether the resource existed previously, and if so whether it was moved elsewhere. If the resource is truly non-existent, the method is POST and the call for allow_missing_post returns true, then Cowboy will move on to the content_types_accepted step. Otherwise the request processing ends there.

+

The moved_permanently and moved_temporarily callbacks must return the new location of the resource if it was in fact moved.

+

The content_types_accepted returns a list of content-types it accepts, but also the name of a callback for each of them. Cowboy will select the appropriate callback for processing the request body and call it.

+

This callback may return one of three different return values.

+

If an error occurred while processing the request body, it must return false and Cowboy will send an appropriate error response.

+

If the method is POST, then you may return true with an URI of where the resource has been created. This is especially useful for writing handlers for collections.

+

Otherwise, return true to indicate success. Cowboy will select the appropriate response to be sent depending on whether a resource has been created, rather than modified, and on the availability of a location header or a body in the response.

DELETE method

-
-

This diagram only applies to DELETE requests.

-

For a description of the cond step, please see -the "Conditional requests" diagram.

-
-
-REST DELETE method flowchart -
-
-

When the resource exists, and the conditional steps -succeed, the resource can be deleted.

-

Deleting the resource is a two steps process. First -the callback delete_resource is executed. Use this -callback to delete the resource.

-

Because the resource may be cached, you must also -delete all cached representations of this resource -in the system. This operation may take a while though, -so you may return before it finished.

-

Cowboy will then call the delete_completed callback. -If you know that the resource has been completely -deleted from your system, including from caches, then -you can return true. If any doubts persist, return -false. Cowboy will assume true by default.

-

To finish, Cowboy checks if you set a response body, -and depending on that, sends the appropriate response.

-

When the resource does not exist, Cowboy will figure out -whether the resource existed previously, and if so whether -it was moved elsewhere in order to redirect the client to -the new URI.

-

The moved_permanently and moved_temporarily callbacks -must return the new location of the resource if it was in -fact moved.

-
-
-
+

This diagram only applies to DELETE requests.

+

For a description of the cond step, please see the "Conditional requests" diagram.

+REST DELETE method flowchart

When the resource exists, and the conditional steps succeed, the resource can be deleted.

+

Deleting the resource is a two steps process. First the callback delete_resource is executed. Use this callback to delete the resource.

+

Because the resource may be cached, you must also delete all cached representations of this resource in the system. This operation may take a while though, so you may return before it finished.

+

Cowboy will then call the delete_completed callback. If you know that the resource has been completely deleted from your system, including from caches, then you can return true. If any doubts persist, return false. Cowboy will assume true by default.

+

To finish, Cowboy checks if you set a response body, and depending on that, sends the appropriate response.

+

When the resource does not exist, Cowboy will figure out whether the resource existed previously, and if so whether it was moved elsewhere in order to redirect the client to the new URI.

+

The moved_permanently and moved_temporarily callbacks must return the new location of the resource if it was in fact moved.

Conditional requests

-
-

This diagram applies to all request methods other than -OPTIONS. It is executed right after the resource_exists -callback, when the resource exists.

-
-
-REST conditional requests flowchart -
-
-

A request becomes conditional when it includes either of -the if-match header; the if-unmodified-since header; the -if-none-match header; or the if-modified-since header.

-

If the condition fails, the request ends immediately -without any retrieval or modification of the resource.

-

The generate_etag and last_modified are called as -needed. Cowboy will only call them once and then cache -the results for subsequent use.

-
-
+

This diagram applies to all request methods other than OPTIONS. It is executed right after the resource_exists callback, when the resource exists.

+REST conditional requests flowchart

A request becomes conditional when it includes either of the if-match header; the if-unmodified-since header; the if-none-match header; or the if-modified-since header.

+

If the condition fails, the request ends immediately without any retrieval or modification of the resource.

+

The generate_etag and last_modified are called as needed. Cowboy will only call them once and then cache the results for subsequent use.

+ diff --git a/docs/en/cowboy/2.0/guide/rest_handlers/index.html b/docs/en/cowboy/2.0/guide/rest_handlers/index.html index 7edacfa9..99d3b986 100644 --- a/docs/en/cowboy/2.0/guide/rest_handlers/index.html +++ b/docs/en/cowboy/2.0/guide/rest_handlers/index.html @@ -62,283 +62,162 @@

REST handlers

-

REST is implemented in Cowboy as a sub protocol. The request -is handled as a state machine with many optional callbacks -describing the resource and modifying the machine’s behavior.

-

The REST handler is the recommended way to handle HTTP requests.

-
+

REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine's behavior.

+

The REST handler is the recommended way to handle HTTP requests.

Initialization

-
-

First, the init/2 callback is called. This callback is common -to all handlers. To use REST for the current request, this function -must return a cowboy_rest tuple.

-
-
-
init(Req, State) ->
-    {cowboy_rest, Req, State}.
-

Cowboy will then switch to the REST protocol and start executing -the state machine.

-

After reaching the end of the flowchart, the terminate/3 callback -will be called if it is defined.

-
-
-
+
init(Req, State) ->
+    {cowboy_rest, Req, State}.
+
+

Cowboy will then switch to the REST protocol and start executing the state machine.

+

After reaching the end of the flowchart, the terminate/3 callback will be called if it is defined.

Methods

-
-

The REST component has code for handling the following HTTP methods: -HEAD, GET, POST, PATCH, PUT, DELETE and OPTIONS.

-

Other methods can be accepted, however they have no specific callback -defined for them at this time.

-
- -
+

The REST component has code for handling the following HTTP methods: HEAD, GET, POST, PATCH, PUT, DELETE and OPTIONS.

+

Other methods can be accepted, however they have no specific callback defined for them at this time.

Callbacks

-
-

All callbacks are optional. Some may become mandatory depending -on what other defined callbacks return. The various flowcharts -in the next chapter should be a useful to determine which callbacks -you need.

-

All callbacks take two arguments, the Req object and the State, -and return a three-element tuple of the form {Value, Req, State}.

-

All callbacks can also return {stop, Req, State} to stop execution -of the request.

-

The following table summarizes the callbacks and their default values. -If the callback isn’t defined, then the default value will be used. -Please look at the flowcharts to find out the result of each return -value.

-

In the following table, "skip" means the callback is entirely skipped -if it is undefined, moving directly to the next step. Similarly, -"none" means there is no default value for this callback.

-
- --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +

All callbacks are optional. Some may become mandatory depending on what other defined callbacks return. The various flowcharts in the next chapter should be a useful to determine which callbacks you need.

+

All callbacks take two arguments, the Req object and the State, and return a three-element tuple of the form {Value, Req, State}.

+

All callbacks can also return {stop, Req, State} to stop execution of the request.

+

The following table summarizes the callbacks and their default values. If the callback isn't defined, then the default value will be used. Please look at the flowcharts to find out the result of each return value.

+

In the following table, "skip" means the callback is entirely skipped if it is undefined, moving directly to the next step. Similarly, "none" means there is no default value for this callback.

+
Callback name Default value

allowed_methods

[<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]

allow_missing_post

true

charsets_provided

skip

content_types_accepted

none

content_types_provided

[{{ <<"text">>, <<"html">>, '*'}, to_html}]

delete_completed

true

delete_resource

false

expires

undefined

forbidden

false

generate_etag

undefined

is_authorized

true

is_conflict

false

known_methods

[<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]

languages_provided

skip

last_modified

undefined

malformed_request

false

moved_permanently

false

moved_temporarily

false

multiple_choices

false

options

ok

previously_existed

false

resource_exists

true

service_available

true

uri_too_long

false

+ + + + - - - + + - - - + + - - - + + - -
Callback nameDefault value
allowed_methods[<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]

valid_content_headers

true

allow_missing_posttrue

valid_entity_length

true

charsets_providedskip

variances

[]

content_types_acceptednone
-
-

As you can see, Cowboy tries to move on with the request whenever -possible by using well thought out default values.

-

In addition to these, there can be any number of user-defined -callbacks that are specified through content_types_accepted/2 -and content_types_provided/2. They can take any name, however -it is recommended to use a separate prefix for the callbacks of -each function. For example, from_html and to_html indicate -in the first case that we’re accepting a resource given as HTML, -and in the second case that we send one as HTML.

-
-
-
+content_types_provided +[{{ <<"text">>, <<"html">>, '*'}, to_html}] + +delete_completed +true + +delete_resource +false + +expires +undefined + +forbidden +false + +generate_etag +undefined + +is_authorized +true + +is_conflict +false + +known_methods +[<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>] + +languages_provided +skip + +last_modified +undefined + +malformed_request +false + +moved_permanently +false + +moved_temporarily +false + +multiple_choices +false + +options +ok + +previously_existed +false + +resource_exists +true + +service_available +true + +uri_too_long +false + +valid_content_headers +true + +valid_entity_length +true + +variances +[] + + +

As you can see, Cowboy tries to move on with the request whenever possible by using well thought out default values.

+

In addition to these, there can be any number of user-defined callbacks that are specified through content_types_accepted/2 and content_types_provided/2. They can take any name, however it is recommended to use a separate prefix for the callbacks of each function. For example, from_html and to_html indicate in the first case that we're accepting a resource given as HTML, and in the second case that we send one as HTML.

Meta data

-
-

Cowboy will set informative values to the Req object at various -points of the execution. You can retrieve them by matching the -Req object directly. The values are defined in the following table:

-
- --- - - - - - - - - - - - - - - - - - - - -
Key Details

media_type

The content-type negotiated for the response entity.

language

The language negotiated for the response entity.

charset

The charset negotiated for the response entity.

-
-

They can be used to send a proper body with the response to a -request that used a method other than HEAD or GET.

-
-
-
+

Cowboy will set informative values to the Req object at various points of the execution. You can retrieve them by matching the Req object directly. The values are defined in the following table:

+ + + + + + + + + + + + +
KeyDetails
media_typeThe content-type negotiated for the response entity.
languageThe language negotiated for the response entity.
charsetThe charset negotiated for the response entity.
+

They can be used to send a proper body with the response to a request that used a method other than HEAD or GET.

Response headers

-
-

Cowboy will set response headers automatically over the execution -of the REST code. They are listed in the following table.

-
- --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Header name Details

content-language

Language used in the response body

content-type

Media type and charset of the response body

etag

Etag of the resource

expires

Expiration date of the resource

last-modified

Last modification date for the resource

location

Relative or absolute URI to the requested resource

vary

List of headers that may change the representation of the resource

-
-
-
+

Cowboy will set response headers automatically over the execution of the REST code. They are listed in the following table.

+ + + + + + + + + + + + + + + + + + + + + + + + +
Header nameDetails
content-languageLanguage used in the response body
content-typeMedia type and charset of the response body
etagEtag of the resource
expiresExpiration date of the resource
last-modifiedLast modification date for the resource
locationRelative or absolute URI to the requested resource
varyList of headers that may change the representation of the resource
+ diff --git a/docs/en/cowboy/2.0/guide/rest_principles/index.html b/docs/en/cowboy/2.0/guide/rest_principles/index.html index 8a5450f7..01246ac8 100644 --- a/docs/en/cowboy/2.0/guide/rest_principles/index.html +++ b/docs/en/cowboy/2.0/guide/rest_principles/index.html @@ -62,153 +62,38 @@

REST principles

-

This chapter will attempt to define the concepts behind REST -and explain what makes a service RESTful.

-

REST is often confused with performing a distinct operation -depending on the HTTP method, while using more than the GET -and POST methods. That’s highly misguided at best.

-

We will first attempt to define REST and will look at what -it means in the context of HTTP and the Web. -For a more in-depth explanation of REST, you can read -Roy T. Fielding’s dissertation -as it does a great job explaining where it comes from and -what it achieves.

-
+

This chapter will attempt to define the concepts behind REST and explain what makes a service RESTful.

+

REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That's highly misguided at best.

+

We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. Fielding's dissertation as it does a great job explaining where it comes from and what it achieves.

REST architecture

-
-

REST is a client-server architecture. The client and the server -both have a different set of concerns. The server stores and/or -manipulates information and makes it available to the user in -an efficient manner. The client takes that information and -displays it to the user and/or uses it to perform subsequent -requests for information. This separation of concerns allows both -the client and the server to evolve independently as it only -requires that the interface stays the same.

-

REST is stateless. That means the communication between the -client and the server always contains all the information needed -to perform the request. There is no session state in the server, -it is kept entirely on the client’s side. If access to a resource -requires authentication, then the client needs to authenticate -itself with every request.

-

REST is cacheable. The client, the server and any intermediary -components can all cache resources in order to improve performance.

-

REST provides a uniform interface between components. This -simplifies the architecture, as all components follow the same -rules to speak to one another. It also makes it easier to understand -the interactions between the different components of the system. -A number of constraints are required to achieve this. They are -covered in the rest of the chapter.

-

REST is a layered system. Individual components cannot see -beyond the immediate layer with which they are interacting. This -means that a client connecting to an intermediate component, like -a proxy, has no knowledge of what lies beyond. This allows -components to be independent and thus easily replaceable or -extendable.

-

REST optionally provides code on demand. Code may be downloaded -to extend client functionality. This is optional however because -the client may not be able to download or run this code, and so -a REST component cannot rely on it being executed.

-
-
-
+

REST is a client-server architecture. The client and the server both have a different set of concerns. The server stores and/or manipulates information and makes it available to the user in an efficient manner. The client takes that information and displays it to the user and/or uses it to perform subsequent requests for information. This separation of concerns allows both the client and the server to evolve independently as it only requires that the interface stays the same.

+

REST is stateless. That means the communication between the client and the server always contains all the information needed to perform the request. There is no session state in the server, it is kept entirely on the client's side. If access to a resource requires authentication, then the client needs to authenticate itself with every request.

+

REST is cacheable. The client, the server and any intermediary components can all cache resources in order to improve performance.

+

REST provides a uniform interface between components. This simplifies the architecture, as all components follow the same rules to speak to one another. It also makes it easier to understand the interactions between the different components of the system. A number of constraints are required to achieve this. They are covered in the rest of the chapter.

+

REST is a layered system. Individual components cannot see beyond the immediate layer with which they are interacting. This means that a client connecting to an intermediate component, like a proxy, has no knowledge of what lies beyond. This allows components to be independent and thus easily replaceable or extendable.

+

REST optionally provides code on demand. Code may be downloaded to extend client functionality. This is optional however because the client may not be able to download or run this code, and so a REST component cannot rely on it being executed.

Resources and resource identifiers

-
-

A resource is an abstract concept. In a REST system, any information -that can be named may be a resource. This includes documents, images, -a collection of resources and any other information. Any information -that can be the target of an hypertext link can be a resource.

-

A resource is a conceptual mapping to a set of entities. The set of -entities evolves over time; a resource doesn’t. For example, a resource -can map to "users who have logged in this past month" and another -to "all users". At some point in time they may map to the same set of -entities, because all users logged in this past month. But they are -still different resources. Similarly, if nobody logged in recently, -then the first resource may map to the empty set. This resource exists -regardless of the information it maps to.

-

Resources are identified by uniform resource identifiers, also known -as URIs. Sometimes internationalized resource identifiers, or IRIs, -may also be used, but these can be directly translated into a URI.

-

In practice we will identify two kinds of resources. Individual -resources map to a set of one element, for example "user Joe". -Collection of resources map to a set of 0 to N elements, -for example "all users".

-
-
-
+

A resource is an abstract concept. In a REST system, any information that can be named may be a resource. This includes documents, images, a collection of resources and any other information. Any information that can be the target of an hypertext link can be a resource.

+

A resource is a conceptual mapping to a set of entities. The set of entities evolves over time; a resource doesn't. For example, a resource can map to "users who have logged in this past month" and another to "all users". At some point in time they may map to the same set of entities, because all users logged in this past month. But they are still different resources. Similarly, if nobody logged in recently, then the first resource may map to the empty set. This resource exists regardless of the information it maps to.

+

Resources are identified by uniform resource identifiers, also known as URIs. Sometimes internationalized resource identifiers, or IRIs, may also be used, but these can be directly translated into a URI.

+

In practice we will identify two kinds of resources. Individual resources map to a set of one element, for example "user Joe". Collection of resources map to a set of 0 to N elements, for example "all users".

Resource representations

-
-

The representation of a resource is a sequence of bytes associated -with metadata.

-

The metadata comes as a list of key-value pairs, where the name -corresponds to a standard that defines the value’s structure and -semantics. With HTTP, the metadata comes in the form of request -or response headers. The headers' structure and semantics are well -defined in the HTTP standard. Metadata includes representation -metadata, resource metadata and control data.

-

The representation metadata gives information about the -representation, such as its media type, the date of last -modification, or even a checksum.

-

Resource metadata could be link to related resources or -information about additional representations of the resource.

-

Control data allows parameterizing the request or response. -For example, we may only want the representation returned if -it is more recent than the one we have in cache. Similarly, -we may want to instruct the client about how it should cache -the representation. This isn’t restricted to caching. We may, -for example, want to store a new representation of a resource -only if it wasn’t modified since we first retrieved it.

-

The data format of a representation is also known as the media -type. Some media types are intended for direct rendering to the -user, while others are intended for automated processing. The -media type is a key component of the REST architecture.

-
-
-
+

The representation of a resource is a sequence of bytes associated with metadata.

+

The metadata comes as a list of key-value pairs, where the name corresponds to a standard that defines the value's structure and semantics. With HTTP, the metadata comes in the form of request or response headers. The headers' structure and semantics are well defined in the HTTP standard. Metadata includes representation metadata, resource metadata and control data.

+

The representation metadata gives information about the representation, such as its media type, the date of last modification, or even a checksum.

+

Resource metadata could be link to related resources or information about additional representations of the resource.

+

Control data allows parameterizing the request or response. For example, we may only want the representation returned if it is more recent than the one we have in cache. Similarly, we may want to instruct the client about how it should cache the representation. This isn't restricted to caching. We may, for example, want to store a new representation of a resource only if it wasn't modified since we first retrieved it.

+

The data format of a representation is also known as the media type. Some media types are intended for direct rendering to the user, while others are intended for automated processing. The media type is a key component of the REST architecture.

Self-descriptive messages

-
-

Messages must be self-descriptive. That means that the data -format of a representation must always come with its media -type (and similarly requesting a resource involves choosing -the media type of the representation returned). If you are -sending HTML, then you must say it is HTML by sending the -media type with the representation. In HTTP this is done -using the content-type header.

-

The media type is often an IANA registered media type, like -text/html or image/png, but does not need to be. Exactly -two things are important for respecting this constraint: that -the media type is well specified, and that the sender and -recipient agree about what the media type refers to.

-

This means that you can create your own media types, like -application/x-mine, and that as long as you write the -specifications for it and that both endpoints agree about -it then the constraint is respected.

-
-
-
+

Messages must be self-descriptive. That means that the data format of a representation must always come with its media type (and similarly requesting a resource involves choosing the media type of the representation returned). If you are sending HTML, then you must say it is HTML by sending the media type with the representation. In HTTP this is done using the content-type header.

+

The media type is often an IANA registered media type, like text/html or image/png, but does not need to be. Exactly two things are important for respecting this constraint: that the media type is well specified, and that the sender and recipient agree about what the media type refers to.

+

This means that you can create your own media types, like application/x-mine, and that as long as you write the specifications for it and that both endpoints agree about it then the constraint is respected.

Hypermedia as the engine of application state

-
-

The last constraint is generally where services that claim -to be RESTful fail. Interactions with a server must be -entirely driven by hypermedia. The client does not need -any prior knowledge of the service in order to use it, -other than an entry point and of course basic understanding -of the media type of the representations, at the very least -enough to find and identify hyperlinks and link relations.

-

To give a simple example, if your service only works with -the application/json media type then this constraint -cannot be respected (as there are no concept of links in -JSON) and thus your service isn’t RESTful. This is the case -for the majority of self-proclaimed REST services.

-

On the other hand if you create a JSON based media type -that has a concept of links and link relations, then -your service might be RESTful.

-

Respecting this constraint means that the entirety of the -service becomes self-discoverable, not only the resources -in it, but also the operations you can perform on it. This -makes clients very thin as there is no need to implement -anything specific to the service to operate on it.

-
-
+

The last constraint is generally where services that claim to be RESTful fail. Interactions with a server must be entirely driven by hypermedia. The client does not need any prior knowledge of the service in order to use it, other than an entry point and of course basic understanding of the media type of the representations, at the very least enough to find and identify hyperlinks and link relations.

+

To give a simple example, if your service only works with the application/json media type then this constraint cannot be respected (as there are no concept of links in JSON) and thus your service isn't RESTful. This is the case for the majority of self-proclaimed REST services.

+

On the other hand if you create a JSON based media type that has a concept of links and link relations, then your service might be RESTful.

+

Respecting this constraint means that the entirety of the service becomes self-discoverable, not only the resources in it, but also the operations you can perform on it. This makes clients very thin as there is no need to implement anything specific to the service to operate on it.

+ diff --git a/docs/en/cowboy/2.0/guide/routing/index.html b/docs/en/cowboy/2.0/guide/routing/index.html index 03031391..14b205ad 100644 --- a/docs/en/cowboy/2.0/guide/routing/index.html +++ b/docs/en/cowboy/2.0/guide/routing/index.html @@ -62,261 +62,181 @@

Routing

-

Cowboy does nothing by default.

-

To make Cowboy useful, you need to map URIs to Erlang modules that will -handle the requests. This is called routing.

-

When Cowboy receives a request, it tries to match the requested host and -path to the configured routes. When there’s a match, the route’s -associated handler is executed.

-

Routes need to be compiled before they can be used by Cowboy. -The result of the compilation is the dispatch rules.

-
+

Cowboy does nothing by default.

+

To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing.

+

When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there's a match, the route's associated handler is executed.

+

Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules.

Syntax

-
-

The general structure for the routes is defined as follow.

-
-
-
Routes = [Host1, Host2, ... HostN].
-

Each host contains matching rules for the host along with optional -constraints, and a list of routes for the path component.

-
-
-
Host1 = {HostMatch, PathsList}.
-Host2 = {HostMatch, Constraints, PathsList}.
-

The list of routes for the path component is defined similar to the -list of hosts.

-
-
-
PathsList = [Path1, Path2, ... PathN].
-

Finally, each path contains matching rules for the path along with -optional constraints, and gives us the handler module to be used -along with its initial state.

-
-
-
Path1 = {PathMatch, Handler, InitialState}.
-Path2 = {PathMatch, Constraints, Handler, InitialState}.
-

Continue reading to learn more about the match syntax and the optional -constraints.

-
-
-
+
Path1 = {PathMatch, Handler, InitialState}.
+Path2 = {PathMatch, Constraints, Handler, InitialState}.
+
+

Continue reading to learn more about the match syntax and the optional constraints.

Match syntax

-
-

The match syntax is used to associate host names and paths with their -respective handlers.

-

The match syntax is the same for host and path with a few subtleties. -Indeed, the segments separator is different, and the host is matched -starting from the last segment going to the first. All examples will -feature both host and path match rules and explain the differences -when encountered.

-

Excluding special values that we will explain at the end of this section, -the simplest match value is a host or a path. It can be given as either -a string() or a binary().

-
-
-
PathMatch1 = "/".
-PathMatch2 = "/path/to/resource".
-
-HostMatch1 = "cowboy.example.org".
-

As you can see, all paths defined this way must start with a slash -character. Note that these two paths are identical as far as routing -is concerned.

-
-
-
PathMatch2 = "/path/to/resource".
-PathMatch3 = "/path/to/resource/".
-

Hosts with and without a trailing dot are equivalent for routing. -Similarly, hosts with and without a leading dot are also equivalent.

-
-
-
HostMatch1 = "cowboy.example.org".
-HostMatch2 = "cowboy.example.org.".
-HostMatch3 = ".cowboy.example.org".
-

It is possible to extract segments of the host and path and to store -the values in the Req object for later use. We call these kind of -values bindings.

-

The syntax for bindings is very simple. A segment that begins with -the : character means that what follows until the end of the segment -is the name of the binding in which the segment value will be stored.

-
-
-
PathMatch = "/hats/:name/prices".
-HostMatch = ":subdomain.example.org".
-

If these two end up matching when routing, you will end up with two -bindings defined, subdomain and name, each containing the -segment value where they were defined. For example, the URL -http://test.example.org/hats/wild_cowboy_legendary/prices will -result in having the value test bound to the name subdomain -and the value wild_cowboy_legendary bound to the name name. -They can later be retrieved using cowboy_req:binding/{2,3}. The -binding name must be given as an atom.

-

There is a special binding name you can use to mimic the underscore -variable in Erlang. Any match against the _ binding will succeed -but the data will be discarded. This is especially useful for -matching against many domain names in one go.

-
-
-
HostMatch = "ninenines.:_".
-

Similarly, it is possible to have optional segments. Anything -between brackets is optional.

-
-
-
PathMatch = "/hats/[page/:number]".
-HostMatch = "[www.]ninenines.eu".
-

You can also have imbricated optional segments.

-
-
-
PathMatch = "/hats/[page/[:number]]".
-

You can retrieve the rest of the host or path using [...]. -In the case of hosts it will match anything before, in the case -of paths anything after the previously matched segments. It is -a special case of optional segments, in that it can have -zero, one or many segments. You can then find the segments using -cowboy_req:host_info/1 and cowboy_req:path_info/1 respectively. -They will be represented as a list of segments.

-
-
-
PathMatch = "/hats/[...]".
-HostMatch = "[...]ninenines.eu".
-

If a binding appears twice in the routing rules, then the match -will succeed only if they share the same value. This copies the -Erlang pattern matching behavior.

-
-
-
PathMatch = "/hats/:name/:name".
-

This is also true when an optional segment is present. In this -case the two values must be identical only if the segment is -available.

-
-
-
PathMatch = "/hats/:name/[:name]".
-

If a binding is defined in both the host and path, then they must -also share the same value.

-
-
-
PathMatch = "/:user/[...]".
-HostMatch = ":user.github.com".
-

Finally, there are two special match values that can be used. The -first is the atom '_' which will match any host or path.

-
-
-
PathMatch = '_'.
-HostMatch = '_'.
-

The second is the special host match "*" which will match the -wildcard path, generally used alongside the OPTIONS method.

-
-
-
HostMatch = "*".
-
- -
+
HostMatch = "*".
+

Constraints

-
-

After the matching has completed, the resulting bindings can be tested -against a set of constraints. Constraints are only tested when the -binding is defined. They run in the order you defined them. The match -will succeed only if they all succeed. If the match fails, then Cowboy -tries the next route in the list.

-

The format used for constraints is the same as match functions in -cowboy_req: they are provided as a list of fields which may have -one or more constraints. While the router accepts the same format, -it will skip fields with no constraints and will also ignore default -values, if any.

-

Read more about constraints.

-
- -
+

After the matching has completed, the resulting bindings can be tested against a set of constraints. Constraints are only tested when the binding is defined. They run in the order you defined them. The match will succeed only if they all succeed. If the match fails, then Cowboy tries the next route in the list.

+

The format used for constraints is the same as match functions in cowboy_req: they are provided as a list of fields which may have one or more constraints. While the router accepts the same format, it will skip fields with no constraints and will also ignore default values, if any.

+

Read more about constraints.

Compilation

-
-

The routes must be compiled before Cowboy can use them. The compilation -step normalizes the routes to simplify the code and speed up the -execution, but the routes are still looked up one by one in the end. -Faster compilation strategies could be to compile the routes directly -to Erlang code, but would require heavier dependencies.

-

To compile routes, just call the appropriate function:

-
-
-
Dispatch = cowboy_router:compile([
-    %% {HostMatch, list({PathMatch, Handler, InitialState})}
-    {'_', [{'_', my_handler, #{}}]}
+
Dispatch = cowboy_router:compile([
+    %% {HostMatch, list({PathMatch, Handler, InitialState})}
+    {'_', [{'_', my_handler, #{}}]}
 ]),
-%% Name, NbAcceptors, TransOpts, ProtoOpts
-cowboy:start_clear(my_http_listener,
-    [{port, 8080}],
-    #{env => #{dispatch => Dispatch}}
-).
-
-
-
+%% Name, NbAcceptors, TransOpts, ProtoOpts +cowboy:start_clear(my_http_listener, + [{port, 8080}], + #{env => #{dispatch => Dispatch}} +). +

Live update

-
-

You can use the cowboy:set_env/3 function for updating the dispatch -list used by routing. This will apply to all new connections accepted -by the listener:

-
-
-
Dispatch = cowboy_router:compile(Routes),
-cowboy:set_env(my_http_listener, dispatch, Dispatch).
-

Note that you need to compile the routes again before updating.

-
- +
Dispatch = cowboy_router:compile(Routes),
+cowboy:set_env(my_http_listener, dispatch, Dispatch).
+ +

Note that you need to compile the routes again before updating.

+ diff --git a/docs/en/cowboy/2.0/guide/specs/index.html b/docs/en/cowboy/2.0/guide/specs/index.html index 621c9a26..e0ad7ea3 100644 --- a/docs/en/cowboy/2.0/guide/specs/index.html +++ b/docs/en/cowboy/2.0/guide/specs/index.html @@ -62,839 +62,337 @@

HTTP and other specifications

-

This chapter intends to list all the specification documents -for or related to HTTP.

-
+

This chapter intends to list all the specification documents for or related to HTTP.

HTTP

-
- -
+

Current

-
    -
  • -

    -CORS: Cross-Origin Resource Sharing -

    -
  • -
  • -

    -CSP2: Content Security Policy Level 2 -

    -
  • -
  • -

    -DNT: Tracking Preference Expression (DNT) -

    -
  • -
  • -

    -eventsource: Server-Sent Events -

    -
  • -
  • -

    -Form content types: Form content types -

    -
  • -
  • -

    -Preload: Preload -

    -
  • -
  • -

    -REST: Fielding’s Dissertation -

    -
  • -
  • -

    -RFC 1945: HTTP/1.0 -

    -
  • -
  • -

    -RFC 1951: DEFLATE Compressed Data Format Specification version 1.3 -

    -
  • -
  • -

    -RFC 1952: GZIP file format specification version 4.3 -

    -
  • -
  • -

    -RFC 2046: Multipart media type (in MIME Part Two: Media Types) -

    -
  • -
  • -

    -RFC 2295: Transparent Content Negotiation in HTTP -

    -
  • -
  • -

    -RFC 2296: HTTP Remote Variant Selection Algorithm: RVSA/1.0 -

    -
  • -
  • -

    -RFC 2817: Upgrading to TLS Within HTTP/1.1 -

    -
  • -
  • -

    -RFC 2818: HTTP Over TLS -

    -
  • -
  • -

    -RFC 3230: Instance Digests in HTTP -

    -
  • -
  • -

    -RFC 4559: SPNEGO-based Kerberos and NTLM HTTP Authentication in Microsoft Windows -

    -
  • -
  • -

    -RFC 5789: PATCH Method for HTTP -

    -
  • -
  • -

    -RFC 5843: Additional Hash Algorithms for HTTP Instance Digests -

    -
  • -
  • -

    -RFC 5861: HTTP Cache-Control Extensions for Stale Content -

    -
  • -
  • -

    -RFC 5988: Web Linking -

    -
  • -
  • -

    -RFC 6265: HTTP State Management Mechanism -

    -
  • -
  • -

    -RFC 6266: Use of the Content-Disposition Header Field -

    -
  • -
  • -

    -RFC 6454: The Web Origin Concept -

    -
  • -
  • -

    -RFC 6455: The WebSocket Protocol -

    -
  • -
  • -

    -RFC 6585: Additional HTTP Status Codes -

    -
  • -
  • -

    -RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage -

    -
  • -
  • -

    -RFC 6797: HTTP Strict Transport Security (HSTS) -

    -
  • -
  • -

    -RFC 6903: Additional Link Relation Types -

    -
  • -
  • -

    -RFC 7034: HTTP Header Field X-Frame-Options -

    -
  • -
  • -

    -RFC 7089: Time-Based Access to Resource States: Memento -

    -
  • -
  • -

    -RFC 7230: HTTP/1.1 Message Syntax and Routing -

    -
  • -
  • -

    -RFC 7231: HTTP/1.1 Semantics and Content -

    -
  • -
  • -

    -RFC 7232: HTTP/1.1 Conditional Requests -

    -
  • -
  • -

    -RFC 7233: HTTP/1.1 Range Requests -

    -
  • -
  • -

    -RFC 7234: HTTP/1.1 Caching -

    -
  • -
  • -

    -RFC 7235: HTTP/1.1 Authentication -

    -
  • -
  • -

    -RFC 7239: Forwarded HTTP Extension -

    -
  • -
  • -

    -RFC 7240: Prefer Header for HTTP -

    -
  • -
  • -

    -RFC 7469: Public Key Pinning Extension for HTTP -

    -
  • -
  • -

    -RFC 7486: HTTP Origin-Bound Authentication (HOBA) -

    -
  • -
  • -

    -RFC 7538: HTTP Status Code 308 (Permanent Redirect) -

    -
  • -
  • -

    -RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2) -

    -
  • -
  • -

    -RFC 7541: HPACK: Header Compression for HTTP/2 -

    -
  • -
  • -

    -RFC 7578: Returning Values from Forms: multipart/form-data -

    -
  • -
  • -

    -RFC 7615: HTTP Authentication-Info and Proxy-Authentication-Info Response Header Fields -

    -
  • -
  • -

    -RFC 7616: HTTP Digest Access Authentication -

    -
  • -
  • -

    -RFC 7617: The Basic HTTP Authentication Scheme -

    -
  • -
  • -

    -RFC 7639: The ALPN HTTP Header Field -

    -
  • -
  • -

    -RFC 7692: Compression Extensions for WebSocket -

    -
  • -
  • -

    -RFC 7694: HTTP Client-Initiated Content-Encoding -

    -
  • -
  • -

    -RFC 7725: An HTTP Status Code to Report Legal Obstacles -

    -
  • -
  • -

    -RFC 7804: Salted Challenge Response HTTP Authentication Mechanism -

    -
  • -
  • -

    -RFC 7838: HTTP Alternative Services -

    -
  • -
  • -

    -RFC 7932: Brotli Compressed Data Format -

    -
  • -
  • -

    -RFC 7936: Clarifying Registry Procedures for the WebSocket Subprotocol Name Registry -

    -
  • -
  • -

    -RFC 8053: HTTP Authentication Extensions for Interactive Clients -

    -
  • -
  • -

    -RFC 8164: Opportunistic Security for HTTP/2 -

    -
  • -
  • -

    -RFC 8187: Indicating Character Encoding and Language for HTTP Header Field Parameters -

    -
  • -
  • -

    -RFC 8188: Encrypted Content-Encoding for HTTP -

    -
  • -
  • -

    -RFC 8246: HTTP Immutable Responses -

    -
  • -
  • -

    -Webmention: Webmention -

    -
  • -
-
-
+
  • CORS: Cross-Origin Resource Sharing +
  • +
  • CSP2: Content Security Policy Level 2 +
  • +
  • DNT: Tracking Preference Expression (DNT) +
  • +
  • eventsource: Server-Sent Events +
  • +
  • Form content types: Form content types +
  • +
  • Preload: Preload +
  • +
  • REST: Fielding's Dissertation +
  • +
  • RFC 1945: HTTP/1.0 +
  • +
  • RFC 1951: DEFLATE Compressed Data Format Specification version 1.3 +
  • +
  • RFC 1952: GZIP file format specification version 4.3 +
  • +
  • RFC 2046: Multipart media type (in MIME Part Two: Media Types) +
  • +
  • RFC 2295: Transparent Content Negotiation in HTTP +
  • +
  • RFC 2296: HTTP Remote Variant Selection Algorithm: RVSA/1.0 +
  • +
  • RFC 2817: Upgrading to TLS Within HTTP/1.1 +
  • +
  • RFC 2818: HTTP Over TLS +
  • +
  • RFC 3230: Instance Digests in HTTP +
  • +
  • RFC 4559: SPNEGO-based Kerberos and NTLM HTTP Authentication in Microsoft Windows +
  • +
  • RFC 5789: PATCH Method for HTTP +
  • +
  • RFC 5843: Additional Hash Algorithms for HTTP Instance Digests +
  • +
  • RFC 5861: HTTP Cache-Control Extensions for Stale Content +
  • +
  • RFC 5988: Web Linking +
  • +
  • RFC 6265: HTTP State Management Mechanism +
  • +
  • RFC 6266: Use of the Content-Disposition Header Field +
  • +
  • RFC 6454: The Web Origin Concept +
  • +
  • RFC 6455: The WebSocket Protocol +
  • +
  • RFC 6585: Additional HTTP Status Codes +
  • +
  • RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage +
  • +
  • RFC 6797: HTTP Strict Transport Security (HSTS) +
  • +
  • RFC 6903: Additional Link Relation Types +
  • +
  • RFC 7034: HTTP Header Field X-Frame-Options +
  • +
  • RFC 7089: Time-Based Access to Resource States: Memento +
  • +
  • RFC 7230: HTTP/1.1 Message Syntax and Routing +
  • +
  • RFC 7231: HTTP/1.1 Semantics and Content +
  • +
  • RFC 7232: HTTP/1.1 Conditional Requests +
  • +
  • RFC 7233: HTTP/1.1 Range Requests +
  • +
  • RFC 7234: HTTP/1.1 Caching +
  • +
  • RFC 7235: HTTP/1.1 Authentication +
  • +
  • RFC 7239: Forwarded HTTP Extension +
  • +
  • RFC 7240: Prefer Header for HTTP +
  • +
  • RFC 7469: Public Key Pinning Extension for HTTP +
  • +
  • RFC 7486: HTTP Origin-Bound Authentication (HOBA) +
  • +
  • RFC 7538: HTTP Status Code 308 (Permanent Redirect) +
  • +
  • RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2) +
  • +
  • RFC 7541: HPACK: Header Compression for HTTP/2 +
  • +
  • RFC 7578: Returning Values from Forms: multipart/form-data +
  • +
  • RFC 7615: HTTP Authentication-Info and Proxy-Authentication-Info Response Header Fields +
  • +
  • RFC 7616: HTTP Digest Access Authentication +
  • +
  • RFC 7617: The Basic HTTP Authentication Scheme +
  • +
  • RFC 7639: The ALPN HTTP Header Field +
  • +
  • RFC 7692: Compression Extensions for WebSocket +
  • +
  • RFC 7694: HTTP Client-Initiated Content-Encoding +
  • +
  • RFC 7725: An HTTP Status Code to Report Legal Obstacles +
  • +
  • RFC 7804: Salted Challenge Response HTTP Authentication Mechanism +
  • +
  • RFC 7838: HTTP Alternative Services +
  • +
  • RFC 7932: Brotli Compressed Data Format +
  • +
  • RFC 7936: Clarifying Registry Procedures for the WebSocket Subprotocol Name Registry +
  • +
  • RFC 8053: HTTP Authentication Extensions for Interactive Clients +
  • +
  • RFC 8164: Opportunistic Security for HTTP/2 +
  • +
  • RFC 8187: Indicating Character Encoding and Language for HTTP Header Field Parameters +
  • +
  • RFC 8188: Encrypted Content-Encoding for HTTP +
  • +
  • RFC 8246: HTTP Immutable Responses +
  • +
  • Webmention: Webmention +
  • +

Upcoming

- -
-
+

Informative

-
    -
  • -

    -Architecture of the World Wide Web -

    -
  • -
  • -

    -RFC 2936: HTTP MIME Type Handler Detection -

    -
  • -
  • -

    -RFC 2964: Use of HTTP State Management -

    -
  • -
  • -

    -RFC 3143: Known HTTP Proxy/Caching Problems -

    -
  • -
  • -

    -RFC 6202: Known Issues and Best Practices for the Use of Long Polling and Streaming in Bidirectional HTTP -

    -
  • -
  • -

    -RFC 6838: Media Type Specifications and Registration Procedures -

    -
  • -
  • -

    -RFC 7478: Web Real-Time Communication Use Cases and Requirements -

    -
  • -
-
-
+
  • Architecture of the World Wide Web +
  • +
  • RFC 2936: HTTP MIME Type Handler Detection +
  • +
  • RFC 2964: Use of HTTP State Management +
  • +
  • RFC 3143: Known HTTP Proxy/Caching Problems +
  • +
  • RFC 6202: Known Issues and Best Practices for the Use of Long Polling and Streaming in Bidirectional HTTP +
  • +
  • RFC 6838: Media Type Specifications and Registration Procedures +
  • +
  • RFC 7478: Web Real-Time Communication Use Cases and Requirements +
  • +
-
-
-
+

Seemingly obsolete

-
    -
  • -

    -RFC 2227: Simple Hit-Metering and Usage-Limiting for HTTP -

    -
  • -
  • -

    -RFC 2310: The Safe Response Header Field -

    -
  • -
  • -

    -RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) -

    -
  • -
  • -

    -RFC 2660: The Secure HyperText Transfer Protocol -

    -
  • -
  • -

    -RFC 2774: An HTTP Extension Framework -

    -
  • -
  • -

    -RFC 2965: HTTP State Management Mechanism (Cookie2) -

    -
  • -
  • -

    -RFC 3229: Delta encoding in HTTP -

    -
  • -
  • -

    -RFC 7168: The Hyper Text Coffee Pot Control Protocol for Tea Efflux Appliances (HTCPCP-TEA) -

    -
  • -
  • -

    -SPDY: SPDY Protocol -

    -
  • -
  • -

    -x-webkit-deflate-frame: Deprecated Websocket compression -

    -
  • -
-
-
-
-
+
  • RFC 2227: Simple Hit-Metering and Usage-Limiting for HTTP +
  • +
  • RFC 2310: The Safe Response Header Field +
  • +
  • RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) +
  • +
  • RFC 2660: The Secure HyperText Transfer Protocol +
  • +
  • RFC 2774: An HTTP Extension Framework +
  • +
  • RFC 2965: HTTP State Management Mechanism (Cookie2) +
  • +
  • RFC 3229: Delta encoding in HTTP +
  • +
  • RFC 7168: The Hyper Text Coffee Pot Control Protocol for Tea Efflux Appliances (HTCPCP-TEA) +
  • +
  • SPDY: SPDY Protocol +
  • +
  • x-webkit-deflate-frame: Deprecated Websocket compression +
  • +

URL

-
-
-
-
-
+

WebDAV

-
-
    -
  • -

    -RFC 3253: Versioning Extensions to WebDAV -

    -
  • -
  • -

    -RFC 3648: WebDAV Ordered Collections Protocol -

    -
  • -
  • -

    -RFC 3744: WebDAV Access Control Protocol -

    -
  • -
  • -

    -RFC 4316: Datatypes for WebDAV Properties -

    -
  • -
  • -

    -RFC 4331: Quota and Size Properties for DAV Collections -

    -
  • -
  • -

    -RFC 4437: WebDAV Redirect Reference Resources -

    -
  • -
  • -

    -RFC 4709: Mounting WebDAV Servers -

    -
  • -
  • -

    -RFC 4791: Calendaring Extensions to WebDAV (CalDAV) -

    -
  • -
  • -

    -RFC 4918: HTTP Extensions for WebDAV -

    -
  • -
  • -

    -RFC 5323: WebDAV SEARCH -

    -
  • -
  • -

    -RFC 5397: WebDAV Current Principal Extension -

    -
  • -
  • -

    -RFC 5689: Extended MKCOL for WebDAV -

    -
  • -
  • -

    -RFC 5842: Binding Extensions to WebDAV -

    -
  • -
  • -

    -RFC 5995: Using POST to Add Members to WebDAV Collections -

    -
  • -
  • -

    -RFC 6352: CardDAV: vCard Extensions to WebDAV -

    -
  • -
  • -

    -RFC 6578: Collection Synchronization for WebDAV -

    -
  • -
  • -

    -RFC 6638: Scheduling Extensions to CalDAV -

    -
  • -
  • -

    -RFC 6764: Locating Services for Calendaring Extensions to WebDAV (CalDAV) and vCard Extensions to WebDAV (CardDAV) -

    -
  • -
  • -

    -RFC 7809: Calendaring Extensions to WebDAV (CalDAV): Time Zones by Reference -

    -
  • -
  • -

    -RFC 7953: Calendar Availability -

    -
  • -
  • -

    -RFC 8144: Use of the Prefer Header Field in WebDAV -

    -
  • -
-
-
-
+
  • RFC 3253: Versioning Extensions to WebDAV +
  • +
  • RFC 3648: WebDAV Ordered Collections Protocol +
  • +
  • RFC 3744: WebDAV Access Control Protocol +
  • +
  • RFC 4316: Datatypes for WebDAV Properties +
  • +
  • RFC 4331: Quota and Size Properties for DAV Collections +
  • +
  • RFC 4437: WebDAV Redirect Reference Resources +
  • +
  • RFC 4709: Mounting WebDAV Servers +
  • +
  • RFC 4791: Calendaring Extensions to WebDAV (CalDAV) +
  • +
  • RFC 4918: HTTP Extensions for WebDAV +
  • +
  • RFC 5323: WebDAV SEARCH +
  • +
  • RFC 5397: WebDAV Current Principal Extension +
  • +
  • RFC 5689: Extended MKCOL for WebDAV +
  • +
  • RFC 5842: Binding Extensions to WebDAV +
  • +
  • RFC 5995: Using POST to Add Members to WebDAV Collections +
  • +
  • RFC 6352: CardDAV: vCard Extensions to WebDAV +
  • +
  • RFC 6578: Collection Synchronization for WebDAV +
  • +
  • RFC 6638: Scheduling Extensions to CalDAV +
  • +
  • RFC 6764: Locating Services for Calendaring Extensions to WebDAV (CalDAV) and vCard Extensions to WebDAV (CardDAV) +
  • +
  • RFC 7809: Calendaring Extensions to WebDAV (CalDAV): Time Zones by Reference +
  • +
  • RFC 7953: Calendar Availability +
  • +
  • RFC 8144: Use of the Prefer Header Field in WebDAV +
  • +

CoAP

-
-
    -
  • -

    -RFC 7252: The Constrained Application Protocol (CoAP) -

    -
  • -
  • -

    -RFC 7390: Group Communication for CoAP -

    -
  • -
  • -

    -RFC 7641: Observing Resources in CoAP -

    -
  • -
  • -

    -RFC 7650: A CoAP Usage for REsource LOcation And Discovery (RELOAD) -

    -
  • -
  • -

    -RFC 7959: Block-Wise Transfers in CoAP -

    -
  • -
  • -

    -RFC 7967: CoAP Option for No Server Response -

    -
  • -
  • -

    -RFC 8075: Guidelines for Mapping Implementations: HTTP to CoAP -

    -
  • -
  • -

    -RFC 8132: PATCH and FETCH Methods for CoAP -

    -
  • -
-
-
+
  • RFC 7252: The Constrained Application Protocol (CoAP) +
  • +
  • RFC 7390: Group Communication for CoAP +
  • +
  • RFC 7641: Observing Resources in CoAP +
  • +
  • RFC 7650: A CoAP Usage for REsource LOcation And Discovery (RELOAD) +
  • +
  • RFC 7959: Block-Wise Transfers in CoAP +
  • +
  • RFC 7967: CoAP Option for No Server Response +
  • +
  • RFC 8075: Guidelines for Mapping Implementations: HTTP to CoAP +
  • +
  • RFC 8132: PATCH and FETCH Methods for CoAP +
  • +
+ diff --git a/docs/en/cowboy/2.0/guide/static_files/index.html b/docs/en/cowboy/2.0/guide/static_files/index.html index 4d5d248f..26549aa5 100644 --- a/docs/en/cowboy/2.0/guide/static_files/index.html +++ b/docs/en/cowboy/2.0/guide/static_files/index.html @@ -62,173 +62,101 @@

Static files

-

Cowboy comes with a ready to use handler for serving static -files. It is provided as a convenience for serving files -during development.

-

For systems in production, consider using one of the many -Content Distribution Network (CDN) available on the market, -as they are the best solution for serving files.

-

The static handler can serve either one file or all files -from a given directory. The etag generation and mime types -can be configured.

-
+

Cowboy comes with a ready to use handler for serving static files. It is provided as a convenience for serving files during development.

+

For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files.

+

The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured.

Serve one file

-
-

You can use the static handler to serve one specific file -from an application’s private directory. This is particularly -useful to serve an index.html file when the client requests -the / path, for example. The path configured is relative -to the given application’s private directory.

-

The following rule will serve the file static/index.html -from the application my_app's priv directory whenever the -path / is accessed:

-
-
-
{"/", cowboy_static, {priv_file, my_app, "static/index.html"}}
-

You can also specify the absolute path to a file, or the -path to the file relative to the current directory:

-
-
-
{"/", cowboy_static, {file, "/var/www/index.html"}}
-
-
-
+
{"/", cowboy_static, {file, "/var/www/index.html"}}
+

Serve all files from a directory

-
-

You can also use the static handler to serve all files that -can be found in the configured directory. The handler will -use the path_info information to resolve the file location, -which means that your route must end with a [...] pattern -for it to work. All files are served, including the ones that -may be found in subfolders.

-

You can specify the directory relative to an application’s -private directory.

-

The following rule will serve any file found in the application -my_app's priv directory inside the static/assets folder -whenever the requested path begins with /assets/:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets"}}
-

You can also specify the absolute path to the directory or -set it relative to the current directory:

-
-
-
{"/assets/[...]", cowboy_static, {dir, "/var/www/assets"}}
-
- -
+
{"/assets/[...]", cowboy_static, {dir, "/var/www/assets"}}
+

Customize the mimetype detection

-
-

By default, Cowboy will attempt to recognize the mimetype -of your static files by looking at the extension.

-

You can override the function that figures out the mimetype -of the static files. It can be useful when Cowboy is missing -a mimetype you need to handle, or when you want to reduce -the list to make lookups faster. You can also give a -hard-coded mimetype that will be used unconditionally.

-

Cowboy comes with two functions built-in. The default -function only handles common file types used when building -Web applications. The other function is an extensive list -of hundreds of mimetypes that should cover almost any need -you may have. You can of course create your own function.

-

To use the default function, you should not have to configure -anything, as it is the default. If you insist, though, the -following will do the job:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{mimetypes, cow_mimetypes, web}]}}
-

As you can see, there is an optional field that may contain -a list of less used options, like mimetypes or etag. All option -types have this optional field.

-

To use the function that will detect almost any mimetype, -the following configuration will do:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{mimetypes, cow_mimetypes, all}]}}
-

You probably noticed the pattern by now. The configuration -expects a module and a function name, so you can use any -of your own functions instead:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{mimetypes, Module, Function}]}}
-

The function that performs the mimetype detection receives -a single argument that is the path to the file on disk. It -is recommended to return the mimetype in tuple form, although -a binary string is also allowed (but will require extra -processing). If the function can’t figure out the mimetype, -then it should return {<<"application">>, <<"octet-stream">>, []}.

-

When the static handler fails to find the extension, -it will send the file as application/octet-stream. -A browser receiving such file will attempt to download it -directly to disk.

-

Finally, the mimetype can be hard-coded for all files. -This is especially useful in combination with the file -and priv_file options as it avoids needless computation:

-
-
-
{"/", cowboy_static, {priv_file, my_app, "static/index.html",
-    [{mimetypes, {<<"text">>, <<"html">>, []}}]}}
-
- -
+
{"/", cowboy_static, {priv_file, my_app, "static/index.html",
+    [{mimetypes, {<<"text">>, <<"html">>, []}}]}}
+

Generate an etag

-
-

By default, the static handler will generate an etag header -value based on the size and modified time. This solution -can not be applied to all systems though. It would perform -rather poorly over a cluster of nodes, for example, as the -file metadata will vary from server to server, giving a -different etag on each server.

-

You can however change the way the etag is calculated:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{etag, Module, Function}]}}
-

This function will receive three arguments: the path to the -file on disk, the size of the file and the last modification -time. In a distributed setup, you would typically use the -file path to retrieve an etag value that is identical across -all your servers.

-

You can also completely disable etag handling:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{etag, false}]}}
-
- +
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
+    [{etag, false}]}}
+ + diff --git a/docs/en/cowboy/2.0/guide/streams/index.html b/docs/en/cowboy/2.0/guide/streams/index.html index 3f217b1a..3b6dcdde 100644 --- a/docs/en/cowboy/2.0/guide/streams/index.html +++ b/docs/en/cowboy/2.0/guide/streams/index.html @@ -62,61 +62,23 @@

Streams

-

A stream is the set of messages that form an HTTP -request/response pair.

-

The term stream comes from HTTP/2. In Cowboy, it is -also used when talking about HTTP/1.1 or HTTP/1.0. -It should not be confused with streaming the request -or response body.

-

All versions of HTTP allow clients to initiate -streams. HTTP/2 is the only one also allowing servers, -through its server push feature. Both client and -server-initiated streams go through the same process -in Cowboy.

-
+

A stream is the set of messages that form an HTTP request/response pair.

+

The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body.

+

All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy.

Stream handlers

-
-

Stream handlers must implement five different callbacks. -Four of them are directly related; one is special.

-

All callbacks receives the stream ID as first argument.

-

Most of them can return a list of commands to be executed -by Cowboy. When callbacks are chained, it is possible to -intercept and modify these commands. This can be useful -for modifying responses for example.

-

The init/3 callback is invoked when a new request -comes in. It receives the Req object and the protocol options -for this listener.

-

The data/4 callback is invoked when data from the request -body is received. It receives both this data and a flag -indicating whether more is to be expected.

-

The info/3 callback is invoked when an Erlang message is -received for this stream. They will typically be messages -sent by the request process.

-

Finally the terminate/3 callback is invoked with the -terminate reason for the stream. The return value is ignored. -Note that as with all terminate callbacks in Erlang, there -is no strong guarantee that it will be called.

-

The special callback early_error/5 is called when an error -occurs before the request headers were fully received and -Cowboy is sending a response. It receives the partial Req -object, the error reason, the protocol options and the response -Cowboy will send. This response must be returned, possibly -modified.

-
-
-
+

Stream handlers must implement five different callbacks. Four of them are directly related; one is special.

+

All callbacks receives the stream ID as first argument.

+

Most of them can return a list of commands to be executed by Cowboy. When callbacks are chained, it is possible to intercept and modify these commands. This can be useful for modifying responses for example.

+

The init/3 callback is invoked when a new request comes in. It receives the Req object and the protocol options for this listener.

+

The data/4 callback is invoked when data from the request body is received. It receives both this data and a flag indicating whether more is to be expected.

+

The info/3 callback is invoked when an Erlang message is received for this stream. They will typically be messages sent by the request process.

+

Finally the terminate/3 callback is invoked with the terminate reason for the stream. The return value is ignored. Note that as with all terminate callbacks in Erlang, there is no strong guarantee that it will be called.

+

The special callback early_error/5 is called when an error occurs before the request headers were fully received and Cowboy is sending a response. It receives the partial Req object, the error reason, the protocol options and the response Cowboy will send. This response must be returned, possibly modified.

Built-in handlers

-
-

Cowboy comes with two handlers.

-

cowboy_stream_h is the default stream handler. -It is the core of much of the functionality of Cowboy. -All chains of stream handlers should call it last.

-

cowboy_compress_h will automatically compress -responses when possible. It is not enabled by default. -It is a good example for writing your own handlers -that will modify responses.

-
-
+

Cowboy comes with two handlers.

+

cowboy_stream_h is the default stream handler. It is the core of much of the functionality of Cowboy. All chains of stream handlers should call it last.

+

cowboy_compress_h will automatically compress responses when possible. It is not enabled by default. It is a good example for writing your own handlers that will modify responses.

+ diff --git a/docs/en/cowboy/2.0/guide/ws_handlers/index.html b/docs/en/cowboy/2.0/guide/ws_handlers/index.html index 2aa5ffd0..711a5411 100644 --- a/docs/en/cowboy/2.0/guide/ws_handlers/index.html +++ b/docs/en/cowboy/2.0/guide/ws_handlers/index.html @@ -62,270 +62,170 @@

Websocket handlers

-

Websocket handlers provide an interface for upgrading HTTP/1.1 -connections to Websocket and sending or receiving frames on -the Websocket connection.

-

As Websocket connections are established through the HTTP/1.1 -upgrade mechanism, Websocket handlers need to be able to first -receive the HTTP request for the upgrade, before switching to -Websocket and taking over the connection. They can then receive -or send Websocket frames, handle incoming Erlang messages or -close the connection.

-
+

Websocket handlers provide an interface for upgrading HTTP/1.1 connections to Websocket and sending or receiving frames on the Websocket connection.

+

As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection.

Upgrade

-
-

The init/2 callback is called when the request is received. -To establish a Websocket connection, you must switch to the -cowboy_websocket module:

-
-
-
init(Req, State) ->
-    {cowboy_websocket, Req, State}.
-

Cowboy will perform the Websocket handshake immediately. Note -that the handshake will fail if the client did not request an -upgrade to Websocket.

-

The Req object becomes unavailable after this function returns. -Any information required for proper execution of the Websocket -handler must be saved in the state.

-
-
-
-

Subprotocol

-
-

The client may provide a list of Websocket subprotocols it -supports in the sec-websocket-protocol header. The server must -select one of them and send it back to the client or the -handshake will fail.

-

For example, a client could understand both STOMP and MQTT over -Websocket, and provide the header:

-
-
-
sec-websocket-protocol: v12.stomp, mqtt
+
init(Req, State) ->
+    {cowboy_websocket, Req, State}.
-

If the server only understands MQTT it can return:

-
-
-
sec-websocket-protocol: mqtt
-
-

This selection must be done in init/2. An example usage could -be:

-
-
-
init(Req, State) ->
-    case cowboy_req:parse_header(<<"sec-websocket-protocol">>, Req) of
-        undefined ->
-            {cowboy_websocket, Req, State};
-        Subprotocols ->
-            case lists:keymember(<<"mqtt">>, 1, Subprotocols) of
-                true ->
-                    Req2 = cowboy_req:set_resp_header(<<"sec-websocket-protocol">>,
-                        <<"mqtt">>, Req),
-                    {cowboy_websocket, Req2, State};
-                false ->
-                    {stop, Req, State}
-            end
-    end.
-
-
-
+
init(Req, State) ->
+    case cowboy_req:parse_header(<<"sec-websocket-protocol">>, Req) of
+        undefined ->
+            {cowboy_websocket, Req, State};
+        Subprotocols ->
+            case lists:keymember(<<"mqtt">>, 1, Subprotocols) of
+                true ->
+                    Req2 = cowboy_req:set_resp_header(<<"sec-websocket-protocol">>,
+                        <<"mqtt">>, Req),
+                    {cowboy_websocket, Req2, State};
+                false ->
+                    {stop, Req, State}
+            end
+    end.
+

Post-upgrade initialization

-
-

Cowboy has separate processes for handling the connection -and requests. Because Websocket takes over the connection, -the Websocket protocol handling occurs in a different -process than the request handling.

-

This is reflected in the different callbacks Websocket -handlers have. The init/2 callback is called from the -temporary request process and the websocket_ callbacks -from the connection process.

-

This means that some initialization cannot be done from -init/2. Anything that would require the current pid, -or be tied to the current pid, will not work as intended. -The optional websocket_init/1 can be used instead:

-
-
-
websocket_init(State) ->
-    erlang:start_timer(1000, self(), <<"Hello!">>),
-    {ok, State}.
-

All Websocket callbacks share the same return values. This -means that we can send frames to the client right after -the upgrade:

-
-
-
websocket_init(State) ->
-    {reply, {text, <<"Hello!">>}, State}.
-
- -
+
websocket_init(State) ->
+    {reply, {text, <<"Hello!">>}, State}.
+

Receiving frames

-
-

Cowboy will call websocket_handle/2 whenever a text, binary, -ping or pong frame arrives from the client.

-

The handler can handle or ignore the frames. It can also -send frames back to the client or stop the connection.

-

The following snippet echoes back any text frame received and -ignores all others:

-
-
-
websocket_handle(Frame = {text, _}, State) ->
-    {reply, Frame, State};
-websocket_handle(_Frame, State) ->
-    {ok, State}.
-

Note that ping and pong frames require no action from the -handler as Cowboy will automatically reply to ping frames. -They are provided for informative purposes only.

-
- -
+
websocket_handle(Frame = {text, _}, State) ->
+    {reply, Frame, State};
+websocket_handle(_Frame, State) ->
+    {ok, State}.
+
+

Note that ping and pong frames require no action from the handler as Cowboy will automatically reply to ping frames. They are provided for informative purposes only.

Receiving Erlang messages

-
-

Cowboy will call websocket_info/2 whenever an Erlang message -arrives.

-

The handler can handle or ignore the messages. It can also -send frames to the client or stop the connection.

-

The following snippet forwards log messages to the client -and ignores all others:

-
-
-
websocket_info({log, Text}, State) ->
-    {reply, {text, Text}, State};
-websocket_info(_Info, State) ->
-    {ok, State}.
-
- -
+
websocket_info({log, Text}, State) ->
+    {reply, {text, Text}, State};
+websocket_info(_Info, State) ->
+    {ok, State}.
+

Sending frames

-
-

All websocket_ callbacks share return values. They may -send zero, one or many frames to the client.

-

To send nothing, just return an ok tuple:

-
-
+ + +

All websocket_ callbacks share return values. They may send zero, one or many frames to the client.

+

To send nothing, just return an ok tuple:

+
-
websocket_info(_Info, State) ->
-    {ok, State}.
-

To send one frame, return a reply tuple with the frame to send:

-
-
-
websocket_info(_Info, State) ->
-    {reply, {text, <<"Hello!">>}, State}.
-

You can send frames of any type: text, binary, ping, pong -or close frames.

-

To send many frames at once, return a reply tuple with the -list of frames to send:

-
-
-
websocket_info(_Info, State) ->
-    {reply, [
-        {text, "Hello"},
-        {text, <<"world!">>},
-        {binary, <<0:8000>>}
-    ], State}.
-

They are sent in the given order.

-
-
-
+
websocket_info(_Info, State) ->
+    {reply, [
+        {text, "Hello"},
+        {text, <<"world!">>},
+        {binary, <<0:8000>>}
+    ], State}.
+
+

They are sent in the given order.

Keeping the connection alive

-
-

Cowboy will automatically respond to ping frames sent by -the client. They are still forwarded to the handler for -informative purposes, but no further action is required.

-

Cowboy does not send ping frames itself. The handler can -do it if required. A better solution in most cases is to -let the client handle pings. Doing it from the handler -would imply having an additional timer per connection and -this can be a considerable cost for servers that need to -handle large numbers of connections.

-

Cowboy can be configured to close idle connections -automatically. It is highly recommended to configure -a timeout here, to avoid having processes linger longer -than needed.

-

The init/2 callback can set the timeout to be used -for the connection. For example, this would make Cowboy -close connections idle for more than 30 seconds:

-
-
-
init(Req, State) ->
-    {cowboy_websocket, Req, State, #{
-        idle_timeout => 30000}}.
-

This value cannot be changed once it is set. It defaults to -60000.

-
- -
+
init(Req, State) ->
+    {cowboy_websocket, Req, State, #{
+        idle_timeout => 30000}}.
+
+

This value cannot be changed once it is set. It defaults to 60000.

Saving memory

-
-

The Websocket connection process can be set to hibernate -after the callback returns.

-

Simply add an hibernate field to the ok or reply tuples:

-
-
-
websocket_init(State) ->
-    {ok, State, hibernate}.
-
-websocket_handle(_Frame, State) ->
-    {ok, State, hibernate}.
-
-websocket_info(_Info, State) ->
-    {reply, {text, <<"Hello!">>}, State, hibernate}.
-

It is highly recommended to write your handlers with -hibernate enabled, as this allows to greatly reduce the -memory usage. Do note however that an increase in the -CPU usage or latency can be observed instead, in particular -for the more busy connections.

-
- -
+
websocket_init(State) ->
+    {ok, State, hibernate}.
+
+websocket_handle(_Frame, State) ->
+    {ok, State, hibernate}.
+
+websocket_info(_Info, State) ->
+    {reply, {text, <<"Hello!">>}, State, hibernate}.
+
+

It is highly recommended to write your handlers with hibernate enabled, as this allows to greatly reduce the memory usage. Do note however that an increase in the CPU usage or latency can be observed instead, in particular for the more busy connections.

Closing the connection

-
-

The connection can be closed at any time, either by telling -Cowboy to stop it or by sending a close frame.

-

To tell Cowboy to close the connection, use a stop tuple:

-
-
-
websocket_info(_Info, State) ->
-    {stop, State}.
-

Sending a close frame will immediately initiate the closing -of the Websocket connection. Note that when sending a list of -frames that include a close frame, any frame found after the -close frame will not be sent.

-
- +
websocket_info(_Info, State) ->
+    {stop, State}.
+ +

Sending a close frame will immediately initiate the closing of the Websocket connection. Note that when sending a list of frames that include a close frame, any frame found after the close frame will not be sent.

+ diff --git a/docs/en/cowboy/2.0/guide/ws_protocol/index.html b/docs/en/cowboy/2.0/guide/ws_protocol/index.html index 2df74448..aac99f8b 100644 --- a/docs/en/cowboy/2.0/guide/ws_protocol/index.html +++ b/docs/en/cowboy/2.0/guide/ws_protocol/index.html @@ -62,70 +62,22 @@

The Websocket protocol

-

This chapter explains what Websocket is and why it is -a vital component of soft realtime Web applications.

-
+

This chapter explains what Websocket is and why it is a vital component of soft realtime Web applications.

Description

-
-

Websocket is an extension to HTTP that emulates plain TCP -connections between the client, typically a Web browser, -and the server. It uses the HTTP Upgrade mechanism to -establish the connection.

-

Websocket connections are fully asynchronous, unlike -HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the -server can only initiate streams in response to requests). -With Websocket, the client and the server can both send -frames at any time without any restriction. It is closer -to TCP than any of the HTTP protocols.

-

Websocket is an IETF standard. Cowboy supports the standard -and all drafts that were previously implemented by browsers, -excluding the initial flawed draft sometimes known as -"version 0".

-
-
-
+

Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection.

+

Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). With Websocket, the client and the server can both send frames at any time without any restriction. It is closer to TCP than any of the HTTP protocols.

+

Websocket is an IETF standard. Cowboy supports the standard and all drafts that were previously implemented by browsers, excluding the initial flawed draft sometimes known as "version 0".

Websocket vs HTTP/2

-
-

For a few years Websocket was the only way to have a -bidirectional asynchronous connection with the server. -This changed when HTTP/2 was introduced. While HTTP/2 -requires the client to first perform a request before -the server can push data, this is only a minor restriction -as the client can do so just as it connects.

-

Websocket was designed as a kind-of-TCP channel to a -server. It only defines the framing and connection -management and lets the developer implement a protocol -on top of it. For example you could implement IRC over -Websocket and use a Javascript IRC client to speak to -the server.

-

HTTP/2 on the other hand is just an improvement over -the HTTP/1.1 connection and request/response mechanism. -It has the same semantics as HTTP/1.1.

-

If all you need is to access an HTTP API, then HTTP/2 -should be your first choice. On the other hand, if what -you need is a different protocol, then you can use -Websocket to implement it.

-
-
-
+

For a few years Websocket was the only way to have a bidirectional asynchronous connection with the server. This changed when HTTP/2 was introduced. While HTTP/2 requires the client to first perform a request before the server can push data, this is only a minor restriction as the client can do so just as it connects.

+

Websocket was designed as a kind-of-TCP channel to a server. It only defines the framing and connection management and lets the developer implement a protocol on top of it. For example you could implement IRC over Websocket and use a Javascript IRC client to speak to the server.

+

HTTP/2 on the other hand is just an improvement over the HTTP/1.1 connection and request/response mechanism. It has the same semantics as HTTP/1.1.

+

If all you need is to access an HTTP API, then HTTP/2 should be your first choice. On the other hand, if what you need is a different protocol, then you can use Websocket to implement it.

Implementation

-
-

Cowboy implements Websocket as a protocol upgrade. Once the -upgrade is performed from the init/2 callback, Cowboy -switches to Websocket. Please consult the next chapter for -more information on initiating and handling Websocket -connections.

-

The implementation of Websocket in Cowboy is validated using -the Autobahn test suite, which is an extensive suite of tests -covering all aspects of the protocol. Cowboy passes the -suite with 100% success, including all optional tests.

-

Cowboy’s Websocket implementation also includes the -permessage-deflate and x-webkit-deflate-frame compression -extensions.

-

Cowboy will automatically use compression when the -compress option is returned from the init/2 function.

-
-
+

Cowboy implements Websocket as a protocol upgrade. Once the upgrade is performed from the init/2 callback, Cowboy switches to Websocket. Please consult the next chapter for more information on initiating and handling Websocket connections.

+

The implementation of Websocket in Cowboy is validated using the Autobahn test suite, which is an extensive suite of tests covering all aspects of the protocol. Cowboy passes the suite with 100% success, including all optional tests.

+

Cowboy's Websocket implementation also includes the permessage-deflate and x-webkit-deflate-frame compression extensions.

+

Cowboy will automatically use compression when the compress option is returned from the init/2 function.

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy.set_env/index.html b/docs/en/cowboy/2.0/manual/cowboy.set_env/index.html index 1852ba03..13b12f32 100644 --- a/docs/en/cowboy/2.0/manual/cowboy.set_env/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy.set_env/index.html @@ -62,117 +62,59 @@

cowboy:set_env(3)

-

Name

-
-

cowboy:set_env - Update a listener’s environment value

-
-
-
+

cowboy:set_env - Update a listener's environment value

Description

-
-
-
-
set_env(Name  :: ranch:ref(),
-        Key   :: atom(),
-        Value :: any())
-    -> ok
-

Set or update an environment value for a previously started -listener.

-

This is most useful for updating the routes dynamically, -without having to restart the listener.

-

The new value will only be available to new connections. -Pre-existing connections will still use the old value.

-
-
-
+
set_env(Name  :: ranch:ref(),
+        Key   :: atom(),
+        Value :: any())
+    -> ok
+
+

Set or update an environment value for a previously started listener.

+

This is most useful for updating the routes dynamically, without having to restart the listener.

+

The new value will only be available to new connections. Pre-existing connections will still use the old value.

Arguments

-
-
-
-Name -
-
-

-The name of the listener to update. -

-

The name of the listener is the first argument given to the -cowboy:start_clear(3), -cowboy:start_tls(3) or -ranch:start_listener(3) function.

+
Name
+

The name of the listener to update.

+

The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function.

-
-Key -
-
-

-The key in the environment map. Common keys include dispatch -and middlewares. -

+
Key
+

The key in the environment map. Common keys include dispatch and middlewares.

-
-Value -
-
-

-The new value. -

-

The type of the value differs depending on the key.

+
Value
+

The new value.

+

The type of the value differs depending on the key.

-
-
- -
+

Return value

-
-

The atom ok is returned on success.

-

An exit:badarg exception is thrown when the listener does -not exist.

-
-
-
+

The atom ok is returned on success.

+

An exit:badarg exception is thrown when the listener does not exist.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Update a listener’s routes
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []},
-        {"/ws", websocket_h, []}
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []},
+        {"/ws", websocket_h, []}
     ]}
 ]),
 
-cowboy:set_env(example, dispatch, Dispatch).
-
-
-
+cowboy:set_env(example, dispatch, Dispatch). +

See also

- - +

cowboy(3), cowboy:start_clear(3), cowboy:start_tls(3), ranch:set_protocol_options(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy.start_clear/index.html b/docs/en/cowboy/2.0/manual/cowboy.start_clear/index.html index a4fad211..f1eb6c53 100644 --- a/docs/en/cowboy/2.0/manual/cowboy.start_clear/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy.start_clear/index.html @@ -62,148 +62,77 @@

cowboy:start_clear(3)

-

Name

-
-

cowboy:start_clear - Listen for connections using plain TCP

-
-
-
+

cowboy:start_clear - Listen for connections using plain TCP

Description

-
-
-
-
start_clear(Name          :: ranch:ref(),
-            TransportOpts :: ranch_tcp:opts(),
-            ProtocolOpts  :: opts())
-    -> {ok, ListenerPid :: pid()}
-     | {error, any()}
-

Start listening for connections over a clear TCP channel.

-

Both HTTP/1.1 and HTTP/2 are supported on this listener. -HTTP/2 has two methods of establishing a connection over -a clear TCP channel. Both the upgrade and the prior knowledge -methods are supported.

-
-
-
+
start_clear(Name          :: ranch:ref(),
+            TransportOpts :: ranch_tcp:opts(),
+            ProtocolOpts  :: opts())
+    -> {ok, ListenerPid :: pid()}
+     | {error, any()}
+
+

Start listening for connections over a clear TCP channel.

+

Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported.

Arguments

-
-
-
-Name -
-
-

-The listener name is used to refer to this listener in -future calls, for example when stopping it or when -updating the routes defined. -

-

It can be any Erlang term. An atom is generally good enough, -for example api, my_app_clear or my_app_tls.

+
Name
+

The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined.

+

It can be any Erlang term. An atom is generally good enough, for example api, my_app_clear or my_app_tls.

-
-TransportOpts -
-
-

-The transport options are where the TCP options, including -the listener’s port number, are defined. Transport options -are provided as a list of keys and values, for example -[{port, 8080}]. -

-

The available options are documented in the -ranch_tcp(3) manual.

+
TransportOpts
+

The transport options are where the TCP options, including the listener's port number, are defined. Transport options are provided as a list of keys and values, for example [{port, 8080}].

+

The available options are documented in the ranch_tcp(3) manual.

-
-ProtocolOpts -
-
-

-The protocol options are in a map containing all the options for -the different protocols that may be involved when connecting -to the listener, including HTTP/1.1 and HTTP/2. -

-

The HTTP/1.1 options are documented in the -cowboy_http(3) manual; -and the HTTP/2 options in -cowboy_http2(3).

+
ProtocolOpts
+

The protocol options are in a map containing all the options for the different protocols that may be involved when connecting to the listener, including HTTP/1.1 and HTTP/2.

+

The HTTP/1.1 options are documented in the cowboy_http(3) manual; and the HTTP/2 options in cowboy_http2(3).

-
-
- -
+

Return value

-
-

An ok tuple is returned on success. It contains the pid of -the top-level supervisor for the listener.

-

An error tuple is returned on error. The error reason may -be any Erlang term.

-

A common error is eaddrinuse. It indicates that the port -configured for Cowboy is already in use.

-
-
-
+

An ok tuple is returned on success. It contains the pid of the top-level supervisor for the listener.

+

An error tuple is returned on error. The error reason may be any Erlang term.

+

A common error is eaddrinuse. It indicates that the port configured for Cowboy is already in use.

Changelog

-
-
    -
  • -

    -2.0: HTTP/2 support added. -

    +
    • 2.0: HTTP/2 support added.
    • -
    • -

      -2.0: Function introduced. Replaces cowboy:start_http/4. -

      +
    • 2.0: Function introduced. Replaces cowboy:start_http/4.
    • -
-
-
-
+

Examples

-
-
-
Start a listener
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []}
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []}
     ]}
 ]),
 
-{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{
-    env => #{dispatch => Dispatch}
-}).
-
-
Start a listener on a random port
-
-
Name = example,
+
Name = example,
 
-{ok, _} = cowboy:start_clear(Name, [], #{
-    env => #{dispatch => Dispatch}
+{ok, _} = cowboy:start_clear(Name, [], #{
+    env => #{dispatch => Dispatch}
 }),
 
-Port = ranch:get_port(Name).
-
-
-
+Port = ranch:get_port(Name). +

See also

- - +

cowboy(3), cowboy:start_tls(3), cowboy:stop_listener(3), ranch(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy.start_tls/index.html b/docs/en/cowboy/2.0/manual/cowboy.start_tls/index.html index 808766d9..e38e5521 100644 --- a/docs/en/cowboy/2.0/manual/cowboy.start_tls/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy.start_tls/index.html @@ -62,153 +62,82 @@

cowboy:start_tls(3)

-

Name

-
-

cowboy:start_tls - Listen for connections using TLS

-
-
-
+

cowboy:start_tls - Listen for connections using TLS

Description

-
-
-
-
start_tls(Name          :: ranch:ref(),
-          TransportOpts :: ranch_ssl:opts(),
-          ProtocolOpts  :: opts())
-    -> {ok, ListenerPid :: pid()}
-     | {error, any()}
-

Start listening for connections over a secure TLS channel.

-

Both HTTP/1.1 and HTTP/2 are supported on this listener. -The ALPN TLS extension must be used to initiate an HTTP/2 -connection.

-
-
-
+
start_tls(Name          :: ranch:ref(),
+          TransportOpts :: ranch_ssl:opts(),
+          ProtocolOpts  :: opts())
+    -> {ok, ListenerPid :: pid()}
+     | {error, any()}
+
+

Start listening for connections over a secure TLS channel.

+

Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection.

Arguments

-
-
-
-Name -
-
-

-The listener name is used to refer to this listener in -future calls, for example when stopping it or when -updating the routes defined. -

-

It can be any Erlang term. An atom is generally good enough, -for example api, my_app_clear or my_app_tls.

+
Name
+

The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined.

+

It can be any Erlang term. An atom is generally good enough, for example api, my_app_clear or my_app_tls.

-
-TransportOpts -
-
-

-The transport options are where the TCP options, including -the listener’s port number, are defined. They also contain -the TLS options, like the server’s certificate. Transport options -are provided as a list of keys and values, for example -[{port, 8443}, {certfile, "path/to/cert.pem"}]. -

-

The available options are documented in the -ranch_ssl(3) manual.

+
TransportOpts
+

The transport options are where the TCP options, including the listener's port number, are defined. They also contain the TLS options, like the server's certificate. Transport options are provided as a list of keys and values, for example [{port, 8443}, {certfile, "path/to/cert.pem"}].

+

The available options are documented in the ranch_ssl(3) manual.

-
-ProtocolOpts -
-
-

-The protocol options are in a map containing all the options for -the different protocols that may be involved when connecting -to the listener, including HTTP/1.1 and HTTP/2. -

-

The HTTP/1.1 options are documented in the -cowboy_http(3) manual; -and the HTTP/2 options in -cowboy_http2(3).

+
ProtocolOpts
+

The protocol options are in a map containing all the options for the different protocols that may be involved when connecting to the listener, including HTTP/1.1 and HTTP/2.

+

The HTTP/1.1 options are documented in the cowboy_http(3) manual; and the HTTP/2 options in cowboy_http2(3).

-
-
- -
+

Return value

-
-

An ok tuple is returned on success. It contains the pid of -the top-level supervisor for the listener.

-

An error tuple is returned on error. The error reason may -be any Erlang term.

-

A common error is eaddrinuse. It indicates that the port -configured for Cowboy is already in use.

-
-
-
+

An ok tuple is returned on success. It contains the pid of the top-level supervisor for the listener.

+

An error tuple is returned on error. The error reason may be any Erlang term.

+

A common error is eaddrinuse. It indicates that the port configured for Cowboy is already in use.

Changelog

-
-
    -
  • -

    -2.0: HTTP/2 support added. -

    +
    • 2.0: HTTP/2 support added.
    • -
    • -

      -2.0: Function introduced. Replaces cowboy:start_https/4. -

      +
    • 2.0: Function introduced. Replaces cowboy:start_https/4.
    • -
-
-
-
+

Examples

-
-
-
Start a listener
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []}
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []}
     ]}
 ]),
 
-{ok, _} = cowboy:start_tls(example, [
-    {port, 8443},
-    {cert, "path/to/cert.pem"}
+{ok, _} = cowboy:start_tls(example, [
+    {port, 8443},
+    {cert, "path/to/cert.pem"}
 ], #{
-    env => #{dispatch => Dispatch}
-}).
-
-
Start a listener on a random port
-
-
Name = example,
+
Name = example,
 
-{ok, _} = cowboy:start_tls(Name, [
-    {cert, "path/to/cert.pem"}
+{ok, _} = cowboy:start_tls(Name, [
+    {cert, "path/to/cert.pem"}
 ], #{
-    env => #{dispatch => Dispatch}
+    env => #{dispatch => Dispatch}
 }),
 
-Port = ranch:get_port(Name).
-
-
-
+Port = ranch:get_port(Name). +

See also

- - +

cowboy(3), cowboy:start_clear(3), cowboy:stop_listener(3), ranch(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy.stop_listener/index.html b/docs/en/cowboy/2.0/manual/cowboy.stop_listener/index.html index 3d5146b1..5647846f 100644 --- a/docs/en/cowboy/2.0/manual/cowboy.stop_listener/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy.stop_listener/index.html @@ -62,87 +62,42 @@

cowboy:stop_listener(3)

-

Name

-
-

cowboy:stop_listener - Stop the given listener

-
-
-
+

cowboy:stop_listener - Stop the given listener

Description

-
-
-
-
stop_listener(Name :: ranch:ref())
-    -> ok | {error, not_found}.
-

Stop a previously started listener.

- -
-
-
+
stop_listener(Name :: ranch:ref())
+    -> ok | {error, not_found}.
+
+

Stop a previously started listener.

+

Alias of ranch:stop_listener(3).

Arguments

-
-
-
-Name -
-
-

-The name of the listener to be stopped. -

-

The name of the listener is the first argument given to the -cowboy:start_clear(3), -cowboy:start_tls(3) or -ranch:start_listener(3) function.

+
Name
+

The name of the listener to be stopped.

+

The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function.

-
-
- -
+

Return value

-
-

The atom ok is returned on success.

-

The {error, not_found} tuple is returned when the listener -does not exist.

-
-
-
+

The atom ok is returned on success.

+

The {error, not_found} tuple is returned when the listener does not exist.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Stop a listener
-
-
ok = cowboy:stop_listener(example).
-
-
-
+
ok = cowboy:stop_listener(example).
+

See also

- - +

cowboy(3), cowboy:start_clear(3), cowboy:start_tls(3), ranch(3), ranch:start_listener(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy/index.html b/docs/en/cowboy/2.0/manual/cowboy/index.html index b21eb2be..b9efb2c0 100644 --- a/docs/en/cowboy/2.0/manual/cowboy/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy/index.html @@ -62,129 +62,76 @@

cowboy(3)

-

Name

-
-

cowboy - HTTP server

-
-
-
+

cowboy - HTTP server

Description

-
-

The module cowboy provides convenience functions for -manipulating Ranch listeners.

-
-
-
+

The module cowboy provides convenience functions for manipulating Ranch listeners.

Exports

-
-
-
-
-
+

Types

-
-

fields()

-
-
-
fields() :: [Name
-           | {Name, Constraints}
-           | {Name, Constraints, Default}]
-
-Name        :: atom()
-Constraints :: Constraint | [Constraint]
-Constraint  :: cowboy_constraints:constraint()
-Default     :: any()
-

Fields description for match operations.

-

This type is used in cowboy_router(3) -for matching bindings and in the match functions found in -cowboy_req(3).

-
-
+
fields() :: [Name
+           | {Name, Constraints}
+           | {Name, Constraints, Default}]
+
+Name        :: atom()
+Constraints :: Constraint | [Constraint]
+Constraint  :: cowboy_constraints:constraint()
+Default     :: any()
+
+

Fields description for match operations.

+

This type is used in cowboy_router(3) for matching bindings and in the match functions found in cowboy_req(3).

http_headers()

-
-
-
http_headers() :: #{binary() => iodata()}
-

HTTP headers.

-
-
+
http_headers() :: #{binary() => iodata()}
+
+

HTTP headers.

http_status()

-
-
-
http_status() :: non_neg_integer() | binary()
-

HTTP response status.

-

A binary status can be used to set a reason phrase. Note -however that HTTP/2 only sends the status code and drops -the reason phrase entirely.

- -
+
http_status() :: non_neg_integer() | binary()
+
+

HTTP response status.

+

A binary status can be used to set a reason phrase. Note however that HTTP/2 only sends the status code and drops the reason phrase entirely.

http_version()

-
-
-
http_version() :: 'HTTP/2' | 'HTTP/1.1' | 'HTTP/1.0'
-

HTTP version.

-

Note that semantically, HTTP/1.1 and HTTP/2 are equivalent.

- -
+
http_version() :: 'HTTP/2' | 'HTTP/1.1' | 'HTTP/1.0'
+
+

HTTP version.

+

Note that semantically, HTTP/1.1 and HTTP/2 are equivalent.

opts()

-
-
-
opts() :: map()
-

Options for the HTTP/1.1, HTTP/2 and Websocket protocols.

-

The protocol options are in a map containing all the options for -the different protocols that may be involved when connecting -to the listener, including HTTP/1.1 and HTTP/2.

-

The HTTP/1.1 options are documented in the -cowboy_http(3) manual -and the HTTP/2 options in -cowboy_http2(3).

- - - -
+
opts() :: map()
+
+

Options for the HTTP/1.1, HTTP/2 and Websocket protocols.

+

The protocol options are in a map containing all the options for the different protocols that may be involved when connecting to the listener, including HTTP/1.1 and HTTP/2.

+

The HTTP/1.1 options are documented in the cowboy_http(3) manual and the HTTP/2 options in cowboy_http2(3).

See also

- - +

cowboy(7), ranch(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_app/index.html b/docs/en/cowboy/2.0/manual/cowboy_app/index.html index 35f2b325..f0de0290 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_app/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_app/index.html @@ -62,171 +62,77 @@

cowboy(7)

-

Name

-
-

cowboy - Small, fast, modern HTTP server for Erlang/OTP

-
-
-
+

cowboy - Small, fast, modern HTTP server for Erlang/OTP

Description

-
-

Cowboy is an HTTP server for Erlang/OTP with support for the -HTTP/1.1, HTTP/2 and Websocket protocols.

-

Cowboy aims to provide a complete HTTP stack. This includes -the implementation of the HTTP RFCs but also any directly -related standards, like Websocket or Server-Sent Events.

-
-
-
+

Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols.

+

Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events.

Modules

-
-

Functions:

-
-

Protocols:

-
+

Protocols:

+
-

Handlers:

-
+

Handlers:

+
-

Behaviors:

-
+

Behaviors:

+
-

Middlewares:

-
+

Middlewares:

+
-
-
-
+ +

Dependencies

-
-
    -
  • -

    -ranch(7) - Socket acceptor pool for TCP protocols -

    +
    • ranch(7) - Socket acceptor pool for TCP protocols
    • -
    • -

      -cowlib(7) - Support library for manipulating Web protocols -

      +
    • cowlib(7) - Support library for manipulating Web protocols
    • -
    • -

      -ssl - Secure communication over sockets -

      +
    • ssl - Secure communication over sockets
    • -
    • -

      -crypto - Crypto functions -

      +
    • crypto - Crypto functions
    • -
-

All these applications must be started before the cowboy -application. To start Cowboy and all dependencies at once:

-
-
-
{ok, _} = application:ensure_all_started(cowboy).
-
-
-
+
{ok, _} = application:ensure_all_started(cowboy).
+

Environment

-
-

The cowboy application does not define any application -environment configuration parameters.

-
- -
+

The cowboy application does not define any application environment configuration parameters.

See also

- -
+

ranch(7), cowlib(7)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_constraints.int/index.html b/docs/en/cowboy/2.0/manual/cowboy_constraints.int/index.html index cbd43283..f230531b 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_constraints.int/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_constraints.int/index.html @@ -62,92 +62,52 @@

cowboy_constraints:int(3)

-

Name

-
-

cowboy_constraints:int - Integer constraint

-
-
-
+

cowboy_constraints:int - Integer constraint

Description

-
-

Constraint functions implement a number of different operations.

-
-
-
int(forward, Bin) -> {ok, Int} | {error, not_an_integer}
+
int(forward, Bin) -> {ok, Int} | {error, not_an_integer}
 
-Bin :: binary()
-Int :: integer()
-

Validate and convert the text representation of an integer.

-
-
-
int(reverse, Int) -> {ok, Bin} | {error, not_an_integer}
-

Convert an integer back to its text representation.

-
-
-
int(format_error, Error) -> HumanReadable
+
int(format_error, Error) -> HumanReadable
 
-Error         :: {not_an_integer, Bin | Int}
-HumanReadable :: iolist()
-

Generate a human-readable error message.

-
-
-
+Error :: {not_an_integer, Bin | Int} +HumanReadable :: iolist() +
+

Generate a human-readable error message.

Arguments

-
-

Arguments vary depending on the operation. Constraint -functions always take the operation type as first argument, -and the value as second argument.

-
- -
+

Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument.

Return value

-
-

The return value varies depending on the operation.

-
-
-
+

The return value varies depending on the operation.

Changelog

-
-
    -
  • -

    -2.0: Interface modified to allow for a variety of operations. -

    +
    • 2.0: Interface modified to allow for a variety of operations.
    • -
    • -

      -1.0: Constraint introduced. -

      +
    • 1.0: Constraint introduced.
    • -
-
-
-
+

Examples

-
-

This function is not meant to be called directly.

-
-
-
+

This function is not meant to be called directly.

See also

- -
+

cowboy_constraints(3), cowboy_constraints:nonempty(3), cowboy_router(3), cowboy_req:match_cookies(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_constraints.nonempty/index.html b/docs/en/cowboy/2.0/manual/cowboy_constraints.nonempty/index.html index 15f1e5fe..55cb37f4 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_constraints.nonempty/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_constraints.nonempty/index.html @@ -62,91 +62,51 @@

cowboy_constraints:nonempty(3)

-

Name

-
-

cowboy_constraints:nonempty - Non-empty constraint

-
-
-
+

cowboy_constraints:nonempty - Non-empty constraint

Description

-
-

Constraint functions implement a number of different operations.

-
-
-
nonempty(forward | reverse, <<>>) -> {error, empty}
-

Reject empty values.

-
-
-
nonempty(forward | reverse, Bin) -> {ok, Bin}
+
nonempty(forward | reverse, Bin) -> {ok, Bin}
 
-Bin :: binary()
-

Accept any other binary values.

-
-
-
nonempty(format_error, Error) -> HumanReadable
+
nonempty(format_error, Error) -> HumanReadable
 
-Error         :: {empty, Bin}
-HumanReadable :: iolist()
-

Generate a human-readable error message.

-
-
-
+Error :: {empty, Bin} +HumanReadable :: iolist() +
+

Generate a human-readable error message.

Arguments

-
-

Arguments vary depending on the operation. Constraint -functions always take the operation type as first argument, -and the value as second argument.

-
- -
+

Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument.

Return value

-
-

The return value varies depending on the operation.

-
-
-
+

The return value varies depending on the operation.

Changelog

-
-
    -
  • -

    -2.0: Interface modified to allow for a variety of operations. -

    +
    • 2.0: Interface modified to allow for a variety of operations.
    • -
    • -

      -1.0: Constraint introduced. -

      +
    • 1.0: Constraint introduced.
    • -
-
-
-
+

Examples

-
-

This function is not meant to be called directly.

-
-
-
+

This function is not meant to be called directly.

See also

- -
+

cowboy_constraints(3), cowboy_constraints:int(3), cowboy_router(3), cowboy_req:match_cookies(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_constraints/index.html b/docs/en/cowboy/2.0/manual/cowboy_constraints/index.html index 68e79529..d911c464 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_constraints/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_constraints/index.html @@ -62,84 +62,43 @@

cowboy_constraints(3)

-

Name

-
-

cowboy_constraints - Constraints

-
-
-
+

cowboy_constraints - Constraints

Description

-
-

The module cowboy_constraints defines the built-in -constraints in Cowboy and provides an interface for -manipulating these constraints.

-

Constraints are functions that define what type of -input is allowed. They are used throughout Cowboy, -from the router to query strings to cookies.

-
-
-
+

The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints.

+

Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies.

Exports

-
-

Built-in constraints:

-
-
-
-
+

Types

-
-

constraint()

-
-
-
constraint() :: int | nonempty | fun()
-

A constraint function.

-

The atom constraints are built-in, see the corresponding -function in the exports list above.

-
-
+
constraint() :: int | nonempty | fun()
+
+

A constraint function.

+

The atom constraints are built-in, see the corresponding function in the exports list above.

reason()

-
-
-
reason() :: {constraint(), Reason, Value}
-
-Reason :: any()
-Value  :: any()
-

Reason for the constraint failure.

-

It includes the constraint function in question, -a machine-readable error reason and the value that -made the constraint fail.

-
- - -
+
reason() :: {constraint(), Reason, Value}
+
+Reason :: any()
+Value  :: any()
+
+

Reason for the constraint failure.

+

It includes the constraint function in question, a machine-readable error reason and the value that made the constraint fail.

See also

- - +

cowboy(7), cowboy(3), cowboy_router(3), cowboy_req:match_cookies(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_handler.terminate/index.html b/docs/en/cowboy/2.0/manual/cowboy_handler.terminate/index.html index 5c4315c0..16a2bd69 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_handler.terminate/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_handler.terminate/index.html @@ -62,109 +62,54 @@

cowboy_handler:terminate(3)

-

Name

-
-

cowboy_handler:terminate - Terminate the handler

-
-
-
+

cowboy_handler:terminate - Terminate the handler

Description

-
-
-
-
terminate(Reason, PartialReq, State, Handler) -> ok
-
-Reason     :: any()
-PartialReq :: map()
-State      :: any()
-Handler    :: module()
-

Call the optional terminate callback if it is defined.

-

Make sure to use this function at the end of the execution -of modules that implement custom handler behaviors.

-
-
-
+
terminate(Reason, PartialReq, State, Handler) -> ok
+
+Reason     :: any()
+PartialReq :: map()
+State      :: any()
+Handler    :: module()
+
+

Call the optional terminate callback if it is defined.

+

Make sure to use this function at the end of the execution of modules that implement custom handler behaviors.

Arguments

-
-
-
-Reason -
-
-

-Reason for termination. -

+
Reason
+

Reason for termination.

-
-PartialReq -
-
-

-The Req object. -

-

It is possible to remove fields from the Req object to save memory -when the handler has no concept of requests/responses. The only -requirement is that a map is provided.

+
PartialReq
+

The Req object.

+

It is possible to remove fields from the Req object to save memory when the handler has no concept of requests/responses. The only requirement is that a map is provided.

-
-State -
-
-

-Handler state. -

+
State
+

Handler state.

-
-Handler -
-
-

-Handler module. -

+
Handler
+

Handler module.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Terminate a handler normally
-
-
cowboy_handler:terminate(normal, Req, State, Handler).
-
-
-
+
cowboy_handler:terminate(normal, Req, State, Handler).
+

See also

- - +

cowboy_handler(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_handler/index.html b/docs/en/cowboy/2.0/manual/cowboy_handler/index.html index bb7d2df7..ae108976 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_handler/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_handler/index.html @@ -62,96 +62,46 @@

cowboy_handler(3)

-

Name

-
-

cowboy_handler - Plain HTTP handlers

-
-
-
+

cowboy_handler - Plain HTTP handlers

Description

-
-

The cowboy_handler middleware executes the handler selected -by the router or any other preceding middleware.

-

This middleware takes the handler module and initial state -from the handler and handler_opts environment values, -respectively. On completion, it adds a result value to -the middleware environment, containing the return value -of the terminate/3 callback (if defined) and ok otherwise.

-

This module also defines a callback interface for handling -HTTP requests.

-
-
-
+

The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware.

+

This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise.

+

This module also defines a callback interface for handling HTTP requests.

Callbacks

-
-

Plain HTTP handlers implement the following interface:

-
-
-
init(Req, State) -> {ok, Req, State}
-
-terminate(Reason, Req, State) -> ok  %% optional
-
-Req    :: cowboy_req:req()
-State  :: any()
-Reason :: normal
-        | {crash, error | exit | throw, any()}
-

These two callbacks are common to all handlers.

-

Plain HTTP handlers do all their work in the init/2 -callback. Returning ok terminates the handler. If no -response is sent, Cowboy will send a 204 No Content.

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the handler. -Cowboy will terminate the process right after this. There -is no need to perform any cleanup in this callback.

-

The following terminate reasons are defined for plain HTTP -handlers:

-
-
-normal -
-
-

- The connection was closed normally. -

+
init(Req, State) -> {ok, Req, State}
+
+terminate(Reason, Req, State) -> ok  %% optional
+
+Req    :: cowboy_req:req()
+State  :: any()
+Reason :: normal
+        | {crash, error | exit | throw, any()}
+
+

These two callbacks are common to all handlers.

+

Plain HTTP handlers do all their work in the init/2 callback. Returning ok terminates the handler. If no response is sent, Cowboy will send a 204 No Content.

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the handler. Cowboy will terminate the process right after this. There is no need to perform any cleanup in this callback.

+

The following terminate reasons are defined for plain HTTP handlers:

+
normal
+

The connection was closed normally.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
- - -
+

Exports

-
-

The following function should be called by modules implementing -custom handlers to execute the optional terminate callback:

-
-
-
-
+

See also

- -
+

cowboy(7)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_http/index.html b/docs/en/cowboy/2.0/manual/cowboy_http/index.html index 50f6d20f..8a635726 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_http/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_http/index.html @@ -62,240 +62,110 @@

cowboy_http(3)

-

Name

-
-

cowboy_http - HTTP/1.1

-
-
-
+

cowboy_http - HTTP/1.1

Description

-
-

The module cowboy_http implements HTTP/1.1 and HTTP/1.0 -as a Ranch protocol.

-
-
-
+

The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol.

Options

-
-
-
+ +
-
opts() :: #{
-    connection_type         => worker | supervisor,
-    env                     => cowboy_middleware:env(),
-    idle_timeout            => timeout(),
-    inactivity_timeout      => timeout(),
-    max_empty_lines         => non_neg_integer(),
-    max_header_name_length  => non_neg_integer(),
-    max_header_value_length => non_neg_integer(),
-    max_headers             => non_neg_integer(),
-    max_keepalive           => non_neg_integer(),
-    max_method_length       => non_neg_integer(),
-    max_request_line_length => non_neg_integer(),
-    middlewares             => [module()],
-    request_timeout         => timeout(),
-    shutdown_timeout        => timeout(),
-    stream_handlers         => [module()]
-}
-

Configuration for the HTTP/1.1 protocol.

-

This configuration is passed to Cowboy when starting listeners -using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

-

It can be updated without restarting listeners using the -Ranch functions ranch:get_protocol_options/1 and -ranch:set_protocol_options/2.

-

The default value is given next to the option name:

-
-
-connection_type (supervisor) -
-
-

- Whether the connection process also acts as a supervisor. -

+
opts() :: #{
+    connection_type         => worker | supervisor,
+    env                     => cowboy_middleware:env(),
+    idle_timeout            => timeout(),
+    inactivity_timeout      => timeout(),
+    max_empty_lines         => non_neg_integer(),
+    max_header_name_length  => non_neg_integer(),
+    max_header_value_length => non_neg_integer(),
+    max_headers             => non_neg_integer(),
+    max_keepalive           => non_neg_integer(),
+    max_method_length       => non_neg_integer(),
+    max_request_line_length => non_neg_integer(),
+    middlewares             => [module()],
+    request_timeout         => timeout(),
+    shutdown_timeout        => timeout(),
+    stream_handlers         => [module()]
+}
+
+

Configuration for the HTTP/1.1 protocol.

+

This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

+

It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2.

+

The default value is given next to the option name:

+
connection_type (supervisor)
+

Whether the connection process also acts as a supervisor.

-
-env (#{}) -
-
-

- Middleware environment. -

+
env (#{})
+

Middleware environment.

-
-idle_timeout (60000) -
-
-

- Time in ms with no data received before Cowboy closes the connection. -

+
idle_timeout (60000)
+

Time in ms with no data received before Cowboy closes the connection.

-
-inactivity_timeout (300000) -
-
-

- Time in ms with nothing received at all before Cowboy closes the connection. -

+
inactivity_timeout (300000)
+

Time in ms with nothing received at all before Cowboy closes the connection.

-
-max_empty_lines (5) -
-
-

- Maximum number of empty lines before a request. -

+
max_empty_lines (5)
+

Maximum number of empty lines before a request.

-
-max_header_name_length (64) -
-
-

- Maximum length of header names. -

+
max_header_name_length (64)
+

Maximum length of header names.

-
-max_header_value_length (4096) -
-
-

- Maximum length of header values. -

+
max_header_value_length (4096)
+

Maximum length of header values.

-
-max_headers (100) -
-
-

- Maximum number of headers allowed per request. -

+
max_headers (100)
+

Maximum number of headers allowed per request.

-
-max_keepalive (100) -
-
-

- Maximum number of requests allowed per connection. -

+
max_keepalive (100)
+

Maximum number of requests allowed per connection.

-
-max_method_length (32) -
-
-

- Maximum length of the method. -

+
max_method_length (32)
+

Maximum length of the method.

-
-max_request_line_length (8000) -
-
-

- Maximum length of the request line. -

+
max_request_line_length (8000)
+

Maximum length of the request line.

-
-middlewares ([cowboy_router, cowboy_handler]) -
-
-

- Middlewares to run for every request. -

+
middlewares ([cowboy_router, cowboy_handler])
+

Middlewares to run for every request.

-
-request_timeout (5000) -
-
-

- Time in ms with no requests before Cowboy closes the connection. -

+
request_timeout (5000)
+

Time in ms with no requests before Cowboy closes the connection.

-
-shutdown_timeout (5000) -
-
-

- Time in ms Cowboy will wait for child processes to shut down before killing them. -

+
shutdown_timeout (5000)
+

Time in ms Cowboy will wait for child processes to shut down before killing them.

-
-stream_handlers ([cowboy_stream_h]) -
-
-

- Ordered list of stream handlers that will handle all stream events. -

+
stream_handlers ([cowboy_stream_h])
+

Ordered list of stream handlers that will handle all stream events.

-
-
-
-
+

Changelog

-
-
    -
  • -

    -2.0: The timeout option was renamed request_timeout. -

    +
    • 2.0: The timeout option was renamed request_timeout.
    • -
    • -

      -2.0: The idle_timeout, inactivity_timeout and shutdown_timeout options were added. -

      +
    • 2.0: The idle_timeout, inactivity_timeout and shutdown_timeout options were added.
    • -
    • -

      -2.0: The max_method_length option was added. -

      +
    • 2.0: The max_method_length option was added.
    • -
    • -

      -2.0: The max_request_line_length default was increased from 4096 to 8000. -

      +
    • 2.0: The max_request_line_length default was increased from 4096 to 8000.
    • -
    • -

      -2.0: The connection_type option was added. -

      +
    • 2.0: The connection_type option was added.
    • -
    • -

      -2.0: The env option is now a map instead of a proplist. -

      +
    • 2.0: The env option is now a map instead of a proplist.
    • -
    • -

      -2.0: The stream_handlers option was added. -

      +
    • 2.0: The stream_handlers option was added.
    • -
    • -

      -2.0: The compress option was removed in favor of the cowboy_compress_h stream handler. -

      +
    • 2.0: The compress option was removed in favor of the cowboy_compress_h stream handler.
    • -
    • -

      -2.0: Options are now a map instead of a proplist. -

      +
    • 2.0: Options are now a map instead of a proplist.
    • -
    • -

      -2.0: Protocol introduced. Replaces cowboy_protocol. -

      +
    • 2.0: Protocol introduced. Replaces cowboy_protocol.
    • -
-
-
- +

cowboy(7), cowboy_http2(3), cowboy_websocket(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_http2/index.html b/docs/en/cowboy/2.0/manual/cowboy_http2/index.html index 89262ad6..041074f5 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_http2/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_http2/index.html @@ -62,123 +62,60 @@

cowboy_http2(3)

-

Name

-
-

cowboy_http2 - HTTP/2

-
-
-
+

cowboy_http2 - HTTP/2

Description

-
-

The module cowboy_http2 implements HTTP/2 -as a Ranch protocol.

-
-
-
+

The module cowboy_http2 implements HTTP/2 as a Ranch protocol.

Options

-
-
-
+ +
-
opts() :: #{
-    connection_type    => worker | supervisor,
-    env                => cowboy_middleware:env(),
-    inactivity_timeout => timeout(),
-    middlewares        => [module()],
-    preface_timeout    => timeout(),
-    shutdown_timeout   => timeout(),
-    stream_handlers    => [module()]
-}
-

Configuration for the HTTP/2 protocol.

-

This configuration is passed to Cowboy when starting listeners -using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

-

It can be updated without restarting listeners using the -Ranch functions ranch:get_protocol_options/1 and -ranch:set_protocol_options/2.

-

The default value is given next to the option name:

-
-
-connection_type (supervisor) -
-
-

- Whether the connection process also acts as a supervisor. -

+
opts() :: #{
+    connection_type    => worker | supervisor,
+    env                => cowboy_middleware:env(),
+    inactivity_timeout => timeout(),
+    middlewares        => [module()],
+    preface_timeout    => timeout(),
+    shutdown_timeout   => timeout(),
+    stream_handlers    => [module()]
+}
+
+

Configuration for the HTTP/2 protocol.

+

This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

+

It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2.

+

The default value is given next to the option name:

+
connection_type (supervisor)
+

Whether the connection process also acts as a supervisor.

-
-env (#{}) -
-
-

- Middleware environment. -

+
env (#{})
+

Middleware environment.

-
-inactivity_timeout (300000) -
-
-

- Time in ms with nothing received at all before Cowboy closes the connection. -

+
inactivity_timeout (300000)
+

Time in ms with nothing received at all before Cowboy closes the connection.

-
-middlewares ([cowboy_router, cowboy_handler]) -
-
-

- Middlewares to run for every request. -

+
middlewares ([cowboy_router, cowboy_handler])
+

Middlewares to run for every request.

-
-preface_timeout (5000) -
-
-

- Time in ms Cowboy is willing to wait for the connection preface. -

+
preface_timeout (5000)
+

Time in ms Cowboy is willing to wait for the connection preface.

-
-shutdown_timeout (5000) -
-
-

- Time in ms Cowboy will wait for child processes to shut down before killing them. -

+
shutdown_timeout (5000)
+

Time in ms Cowboy will wait for child processes to shut down before killing them.

-
-stream_handlers ([cowboy_stream_h]) -
-
-

- Ordered list of stream handlers that will handle all stream events. -

+
stream_handlers ([cowboy_stream_h])
+

Ordered list of stream handlers that will handle all stream events.

-
-
-
-
+

Changelog

-
-
    -
  • -

    -2.0: Protocol introduced. -

    +
    • 2.0: Protocol introduced.
    • -
-
-
- +

cowboy(7), cowboy_http(3), cowboy_websocket(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_loop/index.html b/docs/en/cowboy/2.0/manual/cowboy_loop/index.html index 3bf8477c..c9f639be 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_loop/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_loop/index.html @@ -62,120 +62,60 @@

cowboy_loop(3)

-

Name

-
-

cowboy_loop - Loop handlers

-
-
-
+

cowboy_loop - Loop handlers

Description

-
-

The module cowboy_loop defines a callback interface for -long running HTTP connections.

-

You should switch to this behavior for long polling, -server-sent events and similar long-running requests.

-

There are generally two usage patterns:

-
    -
  • -

    -Loop until receiving a specific message, then send - a response and stop execution (for example long polling); -

    +

    The module cowboy_loop defines a callback interface for long running HTTP connections.

    +

    You should switch to this behavior for long polling, server-sent events and similar long-running requests.

    +

    There are generally two usage patterns:

    +
    • Loop until receiving a specific message, then send a response and stop execution (for example long polling);
    • -
    • -

      -Or initiate a response in init/2 and stream the - body in info/3 as necessary (for example server-sent events). -

      +
    • Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events).
    • -
-
-
-
+

Callbacks

-
-

Loop handlers implement the following interface:

-
-
-
init(Req, State)
-    -> {cowboy_loop, Req, State}
-     | {cowboy_loop, Req, State, hibernate}
-
-info(Info, Req, State)
-    -> {ok, Req, State}
-     | {ok, Req, State, hibernate}
-     | {stop, Req, State}
-
-terminate(Reason, Req, State) -> ok  %% optional
-
-Req    :: cowboy_req:req()
-State  :: any()
-Info   :: any()
-Reason :: stop
-        | {crash, error | exit | throw, any()}
-

The init/2 callback is common to all handlers. To switch -to the loop behavior, it must return cowboy_loop as the -first element of the tuple.

-

The info/3 callback will be called for every Erlang message -received. It may choose to continue the receive loop or stop -it.

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the handler. -Cowboy will terminate the process right after this. There -is no need to perform any cleanup in this callback.

-

The following terminate reasons are defined for loop handlers:

-
-
-stop -
-
-

- The handler requested to close the connection by returning - a stop tuple. -

+
init(Req, State)
+    -> {cowboy_loop, Req, State}
+     | {cowboy_loop, Req, State, hibernate}
+
+info(Info, Req, State)
+    -> {ok, Req, State}
+     | {ok, Req, State, hibernate}
+     | {stop, Req, State}
+
+terminate(Reason, Req, State) -> ok  %% optional
+
+Req    :: cowboy_req:req()
+State  :: any()
+Info   :: any()
+Reason :: stop
+        | {crash, error | exit | throw, any()}
+
+

The init/2 callback is common to all handlers. To switch to the loop behavior, it must return cowboy_loop as the first element of the tuple.

+

The info/3 callback will be called for every Erlang message received. It may choose to continue the receive loop or stop it.

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the handler. Cowboy will terminate the process right after this. There is no need to perform any cleanup in this callback.

+

The following terminate reasons are defined for loop handlers:

+
stop
+

The handler requested to close the connection by returning a stop tuple.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
- - -
+

Changelog

-
-
    -
  • -

    -2.0: Loop handlers no longer need to handle overflow/timeouts. -

    +
    • 2.0: Loop handlers no longer need to handle overflow/timeouts.
    • -
    • -

      -1.0: Behavior introduced. -

      +
    • 1.0: Behavior introduced.
    • -
-
-
-
+

See also

- -
+

cowboy(7), cowboy_handler(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_middleware/index.html b/docs/en/cowboy/2.0/manual/cowboy_middleware/index.html index aa7ffb0f..256644be 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_middleware/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_middleware/index.html @@ -62,115 +62,56 @@

cowboy_middleware(3)

-

Name

-
-

cowboy_middleware - Middlewares

-
-
-
+

cowboy_middleware - Middlewares

Description

-
-

The module cowboy_middleware defines a callback interface for -Cowboy middlewares.

-

Middlewares process the request sequentially in the order they -are configured.

-
-
-
+

The module cowboy_middleware defines a callback interface for Cowboy middlewares.

+

Middlewares process the request sequentially in the order they are configured.

Callbacks

-
-

Middlewares implement the following interface:

-
-
-
execute(Req, Env)
-    -> {ok, Req, Env}
-     | {suspend, module(), atom(), [any()]}
-     | {stop, Req}
-
-Req :: cowboy_req:req()
-Env :: cowboy_middleware:env()
-

The execute/2 is the only callback that needs to be -implemented. It must execute the middleware and return -with instructions for Cowboy.

-
-
-ok -
-
-

-Cowboy should continue processing the request using the -returned Req object and environment. -

+
execute(Req, Env)
+    -> {ok, Req, Env}
+     | {suspend, module(), atom(), [any()]}
+     | {stop, Req}
+
+Req :: cowboy_req:req()
+Env :: cowboy_middleware:env()
+
+

The execute/2 is the only callback that needs to be implemented. It must execute the middleware and return with instructions for Cowboy.

+
ok
+

Cowboy should continue processing the request using the returned Req object and environment.

-
-suspend -
-
-

-Cowboy will hibernate the process. When resuming, Cowboy -will apply the returned module, function and arguments. -

+
suspend
+

Cowboy will hibernate the process. When resuming, Cowboy will apply the returned module, function and arguments.

-
-stop -
-
-

-Cowboy will stop middleware execution. No other middleware -will be executed. This effectively ends the processing of -the request. -

+
stop
+

Cowboy will stop middleware execution. No other middleware will be executed. This effectively ends the processing of the request.

-
- - -
+

Types

-
-

env()

-
-
-
env() :: #{atom() => any()}
-

Middleware environment.

-

A new environment is created for every request. The initial -environment contained the user configured environment values -(like dispatch for example) plus the listener value which -contains the name of the listener for this connection.

-

Middlewares may modify the environment as necessary.

-
-
-
-
+
env() :: #{atom() => any()}
+
+

Middleware environment.

+

A new environment is created for every request. The initial environment contained the user configured environment values (like dispatch for example) plus the listener value which contains the name of the listener for this connection.

+

Middlewares may modify the environment as necessary.

Changelog

-
-
    -
  • -

    -2.0: The env type is now a map instead of a proplist. -

    +
    • 2.0: The env type is now a map instead of a proplist.
    • -
    • -

      -1.0: Behavior introduced. -

      +
    • 1.0: Behavior introduced.
    • -
-
- -
+

See also

- -
+

cowboy(7)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.binding/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.binding/index.html index ae3d37dc..d5a4b18e 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.binding/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.binding/index.html @@ -62,116 +62,60 @@

cowboy_req:binding(3)

-

Name

-
-

cowboy_req:binding - Access a value bound from the route

-
-
-
+

cowboy_req:binding - Access a value bound from the route

Description

-
-
-
-
binding(Name, Req)          -> binding(Name, Req, undefined)
-binding(Name, Req, Default) -> any() | Default
-
-Name    :: atom()
-Req     :: cowboy_req:req()
-Default :: any()
-

Return the value for the given binding.

-
-
-
+
binding(Name, Req)          -> binding(Name, Req, undefined)
+binding(Name, Req, Default) -> any() | Default
+
+Name    :: atom()
+Req     :: cowboy_req:req()
+Default :: any()
+
+

Return the value for the given binding.

Arguments

-
-
-
-Name -
-
-

-Desired binding name as an atom. -

+
Name
+

Desired binding name as an atom.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the binding is missing. -

+
Default
+

Default value returned when the binding is missing.

-
-
- -
+

Return value

-
-

By default the value is a case sensitive binary string, however -constraints may change the type of this value (for example -automatically converting numbers to integer).

-
-
-
+

By default the value is a case sensitive binary string, however constraints may change the type of this value (for example automatically converting numbers to integer).

Changelog

-
-
    -
  • -

    -2.0: Only the value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the username from the path
-
-
%% Route is "/users/:user"
-Username = cowboy_req:binding(user, Req).
-
-
Get the branch name, with a default
-
-
%% Route is "/log[/:branch]"
-Branch = cowboy_req:binding(branch, Req, <<"master">>)
-
-
-
+
%% Route is "/log[/:branch]"
+Branch = cowboy_req:binding(branch, Req, <<"master">>)
+

See also

- - +

cowboy_req(3), cowboy_req:bindings(3), cowboy_req:host_info(3), cowboy_req:path_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.bindings/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.bindings/index.html index 314ddd5c..f1c68012 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.bindings/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.bindings/index.html @@ -62,86 +62,40 @@

cowboy_req:bindings(3)

-

Name

-
-

cowboy_req:bindings - Access all values bound from the route

-
-
-
+

cowboy_req:bindings - Access all values bound from the route

Description

-
-
-
-
bindings(Req :: cowboy_req:req()) -> cowboy_router:bindings()
-

Return a map containing all bindings.

-
-
-
+
bindings(Req :: cowboy_req:req()) -> cowboy_router:bindings()
+
+

Return a map containing all bindings.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

By default values are case sensitive binary strings, however -constraints may change the type of this value (for example -automatically converting numbers to integer).

-
-
-
+

By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer).

Changelog

-
-
    -
  • -

    -2.0: Only the values are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the values are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get all bindings
-
-
Bindings = cowboy_req:bindings(Req).
-
-
-
+
Bindings = cowboy_req:bindings(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:host_info(3), cowboy_req:path_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.body_length/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.body_length/index.html index a882ba8f..348b51dd 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.body_length/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.body_length/index.html @@ -62,89 +62,41 @@

cowboy_req:body_length(3)

-

Name

-
-

cowboy_req:body_length - Body length

-
-
-
+

cowboy_req:body_length - Body length

Description

-
-
-
-
body_length(Req :: cowboy_req:req()) -> undefined | non_neg_integer()
-

Return the length of the request body.

-

The length is not always known before reading the body. -In those cases Cowboy will return undefined. The body -length is available after the body has been fully read.

-
-
-
+
body_length(Req :: cowboy_req:req()) -> undefined | non_neg_integer()
+
+

Return the length of the request body.

+

The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The length of the request body, or undefined if it is -not known.

-
-
-
+

The length of the request body, or undefined if it is not known.

Changelog

-
-
    -
  • -

    -2.0: Only the length is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the length is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the body length
-
-
Length = cowboy_req:body_length(Req).
-
-
-
+
Length = cowboy_req:body_length(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.delete_resp_header/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.delete_resp_header/index.html index 370e66b9..75fe7479 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.delete_resp_header/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.delete_resp_header/index.html @@ -62,95 +62,45 @@

cowboy_req:delete_resp_header(3)

-

Name

-
-

cowboy_req:delete_resp_header - Delete a response header

-
-
-
+

cowboy_req:delete_resp_header - Delete a response header

Description

-
-
-
-
delete_resp_header(Name, Req :: cowboy_req:req()) -> Req
+
delete_resp_header(Name, Req :: cowboy_req:req()) -> Req
 
-Name :: binary()  %% lowercase; case insensitive
-

Delete the given response header.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+Name :: binary() %% lowercase; case insensitive +
+

Delete the given response header.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Name -
-
-

-Header name as a lowercase binary string. -

+
Name
+

Header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the header will still be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the header will still be sent in the response.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Remove the content-type header from the response
-
-
Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),
-
-
-
+
Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:has_resp_header(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.has_body/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.has_body/index.html index 31d28cd7..a8b0cf73 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.has_body/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.has_body/index.html @@ -62,80 +62,38 @@

cowboy_req:has_body(3)

-

Name

-
-

cowboy_req:has_body - Is there a request body?

-
-
-
+

cowboy_req:has_body - Is there a request body?

Description

-
-
-
-
has_body(Req :: cowboy_req:req()) -> boolean()
-

Return whether the request has a body.

-
-
-
+
has_body(Req :: cowboy_req:req()) -> boolean()
+
+

Return whether the request has a body.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A boolean indicating whether the request has a body.

-
-
-
+

A boolean indicating whether the request has a body.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Ensure the request has a body
-
-
true = cowboy_req:has_body(Req).
-
-
-
+
true = cowboy_req:has_body(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.has_resp_body/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.has_resp_body/index.html index 4629681d..361094ad 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.has_resp_body/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.has_resp_body/index.html @@ -62,82 +62,43 @@

cowboy_req:has_resp_body(3)

-

Name

-
-

cowboy_req:has_resp_body - Is there a response body?

-
-
-
+

cowboy_req:has_resp_body - Is there a response body?

Description

-
-
-
-
has_resp_body(Req :: cowboy_req:req()) -> boolean()
-

Return whether a response body has been set.

-
-
-
+
has_resp_body(Req :: cowboy_req:req()) -> boolean()
+
+

Return whether a response body has been set.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A boolean indicating whether a response body has been set.

-

This function will return false when an empty response -body has been set.

-
-
-
+

A boolean indicating whether a response body has been set.

+

This function will return false when an empty response body has been set.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Check whether a body has been set
-
-
false = cowboy_req:has_resp_body(Req0),
-Req1 = cowboy_req:set_resp_body(<<"Hello!">>, Req0),
-true = cowboy_req:has_resp_body(Req1),
-Req = cowboy_req:set_resp_body(<<>>, Req1),
-false = cowboy_req:has_resp_body(Req).
-
-
-
+
false = cowboy_req:has_resp_body(Req0),
+Req1 = cowboy_req:set_resp_body(<<"Hello!">>, Req0),
+true = cowboy_req:has_resp_body(Req1),
+Req = cowboy_req:set_resp_body(<<>>, Req1),
+false = cowboy_req:has_resp_body(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_body(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.has_resp_header/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.has_resp_header/index.html index a060df4b..fb1176db 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.has_resp_header/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.has_resp_header/index.html @@ -62,95 +62,46 @@

cowboy_req:has_resp_header(3)

-

Name

-
-

cowboy_req:has_resp_header - Is the given response header set?

-
-
-
+

cowboy_req:has_resp_header - Is the given response header set?

Description

-
-
-
-
has_resp_header(Name, Req :: cowboy_req:req()) -> boolean()
+
has_resp_header(Name, Req :: cowboy_req:req()) -> boolean()
 
-Name :: binary()  %% lowercase; case insensitive
-

Return whether the given response header has been set.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+Name :: binary() %% lowercase; case insensitive +
+

Return whether the given response header has been set.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Name -
-
-

-Header name as a lowercase binary string. -

+
Name
+

Header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A boolean indicating whether the given response header has been set.

-
-
-
+

A boolean indicating whether the given response header has been set.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Check whether the content-type header has been set
-
-
false = cowboy_req:has_resp_header(<<"content-type">>, Req0),
-Req = cowboy_req:set_resp_header(<<"content-type">>, <<"text/html">>, Req0),
-true = cowboy_req:has_resp_header(<<"content-type">>, Req).
-
-
-
+
false = cowboy_req:has_resp_header(<<"content-type">>, Req0),
+Req = cowboy_req:set_resp_header(<<"content-type">>, <<"text/html">>, Req0),
+true = cowboy_req:has_resp_header(<<"content-type">>, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3), cowboy_req:delete_resp_header(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.header/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.header/index.html index 3ebbe928..52baf836 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.header/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.header/index.html @@ -62,122 +62,67 @@

cowboy_req:header(3)

-

Name

-
-

cowboy_req:header - HTTP header

-
-
-
+

cowboy_req:header - HTTP header

Description

-
-
-
-
header(Name, Req)          -> header(Name, Req, undefined)
-header(Name, Req, Default) -> binary() | Default
-
-Name    :: binary()          %% lowercase; case insensitive
-Req     :: cowboy_req:req()
-Default :: any()
-

Return the value for the given HTTP header.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Headers can also be obtained using pattern matching:

-
-
-
#{headers := #{Name := Value}} = Req.
-

Note that this snippet will crash if the header is missing.

-
-
-
+
#{headers := #{Name := Value}} = Req.
+
+

Note that this snippet will crash if the header is missing.

Arguments

-
-
-
-Name -
-
-

-Desired HTTP header name as a lowercase binary string. -

+
Name
+

Desired HTTP header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the header is missing. -

+
Default
+

Default value returned when the header is missing.

-
-
- -
+

Return value

-
-

The header value is returned as a binary string. When the -header is missing, the default argument is returned.

-
-
-
+

The header value is returned as a binary string. When the header is missing, the default argument is returned.

Changelog

-
-
    -
  • -

    -2.0: Only the header value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the header value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the accept header
-
-
Accept = cowboy_req:header(<<"accept">>, Req).
-
-
Get the content-length header with a default value
-
-
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).
-
-
-
+
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).
+

See also

- - +

cowboy_req(3), cowboy_req:headers(3), cowboy_req:parse_header(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.headers/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.headers/index.html index 869cc9c5..2dc6f2ab 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.headers/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.headers/index.html @@ -62,90 +62,47 @@

cowboy_req:headers(3)

-

Name

-
-

cowboy_req:headers - HTTP headers

-
-
-
+

cowboy_req:headers - HTTP headers

Description

-
-
-
-
headers(Req :: cowboy_req:req()) -> cowboy:http_headers()
-

Return all request headers.

-

Request headers can also be obtained using pattern matching:

-
-
-
#{headers := Headers} = Req.
-
-
-
+
#{headers := Headers} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Headers are returned as a map with keys being lowercase -binary strings, and values as binary strings.

-
-
-
+

Headers are returned as a map with keys being lowercase binary strings, and values as binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the headers are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the headers are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get all headers
-
-
Headers = cowboy_req:headers(Req).
-
-
-
+
Headers = cowboy_req:headers(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:header(3), cowboy_req:parse_header(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.host/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.host/index.html index 2696c2fe..e7eea78c 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.host/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.host/index.html @@ -62,91 +62,47 @@

cowboy_req:host(3)

-

Name

-
-

cowboy_req:host - URI host name

-
-
-
+

cowboy_req:host - URI host name

Description

-
-
-
-
host(Req :: cowboy_req:req()) -> Host :: binary()
-

Return the host name of the effective request URI.

-

The host name can also be obtained using pattern matching:

-
-
-
#{host := Host} = Req.
-
-
-
+
#{host := Host} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The host name is returned as a lowercase binary string. -It is case insensitive.

-
-
-
+

The host name is returned as a lowercase binary string. It is case insensitive.

Changelog

-
-
    -
  • -

    -2.0: Only the host name is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the host name is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s host name
-
-
Host = cowboy_req:host(Req).
-
-
-
+
Host = cowboy_req:host(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:host_info(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.host_info/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.host_info/index.html index 91c20d52..7f02b1fe 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.host_info/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.host_info/index.html @@ -62,87 +62,41 @@

cowboy_req:host_info(3)

-

Name

-
-

cowboy_req:host_info - Access the route’s heading host segments

-
-
-
+

cowboy_req:host_info - Access the route's heading host segments

Description

-
-
-
-
host_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
-

Return the tokens for the heading host segments.

-

This is the part of the host name that was matched using -the ... notation.

-
-
-
+
host_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
+
+

Return the tokens for the heading host segments.

+

This is the part of the host name that was matched using the ... notation.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The tokens are returned as a list of case insensitive -binary strings.

-
-
-
+

The tokens are returned as a list of case insensitive binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the tokens are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the host_info tokens
-
-
HostInfo = cowboy_req:host_info(Req).
-
-
-
+
HostInfo = cowboy_req:host_info(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:path_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.match_cookies/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.match_cookies/index.html index 607ee5d3..1f523bc2 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.match_cookies/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.match_cookies/index.html @@ -62,123 +62,67 @@

cowboy_req:match_cookies(3)

-

Name

-
-

cowboy_req:match_cookies - Match cookies against constraints

-
-
-
+

cowboy_req:match_cookies - Match cookies against constraints

Description

-
-
-
-
match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req())
-    -> #{atom() => any()}
-

Parse the cookies and match specific values against -constraints.

-

Cowboy will only return the cookie values specified in the -fields list, and ignore all others. Fields can be either -the name of the cookie requested; the name along with a -list of constraints; or the name, a list of constraints -and a default value in case the cookie is missing.

-

This function will crash if the cookie is missing and no -default value is provided. This function will also crash -if a constraint fails.

-

The name of the cookie must be provided as an atom. The -key of the returned map will be that atom. The value may -be converted through the use of constraints, making this -function able to extract, validate and convert values all -in one step.

-
-
-
+
match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req())
+    -> #{atom() => any()}
+
+

Parse the cookies and match specific values against constraints.

+

Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing.

+

This function will crash if the cookie is missing and no default value is provided. This function will also crash if a constraint fails.

+

The name of the cookie must be provided as an atom. The key of the returned map will be that atom. The value may be converted through the use of constraints, making this function able to extract, validate and convert values all in one step.

Arguments

-
-
-
-Fields -
-
-

-Cookies to retrieve. -

-

See cowboy(3) for a complete description.

+
Fields
+

Cookies to retrieve.

+

See cowboy(3) for a complete description.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Desired values are returned as a map. The key is the atom -that was given in the list of fields, and the value is the -optionally converted value after applying constraints.

-

The map contains the same keys that were given in the fields.

-

An exception is triggered when the match fails.

-
-
-
+

Desired values are returned as a map. The key is the atom that was given in the list of fields, and the value is the optionally converted value after applying constraints.

+

The map contains the same keys that were given in the fields.

+

An exception is triggered when the match fails.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Match fields
-
-
%% ID and Lang are binaries.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_cookies([id, lang], Req).
-
-
Match fields and apply constraints
-
-
%% ID is an integer and Lang a non-empty binary.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_cookies([{id, int}, {lang, nonempty}], Req).
-
-
Match fields with default values
-
-
#{lang := Lang}
-    = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
-
-
-
+
#{lang := Lang}
+    = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
+

See also

- - +

cowboy_req(3), cowboy_req:parse_cookies(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.match_qs/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.match_qs/index.html index 6cb40e3a..97140d61 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.match_qs/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.match_qs/index.html @@ -62,123 +62,67 @@

cowboy_req:match_qs(3)

-

Name

-
-

cowboy_req:match_qs - Match the query string against constraints

-
-
-
+

cowboy_req:match_qs - Match the query string against constraints

Description

-
-
-
-
match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req())
-    -> #{atom() => any()}
-

Parse the query string and match specific values against -constraints.

-

Cowboy will only return the query string values specified -in the fields list, and ignore all others. Fields can be -either the key requested; the key along with a list of -constraints; or the key, a list of constraints and a -default value in case the key is missing.

-

This function will crash if the key is missing and no -default value is provided. This function will also crash -if a constraint fails.

-

The key must be provided as an atom. The key of the -returned map will be that atom. The value may be converted -through the use of constraints, making this function able -to extract, validate and convert values all in one step.

-
-
-
+
match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req())
+    -> #{atom() => any()}
+
+

Parse the query string and match specific values against constraints.

+

Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing.

+

This function will crash if the key is missing and no default value is provided. This function will also crash if a constraint fails.

+

The key must be provided as an atom. The key of the returned map will be that atom. The value may be converted through the use of constraints, making this function able to extract, validate and convert values all in one step.

Arguments

-
-
-
-Fields -
-
-

-Fields to retrieve from the query string. -

-

See cowboy(3) for a complete description.

+
Fields
+

Fields to retrieve from the query string.

+

See cowboy(3) for a complete description.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Desired values are returned as a map. The key is the atom -that was given in the list of fields, and the value is the -optionally converted value after applying constraints.

-

The map contains the same keys that were given in the fields.

-

An exception is triggered when the match fails.

-
-
-
+

Desired values are returned as a map. The key is the atom that was given in the list of fields, and the value is the optionally converted value after applying constraints.

+

The map contains the same keys that were given in the fields.

+

An exception is triggered when the match fails.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Match fields
-
-
%% ID and Lang are binaries.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_qs([id, lang], Req).
-
-
Match fields and apply constraints
-
-
%% ID is an integer and Lang a non-empty binary.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req).
-
-
Match fields with default values
-
-
#{lang := Lang}
-    = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
-
-
-
+
#{lang := Lang}
+    = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
+

See also

- - +

cowboy_req(3), cowboy_req:qs(3), cowboy_req:parse_qs(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.method/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.method/index.html index b7533c7d..c41b9d1e 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.method/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.method/index.html @@ -62,100 +62,58 @@

cowboy_req:method(3)

-

Name

-
-

cowboy_req:method - HTTP method

-
-
-
+

cowboy_req:method - HTTP method

Description

-
-
-
-
method(Req :: cowboy_req:req()) -> Method :: binary()
-

Return the request’s HTTP method.

-

The method can also be obtained using pattern matching:

-
-
-
#{method := Method} = Req.
-
-
-
+
#{method := Method} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The request’s HTTP method is returned as a binary string. -While methods are case sensitive, standard methods are -always uppercase.

-
-
-
+

The request's HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase.

Changelog

-
-
    -
  • -

    -2.0: Only the method is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the method is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Ensure the request’s method is GET
-
-
<<"GET">> = cowboy_req:method(Req).
-
-
Allow methods from list
-
-
init(Req, State) ->
-    case lists:member(cowboy_req:method(Req), [<<"GET">>, <<"POST">>]) of
-        true -> handle(Req, State);
-        false -> method_not_allowed(Req, State)
-    end.
-
-
-
+
init(Req, State) ->
+    case lists:member(cowboy_req:method(Req), [<<"GET">>, <<"POST">>]) of
+        true -> handle(Req, State);
+        false -> method_not_allowed(Req, State)
+    end.
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.parse_cookies/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.parse_cookies/index.html index 3120c899..3276a59c 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.parse_cookies/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.parse_cookies/index.html @@ -62,91 +62,47 @@

cowboy_req:parse_cookies(3)

-

Name

-
-

cowboy_req:parse_cookies - Parse cookie headers

-
-
-
+

cowboy_req:parse_cookies - Parse cookie headers

Description

-
-
-
-
parse_cookies(Req) -> [{Name, Value}]
-
-Name  :: binary() %% case sensitive
-Value :: binary() %% case sensitive
-

Parse cookie headers.

- -

When the cookie header is missing, [] is returned.

-

While an empty cookie header is not valid, some clients do -send it. Cowboy will in this case also return [].

-
-
-
+
parse_cookies(Req) -> [{Name, Value}]
+
+Name  :: binary() %% case sensitive
+Value :: binary() %% case sensitive
+
+

Parse cookie headers.

+

Alias for cowboy_req:parse_header(<<"cookie">>, Req).

+

When the cookie header is missing, [] is returned.

+

While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return [].

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The cookies are returned as a list of key/values. Keys and -values are case sensitive binary strings.

-
-
-
+

The cookies are returned as a list of key/values. Keys and values are case sensitive binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces cookie/2,3 and cookies/1. -

      +
    • 2.0: Function introduced. Replaces cookie/2,3 and cookies/1.
    • -
-
-
-
+

Examples

-
-
-
Look for a specific cookie
-
-
Cookies = cowboy_req:parse_cookies(Req),
-{_, Token} = lists:keyfind(token, 1, Cookies).
-
-
-
+
Cookies = cowboy_req:parse_cookies(Req),
+{_, Token} = lists:keyfind(token, 1, Cookies).
+

See also

- - +

cowboy_req(3), cowboy_req:parse_header(3), cowboy_req:match_cookies(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.parse_header/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.parse_header/index.html index 351b4f30..3a0b691a 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.parse_header/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.parse_header/index.html @@ -62,283 +62,218 @@

cowboy_req:parse_header(3)

-

Name

-
-

cowboy_req:parse_header - Parse the given HTTP header

-
-
-
+

cowboy_req:parse_header - Parse the given HTTP header

Description

-
-
-
-
parse_header(Name, Req)          -> ParsedValue | Default
-parse_header(Name, Req, Default) -> ParsedValue | Default
-
-Name        :: binary()
-Req         :: cowboy_req:req()
-ParsedValue :: any()
-Default     :: any()
-

Parse the given HTTP header.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

The type of the parsed value varies depending on -the header. Similarly, the default value when calling -cowboy_req:parse_header/2 differs depending on the -header.

-
-
-
+
parse_header(Name, Req)          -> ParsedValue | Default
+parse_header(Name, Req, Default) -> ParsedValue | Default
+
+Name        :: binary()
+Req         :: cowboy_req:req()
+ParsedValue :: any()
+Default     :: any()
+
+

Parse the given HTTP header.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

The type of the parsed value varies depending on the header. Similarly, the default value when calling cowboy_req:parse_header/2 differs depending on the header.

Arguments

-
-
-
-Name -
-
-

-Desired HTTP header name as a lowercase binary string. -

+
Name
+

Desired HTTP header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the header is missing. -

+
Default
+

Default value returned when the header is missing.

-
-
- -
+

Return value

-
-

The parsed header value varies depending on the header. -When the header is missing, the default argument is returned.

-
-
-
+

The parsed header value varies depending on the header. When the header is missing, the default argument is returned.

Headers

-
-

The following snippets detail the types returned by the -different headers. Unless mentioned otherwise, the -default value when the header is missing will be undefined:

-
-
accept
-
-
parse_header(<<"accept">>, Req)
-    -> [{{Type, SubType, Params}, Quality, AcceptExt}]
-
-Type      :: binary()               %% case insensitive
-SubType   :: binary()               %% case insensitive
-Params    :: [{Key, Value}]
-Quality   :: 0..1000
-AcceptExt :: [Key | {Key, Value}]
-Key       :: binary()               %% case insensitive
-Value     :: binary()               %% case sensitive
-
-
accept-charset, accept-encoding and accept-language
-
-
parse_header(Name, Req) -> [{Value, Quality}]
-
-Name    :: <<"accept-charset">>
-         | <<"accept-encoding">>
-         | <<"accept-language">>
-Value   :: binary()                 %% case insensitive
-Quality :: 0..1000
-
-
authorization
-
-
parse_header(<<"authorization">>, Req)
-    -> {basic, Username :: binary(), Password :: binary()}
-     | {bearer, Token :: binary()}
-     | {digest, [{Key :: binary(), Value :: binary()}]}
-
-
content-length
-
+
content-length
+
-
parse_header(<<"content-length">>, Req) -> non_neg_integer()
-

When the content-length header is missing, 0 is returned.

-
-
content-type
-
-
parse_header(<<"content-type">>, Req)
-    -> {Type, SubType, Params}
-
-Type      :: binary()               %% case insensitive
-SubType   :: binary()               %% case insensitive
-Params    :: [{Key, Value}]
-Key       :: binary()               %% case insensitive
-Value     :: binary()               %% case sensitive;
-

Note that the value for the charset parameter is case insensitive -and returned as a lowercase binary string.

-
-
cookie
-
-
parse_header(<<"cookie">>, Req) -> [{Name, Value}]
-
-Name  :: binary()                   %% case sensitive
-Value :: binary()                   %% case sensitive
-

When the cookie header is missing, [] is returned.

-

While an empty cookie header is not valid, some clients do -send it. Cowboy will in this case also return [].

-
-
expect
-
-
parse_header(<<"expect">>, Req) -> continue
-
-
if-match and if-none-match
-
-
parse_header(Name, Req)
-    -> '*' | [{weak | strong, OpaqueTag}]
-
-Name      :: <<"if-match">>
-           | <<"if-none-match">>
-OpaqueTag :: binary()               %% case sensitive
-
-
if-modified-since and if-unmodified-since
-
-
parse_header(Name, Req) -> calendar:datetime()
-
-
range
-
-
parse_header(<<"range">>, Req) -> {From, To} | Final
-
-From  :: non_neg_integer()
-To    :: non_neg_integer() | infinity
-Final :: neg_integer()
-
-
sec-websocket-extensions
-
-
parse_header(<<"sec-websocket-extensions">>, Req)
-    -> [{Extension, Params}]
-
-Extension :: binary()               %% case sensitive
-Params    :: [Key | {Key, Value}]
-Key       :: binary()               %% case sensitive
-Value     :: binary()               %% case sensitive
-
-
sec-websocket-protocol and upgrade
-
-
parse_header(Name, Req) -> [Token]
-
-Name  :: <<"sec-websocket-protocol">>
-       | <<"upgrade">>
-Token :: binary()                   %% case insensitive
-
-
x-forwarded-for
-
-
parse_header(<<"x-forwarded-for">>, Req) -> [Token]
+
parse_header(<<"x-forwarded-for">>, Req) -> [Token]
 
-Token :: binary()                   %% case sensitive
-
-
Unknown headers
-
-
parse_header(_, Req) -> {undefined, RawValue}
-
-
-
+
parse_header(_, Req) -> {undefined, RawValue}
+

Changelog

-
-
    -
  • -

    -2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Parse the accept header with a custom default value
-
-
%% Accept everything when header is missing.
-Accept = cowboy_req:parse_header(<<"accept">>, Req,
-    [{{ <<"*">>, <<"*">>, []}, 1000, []}]).
-
-
Parse the content-length header
-
-
%% Default content-length is 0.
-Length = cowboy_req:header(<<"content-length">>, Req).
-
-
-
+
%% Default content-length is 0.
+Length = cowboy_req:header(<<"content-length">>, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:header(3), cowboy_req:headers(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.parse_qs/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.parse_qs/index.html index 75ac6ea8..68cfb8ae 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.parse_qs/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.parse_qs/index.html @@ -62,117 +62,55 @@

cowboy_req:parse_qs(3)

-

Name

-
-

cowboy_req:parse_qs - Parse the query string

-
-
-
+

cowboy_req:parse_qs - Parse the query string

Description

-
-
-
-
parse_qs(Req :: cowboy_req:req())
-    -> [{Key :: binary(), Value :: binary() | true}]
-

Parse the query string as a list of key/value pairs.

-
-
-
+
parse_qs(Req :: cowboy_req:req())
+    -> [{Key :: binary(), Value :: binary() | true}]
+
+

Parse the query string as a list of key/value pairs.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The parsed query string is returned as a list of key/value pairs. -The key is a binary string. The value is either a binary string, -or the atom true. Both key and value are case sensitive.

-

The atom true is returned when a key is present in the query -string without a value. For example, in the following URIs -the key <<"edit">> will always have the value true:

-
    -
  • -

    -/posts/42?edit -

    +

    The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. Both key and value are case sensitive.

    +

    The atom true is returned when a key is present in the query string without a value. For example, in the following URIs the key <<"edit">> will always have the value true:

    +
    • /posts/42?edit
    • -
    • -

      -/posts/42?edit&exclusive=1 -

      +
    • /posts/42?edit&exclusive=1
    • -
    • -

      -/posts/42?exclusive=1&edit -

      +
    • /posts/42?exclusive=1&edit
    • -
    • -

      -/posts/42?exclusive=1&edit&from=web -

      +
    • /posts/42?exclusive=1&edit&from=web
    • -
-
-
-
+

Changelog

-
-
    -
  • -

    -2.0: The parsed value is not longer cached in the Req object. -

    +
    • 2.0: The parsed value is not longer cached in the Req object.
    • -
    • -

      -2.0: Only the parsed query string is returned, it is no longer wrapped in a tuple. -

      +
    • 2.0: Only the parsed query string is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces qs_val/1 and qs_vals/1. -

      +
    • 2.0: Function introduced. Replaces qs_val/1 and qs_vals/1.
    • -
-
-
-
+

Examples

-
-
-
Parse the query string and convert the keys to atoms
-
-
ParsedQs = cowboy_req:parse_qs(Req),
-AtomsQs = [{binary_to_existing_atom(K, latin1), V}
-    || {K, V} <- ParsedQs].
-
-
-
+
ParsedQs = cowboy_req:parse_qs(Req),
+AtomsQs = [{binary_to_existing_atom(K, latin1), V}
+    || {K, V} <- ParsedQs].
+

See also

- - +

cowboy_req(3), cowboy_req:qs(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.path/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.path/index.html index df803617..1095bd2e 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.path/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.path/index.html @@ -62,90 +62,47 @@

cowboy_req:path(3)

-

Name

-
-

cowboy_req:path - URI path

-
-
-
+

cowboy_req:path - URI path

Description

-
-
-
-
path(Req :: cowboy_req:req()) -> Path :: binary()
-

Return the path of the effective request URI.

-

The path can also be obtained using pattern matching:

-
-
-
#{path := Path} = Req.
-
-
-
+
#{path := Path} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The path is returned as a binary string. It is case sensitive.

-
-
-
+

The path is returned as a binary string. It is case sensitive.

Changelog

-
-
    -
  • -

    -2.0: Only the path is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the path is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s path
-
-
Path = cowboy_req:path(Req).
-
-
-
+
Path = cowboy_req:path(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:path_info(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.path_info/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.path_info/index.html index 702e5c1e..ab05a94a 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.path_info/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.path_info/index.html @@ -62,87 +62,41 @@

cowboy_req:path_info(3)

-

Name

-
-

cowboy_req:path_info - Access the route’s trailing path segments

-
-
-
+

cowboy_req:path_info - Access the route's trailing path segments

Description

-
-
-
-
path_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
-

Return the tokens for the trailing path segments.

-

This is the part of the host name that was matched using -the ... notation.

-
-
-
+
path_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
+
+

Return the tokens for the trailing path segments.

+

This is the part of the host name that was matched using the ... notation.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The tokens are returned as a list of case sensitive -binary strings.

-
-
-
+

The tokens are returned as a list of case sensitive binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the tokens are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the path_info tokens
-
-
PathInfo = cowboy_req:path_info(Req).
-
-
-
+
PathInfo = cowboy_req:path_info(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:host_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.peer/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.peer/index.html index 40433281..010c02f5 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.peer/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.peer/index.html @@ -62,96 +62,51 @@

cowboy_req:peer(3)

-

Name

-
-

cowboy_req:peer - Peer address and port

-
-
-
+

cowboy_req:peer - Peer address and port

Description

-
-
-
-
peer(Req :: cowboy_req:req()) -> Peer
+
peer(Req :: cowboy_req:req()) -> Peer
 
-Peer :: {inet:ip_address(), inet:port_number()}
-

Return the peer’s IP address and port number.

-

The peer can also be obtained using pattern matching:

-
-
-
#{peer := {IP, Port}} = Req.
-
-
-
+
#{peer := {IP, Port}} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The peer’s IP address and port number.

-

The peer is not necessarily the client’s IP address and port. -It is the IP address of the endpoint connecting directly to -the server, which may be a gateway or a proxy.

-

The forwarded header can be used to get better information -about the different endpoints from the client to the server. -Note however that it is only informative; there is no reliable -way of determining the source of an HTTP request.

-
-
-
+

The peer's IP address and port number.

+

The peer is not necessarily the client's IP address and port. It is the IP address of the endpoint connecting directly to the server, which may be a gateway or a proxy.

+

The forwarded header can be used to get better information about the different endpoints from the client to the server. Note however that it is only informative; there is no reliable way of determining the source of an HTTP request.

Changelog

-
-
    -
  • -

    -2.0: Only the peer is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the peer is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the peer IP address and port number.
-
-
{IP, Port} = cowboy_req:peer(Req).
-
-
-
+
{IP, Port} = cowboy_req:peer(Req).
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.port/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.port/index.html index ed23e541..7e0e174b 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.port/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.port/index.html @@ -62,90 +62,48 @@

cowboy_req:port(3)

-

Name

-
-

cowboy_req:port - URI port number

-
-
-
+

cowboy_req:port - URI port number

Description

-
-
-
-
port(Req :: cowboy_req:req()) -> Port :: inet:port_number()
-

Return the port number of the effective request URI.

-

Note that the port number returned by this function is obtained -by parsing the host header. It may be different from the port -the peer used to connect to Cowboy.

-

The port number can also be obtained using pattern matching:

-
-
-
#{port := Port} = Req.
-
-
-
+
#{port := Port} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The port number is returned as an integer.

-
-
-
+

The port number is returned as an integer.

Changelog

-
-
    -
  • -

    -2.0: Only the port number is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the port number is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s port number
-
-
Port = cowboy_req:port(Req).
-
-
-
+
Port = cowboy_req:port(Req).
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.push/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.push/index.html index 9a83b56b..25d13ca7 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.push/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.push/index.html @@ -62,141 +62,74 @@

cowboy_req:push(3)

-

Name

-
-

cowboy_req:push - Push a resource to the client

-
-
-
+

cowboy_req:push - Push a resource to the client

Description

-
-
-
-
push(Path, Headers, Req :: cowboy_req:req())
-    -> push(Path, Headers, Req, #{})
-
-push(Path, Headers, Req :: cowboy_req:req(), Opts)
-    -> ok
-
-Path    :: iodata()                %% case sensitive
-Headers :: cowboy:http_headers()
-Opts    :: cowboy_req:push_opts()
-

Push a resource to the client.

-

Cowboy handles push requests the same way as if they came -from the client, including the creation of a request handling -process, routing and middlewares and so on.

-

This function does nothing when the HTTP/1.1 protocol is -used. You may call it safely without first checking whether -the connection uses HTTP/2.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Note that the headers must be the headers the client is expected -to send if it were to perform the request. They are therefore -request headers, and not response headers.

-

By default, Cowboy will use the GET method, an empty query string, -and take the scheme, host and port directly from the current -request’s URI. You can override them by passing options.

-

It is not possible to push resources after sending a response. -Any attempt will result in an error.

-
-
-
+
push(Path, Headers, Req :: cowboy_req:req())
+    -> push(Path, Headers, Req, #{})
+
+push(Path, Headers, Req :: cowboy_req:req(), Opts)
+    -> ok
+
+Path    :: iodata()                %% case sensitive
+Headers :: cowboy:http_headers()
+Opts    :: cowboy_req:push_opts()
+
+

Push a resource to the client.

+

Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on.

+

This function does nothing when the HTTP/1.1 protocol is used. You may call it safely without first checking whether the connection uses HTTP/2.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Note that the headers must be the headers the client is expected to send if it were to perform the request. They are therefore request headers, and not response headers.

+

By default, Cowboy will use the GET method, an empty query string, and take the scheme, host and port directly from the current request's URI. You can override them by passing options.

+

It is not possible to push resources after sending a response. Any attempt will result in an error.

Arguments

-
-
-
-Path -
-
-

-The status code for the response. -

+
Path
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Req -
-
-

-The Req object. -

+
+

Header names must be given as lowercase binary strings.

+
Req
+

The Req object.

-
-Opts -
-
-

-Customize the HTTP method or the URI scheme, host, port -or query string. -

+
Opts
+

Customize the HTTP method or the URI scheme, host, port or query string.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Push a resource
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, Req),
-
-
Push a resource with a custom host
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, #{host => <<"cdn.example.org">>}, Req),
-
-
-
+
cowboy_req:push("/static/style.css", #{
+    <<"accept">> => <<"text/css">>
+}, #{host => <<"cdn.example.org">>}, Req),
+

See also

- - +

cowboy_req(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.qs/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.qs/index.html index b23ec812..7fd3b24c 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.qs/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.qs/index.html @@ -62,89 +62,47 @@

cowboy_req:qs(3)

-

Name

-
-

cowboy_req:qs - URI query string

-
-
-
+

cowboy_req:qs - URI query string

Description

-
-
-
-
qs(Req :: cowboy_req:req()) -> Qs :: binary()
-

Return the query string of the effective request URI.

-

The query string can also be obtained using pattern matching:

-
-
-
#{qs := Qs} = Req.
-
-
-
+
#{qs := Qs} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The query string is returned as a binary string. It is case sensitive.

-
-
-
+

The query string is returned as a binary string. It is case sensitive.

Changelog

-
-
    -
  • -

    -2.0: Only the query string is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the query string is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s query string
-
-
Qs = cowboy_req:qs(Req).
-
-
-
+
Qs = cowboy_req:qs(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:parse_qs(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.read_body/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.read_body/index.html index 30224c06..7d3e6194 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.read_body/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.read_body/index.html @@ -62,143 +62,72 @@

cowboy_req:read_body(3)

-

Name

-
-

cowboy_req:read_body - Read the request body

-
-
-
+

cowboy_req:read_body - Read the request body

Description

-
-
-
-
read_body(Req :: cowboy_req:req())
-    -> read_body(Req, #{})
-
-read_body(Req :: cowboy_req:req(), Opts)
-    -> {ok,   Data :: binary(), Req}
-     | {more, Data :: binary(), Req}
-
-Opts :: cowboy_req:read_body_opts()
-

Read the request body.

-

This function reads a chunk of the request body. A more tuple -is returned when more data remains to be read. Call the function -repeatedly until an ok tuple is returned to read the entire body.

-

An ok tuple with empty data is returned when the request has no body, -or when calling this function again after the body has already -been read. It is therefore safe to call this function directly. -Note that the body can only be read once.

-

This function reads the request body from the connection process. -The connection process is responsible for reading from the socket. -The exact behavior varies depending on the protocol.

-

The options therefore are only related to the communication -between the request process and the connection process.

-

Cowboy will automatically handle protocol details including -the expect header, chunked transfer-encoding and others.

-

Once the body has been read fully, Cowboy sets the content-length -header if it was not previously provided.

-
-
-
+
read_body(Req :: cowboy_req:req())
+    -> read_body(Req, #{})
+
+read_body(Req :: cowboy_req:req(), Opts)
+    -> {ok,   Data :: binary(), Req}
+     | {more, Data :: binary(), Req}
+
+Opts :: cowboy_req:read_body_opts()
+
+

Read the request body.

+

This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body.

+

An ok tuple with empty data is returned when the request has no body, or when calling this function again after the body has already been read. It is therefore safe to call this function directly. Note that the body can only be read once.

+

This function reads the request body from the connection process. The connection process is responsible for reading from the socket. The exact behavior varies depending on the protocol.

+

The options therefore are only related to the communication between the request process and the connection process.

+

Cowboy will automatically handle protocol details including the expect header, chunked transfer-encoding and others.

+

Once the body has been read fully, Cowboy sets the content-length header if it was not previously provided.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. -

-

The length option can be used to request smaller or bigger -chunks of data to be sent. It is a best effort approach, Cowboy -may send more data than configured on occasions. It defaults -to 8MB.

-

The period indicates how long the connection process will wait -before it provides us with the data it received. It defaults -to 15 seconds.

-

The connection process sends data to the request process when -either the length of data or the period of time is reached.

-

The timeout option is a safeguard in case the connection -process becomes unresponsive. The function will crash if no -message was received in that interval. The timeout should be -larger than the period. It defaults to the period + 1 second.

+
Opts
+

A map of body reading options.

+

The length option can be used to request smaller or bigger chunks of data to be sent. It is a best effort approach, Cowboy may send more data than configured on occasions. It defaults to 8MB.

+

The period indicates how long the connection process will wait before it provides us with the data it received. It defaults to 15 seconds.

+

The connection process sends data to the request process when either the length of data or the period of time is reached.

+

The timeout option is a safeguard in case the connection process becomes unresponsive. The function will crash if no message was received in that interval. The timeout should be larger than the period. It defaults to the period
1 second.

-
-
- -
+

Return value

-
-

A more tuple is returned when there are more data to be read.

-

An ok tuple is returned when there are no more data to be read, -either because this is the last chunk of data, the body has already -been read, or there was no body to begin with.

-

The data is always returned as a binary.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

A more tuple is returned when there are more data to be read.

+

An ok tuple is returned when there are no more data to be read, either because this is the last chunk of data, the body has already been read, or there was no body to begin with.

+

The data is always returned as a binary.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces body/1,2. -

    +
    • 2.0: Function introduced. Replaces body/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read the entire body
-
-
read_body(Req0, Acc) ->
-    case cowboy_req:read_body(Req0) of
-        {ok, Data, Req} -> {ok, << Acc/binary, Data/binary >>, Req};
-        {more, Data, Req} -> read_body(Req, << Acc/binary, Data/binary >>)
-    end.
-
-
Read the body in small chunks
-
-
cowboy_req:read_body(Req, #{length => 64000}).
-
-
-
+
cowboy_req:read_body(Req, #{length => 64000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.read_part/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.read_part/index.html index cddb626c..79bec5ad 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.read_part/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.read_part/index.html @@ -62,162 +62,94 @@

cowboy_req:read_part(3)

-

Name

-
-

cowboy_req:read_part - Read the next multipart headers

-
-
-
+

cowboy_req:read_part - Read the next multipart headers

Description

-
-
-
-
read_part(Req :: cowboy_req:req())
-    -> read_part(Req, #{})
-
-read_part(Req :: cowboy_req:req(), Opts)
-    -> {ok, Headers, Req} | {done, Req}
-
-Opts    :: cowboy_req:read_body_opts()
-Headers :: #{binary() => binary()}
-

Read the next part of a multipart body.

-

This function reads the request body and parses it as -multipart. Each parts of a multipart representation have -their own headers and body. This function parses and returns -headers. Examples of multipart media types are -multipart/form-data and multipart/byteranges.

-

Cowboy will skip any data remaining until the beginning of -the next part. This includes the preamble to the multipart -message but also the body of a previous part if it hasn’t -been read. Both are skipped automatically when calling this -function.

-

Cowboy will read the body before parsing in chunks of size -up to 64KB, with a period of 5 seconds. This is tailored for -reading part headers and might not be the most efficient for -skipping the previous part’s body.

-

The headers returned are MIME headers, NOT HTTP headers. -They can be parsed using the functions from the cow_multipart -module. In addition, the cow_multipart:form_data/1 function -can be used to quickly extract information from multipart/form-data -representations.

-

Once a part has been read, it can not be read again.

-

Once the body has been read, Cowboy sets the content-length -header if it was not previously provided.

-
-
-
+
read_part(Req :: cowboy_req:req())
+    -> read_part(Req, #{})
+
+read_part(Req :: cowboy_req:req(), Opts)
+    -> {ok, Headers, Req} | {done, Req}
+
+Opts    :: cowboy_req:read_body_opts()
+Headers :: #{binary() => binary()}
+
+

Read the next part of a multipart body.

+

This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. Examples of multipart media types are multipart/form-data and multipart/byteranges.

+

Cowboy will skip any data remaining until the beginning of the next part. This includes the preamble to the multipart message but also the body of a previous part if it hasn't been read. Both are skipped automatically when calling this function.

+

Cowboy will read the body before parsing in chunks of size up to 64KB, with a period of 5 seconds. This is tailored for reading part headers and might not be the most efficient for skipping the previous part's body.

+

The headers returned are MIME headers, NOT HTTP headers. They can be parsed using the functions from the cow_multipart module. In addition, the cow_multipart:form_data/1 function can be used to quickly extract information from multipart/form-data representations.

+ +

Once a part has been read, it can not be read again.

+

Once the body has been read, Cowboy sets the content-length header if it was not previously provided.

+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. Please refer to -cowboy_req:read_body(3) -for details about each option. -

-

This function defaults the length to 64KB and the period -to 5 seconds.

+
Opts
+

A map of body reading options. Please refer to cowboy_req:read_body(3) for details about each option.

+

This function defaults the length to 64KB and the period to 5 seconds.

-
-
- -
+

Return value

-
-

An ok tuple is returned containing the next part’s headers -as a map.

-

A done tuple is returned if there are no more parts to read.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

An ok tuple is returned containing the next part's headers as a map.

+

A done tuple is returned if there are no more parts to read.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces part/1,2. -

    +
    • 2.0: Function introduced. Replaces part/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read all parts
-
-
acc_multipart(Req0, Acc) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, Headers, Req1} ->
-            {ok, Body, Req} = stream_body(Req1, <<>>),
-            acc_multipart(Req, [{Headers, Body}|Acc]);
-        {done, Req} ->
-            {lists:reverse(Acc), Req}
-    end.
-
-stream_body(Req0, Acc) ->
-    case cowboy_req:read_part_body(Req0) of
-        {more, Data, Req} ->
-            stream_body(Req, << Acc/binary, Data/binary >>);
-        {ok, Data, Req} ->
-            {ok, << Acc/binary, Data/binary >>, Req}
-    end.
-
-
Read all part headers, skipping bodies
-
-
skip_body_multipart(Req0, Acc) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, Headers, Req} ->
-            skip_body_multipart(Req, [Headers|Acc]);
-        {done, Req} ->
-            {lists:reverse(Acc), Req}
-    end.
-
-
Read a part header in larger chunks
-
-
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).
-
-
-
+
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.read_part_body/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.read_part_body/index.html index 774965b0..71e7fd83 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.read_part_body/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.read_part_body/index.html @@ -62,130 +62,70 @@

cowboy_req:read_part_body(3)

-

Name

-
-

cowboy_req:read_part_body - Read the current part’s body

-
-
-
+

cowboy_req:read_part_body - Read the current part's body

Description

-
-
-
-
read_part_body(Req :: cowboy_req:req())
-    -> read_part_body(Req, #{})
-
-read_part_body(Req :: cowboy_req:req(), Opts)
-    -> {ok,   Data :: binary(), Req}
-     | {more, Data :: binary(), Req}
-
-Opts :: cowboy_req:read_body_opts()
-

Read the body of the current part of the multipart message.

-

This function reads the request body and parses it as -multipart. Each parts of a multipart representation have -their own headers and body. This function returns the -body of the current part. Examples of multipart media types -are multipart/form-data and multipart/byteranges.

-

This function reads a chunk of the part’s body. A more tuple -is returned when more data remains to be read. Call the function -repeatedly until an ok tuple is returned to read the entire body.

-

Once a part has been read, it can not be read again.

-

Once the body has been read, Cowboy sets the content-length -header if it was not previously provided.

-
-
-
+
read_part_body(Req :: cowboy_req:req())
+    -> read_part_body(Req, #{})
+
+read_part_body(Req :: cowboy_req:req(), Opts)
+    -> {ok,   Data :: binary(), Req}
+     | {more, Data :: binary(), Req}
+
+Opts :: cowboy_req:read_body_opts()
+
+

Read the body of the current part of the multipart message.

+

This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function returns the body of the current part. Examples of multipart media types are multipart/form-data and multipart/byteranges.

+

This function reads a chunk of the part's body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body.

+

Once a part has been read, it can not be read again.

+

Once the body has been read, Cowboy sets the content-length header if it was not previously provided.

+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. Please refer to -cowboy_req:read_body(3) -for details about each option. -

-

This function uses the same default options as the -cowboy_req:read_body(3) -function.

+
Opts
+

A map of body reading options. Please refer to cowboy_req:read_body(3) for details about each option.

+

This function uses the same default options as the cowboy_req:read_body(3) function.

-
-
- -
+

Return value

-
-

A more tuple is returned when there are more data to be read.

-

An ok tuple is returned when there are no more data to be read.

-

The data is always returned as a binary.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

A more tuple is returned when there are more data to be read.

+

An ok tuple is returned when there are no more data to be read.

+

The data is always returned as a binary.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces part_body/1,2. -

    +
    • 2.0: Function introduced. Replaces part_body/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read a full part’s body
-
-
stream_body(Req0, Acc) ->
-    case cowboy_req:read_part_body(Req0) of
-        {more, Data, Req} ->
-            stream_body(Req, << Acc/binary, Data/binary >>);
-        {ok, Data, Req} ->
-            {ok, << Acc/binary, Data/binary >>, Req}
-    end.
-
-
Ensure a part’s body is smaller than 64KB
-
-
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).
-
-
-
+
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.read_urlencoded_body/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.read_urlencoded_body/index.html index a0b5790f..18322249 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.read_urlencoded_body/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.read_urlencoded_body/index.html @@ -62,126 +62,64 @@

cowboy_req:read_urlencoded_body(3)

-

Name

-
-

cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body

-
-
-
+

cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body

Description

-
-
-
-
read_urlencoded_body(Req :: cowboy_req:req())
-    -> read_urlencoded_body(Req, #{})
-
-read_urlencoded_body(Req :: cowboy_req:req(), Opts)
-    -> {ok, Body, Req}
-
-Opts :: cowboy_req:read_body_opts()
-Body :: [{Key :: binary(), Value :: binary() | true}]
-

Read and parse a urlencoded request body.

-

This function reads the request body and parses it as -application/x-www-form-urlencoded. It returns a list -of key/values.

-

The urlencoded media type is used by Web browsers when -submitting HTML forms using the POST method.

-

Cowboy needs to read the full body before parsing. By default -it will read bodies of size up to 64KB. It is possible to -provide options to read larger bodies if required.

-

Cowboy will automatically handle protocol details including -the expect header, chunked transfer-encoding and others.

-

Once the body has been read, Cowboy sets the content-length -header if it was not previously provided.

-

This function can only be called once. Calling it again will -result in undefined behavior.

-
-
-
+
read_urlencoded_body(Req :: cowboy_req:req())
+    -> read_urlencoded_body(Req, #{})
+
+read_urlencoded_body(Req :: cowboy_req:req(), Opts)
+    -> {ok, Body, Req}
+
+Opts :: cowboy_req:read_body_opts()
+Body :: [{Key :: binary(), Value :: binary() | true}]
+
+

Read and parse a urlencoded request body.

+

This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values.

+

The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method.

+

Cowboy needs to read the full body before parsing. By default it will read bodies of size up to 64KB. It is possible to provide options to read larger bodies if required.

+

Cowboy will automatically handle protocol details including the expect header, chunked transfer-encoding and others.

+

Once the body has been read, Cowboy sets the content-length header if it was not previously provided.

+

This function can only be called once. Calling it again will result in undefined behavior.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. Please refer to -cowboy_req:read_body(3) -for details about each option. -

-

This function defaults the length to 64KB and the period -to 5 seconds.

+
Opts
+

A map of body reading options. Please refer to cowboy_req:read_body(3) for details about each option.

+

This function defaults the length to 64KB and the period to 5 seconds.

-
-
- -
+

Return value

-
-

An ok tuple is returned containing a list of key/values found -in the body.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

An ok tuple is returned containing a list of key/values found in the body.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces body_qs/1,2. -

    +
    • 2.0: Function introduced. Replaces body_qs/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read a urlencoded body
-
-
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0),
-{_, Lang} = lists:keyfind(<<"lang">>, 1, Body).
-
-
Allow large urlencoded bodies
-
-
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).
-
-
-
+
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.reply/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.reply/index.html index 61ba113e..36d4c9f9 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.reply/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.reply/index.html @@ -62,164 +62,87 @@

cowboy_req:reply(3)

-

Name

-
-

cowboy_req:reply - Send the response

-
-
-
+

cowboy_req:reply - Send the response

Description

-
-
-
-
reply(Status, Req :: cowboy_req:req())
-    -> reply(StatusCode, #{}, Req)
-
-reply(Status, Headers, Req :: cowboy_req:req())
-    -> Req
-
-reply(Status, Headers, Body, Req :: cowboy_req:req())
-    -> Req
-
-Status  :: cowboy:http_status()
-Headers :: cowboy:http_headers()
-Body    :: cowboy_req:resp_body()
-

Send the response.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may overwrite those set by set_resp_header/3 -and set_resp_headers/2.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-

The reply/2,3 functions will send the body set previously, -if any. The reply/4 function always sends the given body, -overriding any previously set.

-

You do not need to set the content-length header when -sending a response body. Cowboy takes care of it automatically. -You should however provide a content-type header.

-

No further data can be transmitted after this function -returns. This includes the push mechanism. Attempting to -send two replies, or to push resources after a reply has -been sent, will result in an error.

-
-
-
+
reply(Status, Req :: cowboy_req:req())
+    -> reply(StatusCode, #{}, Req)
+
+reply(Status, Headers, Req :: cowboy_req:req())
+    -> Req
+
+reply(Status, Headers, Body, Req :: cowboy_req:req())
+    -> Req
+
+Status  :: cowboy:http_status()
+Headers :: cowboy:http_headers()
+Body    :: cowboy_req:resp_body()
+
+

Send the response.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3 and set_resp_headers/2.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

+

The reply/2,3 functions will send the body set previously, if any. The reply/4 function always sends the given body, overriding any previously set.

+

You do not need to set the content-length header when sending a response body. Cowboy takes care of it automatically. You should however provide a content-type header.

+

No further data can be transmitted after this function returns. This includes the push mechanism. Attempting to send two replies, or to push resources after a reply has been sent, will result in an error.

Arguments

-
-
-
-Status -
-
-

-The status code for the response. -

+
Status
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Body -
-
-

-The body can be either a binary value, an iolist or a -sendfile tuple telling Cowboy to send the contents of -a file. -

+
+

Header names must be given as lowercase binary strings.

+
Body
+

The body can be either a binary value, an iolist or a sendfile tuple telling Cowboy to send the contents of a file.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object should be used from that point onward -as it contains updated information about the state of the request.

-
-
-
+

A new Req object is returned.

+

The returned Req object should be used from that point onward as it contains updated information about the state of the request.

Changelog

-
-
    -
  • -

    -2.0: Only the Req is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the Req is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Reply
-
-
Req = cowboy_req:reply(404, Req0).
-
-
Reply with custom headers
-
-
Req = cowboy_req:reply(401, #{
-    <<"www-authenticate">> => <<"Basic realm=\"erlang.org\"">>
-}, Req0).
-
-
Reply with custom headers and a body
-
-
Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, "Hello world!", Req0).
-
-
-
+
Req = cowboy_req:reply(200, #{
+    <<"content-type">> => <<"text/plain">>
+}, "Hello world!", Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:set_resp_body(3), cowboy_req:stream_reply(3), cowboy_req:push(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.resp_header/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.resp_header/index.html index d8fa99c9..f3538cdf 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.resp_header/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.resp_header/index.html @@ -62,113 +62,58 @@

cowboy_req:resp_header(3)

-

Name

-
-

cowboy_req:resp_header - Response header

-
-
-
+

cowboy_req:resp_header - Response header

Description

-
-
-
-
resp_header(Name, Req)          -> resp_header(Name, Req, undefined)
-resp_header(Name, Req, Default) -> binary() | Default
-
-Name    :: binary()          %% lowercase; case insensitive
-Req     :: cowboy_req:req()
-Default :: any()
-

Return the value for the given response header.

-

The response header must have been set previously using -cowboy_req:set_resp_header(3) or -cowboy_req:set_resp_headers(3).

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+
resp_header(Name, Req)          -> resp_header(Name, Req, undefined)
+resp_header(Name, Req, Default) -> binary() | Default
+
+Name    :: binary()          %% lowercase; case insensitive
+Req     :: cowboy_req:req()
+Default :: any()
+
+

Return the value for the given response header.

+

The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3).

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Name -
-
-

-Desired response header name as a lowercase binary string. -

+
Name
+

Desired response header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the header is missing. -

+
Default
+

Default value returned when the header is missing.

-
-
- -
+

Return value

-
-

The header value is returned as a binary string. When the -header is missing, the default argument is returned.

-
-
-
+

The header value is returned as a binary string. When the header is missing, the default argument is returned.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the content-type response header
-
-
Type = cowboy_req:resp_header(<<"content-type">>, Req).
-
-
Get the content-type response header with a default value
-
-
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).
-
-
-
+
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).
+

See also

- - +

cowboy_req(3), cowboy_req:resp_headers(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.resp_headers/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.resp_headers/index.html index bb771112..1d44e3bd 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.resp_headers/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.resp_headers/index.html @@ -62,79 +62,38 @@

cowboy_req:resp_headers(3)

-

Name

-
-

cowboy_req:resp_headers - Response headers

-
-
-
+

cowboy_req:resp_headers - Response headers

Description

-
-
-
-
resp_headers(Req :: cowboy_req:req()) -> cowboy:http_headers()
-

Return all response headers.

-
-
-
+
resp_headers(Req :: cowboy_req:req()) -> cowboy:http_headers()
+
+

Return all response headers.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Headers are returned as a map with keys being lowercase -binary strings, and values as binary strings.

-
-
-
+

Headers are returned as a map with keys being lowercase binary strings, and values as binary strings.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get all response headers
-
-
Headers = cowboy_req:resp_headers(Req).
-
-
-
+
Headers = cowboy_req:resp_headers(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:resp_header(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.scheme/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.scheme/index.html index 31e71352..f5a450eb 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.scheme/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.scheme/index.html @@ -62,89 +62,52 @@

cowboy_req:scheme(3)

-

Name

-
-

cowboy_req:scheme - URI scheme

-
-
-
+

cowboy_req:scheme - URI scheme

Description

-
-
-
-
scheme(Req :: cowboy_req:req()) -> Scheme :: binary()
-

Return the scheme of the effective request URI.

-

The scheme can also be obtained using pattern matching:

-
-
-
#{scheme := Scheme} = Req.
-
-
-
+
#{scheme := Scheme} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The scheme is returned as a binary. It is case insensitive.

-

Cowboy will only set the scheme to <<"http">> or <<"https">>.

-
-
-
+

The scheme is returned as a binary. It is case insensitive.

+

Cowboy will only set the scheme to <<"http">> or <<"https">>.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Redirect HTTP to HTTPS
-
-
init(Req0=#{scheme := <<"http">>}, State) ->
-    Req = cowboy_req:reply(302, #{
-        <<"location">> => cowboy_req:uri(Req, #{scheme => <<"https">>})
-    }, Req0),
-    {ok, Req, State};
-init(Req, State) ->
-    {cowboy_rest, Req, State}.
-
-
-
+
init(Req0=#{scheme := <<"http">>}, State) ->
+    Req = cowboy_req:reply(302, #{
+        <<"location">> => cowboy_req:uri(Req, #{scheme => <<"https">>})
+    }, Req0),
+    {ok, Req, State};
+init(Req, State) ->
+    {cowboy_rest, Req, State}.
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_body/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_body/index.html index c82a6aa6..d3fda72f 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_body/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_body/index.html @@ -62,138 +62,79 @@

cowboy_req:set_resp_body(3)

-

Name

-
-

cowboy_req:set_resp_body - Set the response body

-
-
-
+

cowboy_req:set_resp_body - Set the response body

Description

-
-
-
-
set_resp_body(Body, Req :: cowboy_req:req())
-        -> Req
-
-Body :: cowboy_req:resp_body()
-

Set the response body.

-

The response body will be sent when a reply is initiated. -Note that the functions stream_reply/2,3 and reply/4 -will override the body set by this function.

-

This function can also be used to remove a response body -that was set previously. To do so, simply call this function -with an empty body.

-
-
-
+
set_resp_body(Body, Req :: cowboy_req:req())
+	-> Req
+
+Body :: cowboy_req:resp_body()
+
+

Set the response body.

+

The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function.

+

This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body.

Arguments

-
-
-
-Body -
-
-

-The body can be either a binary value, an iolist or a -sendfile tuple telling Cowboy to send the contents of -a file. -

+
Body
+

The body can be either a binary value, an iolist or a sendfile tuple telling Cowboy to send the contents of a file.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the body will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the body will not be sent in the response.

Changelog

-
-
    -
  • -

    -2.0: The function now accepts a sendfile tuple. -

    +
    • 2.0: The function now accepts a sendfile tuple.
    • -
    • -

      -2.0: The set_resp_body_fun/2,3 functions were removed. -

      +
    • 2.0: The set_resp_body_fun/2,3 functions were removed.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set the response body
-
-
Req = cowboy_req:set_resp_body(<<"Hello world!">>, Req0).
-
-
Set the response body as an iolist
-
-
Req = cowboy_req:set_resp_body([
-    "<html><head><title>",
-    page_title(),
-    "</title></head><body>",
-    page_body(),
-    "</body></html>"
-], Req0).
-
-
Tell Cowboy to send data from a file
-
-
{ok, #file_info{size=Size}} = file:read_file_info(Filename),
-Req = cowboy_req:set_resp_body({sendfile, 0, Size, Filename}, Req0).
-
-
Clear any previously set response body
-
-
Req = cowboy_req:set_resp_body(<<>>, Req0).
-
-
-
+
Req = cowboy_req:set_resp_body(<<>>, Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_cookie/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_cookie/index.html index bd1c7358..2d420826 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_cookie/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_cookie/index.html @@ -62,167 +62,104 @@

cowboy_req:set_resp_cookie(3)

-

Name

-
-

cowboy_req:set_resp_cookie - Set a cookie

-
-
-
+

cowboy_req:set_resp_cookie - Set a cookie

Description

-
-
-
-
set_resp_cookie(Name, Value, Req :: cowboy_req:req())
-    -> set_resp_cookie(Name, Value, [], Req)
-
-set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts)
-    -> Req
-
-Name  :: binary()                  %% case sensitive
-Value :: iodata()                  %% case sensitive
-Opts  :: cow_cookie:cookie_opts()
-

Set a cookie to be sent with the response.

-

Note that cookie names are case sensitive.

-
-
-
+
set_resp_cookie(Name, Value, Req :: cowboy_req:req())
+    -> set_resp_cookie(Name, Value, [], Req)
+
+set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts)
+    -> Req
+
+Name  :: binary()                  %% case sensitive
+Value :: iodata()                  %% case sensitive
+Opts  :: cow_cookie:cookie_opts()
+
+

Set a cookie to be sent with the response.

+

Note that cookie names are case sensitive.

Arguments

-
-
-
-Name -
-
-

-Cookie name. -

+
Name
+

Cookie name.

-
-Value -
-
-

-Cookie value. -

+
Value
+

Cookie value.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-Cookie options. -

+
Opts
+

Cookie options.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the cookie will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the cookie will not be sent in the response.

Changelog

-
-
    -
  • -

    -2.0: set_resp_cookie/3 introduced as an alias to set_resp_cookie/4 with no options. -

    +
    • 2.0: set_resp_cookie/3 introduced as an alias to set_resp_cookie/4 with no options.
    • -
    • -

      -2.0: The first argument type is now binary() instead of iodata(). -

      +
    • 2.0: The first argument type is now binary() instead of iodata().
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set a session cookie
-
-
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0).
-
-
Set a cookie with an expiration time
-
-
Req = cowboy_req:set_resp_cookie(<<"lang">>, <<"fr-FR">>,
-    Req0, #{max_age => 3600}).
-
-
Delete a cookie
-
-
Req = cowboy_req:set_resp_cookie(<<"sessionid">>, <<>>,
-    Req0, #{max_age => 0}).
-
-
Set a cookie for a specific domain and path
-
-
Req = cowboy_req:set_resp_cookie(<<"inaccount">>, <<"1">>,
-    Req0, #{domain => "my.example.org", path => "/account"}).
-
-
Restrict a cookie to HTTPS
-
-
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID,
-    Req0, #{secure => true}).
-
-
Restrict a cookie to HTTP
-
-
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID,
-    Req0, #{http_only => true}).
-
-
-
+
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
+Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID,
+    Req0, #{http_only => true}).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_header/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_header/index.html index 0e29b2c6..bd957907 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_header/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_header/index.html @@ -62,121 +62,60 @@

cowboy_req:set_resp_header(3)

-

Name

-
-

cowboy_req:set_resp_header - Set a response header

-
-
-
+

cowboy_req:set_resp_header - Set a response header

Description

-
-
-
-
set_resp_header(Name, Value, Req :: cowboy_req:req())
-        -> Req
-
-Name  :: binary()  %% lowercase; case insensitive
-Value :: iodata()  %% case depends on header
-

Set a header to be sent with the response.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may be overwritten by those set from the -reply functions.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-
-
-
+
set_resp_header(Name, Value, Req :: cowboy_req:req())
+	-> Req
+
+Name  :: binary()  %% lowercase; case insensitive
+Value :: iodata()  %% case depends on header
+
+

Set a header to be sent with the response.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

Arguments

-
-
-
-Name -
-
-

-Header name as a lowercase binary string. -

+
Name
+

Header name as a lowercase binary string.

-
-Value -
-
-

-Header value. -

+
Value
+

Header value.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the header will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the header will not be sent in the response.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set a header in the response
-
-
Req = cowboy_req:set_resp_header(<<"allow">>, "GET", Req0).
-
-
Construct a header using iolists
-
-
Req = cowboy_req:set_resp_header(<<"allow">>,
-    [allowed_methods(), ", OPTIONS"], Req0).
-
-
-
+
Req = cowboy_req:set_resp_header(<<"allow">>,
+    [allowed_methods(), ", OPTIONS"], Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_headers(3), cowboy_req:has_resp_header(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3), cowboy_req:delete_resp_header(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_headers/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_headers/index.html index 8168794d..5a8e6469 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_headers/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_headers/index.html @@ -62,109 +62,51 @@

cowboy_req:set_resp_headers(3)

-

Name

-
-

cowboy_req:set_resp_headers - Set several response headers

-
-
-
+

cowboy_req:set_resp_headers - Set several response headers

Description

-
-
-
-
set_resp_headers(Headers, Req :: cowboy_req:req())
-    -> Req
-
-Headers :: cowboy:http_headers()
-

Set several headers to be sent with the response.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may be overwritten by those set from the -reply functions. Likewise, headers set by this function may -overwrite headers that were set previously.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-
-
-
+
set_resp_headers(Headers, Req :: cowboy_req:req())
+    -> Req
+
+Headers :: cowboy:http_headers()
+
+

Set several headers to be sent with the response.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. Likewise, headers set by this function may overwrite headers that were set previously.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

Arguments

-
-
-
-Headers -
-
-

-Headers as a map with keys being lowercase binary strings, -and values as binary strings. -

+
Headers
+

Headers as a map with keys being lowercase binary strings, and values as binary strings.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the headers will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the headers will not be sent in the response.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set several response headers
-
-
Req = cowboy_req:set_resp_headers(#{
-    <<"content-type">>     => <<"text/html">>,
-    <<"content-encoding">> => <<"gzip">>
-}, Req0).
-
-
-
+
Req = cowboy_req:set_resp_headers(#{
+    <<"content-type">>     => <<"text/html">>,
+    <<"content-encoding">> => <<"gzip">>
+}, Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_header(3), cowboy_req:has_resp_header(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3), cowboy_req:delete_resp_header(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.stream_body/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.stream_body/index.html index fbd8a6e4..c46178af 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.stream_body/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.stream_body/index.html @@ -62,116 +62,56 @@

cowboy_req:stream_body(3)

-

Name

-
-

cowboy_req:stream_body - Stream the response body

-
-
-
+

cowboy_req:stream_body - Stream the response body

Description

-
-
-
-
stream_body(Data, IsFin, Req :: cowboy_req:req()) -> ok
-
-Data  :: iodata()
-IsFin :: fin | nofin
-

Stream the response body.

-

This function may be called as many times as needed after -initiating a response using the -cowboy_req:stream_reply(3) -function.

-

The second argument indicates if this call is the final -call. Use the nofin value until you know no more data -will be sent. The final call should use fin (possibly -with an empty data value).

-

Note that not using fin for the final call is not an -error; Cowboy will take care of it when the request -handler terminates if needed. Depending on the resource -it may however be more efficient to do it as early as -possible.

-

You do not need to handle HEAD requests specifically as -Cowboy will ensure no data is sent when you call this function.

-
-
-
+
stream_body(Data, IsFin, Req :: cowboy_req:req()) -> ok
+
+Data  :: iodata()
+IsFin :: fin | nofin
+
+

Stream the response body.

+

This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function.

+

The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. The final call should use fin (possibly with an empty data value).

+

Note that not using fin for the final call is not an error; Cowboy will take care of it when the request handler terminates if needed. Depending on the resource it may however be more efficient to do it as early as possible.

+

You do not need to handle HEAD requests specifically as Cowboy will ensure no data is sent when you call this function.

Arguments

-
-
-
-Data -
-
-

-The data to be sent. -

+
Data
+

The data to be sent.

-
-IsFin -
-
-

-A flag indicating whether this is the final piece of data -to be sent. -

+
IsFin
+

A flag indicating whether this is the final piece of data to be sent.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces chunk/2. -

    +
    • 2.0: Function introduced. Replaces chunk/2.
    • -
-
-
-
+

Examples

-
-
-
Stream the response body
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, Req0),
-cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
-timer:sleep(1000),
-cowboy_req:stream_body(<<"World!\n">>, fin, Req).
-
-
-
+
Req = cowboy_req:stream_reply(200, #{
+    <<"content-type">> => <<"text/plain">>
+}, Req0),
+cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
+timer:sleep(1000),
+cowboy_req:stream_body(<<"World!\n">>, fin, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.stream_reply/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.stream_reply/index.html index fd1fe5fe..26220717 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.stream_reply/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.stream_reply/index.html @@ -62,148 +62,76 @@

cowboy_req:stream_reply(3)

-

Name

-
-

cowboy_req:stream_reply - Send the response headers

-
-
-
+

cowboy_req:stream_reply - Send the response headers

Description

-
-
-
-
stream_reply(Status, Req :: cowboy_req:req())
-    -> stream_reply(StatusCode, #{}, Req)
-
-stream_reply(Status, Headers, Req :: cowboy_req:req())
-    -> Req
-
-Status  :: cowboy:http_status()
-Headers :: cowboy:http_headers()
-

Send the response headers.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may overwrite those set by set_resp_header/3.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-

If a response body was set before calling this function, -it will not be sent.

-

Use cowboy_req:stream_body(3) -to stream the response body.

-

You may want to set the content-length header when using -this function, if it is known in advance. This will allow -clients using HTTP/2 and HTTP/1.0 to process the response -more efficiently.

-

The streaming method varies depending on the protocol being -used. HTTP/2 will use the usual DATA frames. HTTP/1.1 will -use chunked transfer-encoding. HTTP/1.0 will send the body -unmodified and close the connection at the end if no -content-length was set.

-

It is not possible to push resources after this function -returns. Any attempt will result in an error.

-
-
-
+
stream_reply(Status, Req :: cowboy_req:req())
+    -> stream_reply(StatusCode, #{}, Req)
+
+stream_reply(Status, Headers, Req :: cowboy_req:req())
+    -> Req
+
+Status  :: cowboy:http_status()
+Headers :: cowboy:http_headers()
+
+

Send the response headers.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

+

If a response body was set before calling this function, it will not be sent.

+

Use cowboy_req:stream_body(3) to stream the response body.

+

You may want to set the content-length header when using this function, if it is known in advance. This will allow clients using HTTP/2 and HTTP/1.0 to process the response more efficiently.

+

The streaming method varies depending on the protocol being used. HTTP/2 will use the usual DATA frames. HTTP/1.1 will use chunked transfer-encoding. HTTP/1.0 will send the body unmodified and close the connection at the end if no content-length was set.

+

It is not possible to push resources after this function returns. Any attempt will result in an error.

Arguments

-
-
-
-Status -
-
-

-The status code for the response. -

+
Status
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Req -
-
-

-The Req object. -

+
+

Header names must be given as lowercase binary strings.

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward -in order to be able to stream the response body.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward in order to be able to stream the response body.

Changelog

-
-
    -
  • -

    -2.0: Only the Req is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the Req is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces chunked_reply/1,2. -

      +
    • 2.0: Function introduced. Replaces chunked_reply/1,2.
    • -
-
-
-
+

Examples

-
-
-
Initiate the response
-
-
Req = cowboy_req:stream_reply(200, Req0).
-
-
Stream the response with custom headers
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, Req0),
-cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
-timer:sleep(1000),
-cowboy_req:stream_body(<<"World!\n">>, fin, Req).
-
-
-
+
Req = cowboy_req:stream_reply(200, #{
+    <<"content-type">> => <<"text/plain">>
+}, Req0),
+cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
+timer:sleep(1000),
+cowboy_req:stream_body(<<"World!\n">>, fin, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:reply(3), cowboy_req:stream_body(3), cowboy_req:push(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.uri/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.uri/index.html index 8ba3971c..eb2f347d 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.uri/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.uri/index.html @@ -62,177 +62,106 @@

cowboy_req:uri(3)

-

Name

-
-

cowboy_req:uri - Reconstructed URI

-
-
-
+

cowboy_req:uri - Reconstructed URI

Description

-
-
-
-
uri(Req :: cowboy_req:req())       -> uri(Req, #{})
-uri(Req :: cowboy_req:req(), Opts) -> URI :: iodata()
-
-Opts :: #{
-    scheme   => iodata()           | undefined,
-    host     => iodata()           | undefined,
-    port     => inet:port_number() | undefined,
-    path     => iodata()           | undefined,
-    qs       => iodata()           | undefined,
-    fragment => iodata()           | undefined
-}
-

Reconstruct the effective request URI, optionally modifying components.

-

By default Cowboy will build a URI using the components found -in the request. Options allow disabling or replacing individual -components.

-
-
-
+
uri(Req :: cowboy_req:req())       -> uri(Req, #{})
+uri(Req :: cowboy_req:req(), Opts) -> URI :: iodata()
+
+Opts :: #{
+    scheme   => iodata()           | undefined,
+    host     => iodata()           | undefined,
+    port     => inet:port_number() | undefined,
+    path     => iodata()           | undefined,
+    qs       => iodata()           | undefined,
+    fragment => iodata()           | undefined
+}
+
+

Reconstruct the effective request URI, optionally modifying components.

+

By default Cowboy will build a URI using the components found in the request. Options allow disabling or replacing individual components.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-Map for overriding individual components. -

-

To replace a component, provide its new value as a binary -string or an iolist. To disable a component, set its value -to undefined.

-

As this function always returns a valid URI, there are some -things to note:

-
    -
  • -

    -Disabling the host also disables the scheme and port. -

    +
    Opts
    +

    Map for overriding individual components.

    +

    To replace a component, provide its new value as a binary string or an iolist. To disable a component, set its value to undefined.

    +

    As this function always returns a valid URI, there are some things to note:

    +
    • Disabling the host also disables the scheme and port.
    • -
    • -

      -There is no fragment component by default as these are - not sent with the request. -

      +
    • There is no fragment component by default as these are not sent with the request.
    • -
    • -

      -The port number may not appear in the resulting URI if - it is the default port for the given scheme (http: 80; https: 443). -

      +
    • The port number may not appear in the resulting URI if it is the default port for the given scheme (http: 80; https: 443).
    • -
+
-
-
- -
+

Return value

-
-

The reconstructed URI is returned as an iolist or a binary string.

-
-
-
+

The reconstructed URI is returned as an iolist or a binary string.

Changelog

-
-
    -
  • -

    -2.0: Individual components can be replaced or disabled. -

    +
    • 2.0: Individual components can be replaced or disabled.
    • -
    • -

      -2.0: Only the URI is returned, it is no longer wrapped in a tuple. -

      +
    • 2.0: Only the URI is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces host_url/1 and url/1. -

      +
    • 2.0: Function introduced. Replaces host_url/1 and url/1.
    • -
-
-
-
+

Examples

-
-

With an effective request URI http://example.org/path/to/res?edit=1 -we can have:

-
-
Protocol relative form
-
-
%% //example.org/path/to/res?edit=1
-cowboy_req:uri(Req, #{scheme => undefined}).
-
-
Serialized origin for use in the origin header
-
-
%% http://example.org
-cowboy_req:uri(Req, #{path => undefined, qs => undefined}).
-
-
HTTP/1.1 origin form (path and query string only)
-
-
%% /path/to/res?edit=1
-cowboy_req:uri(Req, #{host => undefined}).
-
-
Add a fragment to the URI
-
-
%% http://example.org/path/to/res?edit=1#errors
-cowboy_req:uri(Req, #{fragment => <<"errors">>}).
-
-
Ensure the scheme is HTTPS
-
-
%% https://example.org/path/to/res?edit=1
-cowboy_req:uri(Req, #{scheme => <<"https">>}).
-
-
Convert the URI to a binary string
-
-
iolist_to_binary(cowboy_req:uri(Req)).
-
-
-
+
iolist_to_binary(cowboy_req:uri(Req)).
+

See also

- - +

cowboy_req(3), cowboy_req:scheme(3), cowboy_req:host(3), cowboy_req:port(3), cowboy_req:path(3), cowboy_req:qs(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req.version/index.html b/docs/en/cowboy/2.0/manual/cowboy_req.version/index.html index d78d9796..840d85cd 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req.version/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req.version/index.html @@ -62,88 +62,47 @@

cowboy_req:version(3)

-

Name

-
-

cowboy_req:version - HTTP version

-
-
-
+

cowboy_req:version - HTTP version

Description

-
-
-
-
version(Req :: cowboy_req:req()) -> Version :: cowboy:http_version()
-

Return the HTTP version used for the request.

-

The version can also be obtained using pattern matching:

-
-
-
#{version := Version} = Req.
-
-
-
+
#{version := Version} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The HTTP version used for the request is returned as an -atom. It is provided for informative purposes only.

-
-
-
+

The HTTP version used for the request is returned as an atom. It is provided for informative purposes only.

Changelog

-
-
    -
  • -

    -2.0: Only the version is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the version is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the HTTP version
-
-
Version = cowboy_req:version(Req).
-
-
-
+
Version = cowboy_req:version(Req).
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_req/index.html b/docs/en/cowboy/2.0/manual/cowboy_req/index.html index df055476..27d28cd0 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_req/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_req/index.html @@ -62,389 +62,206 @@

cowboy_req(3)

-

Name

-
-

cowboy_req - HTTP request and response

-
-
-
+

cowboy_req - HTTP request and response

Description

-
-

The module cowboy_req provides functions to access, manipulate -and respond to requests.

-

There are four types of functions in this module. They can be -differentiated by their name and their return type:

-
- ---- - - - - +

The module cowboy_req provides functions to access, manipulate and respond to requests.

+

There are four types of functions in this module. They can be differentiated by their name and their return type:

+
Type Name pattern Return type
+ + + + + + - - - - - - + + + - - - - + + + - - - - + + + - - - - - - -
TypeName patternReturn type
accessno verb, parse_*, match_*Value

access

no verb, parse_*, match_*

Value

questionhas_*boolean()

question

has_*

boolean()

modificationset_*Req

modification

set_*

Req

actionany other verbok | {Result, Value, Req}

action

any other verb

ok | {Result, Value, Req}

-
-

Any Req returned must be used in place of the one passed as -argument. Functions that perform an action in particular write -state in the Req object to make sure you are using the function -correctly. For example, it’s only possible to send one response, -and to read the body once.

-
-
-
+ +

Any Req returned must be used in place of the one passed as argument. Functions that perform an action in particular write state in the Req object to make sure you are using the function correctly. For example, it's only possible to send one response, and to read the body once.

Exports

-
-

Raw request:

-
-

Processed request:

-
-

Request body:

-
-

Response:

-
-
-
-
+

Raw request:

+ +

Processed request:

+ +

Request body:

+ +

Response:

+

Types

-
-

push_opts()

-
-
-
push_opts() :: #{
-    method => binary(),            %% case sensitive
-    scheme => binary(),            %% lowercase; case insensitive
-    host   => binary(),            %% lowercase; case insensitive
-    port   => inet:port_number(),
-    qs     => binary()             %% case sensitive
-}
-

Push options.

-

By default, Cowboy will use the GET method, an empty query string, -and take the scheme, host and port directly from the current -request’s URI.

-
-
+
push_opts() :: #{
+    method => binary(),            %% case sensitive
+    scheme => binary(),            %% lowercase; case insensitive
+    host   => binary(),            %% lowercase; case insensitive
+    port   => inet:port_number(),
+    qs     => binary()             %% case sensitive
+}
+
+

Push options.

+

By default, Cowboy will use the GET method, an empty query string, and take the scheme, host and port directly from the current request's URI.

read_body_opts()

-
-
-
read_body_opts() :: #{
-    length  => non_neg_integer(),
-    period  => non_neg_integer(),
-    timeout => timeout()
-}
-

Body reading options.

-

The defaults are function-specific.

-
-
+
read_body_opts() :: #{
+    length  => non_neg_integer(),
+    period  => non_neg_integer(),
+    timeout => timeout()
+}
+
+

Body reading options.

+

The defaults are function-specific.

req()

-
-
-
req() :: #{
-    method  := binary(),               %% case sensitive
-    version := cowboy:http_version() | atom(),
-    scheme  := binary(),               %% lowercase; case insensitive
-    host    := binary(),               %% lowercase; case insensitive
-    port    := inet:port_number(),
-    path    := binary(),               %% case sensitive
-    qs      := binary(),               %% case sensitive
-    headers := cowboy:http_headers(),
-    peer    := {inet:ip_address(), inet:port_number()}
-}
-

The Req object.

-

Contains information about the request and response. While -some fields are publicly documented, others aren’t and shouldn’t -be used.

-

You may add custom fields if required. Make sure to namespace -them by prepending an underscore and the name of your application:

-
-
Setting a custom field
-
-
Req#{_myapp_auth_method => pubkey}.
- -
+
Req#{_myapp_auth_method => pubkey}.
+

resp_body()

-
-
-
resp_body() :: iodata()
-    | {sendfile, Offset, Length, Filename}
+
resp_body() :: iodata()
+    | {sendfile, Offset, Length, Filename}
 
-Offset   :: non_neg_integer()
-Length   :: non_neg_integer()
-Filename :: file:name_all()
-

Response body.

-

It can take two forms: the actual data to be sent or a -tuple indicating which file to send.

-

When sending data directly, the type is either a binary or -an iolist. Iolists are an efficient way to build output. -Instead of concatenating strings or binaries, you can simply -build a list containing the fragments you want to send in the -order they should be sent:

-
-
Example iolists usage
-
-
1> RespBody = ["Hello ", [<<"world">>, $!]].
-["Hello ",[<<"world">>,33]]
-2> io:format("~s~n", [RespBody]).
-Hello world!
-

Note that the length must be greater than zero for any data -to be sent. Cowboy will send an empty body when the length -is zero.

- - - -
+
1> RespBody = ["Hello ", [<<"world">>, $!]].
+["Hello ",[<<"world">>,33]]
+2> io:format("~s~n", [RespBody]).
+Hello world!
+
+

Note that the length must be greater than zero for any data to be sent. Cowboy will send an empty body when the length is zero.

See also

- - +

cowboy(7)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_rest/index.html b/docs/en/cowboy/2.0/manual/cowboy_rest/index.html index dc58cef1..9b2e96d4 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_rest/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_rest/index.html @@ -62,641 +62,464 @@

cowboy_rest(3)

-

Name

-
-

cowboy_rest - REST handlers

-
-
-
+

cowboy_rest - REST handlers

Description

-
-

The module cowboy_rest implements the HTTP state machine.

-

Implementing REST handlers is not enough to provide a REST -interface; this interface must also follow the REST -constraints including HATEOAS (hypermedia as the engine -of application state).

-
-
-
+

The module cowboy_rest implements the HTTP state machine.

+

Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state).

Callbacks

-
-

REST handlers implement the following interface:

-
-
-
init(Req, State)
-    -> {cowboy_rest, Req, State}
-
-Callback(Req, State)
-    -> {Result, Req, State}
-     | {stop, Req, State}
-
-terminate(Reason, Req, State) -> ok  %% optional
-
-Req    :: cowboy_req:req()
-State  :: any()
-Reason :: normal
-        | {crash, error | exit | throw, any()}
-
-Callback - see below
-Result   - see below
-Default  - see below
-

The init/2 callback is common to all handlers. To switch -to the REST handler behavior, it must return cowboy_rest -as the first element of the tuple.

-

The Callback/2 above represents all the REST-specific -callbacks. They are described in the following section -of this manual. REST-specific callbacks differ by their -name, semantics, result and default values. The default -value is the one used when the callback has not been -implemented. They otherwise all follow the same interface.

-

The stop tuple can be returned to stop REST processing. -If no response was sent before then, Cowboy will send a -204 No Content.

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the handler. -Cowboy will terminate the process right after this. There -is no need to perform any cleanup in this callback.

-

The following terminate reasons are defined for loop handlers:

-
-
-normal -
-
-

- The handler terminated normally. -

+

REST handlers implement the following interface:

+
+
init(Req, State)
+    -> {cowboy_rest, Req, State}
+
+Callback(Req, State)
+    -> {Result, Req, State}
+     | {stop, Req, State}
+
+terminate(Reason, Req, State) -> ok  %% optional
+
+Req    :: cowboy_req:req()
+State  :: any()
+Reason :: normal
+        | {crash, error | exit | throw, any()}
+
+Callback - see below
+Result   - see below
+Default  - see below
+
+

The init/2 callback is common to all handlers. To switch to the REST handler behavior, it must return cowboy_rest as the first element of the tuple.

+

The Callback/2 above represents all the REST-specific callbacks. They are described in the following section of this manual. REST-specific callbacks differ by their name, semantics, result and default values. The default value is the one used when the callback has not been implemented. They otherwise all follow the same interface.

+

The stop tuple can be returned to stop REST processing. If no response was sent before then, Cowboy will send a 204 No Content.

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the handler. Cowboy will terminate the process right after this. There is no need to perform any cleanup in this callback.

+

The following terminate reasons are defined for loop handlers:

+
normal
+

The handler terminated normally.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
-
-
-
+

REST callbacks

-
-

AcceptCallback

-
-
-
AcceptCallback(Req, State) -> {Result, Req, State}
-
-Result  :: true | {true, URI :: iodata()} | false}
-Default  - crash
-

Process the request body.

-

This function should create or update the resource using the -request body.

-

For PUT requests, the body is a representation of the resource -that is being created or replaced.

-

For POST requests, the body is typically application-specific -instructions on how to process the request, but it may also -be a representation of the resource. When creating a new -resource with POST at a different location, return {true, URI} -with URI the new location.

-

For PATCH requests, the body is a series of instructions on -how to update the resource. Patch files or JSON Patch are -examples of such media types.

-

A response body may be sent. The appropriate media type, charset -and language for the response can be retrieved from the Req -object using the media_type, charset and language keys, -respectively. The body can be set using -cowboy_req:set_resp_body(3).

-
-
+
+
AcceptCallback(Req, State) -> {Result, Req, State}
+
+Result  :: true | {true, URI :: iodata()} | false}
+Default  - crash
+
+

Process the request body.

+

This function should create or update the resource using the request body.

+

For PUT requests, the body is a representation of the resource that is being created or replaced.

+

For POST requests, the body is typically application-specific instructions on how to process the request, but it may also be a representation of the resource. When creating a new resource with POST at a different location, return {true, URI} with URI the new location.

+

For PATCH requests, the body is a series of instructions on how to update the resource. Patch files or JSON Patch are examples of such media types.

+

A response body may be sent. The appropriate media type, charset and language for the response can be retrieved from the Req object using the media_type, charset and language keys, respectively. The body can be set using cowboy_req:set_resp_body(3).

allowed_methods

-
-
-
allowed_methods(Req, State) -> {Result, Req, State}
+
allowed_methods(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% case sensitive
-Default :: [<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]
-

Return the list of allowed methods.

-
-
+Result :: [binary()] %% case sensitive +Default :: [<<"GET">>, <<"HEAD">>, <<"OPTIONS">>] +
+

Return the list of allowed methods.

allow_missing_post

-
-
-
allow_missing_post(Req, State) -> {Result, Req, State}
+
allow_missing_post(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether POST is allowed when the resource doesn’t exist.

-

Returning true here means that a new resource will be -created. The URI for the newly created resource should be -returned from the AcceptCallback function.

-
-
+Result :: boolean() +Default :: true +
+

Return whether POST is allowed when the resource doesn't exist.

+

Returning true here means that a new resource will be created. The URI for the newly created resource should be returned from the AcceptCallback function.

charsets_provided

-
-
-
charsets_provided(Req, State) -> {Result, Req, State}
+
charsets_provided(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% lowercase; case insensitive
-Default  - skip this step
-

Return the list of charsets the resource provides in order -of preference.

-

During content negotiation Cowboy will pick the most -appropriate charset for the client. The client advertises -charsets it prefers with the accept-charset header. When -that header is missing, Cowboy picks the first charset -from the resource.

-

Cowboy will add the negotiated charset to the Req object -after this step completes:

-
-
+

Cowboy will add the negotiated charset to the Req object after this step completes:

+
-
req() :: #{
-    charset => binary()  %% lowercase; case insensitive
-}
-
-
+
req() :: #{
+    charset => binary()  %% lowercase; case insensitive
+}
+

content_types_accepted

-
-
-
content_types_accepted(Req, State) -> {Result, Req, State}
-
-Result     :: [{binary() | ParsedMime, AcceptCallback :: atom()}]
-ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-
-Default     - crash
-

Return the list of media types the resource accepts in -order of preference.

-

A media type is made of different parts. The media type -text/html;charset=utf-8 is of type text, subtype html -and has a single parameter charset with value utf-8.

-

Cowboy will match the content-type request header against -the media types the server accepts and select the appropriate -callback. When that header is missing, or when the server does not -accept this media type, the request fails and an error response -is returned. Cowboy will execute the callback immediately otherwise.

-

An empty parameters list [] means that no parameters will be -accepted. When any parameter is acceptable, the tuple form -should be used with parameters as the atom '*'.

-

Cowboy treats all parameters as case sensitive, except for the -charset parameter, which is known to be case insensitive. You -should therefore always provide the charset as a lowercase -binary string.

- -
+
+
content_types_accepted(Req, State) -> {Result, Req, State}
+
+Result     :: [{binary() | ParsedMime, AcceptCallback :: atom()}]
+ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+Default     - crash
+
+ +

Return the list of media types the resource accepts in order of preference.

+

A media type is made of different parts. The media type text/html;charset=utf-8 is of type text, subtype html and has a single parameter charset with value utf-8.

+ + + +

Cowboy will match the content-type request header against the media types the server accepts and select the appropriate callback. When that header is missing, or when the server does not accept this media type, the request fails and an error response is returned. Cowboy will execute the callback immediately otherwise.

+ +

An empty parameters list [] means that no parameters will be accepted. When any parameter is acceptable, the tuple form should be used with parameters as the atom '*'.

+

Cowboy treats all parameters as case sensitive, except for the charset parameter, which is known to be case insensitive. You should therefore always provide the charset as a lowercase binary string.

+ + + + + +

content_types_provided

-
-
-
content_types_provided(Req, State) -> {Result, Req, State}
-
-Result     :: [{binary() | ParsedMime, ProvideCallback :: atom()}]
-ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-
-Default     - [{{ <<"text">>, <<"html">>, '*'}, to_html}]
-

Return the list of media types the resource provides in -order of preference.

-

A media type is made of different parts. The media type -text/html;charset=utf-8 is of type text, subtype html -and has a single parameter charset with value utf-8.

-

During content negotiation Cowboy will pick the most appropriate -media type for the client. The client advertises media types it -prefers with the accept header. When that header is missing, -the content negotiation fails and an error response is returned.

-

The callback given for the selected media type will be called -at the end of the execution of GET and HEAD requests when a -representation must be sent to the client.

-

An empty parameters list [] means that no parameters will be -accepted. When any parameter is acceptable, the tuple form -should be used with parameters as the atom '*'.

-

Cowboy treats all parameters as case sensitive, except for the -charset parameter, which is known to be case insensitive. You -should therefore always provide the charset as a lowercase -binary string.

-

Cowboy will add the negotiated media_type to the Req object -after this step completes:

-
-
-
req() :: #{
-    media_type => ParsedMime
-}
-
-
+
+
content_types_provided(Req, State) -> {Result, Req, State}
+
+Result     :: [{binary() | ParsedMime, ProvideCallback :: atom()}]
+ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+Default     - [{{ <<"text">>, <<"html">>, '*'}, to_html}]
+
+ + +

Return the list of media types the resource provides in order of preference.

+

A media type is made of different parts. The media type text/html;charset=utf-8 is of type text, subtype html and has a single parameter charset with value utf-8.

+ + + +

During content negotiation Cowboy will pick the most appropriate media type for the client. The client advertises media types it prefers with the accept header. When that header is missing, the content negotiation fails and an error response is returned.

+

The callback given for the selected media type will be called at the end of the execution of GET and HEAD requests when a representation must be sent to the client.

+ +

An empty parameters list [] means that no parameters will be accepted. When any parameter is acceptable, the tuple form should be used with parameters as the atom '*'.

+

Cowboy treats all parameters as case sensitive, except for the charset parameter, which is known to be case insensitive. You should therefore always provide the charset as a lowercase binary string.

+

Cowboy will add the negotiated media_type to the Req object after this step completes:

+
+
req() :: #{
+    media_type => ParsedMime
+}
+
+

delete_completed

-
-
-
delete_completed(Req, State) -> {Result, Req, State}
+
delete_completed(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the resource has been fully deleted from the -system, including from any internal cache.

-

Returning false will result in a 202 Accepted response -being sent instead of a 200 OK or 204 No Content.

-
-
+Result :: boolean() +Default :: true +
+

Return whether the resource has been fully deleted from the system, including from any internal cache.

+

Returning false will result in a 202 Accepted response being sent instead of a 200 OK or 204 No Content.

delete_resource

-
-
-
delete_resource(Req, State) -> {Result, Req, State}
+
delete_resource(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Delete the resource.

-

Cowboy will send an error response when this function -returns false.

- -
+Result :: boolean() +Default :: false +
+

Delete the resource.

+

Cowboy will send an error response when this function returns false.

expires

-
-
-
expires(Req, State) -> {Result, Req, State}
+
expires(Req, State) -> {Result, Req, State}
 
-Result  :: calendar:datetime() | binary() | undefined
-Default :: undefined
-

Return the resource’s expiration date.

- -
+Result :: calendar:datetime() | binary() | undefined +Default :: undefined +
+

Return the resource's expiration date.

forbidden

-
-
-
forbidden(Req, State) -> {Result, Req, State}
+
forbidden(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether access to the resource is forbidden.

-

A 403 Forbidden response will be sent if this -function returns true. This status code means that -access is forbidden regardless of authentication, -and that the request shouldn’t be repeated.

- -
+Result :: boolean() +Default :: false +
+

Return whether access to the resource is forbidden.

+

A 403 Forbidden response will be sent if this function returns true. This status code means that access is forbidden regardless of authentication, and that the request shouldn't be repeated.

generate_etag

-
-
-
generate_etag(Req, State) -> {Result, Req, State}
+
generate_etag(Req, State) -> {Result, Req, State}
 
-Result  :: binary() | {weak | strong, binary()}
-Default  - no etag value
-

Return the entity tag of the resource.

-

When a binary is returned, the value is automatically -parsed to a tuple. The binary must be in the same -format as the etag header, including quotes.

- -
+Result :: binary() | {weak | strong, binary()} +Default - no etag value +
+

Return the entity tag of the resource.

+

When a binary is returned, the value is automatically parsed to a tuple. The binary must be in the same format as the etag header, including quotes.

is_authorized

-
-
-
is_authorized(Req, State) -> {Result, Req, State}
+
is_authorized(Req, State) -> {Result, Req, State}
 
-Result  :: true | {false, AuthHeader :: iodata()}
-Default  - true
-

Return whether the user is authorized to perform the action.

-

This function should be used to perform any necessary -authentication of the user before attempting to perform -any action on the resource.

-

When authentication fails, the AuthHeader value will -be sent in the www-authenticate header for the -401 Unauthorized response.

- -
+Result :: true | {false, AuthHeader :: iodata()} +Default - true +
+

Return whether the user is authorized to perform the action.

+

This function should be used to perform any necessary authentication of the user before attempting to perform any action on the resource.

+

When authentication fails, the AuthHeader value will be sent in the www-authenticate header for the 401 Unauthorized response.

is_conflict

-
-
-
is_conflict(Req, State) -> {Result, Req, State}
+
is_conflict(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the PUT request results in a conflict.

-

A 409 Conflict response is sent when true.

- -
+Result :: boolean() +Default :: false +
+

Return whether the PUT request results in a conflict.

+

A 409 Conflict response is sent when true.

known_methods

-
-
-
known_methods(Req, State) -> {Result, Req, State}
+
known_methods(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% case sensitive
-Default :: [<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>,
-            <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]
-

Return the list of known methods.

-

The full list of methods known by the server should be -returned, regardless of their use in the resource.

-

The default value lists the methods Cowboy knows and -implement in cowboy_rest.

- -
+Result :: [binary()] %% case sensitive +Default :: [<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, + <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>] +
+

Return the list of known methods.

+

The full list of methods known by the server should be returned, regardless of their use in the resource.

+

The default value lists the methods Cowboy knows and implement in cowboy_rest.

languages_provided

-
-
-
languages_provided(Req, State) -> {Result, Req, State}
+
languages_provided(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% lowercase; case insensitive
-Default  - skip this step
-

Return the list of languages the resource provides in order -of preference.

-

During content negotiation Cowboy will pick the most -appropriate language for the client. The client advertises -languages it prefers with the accept-language header. When -that header is missing, Cowboy picks the first language -from the resource.

-

Cowboy will add the negotiated language to the Req object -after this step completes:

-
-
+

Cowboy will add the negotiated language to the Req object after this step completes:

+
-
req() :: #{
-    language => binary()  %% lowercase; case insensitive
-}
-
-
+
req() :: #{
+    language => binary()  %% lowercase; case insensitive
+}
+

last_modified

-
-
-
last_modified(Req, State) -> {Result, Req, State}
+
last_modified(Req, State) -> {Result, Req, State}
 
-Result  :: calendar:datetime()
-Default  - no last modified value
-

Return the resource’s last modification date.

-

This date will be used to test against the if-modified-since -and if-unmodified-since headers, and sent as the last-modified -header in the response to GET and HEAD requests.

- -
+Result :: calendar:datetime() +Default - no last modified value +
+

Return the resource's last modification date.

+

This date will be used to test against the if-modified-since and if-unmodified-since headers, and sent as the last-modified header in the response to GET and HEAD requests.

malformed_request

-
-
-
malformed_request(Req, State) -> {Result, Req, State}
+
malformed_request(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the request is malformed.

-

A request is malformed when a component required by the -resource is invalid. This may include the query string -or individual headers. They should be parsed and validated -in this function. The body should not be read at this point.

- -
+Result :: boolean() +Default :: false +
+

Return whether the request is malformed.

+

A request is malformed when a component required by the resource is invalid. This may include the query string or individual headers. They should be parsed and validated in this function. The body should not be read at this point.

moved_permanently

-
-
-
moved_permanently(Req, State) -> {Result, Req, State}
+
moved_permanently(Req, State) -> {Result, Req, State}
 
-Result  :: {true, URI :: iodata()} | false
-Default :: false
-

Return whether the resource was permanently moved, and -what its new location is.

- -
+Result :: {true, URI :: iodata()} | false +Default :: false +
+

Return whether the resource was permanently moved, and what its new location is.

moved_temporarily

-
-
-
moved_temporarily(Req, State) -> {Result, Req, State}
+
moved_temporarily(Req, State) -> {Result, Req, State}
 
-Result  :: {true, URI :: iodata()} | false
-Default :: false
-

Return whether the resource was temporarily moved, and -what its new location is.

- -
+Result :: {true, URI :: iodata()} | false +Default :: false +
+

Return whether the resource was temporarily moved, and what its new location is.

multiple_choices

-
-
-
multiple_choices(Req, State) -> {Result, Req, State}
-
-Result  :: boolean()
-Default :: false
-

Return whether the client should engage in reactive -negotiation.

-

Return true when the server has multiple representations -of a resource, each with their specific identifier, but is -unable to determine which is best for the client. For -example an image might have different sizes and the server -is unable to determine the capabilities of the client.

-

When returning true the server should send a body with -links to the different representations. If the server has -a preferred representation it can send its link inside a -location header.

- -
+
+
multiple_choices(Req, State) -> {Result, Req, State}
+
+Result  :: boolean()
+Default :: false
+
+

Return whether the client should engage in reactive negotiation.

+

Return true when the server has multiple representations of a resource, each with their specific identifier, but is unable to determine which is best for the client. For example an image might have different sizes and the server is unable to determine the capabilities of the client.

+

When returning true the server should send a body with links to the different representations. If the server has a preferred representation it can send its link inside a location header.

options

-
-
-
options(Req, State) -> {ok, Req, State}
-

Respond to an OPTIONS request.

-

The response should inform the client the communication -options available for this resource. By default Cowboy -will send a 200 OK response with the allow header set.

-
-
+
options(Req, State) -> {ok, Req, State}
+
+

Respond to an OPTIONS request.

+

The response should inform the client the communication options available for this resource. By default Cowboy will send a 200 OK response with the allow header set.

previously_existed

-
-
-
previously_existed(Req, State) -> {Result, Req, State}
+
previously_existed(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the resource existed previously.

- -
+Result :: boolean() +Default :: false +
+

Return whether the resource existed previously.

ProvideCallback

-
-
-
ProvideCallback(Req, State) -> {Result, Req, State}
+
ProvideCallback(Req, State) -> {Result, Req, State}
 
-Result  :: cowboy_req:resp_body()
-Default  - crash
-

Return the response body.

-

The response body can be provided either as the actual data -to be sent or a tuple indicating which file to send.

-

This function is called for both GET and HEAD requests. For -the latter the body is not sent, however.

-

Note that there used to be a way to stream the response body. -It was temporarily removed and will be added back in a later -release.

- -
+Result :: cowboy_req:resp_body() +Default - crash +
+

Return the response body.

+

The response body can be provided either as the actual data to be sent or a tuple indicating which file to send.

+

This function is called for both GET and HEAD requests. For the latter the body is not sent, however.

+ + + +

Note that there used to be a way to stream the response body. It was temporarily removed and will be added back in a later release.

+

resource_exists

-
-
-
resource_exists(Req, State) -> {Result, Req, State}
+
resource_exists(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the resource exists.

- -
+Result :: boolean() +Default :: true +
+

Return whether the resource exists.

service_available

-
-
-
service_available(Req, State) -> {Result, Req, State}
+
service_available(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the service is available.

-

A 503 Service Unavailable response will be sent when this -function returns false.

- -
+Result :: boolean() +Default :: true +
+

Return whether the service is available.

+

A 503 Service Unavailable response will be sent when this function returns false.

uri_too_long

-
-
-
uri_too_long(Req, State) -> {Result, Req, State}
+
uri_too_long(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the requested URI is too long.

-

This function can be used to further restrict the length -of the URI for this specific resource.

- -
+Result :: boolean() +Default :: false +
+

Return whether the requested URI is too long.

+

This function can be used to further restrict the length of the URI for this specific resource.

valid_content_headers

-
-
-
valid_content_headers(Req, State) -> {Result, Req, State}
+
valid_content_headers(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the content headers are valid.

-

This callback can be used to reject requests that have -invalid content header values, for example an unsupported -content-encoding.

- -
+Result :: boolean() +Default :: true +
+

Return whether the content headers are valid.

+

This callback can be used to reject requests that have invalid content header values, for example an unsupported content-encoding.

valid_entity_length

-
-
-
valid_entity_length(Req, State) -> {Result, Req, State}
+
valid_entity_length(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the request body length is within acceptable boundaries.

-

A 413 Request Entity Too Large response will be sent if this -function returns false.

- -
+Result :: boolean() +Default :: true +
+

Return whether the request body length is within acceptable boundaries.

+

A 413 Request Entity Too Large response will be sent if this function returns false.

variances

-
-
-
variances(Req, State) -> {Result, Req, State}
+
variances(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% case insensitive
-Default :: []
-

Return the list of request headers that affect the -representation of the resource.

-

Cowboy automatically adds the accept, accept-charset and -accept-language headers when necessary.

- - - -
+Result :: [binary()] %% case insensitive +Default :: [] +
+

Return the list of request headers that affect the representation of the resource.

+

Cowboy automatically adds the accept, accept-charset and accept-language headers when necessary.

See also

- - +

cowboy(7), cowboy_handler(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_router.compile/index.html b/docs/en/cowboy/2.0/manual/cowboy_router.compile/index.html index 112c1524..28bea031 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_router.compile/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_router.compile/index.html @@ -62,87 +62,48 @@

cowboy_router:compile(3)

-

Name

-
-

cowboy_router:compile - Compile routes to the resources

-
-
-
+

cowboy_router:compile - Compile routes to the resources

Description

-
-
-
-
compile(cowboy_router:routes()) -> cowboy_router:dispatch_rules()
-

Compile routes to the resources.

-

Takes a human readable list of routes and transforms it -into a form more efficient to process.

-
-
-
+
compile(cowboy_router:routes()) -> cowboy_router:dispatch_rules()
+
+

Compile routes to the resources.

+

Takes a human readable list of routes and transforms it into a form more efficient to process.

Arguments

-
-
-
-Routes -
-
-

-Human readable list of routes. -

+
Routes
+

Human readable list of routes.

-
-
- -
+

Return value

-
-

An opaque dispatch rules value is returned. This value -must be given to Cowboy as a middleware environment value.

-
-
-
+

An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Compile routes and start a listener
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []},
-        {"/[...], cowboy_static, {priv_dir, my_example_app, ""}}
-    ]}
-]),
-
-{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{
-    env => #{dispatch => Dispatch}
-}).
-
-
-
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []},
+        {"/[...], cowboy_static, {priv_dir, my_example_app, ""}}
+    ]}
+]),
+
+{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{
+    env => #{dispatch => Dispatch}
+}).
+

See also

- - +

cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_router/index.html b/docs/en/cowboy/2.0/manual/cowboy_router/index.html index a4c31b82..d6cb8147 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_router/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_router/index.html @@ -62,110 +62,65 @@

cowboy_router(3)

-

Name

-
-

cowboy_router - Router middleware

-
-
-
+

cowboy_router - Router middleware

Description

-
-

The cowboy_router middleware maps the requested host and -path to the handler to be used for processing the request.

-

The router takes the dispatch rules as input from the -middleware environment. Dispatch rules are generated by -calling the -cowboy_router:compile(3) -function.

-

When a route matches, the router sets the handler and -handler_opts middleware environment values containing -the handler module and initial state, respectively.

-

The router will stop execution when no route matches. -It will send a 400 response if no host was found, and -a 404 response otherwise.

-
-
-
+

The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request.

+

The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function.

+

When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively.

+

The router will stop execution when no route matches. It will send a 400 response if no host was found, and a 404 response otherwise.

Exports

-
-
-
-
-
+

Types

-
-

bindings()

-
-
-
bindings() :: #{atom() => any()}
-

Bindings found during routing.

-
-
+
bindings() :: #{atom() => any()}
+
+

Bindings found during routing.

dispatch_rules()

-

Opaque type containing the compiled routes.

-
-
+

Opaque type containing the compiled routes.

routes()

-
-
-
routes() = [
-    {Host, PathList} |
-    {Host, Fields, PathList}
+
routes() = [
+    {Host, PathList} |
+    {Host, Fields, PathList}
 ]
 
-PathList :: [
-    {Path, Handler, InitialState} |
-    {Path, Fields, Handler, InitialState}
+PathList :: [
+    {Path, Handler, InitialState} |
+    {Path, Fields, Handler, InitialState}
 ]
 
-Host         :: '_' | iodata()
-Path         :: '_' | iodata()
-Fields       :: cowboy:fields()
-Handler      :: module()
-InitialState :: any()
-

Human readable list of routes to handlers.

-

Cowboy uses this list to map hosts and paths, optionally -augmented with constraints applied to the bindings, to -handler modules.

-

The syntax for routes is currently defined in the user guide.

-
-
+Host :: '_' | iodata() +Path :: '_' | iodata() +Fields :: cowboy:fields() +Handler :: module() +InitialState :: any() +
+

Human readable list of routes to handlers.

+

Cowboy uses this list to map hosts and paths, optionally augmented with constraints applied to the bindings, to handler modules.

+

The syntax for routes is currently defined in the user guide.

+ +

tokens()

-
-
-
tokens() :: [binary()]
-

List of host_info and path_info tokens that were found -using the ... syntax.

- - - -
+
tokens() :: [binary()]
+
+

List of host_info and path_info tokens that were found using the ... syntax.

See also

- - +

cowboy(7), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:host_info(3), cowboy_req:path_info(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_static/index.html b/docs/en/cowboy/2.0/manual/cowboy_static/index.html index 9a74ad94..47c98159 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_static/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_static/index.html @@ -62,175 +62,110 @@

cowboy_static(3)

-

Name

-
-

cowboy_static - Static file handler

-
-
-
+

cowboy_static - Static file handler

Description

-
-

The module cowboy_static implements file serving capabilities -using the REST semantics provided by cowboy_rest.

-

The static file handler is a pre-written handler coming with -Cowboy. To serve files, use it in your routes.

-
-
-
+

The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest.

+

The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes.

Options

-
-
-
-
opts() :: {priv_file, App, Path}
-        | {priv_file, App, Path, Extra}
-        | {file, Path}
-        | {file, Path, Extra}
-        | {priv_dir, App, Path}
-        | {priv_dir, App, Path, Extra}
-        | {dir, Path}
-        | {dir, Path, Extra}
-
-App        :: atom()
-Path       :: binary() | string()
-Extra      :: [Etag | Mimetypes]
-
-Etag       :: {etag, module(), function()}
-            | {etag, false}
-
-Mimetypes  :: {mimetypes, module(), function()}
-            | {mimetypes, binary() | ParsedMime}
-
-ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-

Static handler configuration.

-
-
-priv_file -
-
-

-Send a file. -

-

The path is relative to the given application’s private -directory.

+
opts() :: {priv_file, App, Path}
+        | {priv_file, App, Path, Extra}
+        | {file, Path}
+        | {file, Path, Extra}
+        | {priv_dir, App, Path}
+        | {priv_dir, App, Path, Extra}
+        | {dir, Path}
+        | {dir, Path, Extra}
+
+App        :: atom()
+Path       :: binary() | string()
+Extra      :: [Etag | Mimetypes]
+
+Etag       :: {etag, module(), function()}
+            | {etag, false}
+
+Mimetypes  :: {mimetypes, module(), function()}
+            | {mimetypes, binary() | ParsedMime}
+
+ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+

Static handler configuration.

+
priv_file
+

Send a file.

+

The path is relative to the given application's private directory.

-
-file -
-
-

-Send a file. -

-

The path is either absolute or relative to the Erlang node’s -current directory.

+
file
+

Send a file.

+

The path is either absolute or relative to the Erlang node's current directory.

-
-priv_dir -
-
-

-Recursively serve files from a directory. -

-

The path is relative to the given application’s private -directory.

+
priv_dir
+

Recursively serve files from a directory.

+

The path is relative to the given application's private directory.

-
-dir -
-
-

-Recursively serve files from a directory. -

-

The path is either absolute or relative to the Erlang node’s -current directory.

+
dir
+

Recursively serve files from a directory.

+

The path is either absolute or relative to the Erlang node's current directory.

-
-

The extra options allow you to define how the etag should be -calculated and how the MIME type of files should be detected.

-

By default the static handler will generate an etag based -on the size and modification time of the file. You may disable -the etag entirely with {etag, false} or provide a module -and function that will be called when needed:

-
-
-
generate_etag(Path, Size, Mtime) -> {strong | weak, binary()}
-
-Path  :: binary()
-Size  :: non_neg_integer()
-Mtime :: file:date_time()
-

By default the static handler will detect Web-related MIME types -by looking at the file extension. You can provide a specific -MIME type that will always be used, or a module and function that -will be called when needed:

-
-
-
detect_mimetype(Path) -> ParsedMime
-
-Path       :: binary()
-ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-

Cowboy comes with two such functions; the default function -cow_mimetypes:web/1, and a second function generated from -the Apache mime.types file, cow_mimetypes:all/1.

-

The MIME type function should return -{<<"application">>, <<"octet-stream">>, []} -when it fails to detect a file’s MIME type.

- - -
+
detect_mimetype(Path) -> ParsedMime
+
+Path       :: binary()
+ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+ +

Cowboy comes with two such functions; the default function cow_mimetypes:web/1, and a second function generated from the Apache mime.types file, cow_mimetypes:all/1.

+

The MIME type function should return {<<"application">>, <<"octet-stream">>, []} when it fails to detect a file's MIME type.

Changelog

-
-
    -
  • -

    -1.0: Handler introduced. -

    +
    • 1.0: Handler introduced.
    • -
-
- -
+

Examples

-
-
-
Custom etag function
-
-
generate_etag(Path, Size, Mtime) ->
-    {strong, integer_to_binary(
-        erlang:phash2({Path, Size, Mtime}, 16#ffffffff))}.
-
-
Custom MIME type function
-
-
always_octet_stream(_Path) ->
-    case filename:extension(Path) of
-        <<".erl">> -> {<<"text">>, <<"plain">>, []};
-        _ -> {<<"application">>, <<"octet-stream">>, []}
-    end.
-
-
-
+
always_octet_stream(_Path) ->
+    case filename:extension(Path) of
+        <<".erl">> -> {<<"text">>, <<"plain">>, []};
+        _ -> {<<"application">>, <<"octet-stream">>, []}
+    end.
+

See also

- - +

cowboy(7), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_stream/index.html b/docs/en/cowboy/2.0/manual/cowboy_stream/index.html index 488e5d87..095b0831 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_stream/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_stream/index.html @@ -62,411 +62,282 @@

cowboy_stream(3)

-

Name

-
-

cowboy_handler - Stream handlers

-
-
-
+

cowboy_handler - Stream handlers

Description

-
-

The module cowboy_stream defines a callback interface -and a protocol for handling HTTP streams.

-

An HTTP request and its associated response is called -a stream. A connection may have many streams. In HTTP/1.1 -they are executed sequentially, while in HTTP/2 they are -executed concurrently.

-

Cowboy calls the stream handler for nearly all events -related to a stream. Exceptions vary depending on the -protocol.

-

Extra care must be taken when implementing stream handlers -to ensure compatibility. While some modification of the -events and commands is allowed, it is generally not a good -idea to completely omit them.

-
-
-
+

The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams.

+

An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently.

+

Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol.

+

Extra care must be taken when implementing stream handlers to ensure compatibility. While some modification of the events and commands is allowed, it is generally not a good idea to completely omit them.

Callbacks

-
-

Stream handlers must implement the following interface:

-
-
-
init(StreamID, Req, Opts) -> {Commands, State}
-data(StreamID, IsFin, Data, State) -> {Commands, State}
-info(StreamID, Info, State) -> {Commands, State}
-terminate(StreamID, Reason, State) -> any()
-early_error(StreamID, Reason, PartialReq, Resp, Opts) -> Resp
-
-StreamID   :: cowboy_stream:streamid()
-Req        :: cowboy_req:req()
-Opts       :: cowboy:opts()
-Commands   :: cowboy_stream:commands()
-State      :: any()
-IsFin      :: cowboy_stream:fin()
-Data       :: binary()
-Info       :: any()
-Reason     :: cowboy_stream:reason()
-PartialReq  - cowboy_req:req(), except all fields are optional
-Resp       :: cowboy_stream:resp_command()
-

HTTP/1.1 will initialize a stream only when the request-line -and all headers have been received. When errors occur before -that point Cowboy will call the callback early_error/5 -with a partial request, the error reason and the response -Cowboy intends to send. All other events go throuh the -stream handler using the normal callbacks.

-

HTTP/2 will initialize the stream when the HEADERS block has -been fully received and decoded. Any protocol error occuring -before that will not result in a response being sent and -will therefore not go through the stream handler. In addition -Cowboy may terminate streams without sending an HTTP response -back.

-

The stream is initialized by calling init/3. All streams -that are initialized will eventually be terminated by calling -terminate/3.

-

When Cowboy receives data for the stream it will call data/4. -The data given is the request body after any transfer decoding -has been applied.

-

When Cowboy receives a message addressed to a stream, or when -Cowboy needs to inform the stream handler that an internal -event has occurred, it will call info/3.

-
-
-
+
init(StreamID, Req, Opts) -> {Commands, State}
+data(StreamID, IsFin, Data, State) -> {Commands, State}
+info(StreamID, Info, State) -> {Commands, State}
+terminate(StreamID, Reason, State) -> any()
+early_error(StreamID, Reason, PartialReq, Resp, Opts) -> Resp
+
+StreamID   :: cowboy_stream:streamid()
+Req        :: cowboy_req:req()
+Opts       :: cowboy:opts()
+Commands   :: cowboy_stream:commands()
+State      :: any()
+IsFin      :: cowboy_stream:fin()
+Data       :: binary()
+Info       :: any()
+Reason     :: cowboy_stream:reason()
+PartialReq  - cowboy_req:req(), except all fields are optional
+Resp       :: cowboy_stream:resp_command()
+
+

HTTP/1.1 will initialize a stream only when the request-line and all headers have been received. When errors occur before that point Cowboy will call the callback early_error/5 with a partial request, the error reason and the response Cowboy intends to send. All other events go throuh the stream handler using the normal callbacks.

+

HTTP/2 will initialize the stream when the HEADERS block has been fully received and decoded. Any protocol error occuring before that will not result in a response being sent and will therefore not go through the stream handler. In addition Cowboy may terminate streams without sending an HTTP response back.

+

The stream is initialized by calling init/3. All streams that are initialized will eventually be terminated by calling terminate/3.

+

When Cowboy receives data for the stream it will call data/4. The data given is the request body after any transfer decoding has been applied.

+

When Cowboy receives a message addressed to a stream, or when Cowboy needs to inform the stream handler that an internal event has occurred, it will call info/3.

Commands

-
-

Stream handlers can return a list of commands to be executed -from the init/3, data/4 and info/3 callbacks. In addition, -the early_error/5 callback must return a response command.

-

The following commands are defined:

-
+

Stream handlers can return a list of commands to be executed from the init/3, data/4 and info/3 callbacks. In addition, the early_error/5 callback must return a response command.

+ + + + + +

The following commands are defined:

response

-

Send a response to the client.

-
-
-
{response, cowboy:http_status(), cowboy:http_headers(),
-    cowboy_req:resp_body()}
-

No more data can be sent after this command.

-
-
+
{response, cowboy:http_status(), cowboy:http_headers(),
+    cowboy_req:resp_body()}
+
+

No more data can be sent after this command.

headers

-

Initiate a response to the client.

-
-
-
{headers, cowboy:http_status(), cowboy:http_headers()}
-

This initiates a response to the client. The stream -will end when a data command with the fin flag is -returned.

- -
+
{headers, cowboy:http_status(), cowboy:http_headers()}
+
+

This initiates a response to the client. The stream will end when a data command with the fin flag is returned.

data

-

Send data to the client.

-
-
-
{data, fin(), iodata()}
- -
+
{data, fin(), iodata()}
+

push

-

Push a resource to the client.

-
-
-
{push, Method, Scheme, Host, inet:port_number(),
-    Path, Qs, cowboy:http_headers()}
+
{push, Method, Scheme, Host, inet:port_number(),
+    Path, Qs, cowboy:http_headers()}
 
-Method = Scheme = Host = Path = Qs = binary()
-

The command will be ignored if the protocol does not provide -any server push mechanism.

- -
+Method = Scheme = Host = Path = Qs = binary() +
+

The command will be ignored if the protocol does not provide any server push mechanism.

flow

-
-
-
{flow, pos_integer()}
-

Request more data to be read from the request body. The -exact behavior depends on the protocol.

- -
+
{flow, pos_integer()}
+
+

Request more data to be read from the request body. The exact behavior depends on the protocol.

spawn

-

Inform Cowboy that a process was spawned and should be -supervised.

-
-
-
{spawn, pid(), timeout()}
- -
+
{spawn, pid(), timeout()}
+

error_response

-

Send an error response if no response was sent previously.

-
-
-
{error_response, cowboy:http_status(), cowboy:http_headers(), iodata()}
- -
+
{error_response, cowboy:http_status(), cowboy:http_headers(), iodata()}
+

switch_protocol

-

Switch to a different protocol.

-
-
-
{switch_protocol, cowboy:http_headers(), module(), state()}
-

Contains the headers that will be sent in the 101 response, -along with the module implementing the protocol we are -switching to and its initial state.

- -
+
{switch_protocol, cowboy:http_headers(), module(), state()}
+
+

Contains the headers that will be sent in the 101 response, along with the module implementing the protocol we are switching to and its initial state.

stop

-

Stop the stream.

-
-
-
stop
-

While no more data can be sent after the fin flag was set, -the stream is still tracked by Cowboy until it is stopped by -the handler.

-

The behavior when stopping a stream for which no response -has been sent will vary depending on the protocol. The stream -will end successfully as far as the client is concerned.

-

To indicate that an error occurred, either use error_response -before stopping, or use internal_error.

- -
+
stop
+
+

While no more data can be sent after the fin flag was set, the stream is still tracked by Cowboy until it is stopped by the handler.

+

The behavior when stopping a stream for which no response has been sent will vary depending on the protocol. The stream will end successfully as far as the client is concerned.

+

To indicate that an error occurred, either use error_response before stopping, or use internal_error.

internal_error

-

Stop the stream with an error.

-
-
-
{internal_error, Reason, HumanReadable}
-
-Reason        = any()
-HumanReadable = atom()
-

This command should be used when the stream cannot continue -because of an internal error. An error_response command -may be sent before that to advertise to the client why the -stream is dropped.

- - - -
+
{internal_error, Reason, HumanReadable}
+
+Reason        = any()
+HumanReadable = atom()
+
+

This command should be used when the stream cannot continue because of an internal error. An error_response command may be sent before that to advertise to the client why the stream is dropped.

Predefined events

-
-

Cowboy will forward all messages sent to the stream to -the info/3 callback. To send a message to a stream, -send a message to the connection process with the form -{{Pid, StreamID}, Msg}. The connection process will -then forward Msg to the stream handlers.

-

Cowboy will also forward the exit signals for the -processes that the stream spawned.

-
+

Cowboy will forward all messages sent to the stream to the info/3 callback. To send a message to a stream, send a message to the connection process with the form {{Pid, StreamID}, Msg}. The connection process will then forward Msg to the stream handlers.

+

Cowboy will also forward the exit signals for the processes that the stream spawned.

EXIT

-

A process spawned by this stream has exited.

-
-
+ + +

A process spawned by this stream has exited.

+
-
{'EXIT', pid(), any()}
-

This is the raw exit message without any modification.

-
-
+
{'EXIT', pid(), any()}
+
+

This is the raw exit message without any modification.

+ + + + + + + + + + + + + + + + +

response

-

Same as the response command.

-

Usually sent when the request process replies to the client. -May also be sent by Cowboy internally.

-
-
+

Same as the response command.

+

Usually sent when the request process replies to the client. May also be sent by Cowboy internally.

headers

-

Same as the headers command.

-

Sent when the request process starts replying to the client.

-
-
+

Same as the headers command.

+

Sent when the request process starts replying to the client.

data

-

Same as the data command.

-

Sent when the request process streams data to the client.

-
-
+

Same as the data command.

+

Sent when the request process streams data to the client.

push

-

Same as the push command.

-

Sent when the request process pushes a resource to the client.

-
-
+

Same as the push command.

+

Sent when the request process pushes a resource to the client.

switch_protocol

- -

Sent when switching to the HTTP/2 or Websocket protocol.

-
-
- -
+

Same as the switch_protocol command.

+ +

Sent when switching to the HTTP/2 or Websocket protocol.

Exports

-
-

The following function should be called by modules implementing -stream handlers to execute the next stream handler in the list:

-
-
-
-
+

Types

-
-

commands()

-
-
-
commands() :: [Command]
-

See the list of commands for details.

-
-
+
commands() :: [Command]
+
+

See the list of commands for details.

fin()

-
-
-
fin() :: fin | nofin
-

Used in commands and events to indicate that this is -the end of the stream.

-
-
+
fin() :: fin | nofin
+
+

Used in commands and events to indicate that this is the end of the stream.

partial_req()

-
-
-
req() :: #{
-    method  => binary(),               %% case sensitive
-    version => cowboy:http_version() | atom(),
-    scheme  => binary(),               %% lowercase; case insensitive
-    host    => binary(),               %% lowercase; case insensitive
-    port    => inet:port_number(),
-    path    => binary(),               %% case sensitive
-    qs      => binary(),               %% case sensitive
-    headers => cowboy:http_headers(),
-    peer    => {inet:ip_address(), inet:port_number()}
-}
-

Partial request information received when an early error is -detected.

- -
+
req() :: #{
+    method  => binary(),               %% case sensitive
+    version => cowboy:http_version() | atom(),
+    scheme  => binary(),               %% lowercase; case insensitive
+    host    => binary(),               %% lowercase; case insensitive
+    port    => inet:port_number(),
+    path    => binary(),               %% case sensitive
+    qs      => binary(),               %% case sensitive
+    headers => cowboy:http_headers(),
+    peer    => {inet:ip_address(), inet:port_number()}
+}
+
+

Partial request information received when an early error is detected.

reason()

-
-
-
reason() :: normal
-    | {internal_error, timeout | {error | exit | throw, any()}, HumanReadable}
-    | {socket_error, closed | atom(), HumanReadable}
-    | {stream_error, Error, HumanReadable}
-    | {connection_error, Error, HumanReadable}
-    | {stop, cow_http2:frame(), HumanReadable}
-
-Error         = atom()
-HumanReadable = atom()
-

Reason for the stream termination.

- -
+
reason() :: normal
+    | {internal_error, timeout | {error | exit | throw, any()}, HumanReadable}
+    | {socket_error, closed | atom(), HumanReadable}
+    | {stream_error, Error, HumanReadable}
+    | {connection_error, Error, HumanReadable}
+    | {stop, cow_http2:frame(), HumanReadable}
+
+Error         = atom()
+HumanReadable = atom()
+
+

Reason for the stream termination.

resp_command()

-
-
-
resp_command() :: {response, cowboy:http_status(),
-    cowboy:http_headers(), cowboy_req:resp_body()}
-

See the response command for details.

- -
+
resp_command() :: {response, cowboy:http_status(),
+    cowboy:http_headers(), cowboy_req:resp_body()}
+
+

See the response command for details.

streamid()

-
-
-
streamid() :: any()
-

The identifier for this stream.

-

The identifier is unique over the connection process. -It is possible to form a unique identifier node-wide and -cluster-wide by wrapping it in a {self(), StreamID} -tuple.

- - - -
+
streamid() :: any()
+
+

The identifier for this stream.

+

The identifier is unique over the connection process. It is possible to form a unique identifier node-wide and cluster-wide by wrapping it in a {self(), StreamID} tuple.

Changelog

-
-
    -
  • -

    -2.0: Module introduced. -

    +
    • 2.0: Module introduced.
    • -
-
- - +

cowboy(7), cowboy_http(3), cowboy_http2(3)

+ diff --git a/docs/en/cowboy/2.0/manual/cowboy_websocket/index.html b/docs/en/cowboy/2.0/manual/cowboy_websocket/index.html index 8710a2f9..0291d043 100644 --- a/docs/en/cowboy/2.0/manual/cowboy_websocket/index.html +++ b/docs/en/cowboy/2.0/manual/cowboy_websocket/index.html @@ -62,295 +62,144 @@

cowboy_websocket(3)

-

Name

-
-

cowboy_websocket - Websocket

-
-
-
+

cowboy_websocket - Websocket

Description

-
-

The module cowboy_websocket implements Websocket -as a Ranch protocol. It also defines a callback interface -for handling Websocket connections.

-
-
-
+

The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections.

Callbacks

-
-

Websocket handlers must implement the following callback -interface:

-
-
-
init(Req, State)
-    -> {cowboy_websocket, Req, State}
-     | {cowboy_websocket, Req, State, Opts}
-
-websocket_init(State)            -> CallResult  %% optional
-websocket_handle(InFrame, State) -> CallResult
-websocket_info(Info, State)      -> CallResult
-
-terminate(Reason, PartialReq, State) -> ok      %% optional
-
-Req        :: cowboy_req:req()
-PartialReq :: map()
-State      :: any()
-Opts       :: cowboy_websocket:opts()
-InFrame    :: {text | binary | ping | pong, binary()}
-OutFrame   :: cow_ws:frame()                    %% see types below
-Info       :: any()
-
-CallResult :: {ok, State}
-            | {ok, State, hibernate}
-            | {reply, OutFrame | [OutFrame], State}
-            | {reply, OutFrame | [OutFrame], State, hibernate}
-            | {stop, State}
-
-Reason     :: normal | stop | timeout
-            | remote | {remote, cow_ws:close_code(), binary()}
-            | {error, badencoding | badframe | closed | atom()}
-            | {crash, error | exit | throw, any()}
-

The init/2 callback is common to all handlers. To upgrade -the connection to Websocket, it must return cowboy_websocket -as the first element of the tuple.

-

Any operation requiring the HTTP request must be done in the -init/2 function, as the Req object will not be available -after it returns. Websocket sub-protocol selection should -therefore be done in this function.

-

The optional websocket_init/1 callback will be called once -the connection has been upgraded to Websocket. It can be used -to perform any required initialization of the handler.

-

Note that the init/2 function does not run in the same -process as the Websocket callbacks. Any Websocket-specific -initialization must be done in websocket_init/1.

-

The websocket_handle/2 callback will be called for every -frame received. The websocket_info/2 callback will be -called for every Erlang message received.

-

All three Websocket callbacks may send one or more frames -back to the client (by returning a reply tuple) or terminate -the connection (by sending a close frame or returning a stop -tuple).

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the connection. This -callback is common to all handlers. Note that Websocket will -not provide the full Req object by default, to save memory.

-

Cowboy will terminate the process right after closing the -Websocket connection. This means that there is no need to -perform any cleanup in the terminate/3 callback.

-

The following terminate reasons are defined for Websocket -connections:

-
-
-normal -
-
-

- The connection was closed normally before establishing a Websocket - connection. This typically happens if an ok tuple is returned - from the init/2 callback. -

+
init(Req, State)
+    -> {cowboy_websocket, Req, State}
+     | {cowboy_websocket, Req, State, Opts}
+
+websocket_init(State)            -> CallResult  %% optional
+websocket_handle(InFrame, State) -> CallResult
+websocket_info(Info, State)      -> CallResult
+
+terminate(Reason, PartialReq, State) -> ok      %% optional
+
+Req        :: cowboy_req:req()
+PartialReq :: map()
+State      :: any()
+Opts       :: cowboy_websocket:opts()
+InFrame    :: {text | binary | ping | pong, binary()}
+OutFrame   :: cow_ws:frame()                    %% see types below
+Info       :: any()
+
+CallResult :: {ok, State}
+            | {ok, State, hibernate}
+            | {reply, OutFrame | [OutFrame], State}
+            | {reply, OutFrame | [OutFrame], State, hibernate}
+            | {stop, State}
+
+Reason     :: normal | stop | timeout
+            | remote | {remote, cow_ws:close_code(), binary()}
+            | {error, badencoding | badframe | closed | atom()}
+            | {crash, error | exit | throw, any()}
+
+

The init/2 callback is common to all handlers. To upgrade the connection to Websocket, it must return cowboy_websocket as the first element of the tuple.

+

Any operation requiring the HTTP request must be done in the init/2 function, as the Req object will not be available after it returns. Websocket sub-protocol selection should therefore be done in this function.

+

The optional websocket_init/1 callback will be called once the connection has been upgraded to Websocket. It can be used to perform any required initialization of the handler.

+

Note that the init/2 function does not run in the same process as the Websocket callbacks. Any Websocket-specific initialization must be done in websocket_init/1.

+

The websocket_handle/2 callback will be called for every frame received. The websocket_info/2 callback will be called for every Erlang message received.

+

All three Websocket callbacks may send one or more frames back to the client (by returning a reply tuple) or terminate the connection (by sending a close frame or returning a stop tuple).

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the connection. This callback is common to all handlers. Note that Websocket will not provide the full Req object by default, to save memory.

+

Cowboy will terminate the process right after closing the Websocket connection. This means that there is no need to perform any cleanup in the terminate/3 callback.

+

The following terminate reasons are defined for Websocket connections:

+
normal
+

The connection was closed normally before establishing a Websocket connection. This typically happens if an ok tuple is returned from the init/2 callback.

-
-remote -
-
-

- The remote endpoint closed the connection without giving any - further details. -

+
remote
+

The remote endpoint closed the connection without giving any further details.

-
-{remote, Code, Payload} -
-
-

- The remote endpoint closed the connection with the given - Code and Payload as the reason. -

+
{remote, Code, Payload}
+

The remote endpoint closed the connection with the given Code and Payload as the reason.

-
-stop -
-
-

- The handler requested to close the connection, either by returning - a stop tuple or by sending a close frame. -

+
stop
+

The handler requested to close the connection, either by returning a stop tuple or by sending a close frame.

-
-timeout -
-
-

- The connection has been closed due to inactivity. The timeout - value can be configured from init/2. -

+
timeout
+

The connection has been closed due to inactivity. The timeout value can be configured from init/2.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
-{error, badencoding} -
-
-

- A text frame was sent by the client with invalid encoding. All - text frames must be valid UTF-8. -

+
{error, badencoding}
+

A text frame was sent by the client with invalid encoding. All text frames must be valid UTF-8.

-
-{error, badframe} -
-
-

- A protocol error has been detected. -

+
{error, badframe}
+

A protocol error has been detected.

-
-{error, closed} -
-
-

- The socket has been closed brutally without a close frame being - received first. -

+
{error, closed}
+

The socket has been closed brutally without a close frame being received first.

-
-{error, Reason} -
-
-

- A socket error ocurred. -

+
{error, Reason}
+

A socket error ocurred.

-
- - -
+

Types

-
-

cow_ws:frame()

-
-
-
frame() :: {text, iodata()}
-    | {binary, iodata()}
-    | ping | {ping, iodata()}
-    | pong | {pong, iodata()}
-    | close | {close, iodata()} | {close, close_code(), iodata()}
-
-close_code() :: 1000..1003 | 1006..1011 | 3000..4999
-

Websocket frames that can be sent as a response.

-

Note that there is no need to send pong frames back as -Cowboy does it automatically for you.

-
-
+
frame() :: {text, iodata()}
+    | {binary, iodata()}
+    | ping | {ping, iodata()}
+    | pong | {pong, iodata()}
+    | close | {close, iodata()} | {close, close_code(), iodata()}
+
+close_code() :: 1000..1003 | 1006..1011 | 3000..4999
+
+

Websocket frames that can be sent as a response.

+

Note that there is no need to send pong frames back as Cowboy does it automatically for you.

opts()

-
-
-
opts() :: #{
-    compress => boolean(),
-    idle_timeout => timeout(),
-    req_filter => fun((cowboy_req:req()) -> map())
-}
-

Websocket handler options.

-

This configuration is passed to Cowboy from the init/2 -function:

-
-
-
init(Req, State) ->
-    Opts = #{compress => true},
-    {cowboy_websocket, Req, State, Opts}.
-

The default value is given next to the option name:

-
-
-compress (false) -
-
-

- Whether to enable the Websocket frame compression - extension. Frames will only be compressed for the - clients that support this extension. -

+
init(Req, State) ->
+    Opts = #{compress => true},
+    {cowboy_websocket, Req, State, Opts}.
+
+

The default value is given next to the option name:

+
compress (false)
+

Whether to enable the Websocket frame compression extension. Frames will only be compressed for the clients that support this extension.

-
-idle_timeout (60000) -
-
-

- Time in milliseconds that Cowboy will keep the - connection open without receiving anything from - the client. -

+
idle_timeout (60000)
+

Time in milliseconds that Cowboy will keep the connection open without receiving anything from the client.

-
-req_filter -
-
-

- A function applied to the Req to compact it and - only keep required information. The Req is only - given back in the terminate/3 callback. By default - it keeps the method, version, URI components and peer - information. -

+
req_filter
+

A function applied to the Req to compact it and only keep required information. The Req is only given back in the terminate/3 callback. By default it keeps the method, version, URI components and peer information.

-
- - - -
+

Changelog

-
-
    -
  • -

    -2.0: The Req object is no longer passed to Websocket callbacks. -

    +
    • 2.0: The Req object is no longer passed to Websocket callbacks.
    • -
    • -

      -2.0: The callback websocket_terminate/3 was removed in favor of terminate/3. -

      +
    • 2.0: The callback websocket_terminate/3 was removed in favor of terminate/3.
    • -
    • -

      -1.0: Protocol introduced. -

      +
    • 1.0: Protocol introduced.
    • -
-
-
- +

cowboy(7), cowboy_handler(3), cowboy_http(3), cowboy_http2(3)

+ diff --git a/docs/en/cowboy/2.0/manual/http_status_codes/index.html b/docs/en/cowboy/2.0/manual/http_status_codes/index.html index 95c6ef0d..485dc418 100644 --- a/docs/en/cowboy/2.0/manual/http_status_codes/index.html +++ b/docs/en/cowboy/2.0/manual/http_status_codes/index.html @@ -62,271 +62,92 @@

HTTP status codes(7)

-

Name

-
-

HTTP status codes - status codes used by Cowboy

-
-
-
+

HTTP status codes - status codes used by Cowboy

Description

-
-

This chapter aims to list all HTTP status codes that Cowboy -may return, with details on the reasons why. The list given -here only includes the replies that Cowboy sends, not user -replies.

-
-
-
+

This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies.

100 Continue

-
-

When the client sends an expect: 100-continue header, -Cowboy automatically sends a this status code before -trying to read the request body. This behavior can be -disabled using the appropriate body option.

-
-
-
+

When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. This behavior can be disabled using the appropriate body option.

101 Switching Protocols

-
-

This is the status code sent when switching to the -Websocket protocol.

-
-
-
+

This is the status code sent when switching to the Websocket protocol.

200 OK

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

201 Created

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

202 Accepted

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

204 No Content

-
-

This status code is sent when the processing of a request -ends without any reply having been sent. It may also be -sent by cowboy_rest under normal conditions.

-
-
-
+

This status code is sent when the processing of a request ends without any reply having been sent. It may also be sent by cowboy_rest under normal conditions.

300 Multiple Choices

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

301 Moved Permanently

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

303 See Other

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

304 Not Modified

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

307 Temporary Redirect

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

400 Bad Request

-
-

Cowboy will send this status code for any of the -following reasons:

-
    -
  • -

    -Too many empty lines were sent before the request. -

    +

    Cowboy will send this status code for any of the following reasons:

    +
    • Too many empty lines were sent before the request.
    • -
    • -

      -The request-line could not be parsed. -

      +
    • The request-line could not be parsed.
    • -
    • -

      -Too many headers were sent. -

      +
    • Too many headers were sent.
    • -
    • -

      -A header name was too long. -

      +
    • A header name was too long.
    • -
    • -

      -A header value was too long. -

      +
    • A header value was too long.
    • -
    • -

      -The host header was missing from an HTTP/1.1 request. -

      +
    • The host header was missing from an HTTP/1.1 request.
    • -
    • -

      -The host header could not be parsed. -

      +
    • The host header could not be parsed.
    • -
    • -

      -The requested host was not found. -

      +
    • The requested host was not found.
    • -
    • -

      -The requested path could not be parsed. -

      +
    • The requested path could not be parsed.
    • -
    • -

      -The accept header could not be parsed when using REST. -

      +
    • The accept header could not be parsed when using REST.
    • -
    • -

      -REST under normal conditions. -

      +
    • REST under normal conditions.
    • -
    • -

      -A Websocket upgrade failed. -

      +
    • A Websocket upgrade failed.
    • -
-
-
-
+

401 Unauthorized

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

403 Forbidden

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

404 Not Found

-
-

This status code is sent when the router successfully -resolved the host but didn’t find a matching path for -the request. It may also be sent by cowboy_rest under -normal conditions.

-
-
-
+

This status code is sent when the router successfully resolved the host but didn't find a matching path for the request. It may also be sent by cowboy_rest under normal conditions.

405 Method Not Allowed

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

406 Not Acceptable

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

408 Request Timeout

-
-

Cowboy will send this status code to the client if the -client started to send a request, indicated by the -request-line being received fully, but failed to send -all headers in a reasonable time.

-
-
-
+

Cowboy will send this status code to the client if the client started to send a request, indicated by the request-line being received fully, but failed to send all headers in a reasonable time.

409 Conflict

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

410 Gone

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

412 Precondition Failed

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

413 Request Entity Too Large

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

414 Request-URI Too Long

-
-

Cowboy will send this status code to the client if the -request-line is too long. It may also be sent by -cowboy_rest under normal conditions.

-
-
-
+

Cowboy will send this status code to the client if the request-line is too long. It may also be sent by cowboy_rest under normal conditions.

415 Unsupported Media Type

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

500 Internal Server Error

-
-

This status code is sent when a crash occurs in HTTP, loop -or REST handlers, or when an invalid return value is -returned. It may also be sent by cowboy_rest under -normal conditions.

-
-
-
+

This status code is sent when a crash occurs in HTTP, loop or REST handlers, or when an invalid return value is returned. It may also be sent by cowboy_rest under normal conditions.

501 Not Implemented

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

503 Service Unavailable

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

505 HTTP Version Not Supported

-
-

Cowboy only supports the versions 1.0 and 1.1 of HTTP. -In all other cases this status code is sent back to the -client and the connection is closed.

-
-
+

Cowboy only supports the versions 1.0 and 1.1 of HTTP. In all other cases this status code is sent back to the client and the connection is closed.

+ diff --git a/docs/en/cowboy/2.0/manual/index.html b/docs/en/cowboy/2.0/manual/index.html index 9d5602a5..b7771995 100644 --- a/docs/en/cowboy/2.0/manual/index.html +++ b/docs/en/cowboy/2.0/manual/index.html @@ -62,171 +62,77 @@

Cowboy Function Reference

-

Name

-
-

cowboy - Small, fast, modern HTTP server for Erlang/OTP

-
-
-
+

cowboy - Small, fast, modern HTTP server for Erlang/OTP

Description

-
-

Cowboy is an HTTP server for Erlang/OTP with support for the -HTTP/1.1, HTTP/2 and Websocket protocols.

-

Cowboy aims to provide a complete HTTP stack. This includes -the implementation of the HTTP RFCs but also any directly -related standards, like Websocket or Server-Sent Events.

-
-
-
+

Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols.

+

Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events.

Modules

-
-

Functions:

-
-

Protocols:

-
+

Protocols:

+
-

Handlers:

-
+

Handlers:

+
-

Behaviors:

-
+

Behaviors:

+
-

Middlewares:

-
+

Middlewares:

+
-
-
-
+ +

Dependencies

-
-
    -
  • -

    -ranch(7) - Socket acceptor pool for TCP protocols -

    +
    • ranch(7) - Socket acceptor pool for TCP protocols
    • -
    • -

      -cowlib(7) - Support library for manipulating Web protocols -

      +
    • cowlib(7) - Support library for manipulating Web protocols
    • -
    • -

      -ssl - Secure communication over sockets -

      +
    • ssl - Secure communication over sockets
    • -
    • -

      -crypto - Crypto functions -

      +
    • crypto - Crypto functions
    • -
-

All these applications must be started before the cowboy -application. To start Cowboy and all dependencies at once:

-
-
-
{ok, _} = application:ensure_all_started(cowboy).
-
-
-
+
{ok, _} = application:ensure_all_started(cowboy).
+

Environment

-
-

The cowboy application does not define any application -environment configuration parameters.

-
- -
+

The cowboy application does not define any application environment configuration parameters.

See also

- -
+

ranch(7), cowlib(7)

+ diff --git a/docs/en/cowboy/2.1/guide/constraints/index.html b/docs/en/cowboy/2.1/guide/constraints/index.html index 0081ed1d..99e4eb17 100644 --- a/docs/en/cowboy/2.1/guide/constraints/index.html +++ b/docs/en/cowboy/2.1/guide/constraints/index.html @@ -62,141 +62,86 @@

Constraints

-

Constraints are validation and conversion functions applied -to user input.

-

They are used in various places in Cowboy, including the -router and the cowboy_req match functions.

-
+

Constraints are validation and conversion functions applied to user input.

+

They are used in various places in Cowboy, including the router and the cowboy_req match functions.

Syntax

-
-

Constraints are provided as a list of fields. For each field -in the list, specific constraints can be applied, as well as -a default value if the field is missing.

-

A field can take the form of an atom field, a tuple with -constraints {field, Constraints} or a tuple with constraints -and a default value {field, Constraints, Default}. -The field form indicates the field is mandatory.

-

Note that when used with the router, only the second form -makes sense, as it does not use the default and the field -is always defined.

-

Constraints for each field are provided as an ordered list -of atoms or funs to apply. Built-in constraints are provided -as atoms, while custom constraints are provided as funs.

-

When multiple constraints are provided, they are applied in -the order given. If the value has been modified by a constraint -then the next one receives the new value.

-

For example, the following constraints will first validate -and convert the field my_value to an integer, and then -check that the integer is positive:

-
-
-
PositiveFun = fun
-    (_, V) when V > 0 ->
-        {ok, V};
-    (_, _) ->
-        {error, not_positive}
-end,
-{my_value, [int, PositiveFun]}.
-

We ignore the first fun argument in this snippet. We shouldn’t. -We will simply learn what it is later in this chapter.

-

When there’s only one constraint, it can be provided directly -without wrapping it into a list:

-
-
-
{my_value, int}
-
-
-
+
{my_value, int}
+

Built-in constraints

-
-

Built-in constraints are specified as an atom:

-
- --- - - - - - - - - - +

Built-in constraints are specified as an atom:

+
Constraint Description

int

Converts binary value to integer.

+ + + + - - - + + - -
ConstraintDescription
intConverts binary value to integer.

nonempty

Ensures the binary value is non-empty.

nonemptyEnsures the binary value is non-empty.
-
-
- -
+

Custom constraints

-
-

Custom constraints are specified as a fun. This fun takes -two arguments. The first argument indicates the operation -to be performed, and the second is the value. What the -value is and what must be returned depends on the operation.

-

Cowboy currently defines three operations. The operation -used for validating and converting user input is the forward -operation.

-
-
-
int(forward, Value) ->
-    try
-        {ok, binary_to_integer(Value)}
-    catch _:_ ->
-        {error, not_an_integer}
-    end;
-

The value must be returned even if it is not converted -by the constraint.

-

The reverse operation does the opposite: it -takes a converted value and changes it back to what the -user input would have been.

-
-
-
int(reverse, Value) ->
-        try
-                {ok, integer_to_binary(Value)}
-        catch _:_ ->
-                {error, not_an_integer}
-        end;
-

Finally, the format_error operation takes an error -returned by any other operation and returns a formatted -human-readable error message.

-
-
-
int(format_error, {not_an_integer, Value}) ->
-        io_lib:format("The value ~p is not an integer.", [Value]).
-

Notice that for this case you get both the error and -the value that was given to the constraint that produced -this error.

-

Cowboy will not catch exceptions coming from constraint -functions. They should be written to not emit any exceptions.

-
-
+
int(format_error, {not_an_integer, Value}) ->
+	io_lib:format("The value ~p is not an integer.", [Value]).
+ +

Notice that for this case you get both the error and the value that was given to the constraint that produced this error.

+

Cowboy will not catch exceptions coming from constraint functions. They should be written to not emit any exceptions.

+ diff --git a/docs/en/cowboy/2.1/guide/cookies/index.html b/docs/en/cowboy/2.1/guide/cookies/index.html index 9468bbb1..9d56a3a5 100644 --- a/docs/en/cowboy/2.1/guide/cookies/index.html +++ b/docs/en/cowboy/2.1/guide/cookies/index.html @@ -62,144 +62,103 @@

Using cookies

-

Cookies are a mechanism allowing applications to maintain -state on top of the stateless HTTP protocol.

-

Cookies are a name/value store where the names and values are -stored in plain text. They expire either after a delay -or when the browser closes. They can be configured on a -specific domain name or path, and restricted to secure -resources (sent or downloaded over HTTPS), or restricted -to the server (disallowing access from client-side scripts).

-

Cookie names are de facto case sensitive.

-

Cookies are stored client-side and sent with every subsequent -request that matches the domain and path for which they were -stored, until they expire. This can create a non-negligible -cost.

-

Cookies should not be considered secure. They are stored on -the user’s computer in plain text, and can be read by any -program. They can also be read by proxies when using clear -connections. Always validate the value before using it, -and never store any sensitive information inside it.

-

Cookies set by the server are only available in requests -following the client reception of the response containing -them.

-

Cookies may be sent repeatedly. This is often useful to -update the expiration time and avoid losing a cookie.

-
+

Cookies are a mechanism allowing applications to maintain state on top of the stateless HTTP protocol.

+

Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts).

+

Cookie names are de facto case sensitive.

+

Cookies are stored client-side and sent with every subsequent request that matches the domain and path for which they were stored, until they expire. This can create a non-negligible cost.

+

Cookies should not be considered secure. They are stored on the user's computer in plain text, and can be read by any program. They can also be read by proxies when using clear connections. Always validate the value before using it, and never store any sensitive information inside it.

+

Cookies set by the server are only available in requests following the client reception of the response containing them.

+

Cookies may be sent repeatedly. This is often useful to update the expiration time and avoid losing a cookie.

Setting cookies

-
-

By default cookies are defined for the duration of the session:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0).
-

They can also be set for a duration in seconds:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{max_age => 3600}).
-

To delete cookies, set max_age to 0:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{max_age => 0}).
-

To restrict cookies to a specific domain and path, the options -of the same name can be used:

-
-
-
Req = cowboy_req:set_resp_cookie(<<"inaccount">>, <<"1">>, Req0,
-    #{domain => "my.example.org", path => "/account"}).
-

Cookies will be sent with requests to this domain and all -its subdomains, and to resources on this path or deeper -in the path hierarchy.

-

To restrict cookies to secure channels (typically resources -available over HTTPS):

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{secure => true}).
-

To prevent client-side scripts from accessing a cookie:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{http_only => true}).
-

Cookies may also be set client-side, for example using -Javascript.

-
-
-
+
SessionID = generate_session_id(),
+Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
+    #{http_only => true}).
+
+

Cookies may also be set client-side, for example using Javascript.

Reading cookies

-
-

The client only ever sends back the cookie name and value. -All other options that can be set are never sent back.

-

Cowboy provides two functions for reading cookies. Both -involve parsing the cookie header(s) and so should not -be called repeatedly.

-

You can get all cookies as a key/value list:

-
-
-
Cookies = cowboy_req:parse_cookies(Req),
-{_, Lang} = lists:keyfind(<<"lang">>, 1, Cookies).
-

Or you can perform a match against cookies and retrieve -only the ones you need, while at the same time doing -any required post processing using constraints. -This function returns a map:

-
-
-
#{id := ID, lang := Lang} = cowboy_req:match_cookies([id, lang], Req).
-

You can use constraints to validate the values while matching -them. The following snippet will crash if the id cookie is -not an integer number or if the lang cookie is empty. Additionally -the id cookie value will be converted to an integer term:

-
-
-
CookiesMap = cowboy_req:match_cookies([{id, int}, {lang, nonempty}], Req).
-

Note that if two cookies share the same name, then the map value -will be a list of the two cookie values.

-

A default value can be provided. The default will be used -if the lang cookie is not found. It will not be used if -the cookie is found but has an empty value:

-
-
-
#{lang := Lang} = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
-

If no default is provided and the value is missing, an -exception is thrown.

-
- +
#{lang := Lang} = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
+ +

If no default is provided and the value is missing, an exception is thrown.

+ diff --git a/docs/en/cowboy/2.1/guide/erlang_web/index.html b/docs/en/cowboy/2.1/guide/erlang_web/index.html index 6bc96a17..69f6bca2 100644 --- a/docs/en/cowboy/2.1/guide/erlang_web/index.html +++ b/docs/en/cowboy/2.1/guide/erlang_web/index.html @@ -62,194 +62,52 @@

Erlang and the Web

-

Erlang is the ideal platform for writing Web applications. -Its features are a perfect match for the requirements of -modern Web applications.

-
+

Erlang is the ideal platform for writing Web applications. Its features are a perfect match for the requirements of modern Web applications.

The Web is concurrent

-
-

When you access a website there is little concurrency -involved. A few connections are opened and requests -are sent through these connections. Then the web page -is displayed on your screen. Your browser will only -open up to 4 or 8 connections to the server, depending -on your settings. This isn’t much.

-

But think about it. You are not the only one accessing -the server at the same time. There can be hundreds, if -not thousands, if not millions of connections to the -same server at the same time.

-

Even today a lot of systems used in production haven’t -solved the C10K problem (ten thousand concurrent connections). -And the ones who did are trying hard to get to the next -step, C100K, and are pretty far from it.

-

Erlang meanwhile has no problem handling millions of -connections. At the time of writing there are application -servers written in Erlang that can handle more than two -million connections on a single server in a real production -application, with spare memory and CPU!

-

The Web is concurrent, and Erlang is a language designed -for concurrency, so it is a perfect match.

-

Of course, various platforms need to scale beyond a few -million connections. This is where Erlang’s built-in -distribution mechanisms come in. If one server isn’t -enough, add more! Erlang allows you to use the same code -for talking to local processes or to processes in other -parts of your cluster, which means you can scale very -quickly if the need arises.

-

The Web has large userbases, and the Erlang platform was -designed to work in a distributed setting, so it is a -perfect match.

-

Or is it? Surely you can find solutions to handle that many -concurrent connections with your favorite language… But all -these solutions will break down in the next few years. Why? -Firstly because servers don’t get any more powerful, they -instead get a lot more cores and memory. This is only useful -if your application can use them properly, and Erlang is -light-years away from anything else in that area. Secondly, -today your computer and your phone are online, tomorrow your -watch, goggles, bike, car, fridge and tons of other devices -will also connect to various applications on the Internet.

-

Only Erlang is prepared to deal with what’s coming.

-
-
-
+

When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. This isn't much.

+

But think about it. You are not the only one accessing the server at the same time. There can be hundreds, if not thousands, if not millions of connections to the same server at the same time.

+

Even today a lot of systems used in production haven't solved the C10K problem (ten thousand concurrent connections). And the ones who did are trying hard to get to the next step, C100K, and are pretty far from it.

+

Erlang meanwhile has no problem handling millions of connections. At the time of writing there are application servers written in Erlang that can handle more than two million connections on a single server in a real production application, with spare memory and CPU!

+

The Web is concurrent, and Erlang is a language designed for concurrency, so it is a perfect match.

+

Of course, various platforms need to scale beyond a few million connections. This is where Erlang's built-in distribution mechanisms come in. If one server isn't enough, add more! Erlang allows you to use the same code for talking to local processes or to processes in other parts of your cluster, which means you can scale very quickly if the need arises.

+

The Web has large userbases, and the Erlang platform was designed to work in a distributed setting, so it is a perfect match.

+

Or is it? Surely you can find solutions to handle that many concurrent connections with your favorite language... But all these solutions will break down in the next few years. Why? Firstly because servers don't get any more powerful, they instead get a lot more cores and memory. This is only useful if your application can use them properly, and Erlang is light-years away from anything else in that area. Secondly, today your computer and your phone are online, tomorrow your watch, goggles, bike, car, fridge and tons of other devices will also connect to various applications on the Internet.

+

Only Erlang is prepared to deal with what's coming.

The Web is soft real time

-
-

What does soft real time mean, you ask? It means we want the -operations done as quickly as possible, and in the case of -web applications, it means we want the data propagated fast.

-

In comparison, hard real time has a similar meaning, but also -has a hard time constraint, for example an operation needs to -be done in under N milliseconds otherwise the system fails -entirely.

-

Users aren’t that needy yet, they just want to get access -to their content in a reasonable delay, and they want the -actions they make to register at most a few seconds after -they submitted them, otherwise they’ll start worrying about -whether it successfully went through.

-

The Web is soft real time because taking longer to perform an -operation would be seen as bad quality of service.

-

Erlang is a soft real time system. It will always run -processes fairly, a little at a time, switching to another -process after a while and preventing a single process to -steal resources from all others. This means that Erlang -can guarantee stable low latency of operations.

-

Erlang provides the guarantees that the soft real time Web -requires.

-
-
-
+

What does soft real time mean, you ask? It means we want the operations done as quickly as possible, and in the case of web applications, it means we want the data propagated fast.

+

In comparison, hard real time has a similar meaning, but also has a hard time constraint, for example an operation needs to be done in under N milliseconds otherwise the system fails entirely.

+

Users aren't that needy yet, they just want to get access to their content in a reasonable delay, and they want the actions they make to register at most a few seconds after they submitted them, otherwise they'll start worrying about whether it successfully went through.

+

The Web is soft real time because taking longer to perform an operation would be seen as bad quality of service.

+

Erlang is a soft real time system. It will always run processes fairly, a little at a time, switching to another process after a while and preventing a single process to steal resources from all others. This means that Erlang can guarantee stable low latency of operations.

+

Erlang provides the guarantees that the soft real time Web requires.

The Web is asynchronous

-
-

Long ago, the Web was synchronous because HTTP was synchronous. -You fired a request, and then waited for a response. Not anymore. -It all began when XmlHttpRequest started being used. It allowed -the client to perform asynchronous calls to the server.

-

Then Websocket appeared and allowed both the server and the client -to send data to the other endpoint completely asynchronously. The -data is contained within frames and no response is necessary.

-

Erlang processes work the same. They send each other data contained -within messages and then continue running without needing a response. -They tend to spend most of their time inactive, waiting for a new -message, and the Erlang VM happily activate them when one is received.

-

It is therefore quite easy to imagine Erlang being good at receiving -Websocket frames, which may come in at unpredictable times, pass the -data to the responsible processes which are always ready waiting for -new messages, and perform the operations required by only activating -the required parts of the system.

-

The more recent Web technologies, like Websocket of course, but also -HTTP/2.0, are all fully asynchronous protocols. The concept -of requests and responses is retained of course, but anything could -be sent in between, by both the client or the browser, and the -responses could also be received in a completely different order.

-

Erlang is by nature asynchronous and really good at it thanks to the -great engineering that has been done in the VM over the years. It’s -only natural that it’s so good at dealing with the asynchronous Web.

-
-
-
+

Long ago, the Web was synchronous because HTTP was synchronous. You fired a request, and then waited for a response. Not anymore. It all began when XmlHttpRequest started being used. It allowed the client to perform asynchronous calls to the server.

+

Then Websocket appeared and allowed both the server and the client to send data to the other endpoint completely asynchronously. The data is contained within frames and no response is necessary.

+

Erlang processes work the same. They send each other data contained within messages and then continue running without needing a response. They tend to spend most of their time inactive, waiting for a new message, and the Erlang VM happily activate them when one is received.

+

It is therefore quite easy to imagine Erlang being good at receiving Websocket frames, which may come in at unpredictable times, pass the data to the responsible processes which are always ready waiting for new messages, and perform the operations required by only activating the required parts of the system.

+

The more recent Web technologies, like Websocket of course, but also HTTP/2.0, are all fully asynchronous protocols. The concept of requests and responses is retained of course, but anything could be sent in between, by both the client or the browser, and the responses could also be received in a completely different order.

+

Erlang is by nature asynchronous and really good at it thanks to the great engineering that has been done in the VM over the years. It's only natural that it's so good at dealing with the asynchronous Web.

The Web is omnipresent

-
-

The Web has taken a very important part of our lives. We’re -connected at all times, when we’re on our phone, using our computer, -passing time using a tablet while in the bathroom… And this -isn’t going to slow down, every single device at home or on us -will be connected.

-

All these devices are always connected. And with the number of -alternatives to give you access to the content you seek, users -tend to not stick around when problems arise. Users today want -their applications to be always available and if it’s having -too many issues they just move on.

-

Despite this, when developers choose a product to use for building -web applications, their only concern seems to be "Is it fast?", -and they look around for synthetic benchmarks showing which one -is the fastest at sending "Hello world" with only a handful -concurrent connections. Web benchmarks haven’t been representative -of reality in a long time, and are drifting further away as -time goes on.

-

What developers should really ask themselves is "Can I service -all my users with no interruption?" and they’d find that they have -two choices. They can either hope for the best, or they can use -Erlang.

-

Erlang is built for fault tolerance. When writing code in any other -language, you have to check all the return values and act accordingly -to avoid any unforeseen issues. If you’re lucky, you won’t miss -anything important. When writing Erlang code, you can just check -the success condition and ignore all errors. If an error happens, -the Erlang process crashes and is then restarted by a special -process called a supervisor.

-

Erlang developers thus have no need to fear unhandled -errors, and can focus on handling only the errors that should -give some feedback to the user and let the system take care of -the rest. This also has the advantage of allowing them to write -a lot less code, and let them sleep at night.

-

Erlang’s fault tolerance oriented design is the first piece of -what makes it the best choice for the omnipresent, always available -Web.

-

The second piece is Erlang’s built-in distribution. Distribution -is a key part of building a fault tolerant system, because it -allows you to handle bigger failures, like a whole server going -down, or even a data center entirely.

-

Fault tolerance and distribution are important today, and will be -vital in the future of the Web. Erlang is ready.

-
-
-
+

The Web has taken a very important part of our lives. We're connected at all times, when we're on our phone, using our computer, passing time using a tablet while in the bathroom... And this isn't going to slow down, every single device at home or on us will be connected.

+

All these devices are always connected. And with the number of alternatives to give you access to the content you seek, users tend to not stick around when problems arise. Users today want their applications to be always available and if it's having too many issues they just move on.

+

Despite this, when developers choose a product to use for building web applications, their only concern seems to be "Is it fast?", and they look around for synthetic benchmarks showing which one is the fastest at sending "Hello world" with only a handful concurrent connections. Web benchmarks haven't been representative of reality in a long time, and are drifting further away as time goes on.

+

What developers should really ask themselves is "Can I service all my users with no interruption?" and they'd find that they have two choices. They can either hope for the best, or they can use Erlang.

+

Erlang is built for fault tolerance. When writing code in any other language, you have to check all the return values and act accordingly to avoid any unforeseen issues. If you're lucky, you won't miss anything important. When writing Erlang code, you can just check the success condition and ignore all errors. If an error happens, the Erlang process crashes and is then restarted by a special process called a supervisor.

+

Erlang developers thus have no need to fear unhandled errors, and can focus on handling only the errors that should give some feedback to the user and let the system take care of the rest. This also has the advantage of allowing them to write a lot less code, and let them sleep at night.

+

Erlang's fault tolerance oriented design is the first piece of what makes it the best choice for the omnipresent, always available Web.

+

The second piece is Erlang's built-in distribution. Distribution is a key part of building a fault tolerant system, because it allows you to handle bigger failures, like a whole server going down, or even a data center entirely.

+

Fault tolerance and distribution are important today, and will be vital in the future of the Web. Erlang is ready.

Learn Erlang

-
-

If you are new to Erlang, you may want to grab a book or -two to get started. Those are my recommendations as the -author of Cowboy.

-
+

If you are new to Erlang, you may want to grab a book or two to get started. Those are my recommendations as the author of Cowboy.

The Erlanger Playbook

-

The Erlanger Playbook is an ebook I am currently writing, -which covers a number of different topics from code to -documentation to testing Erlang applications. It also has -an Erlang section where it covers directly the building -blocks and patterns, rather than details like the syntax.

-

You can most likely read it as a complete beginner, but -you will need a companion book to make the most of it. -Buy it from the Nine Nines website.

-
-
+

The Erlanger Playbook is an ebook I am currently writing, which covers a number of different topics from code to documentation to testing Erlang applications. It also has an Erlang section where it covers directly the building blocks and patterns, rather than details like the syntax.

+

You can most likely read it as a complete beginner, but you will need a companion book to make the most of it. Buy it from the Nine Nines website.

Programming Erlang

-

This book is from one of the creator of Erlang, Joe -Armstrong. It provides a very good explanation of what -Erlang is and why it is so. It serves as a very good -introduction to the language and platform.

-

The book is Programming Erlang, -and it also features a chapter on Cowboy.

-
-
+

This book is from one of the creator of Erlang, Joe Armstrong. It provides a very good explanation of what Erlang is and why it is so. It serves as a very good introduction to the language and platform.

+

The book is Programming Erlang, and it also features a chapter on Cowboy.

Learn You Some Erlang for Great Good!

-

LYSE is a much more complete -book covering many aspects of Erlang, while also providing -stories and humor. Be warned: it’s pretty verbose. It comes -with a free online version and a more refined paper and -ebook version.

-
-
-
+

LYSE is a much more complete book covering many aspects of Erlang, while also providing stories and humor. Be warned: it's pretty verbose. It comes with a free online version and a more refined paper and ebook version.

+ diff --git a/docs/en/cowboy/2.1/guide/flow_diagram/index.html b/docs/en/cowboy/2.1/guide/flow_diagram/index.html index 2bba77ce..fa42249d 100644 --- a/docs/en/cowboy/2.1/guide/flow_diagram/index.html +++ b/docs/en/cowboy/2.1/guide/flow_diagram/index.html @@ -62,113 +62,30 @@

Flow diagram

-

Cowboy is a lightweight HTTP server with support for HTTP/1.1, -HTTP/2 and Websocket.

-

It is built on top of Ranch. Please see the Ranch guide for more -information about how the network connections are handled.

-
+

Cowboy is a lightweight HTTP server with support for HTTP/1.1, HTTP/2 and Websocket.

+

It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled.

Overview

-
-
-
-HTTP request/response flowchart -
-
-

As you can see on the diagram, the client -begins by connecting to the server. This step is handled -by a Ranch acceptor, which is a process dedicated to -accepting new connections.

-

After Ranch accepts a new connection, whether it is an -HTTP/1.1 or HTTP/2 connection, Cowboy starts receiving -requests and handling them.

-

In HTTP/1.1 all requests come sequentially. In HTTP/2 -the requests may arrive and be processed concurrently.

-

When a request comes in, Cowboy creates a stream, which -is a set of request/response and all the events associated -with them. The protocol code in Cowboy defers the handling -of these streams to stream handler modules. When you -configure Cowboy you may define one or more module that -will receive all events associated with a stream, including -the request, response, bodies, Erlang messages and more.

-

By default Cowboy comes configured with a stream handler -called cowboy_stream_h. This stream handler will create -a new process for every request coming in, and then -communicate with this process to read the body or send -a response back. The request process executes middlewares -which, by default, including the router and then the -execution of handlers. Like stream handlers, middlewares -may also be customized.

-

A response may be sent at almost any point in this -diagram. If the response must be sent before the stream -is initialized (because an error occurred early, for -example) then stream handlers receive a special event -indicating this error.

-
-
-
+HTTP request/response flowchart

As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections.

+

After Ranch accepts a new connection, whether it is an HTTP/1.1 or HTTP/2 connection, Cowboy starts receiving requests and handling them.

+

In HTTP/1.1 all requests come sequentially. In HTTP/2 the requests may arrive and be processed concurrently.

+

When a request comes in, Cowboy creates a stream, which is a set of request/response and all the events associated with them. The protocol code in Cowboy defers the handling of these streams to stream handler modules. When you configure Cowboy you may define one or more module that will receive all events associated with a stream, including the request, response, bodies, Erlang messages and more.

+

By default Cowboy comes configured with a stream handler called cowboy_stream_h. This stream handler will create a new process for every request coming in, and then communicate with this process to read the body or send a response back. The request process executes middlewares which, by default, including the router and then the execution of handlers. Like stream handlers, middlewares may also be customized.

+

A response may be sent at almost any point in this diagram. If the response must be sent before the stream is initialized (because an error occurred early, for example) then stream handlers receive a special event indicating this error.

Protocol-specific headers

-
-

Cowboy takes care of protocol-specific headers and prevents -you from sending them manually. For HTTP/1.1 this includes -the transfer-encoding and connection headers. For HTTP/2 -this includes the colon headers like :status.

-

Cowboy will also remove protocol-specific headers from -requests before passing them to stream handlers. Cowboy -tries to hide the implementation details of all protocols -as well as possible.

-
-
-
+

Cowboy takes care of protocol-specific headers and prevents you from sending them manually. For HTTP/1.1 this includes the transfer-encoding and connection headers. For HTTP/2 this includes the colon headers like :status.

+

Cowboy will also remove protocol-specific headers from requests before passing them to stream handlers. Cowboy tries to hide the implementation details of all protocols as well as possible.

Number of processes per connection

-
-

By default, Cowboy will use one process per connection, -plus one process per set of request/response (called a -stream, internally).

-

The reason it creates a new process for every request is due -to the requirements of HTTP/2 where requests are executed -concurrently and independently from the connection. The -frames from the different requests end up interleaved on -the single TCP connection.

-

The request processes are never reused. There is therefore -no need to perform any cleanup after the response has been -sent. The process will terminate and Erlang/OTP will reclaim -all memory at once.

-

Cowboy ultimately does not require more than one process -per connection. It is possible to interact with the connection -directly from a stream handler, a low level interface to Cowboy. -They are executed from within the connection process, and can -handle the incoming requests and send responses. This is however -not recommended in normal circumstances, as a stream handler -taking too long to execute could have a negative impact on -concurrent requests or the state of the connection itself.

-
-
-
+

By default, Cowboy will use one process per connection, plus one process per set of request/response (called a stream, internally).

+

The reason it creates a new process for every request is due to the requirements of HTTP/2 where requests are executed concurrently and independently from the connection. The frames from the different requests end up interleaved on the single TCP connection.

+

The request processes are never reused. There is therefore no need to perform any cleanup after the response has been sent. The process will terminate and Erlang/OTP will reclaim all memory at once.

+

Cowboy ultimately does not require more than one process per connection. It is possible to interact with the connection directly from a stream handler, a low level interface to Cowboy. They are executed from within the connection process, and can handle the incoming requests and send responses. This is however not recommended in normal circumstances, as a stream handler taking too long to execute could have a negative impact on concurrent requests or the state of the connection itself.

Date header

-
-

Because querying for the current date and time can be expensive, -Cowboy generates one Date header value every second, shares it -to all other processes, which then simply copy it in the response. -This allows compliance with HTTP/1.1 with no actual performance loss.

-
-
-
+

Because querying for the current date and time can be expensive, Cowboy generates one Date header value every second, shares it to all other processes, which then simply copy it in the response. This allows compliance with HTTP/1.1 with no actual performance loss.

Binaries

-
-

Cowboy makes extensive use of binaries.

-

Binaries are more efficient than lists for representing -strings because they take less memory space. Processing -performance can vary depending on the operation. Binaries -are known for generally getting a great boost if the code -is compiled natively. Please see the HiPE documentation -for more details.

-

Binaries may end up being shared between processes. This -can lead to some large memory usage when one process keeps -the binary data around forever without freeing it. If you -see some weird memory usage in your application, this might -be the cause.

-
-
+

Cowboy makes extensive use of binaries.

+

Binaries are more efficient than lists for representing strings because they take less memory space. Processing performance can vary depending on the operation. Binaries are known for generally getting a great boost if the code is compiled natively. Please see the HiPE documentation for more details.

+

Binaries may end up being shared between processes. This can lead to some large memory usage when one process keeps the binary data around forever without freeing it. If you see some weird memory usage in your application, this might be the cause.

+ diff --git a/docs/en/cowboy/2.1/guide/getting_started/index.html b/docs/en/cowboy/2.1/guide/getting_started/index.html index 480a5535..74a900dd 100644 --- a/docs/en/cowboy/2.1/guide/getting_started/index.html +++ b/docs/en/cowboy/2.1/guide/getting_started/index.html @@ -62,161 +62,104 @@

Getting started

-

Erlang is more than a language, it is also an operating system -for your applications. Erlang developers rarely write standalone -modules, they write libraries or applications, and then bundle -those into what is called a release. A release contains the -Erlang VM plus all applications required to run the node, so -it can be pushed to production directly.

-

This chapter walks you through all the steps of setting up -Cowboy, writing your first application and generating your first -release. At the end of this chapter you should know everything -you need to push your first Cowboy application to production.

-
+

Erlang is more than a language, it is also an operating system for your applications. Erlang developers rarely write standalone modules, they write libraries or applications, and then bundle those into what is called a release. A release contains the Erlang VM plus all applications required to run the node, so it can be pushed to production directly.

+

This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. At the end of this chapter you should know everything you need to push your first Cowboy application to production.

Prerequisites

-
-

We are going to use the Erlang.mk -build system. If you are using Windows, please check the -Installation instructions -to get your environment setup before you continue.

-
-
-
+

We are going to use the Erlang.mk build system. If you are using Windows, please check the Installation instructions to get your environment setup before you continue.

Bootstrap

-
-

First, let’s create the directory for our application.

-
-
$ mkdir hello_erlang
-$ cd hello_erlang
-

Then we need to download Erlang.mk. Either use the following -command or download it manually.

-
-
-
$ wget https://erlang.mk/erlang.mk
-

We can now bootstrap our application. Since we are going to generate -a release, we will also bootstrap it at the same time.

-
-
-
$ make -f erlang.mk bootstrap bootstrap-rel
-

This creates a Makefile, a base application, and the release files -necessary for creating the release. We can already build and start -this release.

-
-
$ make run
-...
-(hello_erlang@127.0.0.1)1>
-

Entering the command i(). will show the running processes, including -one called hello_erlang_sup. This is the supervisor for our -application.

-

The release currently does nothing. In the rest of this chapter we -will add Cowboy as a dependency and write a simple "Hello world!" -handler.

-
-
-
+... +(hello_erlang@127.0.0.1)1> +
+

Entering the command i(). will show the running processes, including one called hello_erlang_sup. This is the supervisor for our application.

+

The release currently does nothing. In the rest of this chapter we will add Cowboy as a dependency and write a simple "Hello world!" handler.

Cowboy setup

-
-

We will modify the Makefile to tell the build system it needs to -fetch and compile Cowboy:

-
-
-
PROJECT = hello_erlang
+
PROJECT = hello_erlang
 
-DEPS = cowboy
-dep_cowboy_commit = 2.1.0
+DEPS = cowboy
+dep_cowboy_commit = 2.1.0
 
-DEP_PLUGINS = cowboy
+DEP_PLUGINS = cowboy
 
-include erlang.mk
-

We also tell the build system to load the plugins Cowboy provides. -These include predefined templates that we will use soon.

-

If you do make run now, Cowboy will be included in the release -and started automatically. This is not enough however, as Cowboy -doesn’t do anything by default. We still need to tell Cowboy to -listen for connections.

-
- -
+include erlang.mk +
+

We also tell the build system to load the plugins Cowboy provides. These include predefined templates that we will use soon.

+

If you do make run now, Cowboy will be included in the release and started automatically. This is not enough however, as Cowboy doesn't do anything by default. We still need to tell Cowboy to listen for connections.

Listening for connections

-
-

First we define the routes that Cowboy will use to map requests -to handler modules, and then we start the listener. This is best -done at application startup.

-

Open the src/hello_erlang_app.erl file and add the necessary -code to the start/2 function to make it look like this:

-
-
-
start(_Type, _Args) ->
-    Dispatch = cowboy_router:compile([
-        {'_', [{"/", hello_handler, []}]}
+
start(_Type, _Args) ->
+    Dispatch = cowboy_router:compile([
+        {'_', [{"/", hello_handler, []}]}
     ]),
-    {ok, _} = cowboy:start_clear(my_http_listener,
-        [{port, 8080}],
-        #{env => #{dispatch => Dispatch}}
+    {ok, _} = cowboy:start_clear(my_http_listener,
+        [{port, 8080}],
+        #{env => #{dispatch => Dispatch}}
     ),
-    hello_erlang_sup:start_link().
-

Routes are explained in details in the Routing -chapter. For this tutorial we map the path / to the handler -module hello_handler. This module doesn’t exist yet.

-

Build and start the release, then open http://localhost:8080 -in your browser. You will get a 500 error because the module is missing. -Any other URL, like http://localhost:8080/test, will result in a -404 error.

-
- -
+ hello_erlang_sup:start_link(). +
+

Routes are explained in details in the Routing chapter. For this tutorial we map the path / to the handler module hello_handler. This module doesn't exist yet.

+

Build and start the release, then open http://localhost:8080 in your browser. You will get a 500 error because the module is missing. Any other URL, like http://localhost:8080/test, will result in a 404 error.

Handling requests

-
-

Cowboy features different kinds of handlers, including REST -and Websocket handlers. For this tutorial we will use a plain -HTTP handler.

-

Generate a handler from a template:

-
-
-
$ make new t=cowboy.http n=hello_handler
-

Then, open the src/hello_handler.erl file and modify -the init/2 function like this to send a reply.

-
-
-
init(Req0, State) ->
-    Req = cowboy_req:reply(200,
-        #{<<"content-type">> => <<"text/plain">>},
-        <<"Hello Erlang!">>,
-        Req0),
-    {ok, Req, State}.
-

What the above code does is send a 200 OK reply, with the -Content-type header set to text/plain and the response -body set to Hello Erlang!.

-

If you run the release and open http://localhost:8080 -in your browser, you should get a nice Hello Erlang! displayed!

-
- +
init(Req0, State) ->
+    Req = cowboy_req:reply(200,
+        #{<<"content-type">> => <<"text/plain">>},
+        <<"Hello Erlang!">>,
+        Req0),
+    {ok, Req, State}.
+ +

What the above code does is send a 200 OK reply, with the Content-type header set to text/plain and the response body set to Hello Erlang!.

+

If you run the release and open http://localhost:8080 in your browser, you should get a nice Hello Erlang! displayed!

+ diff --git a/docs/en/cowboy/2.1/guide/handlers/index.html b/docs/en/cowboy/2.1/guide/handlers/index.html index aa49c1c0..2d7b354b 100644 --- a/docs/en/cowboy/2.1/guide/handlers/index.html +++ b/docs/en/cowboy/2.1/guide/handlers/index.html @@ -62,91 +62,57 @@

Handlers

-

Handlers are Erlang modules that handle HTTP requests.

-
+

Handlers are Erlang modules that handle HTTP requests.

Plain HTTP handlers

-
-

The most basic handler in Cowboy implements the mandatory -init/2 callback, manipulates the request, optionally -sends a response and then returns.

-

This callback receives the Req object and the initial -state defined in the router configuration.

-

A handler that does nothing would look like this:

-
-
-
init(Req, State) ->
-    {ok, Req, State}.
-

Despite sending no reply, a 204 No Content response will be -sent to the client, as Cowboy makes sure that a response is -sent for every request.

-

We need to use the Req object to reply.

-
-
-
init(Req0, State) ->
-    Req = cowboy_req:reply(200, #{
-        <<"content-type">> => <<"text/plain">>
-    }, <<"Hello World!">>, Req0),
-    {ok, Req, State}.
-

Cowboy will immediately send a response when cowboy:reply/4 -is called.

-

We then return a 3-tuple. ok means that the handler ran -successfully. We also give the modified Req back to Cowboy.

-

The last value of the tuple is a state that will be used -in every subsequent callbacks to this handler. Plain HTTP -handlers only have one additional callback, the optional -and rarely used terminate/3.

-
-
-
+
init(Req0, State) ->
+    Req = cowboy_req:reply(200, #{
+        <<"content-type">> => <<"text/plain">>
+    }, <<"Hello World!">>, Req0),
+    {ok, Req, State}.
+
+

Cowboy will immediately send a response when cowboy:reply/4 is called.

+

We then return a 3-tuple. ok means that the handler ran successfully. We also give the modified Req back to Cowboy.

+

The last value of the tuple is a state that will be used in every subsequent callbacks to this handler. Plain HTTP handlers only have one additional callback, the optional and rarely used terminate/3.

Other handlers

-
-

The init/2 callback can also be used to inform Cowboy -that this is a different kind of handler and that Cowboy -should switch to it. To do this you simply need to return -the module name of the handler type you want to switch to.

-

Cowboy comes with three handler types you can switch to: -cowboy_rest, cowboy_websocket -and cowboy_loop. In addition to those you -can define your own handler types.

-

Switching is simple. Instead of returning ok, you simply -return the name of the handler type you want to use. The -following snippet switches to a Websocket handler:

-
-
-
init(Req, State) ->
-    {cowboy_websocket, Req, State}.
-
- -
+
init(Req, State) ->
+    {cowboy_websocket, Req, State}.
+

Cleaning up

-
-

All handler types provide the optional terminate/3 callback.

-
-
-
terminate(_Reason, _Req, _State) ->
-    ok.
-

This callback is strictly reserved for any required cleanup. -You cannot send a response from this function. There is no -other return value.

-

This callback is optional because it is rarely necessary. -Cleanup should be done in separate processes directly (by -monitoring the handler process to detect when it exits).

-

Cowboy does not reuse processes for different requests. The -process will terminate soon after this call returns.

-
- +
terminate(_Reason, _Req, _State) ->
+    ok.
+ +

This callback is strictly reserved for any required cleanup. You cannot send a response from this function. There is no other return value.

+

This callback is optional because it is rarely necessary. Cleanup should be done in separate processes directly (by monitoring the handler process to detect when it exits).

+

Cowboy does not reuse processes for different requests. The process will terminate soon after this call returns.

+ diff --git a/docs/en/cowboy/2.1/guide/index.html b/docs/en/cowboy/2.1/guide/index.html index 520577a7..aa488e54 100644 --- a/docs/en/cowboy/2.1/guide/index.html +++ b/docs/en/cowboy/2.1/guide/index.html @@ -62,204 +62,81 @@

Cowboy User Guide

-
+ +

Rationale

- -
-
+

Introduction

- -
-
+

Configuration

-
- -
-
-
+

Handlers

- -
- - - -
+

Advanced

-
- -
-
- + + diff --git a/docs/en/cowboy/2.1/guide/introduction/index.html b/docs/en/cowboy/2.1/guide/introduction/index.html index 7a8642d8..9c529bd7 100644 --- a/docs/en/cowboy/2.1/guide/introduction/index.html +++ b/docs/en/cowboy/2.1/guide/introduction/index.html @@ -62,79 +62,40 @@

Introduction

-

Cowboy is a small, fast and modern HTTP server for Erlang/OTP.

-

Cowboy aims to provide a complete modern Web stack. -This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and -Webmachine-based REST.

-

Cowboy comes with functions for introspection and tracing, enabling -developers to know precisely what is happening at any time. Its modular -design also easily enable developers to add instrumentation.

-

Cowboy is a high quality project. It has a small code base, is very -efficient (both in latency and memory use) and can easily be embedded -in another application.

-

Cowboy is clean Erlang code. It includes hundreds of tests and its code -is fully compliant with the Dialyzer. It is also well documented and -features a Function Reference, a User Guide and numerous Tutorials.

-
+

Cowboy is a small, fast and modern HTTP server for Erlang/OTP.

+

Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST.

+

Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation.

+

Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application.

+

Cowboy is clean Erlang code. It includes hundreds of tests and its code is fully compliant with the Dialyzer. It is also well documented and features a Function Reference, a User Guide and numerous Tutorials.

Prerequisites

-
-

Beginner Erlang knowledge is recommended for reading this guide.

-

Knowledge of the HTTP protocol is recommended but not required, as it -will be detailed throughout the guide.

-
-
-
+

Beginner Erlang knowledge is recommended for reading this guide.

+

Knowledge of the HTTP protocol is recommended but not required, as it will be detailed throughout the guide.

Supported platforms

-
-

Cowboy is tested and supported on Linux, FreeBSD, Windows and OSX.

-

Cowboy has been reported to work on other platforms, but we make no -guarantee that the experience will be safe and smooth. You are advised -to perform the necessary testing and security audits prior to deploying -on other platforms.

-

Cowboy is developed for Erlang/OTP 19.0 and newer.

-
-
-
+

Cowboy is tested and supported on Linux, FreeBSD, Windows and OSX.

+

Cowboy has been reported to work on other platforms, but we make no guarantee that the experience will be safe and smooth. You are advised to perform the necessary testing and security audits prior to deploying on other platforms.

+

Cowboy is developed for Erlang/OTP 19.0 and newer.

License

-
-

Cowboy uses the ISC License.

-
-
-
Copyright (c) 2011-2017, Loïc Hoguin <essen@ninenines.eu>
+

Cowboy uses the ISC License.

+
Copyright (c) 2011-2017, Loïc Hoguin <essen@ninenines.eu>
 
 Permission to use, copy, modify, and/or distribute this software for any
 purpose with or without fee is hereby granted, provided that the above
 copyright notice and this permission notice appear in all copies.
 
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-
-
-
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Versioning

-
- -
-
-
+

Cowboy uses Semantic Versioning 2.0.0.

Conventions

-
-

In the HTTP protocol, the method name is case sensitive. All standard -method names are uppercase.

-

Header names are case insensitive. When using HTTP/1.1, Cowboy converts -all the request header names to lowercase. HTTP/2 requires clients to -send them as lowercase. Any other header name is expected to be provided -lowercased, including when querying information about the request or -when sending responses.

-

The same applies to any other case insensitive value.

-
-
+

In the HTTP protocol, the method name is case sensitive. All standard method names are uppercase.

+

Header names are case insensitive. When using HTTP/1.1, Cowboy converts all the request header names to lowercase. HTTP/2 requires clients to send them as lowercase. Any other header name is expected to be provided lowercased, including when querying information about the request or when sending responses.

+

The same applies to any other case insensitive value.

+ diff --git a/docs/en/cowboy/2.1/guide/listeners/index.html b/docs/en/cowboy/2.1/guide/listeners/index.html index 63bbae5c..79f5ec00 100644 --- a/docs/en/cowboy/2.1/guide/listeners/index.html +++ b/docs/en/cowboy/2.1/guide/listeners/index.html @@ -62,109 +62,61 @@

Listeners

-

A listener is a set of processes that listens on a port for -new connections. Incoming connections get handled by Cowboy. -Depending on the connection handshake, one or another protocol -may be used.

-

This chapter is specific to Cowboy. Please refer to the -Ranch User Guide -for more information about listeners.

-

Cowboy provides two types of listeners: one listening for -clear TCP connections, and one listening for secure TLS -connections. Both of them support the HTTP/1.1 and HTTP/2 -protocols.

-
+

A listener is a set of processes that listens on a port for new connections. Incoming connections get handled by Cowboy. Depending on the connection handshake, one or another protocol may be used.

+

This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners.

+

Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. Both of them support the HTTP/1.1 and HTTP/2 protocols.

Clear TCP listener

-
-

The clear TCP listener will accept connections on the -given port. A typical HTTP server would listen on port 80. -Port 80 requires special permissions on most platforms -however so a common alternative is port 8080.

-

The following snippet starts listening for connections -on port 8080:

-
-
-
start(_Type, _Args) ->
-    Dispatch = cowboy_router:compile([
-        {'_', [{"/", hello_handler, []}]}
+
start(_Type, _Args) ->
+    Dispatch = cowboy_router:compile([
+        {'_', [{"/", hello_handler, []}]}
     ]),
-    {ok, _} = cowboy:start_clear(my_http_listener,
-        [{port, 8080}],
-        #{env => #{dispatch => Dispatch}}
+    {ok, _} = cowboy:start_clear(my_http_listener,
+        [{port, 8080}],
+        #{env => #{dispatch => Dispatch}}
     ),
-    hello_erlang_sup:start_link().
-

The Getting Started chapter uses a -clear TCP listener.

-

Clients connecting to Cowboy on the clear listener port are -expected to use either HTTP/1.1 or HTTP/2.

-

Cowboy supports both methods of initiating a clear -HTTP/2 connection: through the Upgrade mechanism -(RFC 7540 3.2) -or by sending the preface directly -(RFC 7540 3.4).

-

Compatibility with HTTP/1.0 is provided by Cowboy’s HTTP/1.1 -implementation.

-
-
-
+ hello_erlang_sup:start_link(). +
+

The Getting Started chapter uses a clear TCP listener.

+

Clients connecting to Cowboy on the clear listener port are expected to use either HTTP/1.1 or HTTP/2.

+

Cowboy supports both methods of initiating a clear HTTP/2 connection: through the Upgrade mechanism (RFC 7540 3.2) or by sending the preface directly (RFC 7540 3.4).

+

Compatibility with HTTP/1.0 is provided by Cowboy's HTTP/1.1 implementation.

Secure TLS listener

-
-

The secure TLS listener will accept connections on the -given port. A typical HTTPS server would listen on port 443. -Port 443 requires special permissions on most platforms -however so a common alternative is port 8443.

-

The function provided by Cowboy will ensure that the TLS -options given are following the HTTP/2 RFC with regards -to security. For example some TLS extensions or ciphers -may be disabled. This also applies to HTTP/1.1 connections -on this listener. If this is not desirable, Ranch can be -used directly to setup a custom listener.

-
-
+

The function provided by Cowboy will ensure that the TLS options given are following the HTTP/2 RFC with regards to security. For example some TLS extensions or ciphers may be disabled. This also applies to HTTP/1.1 connections on this listener. If this is not desirable, Ranch can be used directly to setup a custom listener.

+
-
start(_Type, _Args) ->
-    Dispatch = cowboy_router:compile([
-        {'_', [{"/", hello_handler, []}]}
+
start(_Type, _Args) ->
+    Dispatch = cowboy_router:compile([
+        {'_', [{"/", hello_handler, []}]}
     ]),
-    {ok, _} = cowboy:start_tls(my_http_listener,
+    {ok, _} = cowboy:start_tls(my_http_listener,
         [
-            {port, 8443},
-            {certfile, "/path/to/certfile"},
-            {keyfile, "/path/to/keyfile"}
+            {port, 8443},
+            {certfile, "/path/to/certfile"},
+            {keyfile, "/path/to/keyfile"}
         ],
-        #{env => #{dispatch => Dispatch}}
+        #{env => #{dispatch => Dispatch}}
     ),
-    hello_erlang_sup:start_link().
-

Clients connecting to Cowboy on the secure listener are -expected to use the ALPN TLS extension to indicate what -protocols they understand. Cowboy always prefers HTTP/2 -over HTTP/1.1 when both are supported. When neither are -supported by the client, or when the ALPN extension was -missing, Cowboy expects HTTP/1.1 to be used.

-

Cowboy also advertises HTTP/2 support through the older -NPN TLS extension for compatibility. Note however that -this support will likely not be enabled by default when -Cowboy 2.0 gets released.

-

Compatibility with HTTP/1.0 is provided by Cowboy’s HTTP/1.1 -implementation.

-
-
-
+ hello_erlang_sup:start_link(). +
+

Clients connecting to Cowboy on the secure listener are expected to use the ALPN TLS extension to indicate what protocols they understand. Cowboy always prefers HTTP/2 over HTTP/1.1 when both are supported. When neither are supported by the client, or when the ALPN extension was missing, Cowboy expects HTTP/1.1 to be used.

+

Cowboy also advertises HTTP/2 support through the older NPN TLS extension for compatibility. Note however that this support will likely not be enabled by default when Cowboy 2.0 gets released.

+

Compatibility with HTTP/1.0 is provided by Cowboy's HTTP/1.1 implementation.

Protocol configuration

-
-

The HTTP/1.1 and HTTP/2 protocols share the same semantics; -only their framing differs. The first is a text protocol and -the second a binary protocol.

-

Cowboy doesn’t separate the configuration for HTTP/1.1 and -HTTP/2. Everything goes into the same map. Many options are -shared.

-
- +

The HTTP/1.1 and HTTP/2 protocols share the same semantics; only their framing differs. The first is a text protocol and the second a binary protocol.

+

Cowboy doesn't separate the configuration for HTTP/1.1 and HTTP/2. Everything goes into the same map. Many options are shared.

+ + + diff --git a/docs/en/cowboy/2.1/guide/loop_handlers/index.html b/docs/en/cowboy/2.1/guide/loop_handlers/index.html index 82075e75..fc370036 100644 --- a/docs/en/cowboy/2.1/guide/loop_handlers/index.html +++ b/docs/en/cowboy/2.1/guide/loop_handlers/index.html @@ -62,131 +62,72 @@

Loop handlers

-

Loop handlers are a special kind of HTTP handlers used when the -response can not be sent right away. The handler enters instead -a receive loop waiting for the right message before it can send -a response.

-

Loop handlers are used for requests where a response might not -be immediately available, but where you would like to keep the -connection open for a while in case the response arrives. The -most known example of such practice is known as long polling.

-

Loop handlers can also be used for requests where a response is -partially available and you need to stream the response body -while the connection is open. The most known example of such -practice is server-sent events.

-

While the same can be accomplished using plain HTTP handlers, -it is recommended to use loop handlers because they are well-tested -and allow using built-in features like hibernation and timeouts.

-

Loop handlers essentially wait for one or more Erlang messages -and feed these messages to the info/3 callback. It also features -the init/2 and terminate/3 callbacks which work the same as -for plain HTTP handlers.

-
+

Loop handlers are a special kind of HTTP handlers used when the response can not be sent right away. The handler enters instead a receive loop waiting for the right message before it can send a response.

+

Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling.

+

Loop handlers can also be used for requests where a response is partially available and you need to stream the response body while the connection is open. The most known example of such practice is server-sent events.

+

While the same can be accomplished using plain HTTP handlers, it is recommended to use loop handlers because they are well-tested and allow using built-in features like hibernation and timeouts.

+

Loop handlers essentially wait for one or more Erlang messages and feed these messages to the info/3 callback. It also features the init/2 and terminate/3 callbacks which work the same as for plain HTTP handlers.

Initialization

-
-

The init/2 function must return a cowboy_loop tuple to enable -loop handler behavior. This tuple may optionally contain -a timeout value and/or the atom hibernate to make the -process enter hibernation until a message is received.

-

This snippet enables the loop handler:

-
-
-
init(Req, State) ->
-    {cowboy_loop, Req, State}.
-

This also makes the process hibernate:

-
-
-
init(Req, State) ->
-    {cowboy_loop, Req, State, hibernate}.
-
-
-
+
init(Req, State) ->
+    {cowboy_loop, Req, State, hibernate}.
+

Receive loop

-
-

Once initialized, Cowboy will wait for messages to arrive -in the process' mailbox. When a message arrives, Cowboy -calls the info/3 function with the message, the Req object -and the handler’s state.

-

The following snippet sends a reply when it receives a -reply message from another process, or waits for another -message otherwise.

-
-
-
info({reply, Body}, Req, State) ->
-    cowboy_req:reply(200, #{}, Body, Req),
-    {stop, Req, State};
-info(_Msg, Req, State) ->
-    {ok, Req, State, hibernate}.
-

Do note that the reply tuple here may be any message -and is simply an example.

-

This callback may perform any necessary operation including -sending all or parts of a reply, and will subsequently -return a tuple indicating if more messages are to be expected.

-

The callback may also choose to do nothing at all and just -skip the message received.

-

If a reply is sent, then the stop tuple should be returned. -This will instruct Cowboy to end the request.

-

Otherwise an ok tuple should be returned.

-
- -
+
info({reply, Body}, Req, State) ->
+    cowboy_req:reply(200, #{}, Body, Req),
+    {stop, Req, State};
+info(_Msg, Req, State) ->
+    {ok, Req, State, hibernate}.
+
+

Do note that the reply tuple here may be any message and is simply an example.

+

This callback may perform any necessary operation including sending all or parts of a reply, and will subsequently return a tuple indicating if more messages are to be expected.

+

The callback may also choose to do nothing at all and just skip the message received.

+

If a reply is sent, then the stop tuple should be returned. This will instruct Cowboy to end the request.

+

Otherwise an ok tuple should be returned.

Streaming loop

-
-

Another common case well suited for loop handlers is -streaming data received in the form of Erlang messages. -This can be done by initiating a chunked reply in the -init/2 callback and then using cowboy_req:chunk/2 -every time a message is received.

-

The following snippet does exactly that. As you can see -a chunk is sent every time an event message is received, -and the loop is stopped by sending an eof message.

-
-
-
init(Req, State) ->
-    Req2 = cowboy_req:stream_reply(200, Req),
-    {cowboy_loop, Req2, State}.
-
-info(eof, Req, State) ->
-    {stop, Req, State};
-info({event, Data}, Req, State) ->
-    cowboy_req:stream_body(Data, nofin, Req),
-    {ok, Req, State};
-info(_Msg, Req, State) ->
-    {ok, Req, State}.
-
- -
+
init(Req, State) ->
+    Req2 = cowboy_req:stream_reply(200, Req),
+    {cowboy_loop, Req2, State}.
+
+info(eof, Req, State) ->
+    {stop, Req, State};
+info({event, Data}, Req, State) ->
+    cowboy_req:stream_body(Data, nofin, Req),
+    {ok, Req, State};
+info(_Msg, Req, State) ->
+    {ok, Req, State}.
+

Cleaning up

-
-

It is recommended that you set the connection header to -close when replying, as this process may be reused for -a subsequent request.

-

Please refer to the Handlers chapter -for general instructions about cleaning up.

-
- -
+

It is recommended that you set the connection header to close when replying, as this process may be reused for a subsequent request.

+

Please refer to the Handlers chapter for general instructions about cleaning up.

Hibernate

-
-

To save memory, you may hibernate the process in between -messages received. This is done by returning the atom -hibernate as part of the loop tuple callbacks normally -return. Just add the atom at the end and Cowboy will hibernate -accordingly.

-
-
+

To save memory, you may hibernate the process in between messages received. This is done by returning the atom hibernate as part of the loop tuple callbacks normally return. Just add the atom at the end and Cowboy will hibernate accordingly.

+ diff --git a/docs/en/cowboy/2.1/guide/middlewares/index.html b/docs/en/cowboy/2.1/guide/middlewares/index.html index 71dde058..8ff8dd01 100644 --- a/docs/en/cowboy/2.1/guide/middlewares/index.html +++ b/docs/en/cowboy/2.1/guide/middlewares/index.html @@ -62,92 +62,38 @@

Middlewares

-

Cowboy delegates the request processing to middleware components. -By default, two middlewares are defined, for the routing and handling -of the request, as is detailed in most of this guide.

-

Middlewares give you complete control over how requests are to be -processed. You can add your own middlewares to the mix or completely -change the chain of middlewares as needed.

-

Cowboy will execute all middlewares in the given order, unless one -of them decides to stop processing.

-
+

Cowboy delegates the request processing to middleware components. By default, two middlewares are defined, for the routing and handling of the request, as is detailed in most of this guide.

+

Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed.

+

Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing.

Usage

-
-

Middlewares only need to implement a single callback: execute/2. -It is defined in the cowboy_middleware behavior.

-

This callback has two arguments. The first is the Req object. -The second is the environment.

-

Middlewares can return one of three different values:

-
    -
  • -

    -{ok, Req, Env} to continue the request processing -

    +

    Middlewares only need to implement a single callback: execute/2. It is defined in the cowboy_middleware behavior.

    +

    This callback has two arguments. The first is the Req object. The second is the environment.

    +

    Middlewares can return one of three different values:

    +
    • {ok, Req, Env} to continue the request processing
    • -
    • -

      -{suspend, Module, Function, Args} to hibernate -

      +
    • {suspend, Module, Function, Args} to hibernate
    • -
    • -

      -{stop, Req} to stop processing and move on to the next request -

      +
    • {stop, Req} to stop processing and move on to the next request
    • -
-

Of note is that when hibernating, processing will resume on the given -MFA, discarding all previous stacktrace. Make sure you keep the Req -and Env in the arguments of this MFA for later use.

-

If an error happens during middleware processing, Cowboy will not try -to send an error back to the socket, the process will just crash. It -is up to the middleware to make sure that a reply is sent if something -goes wrong.

-
-
-
+ +

Of note is that when hibernating, processing will resume on the given MFA, discarding all previous stacktrace. Make sure you keep the Req and Env in the arguments of this MFA for later use.

+

If an error happens during middleware processing, Cowboy will not try to send an error back to the socket, the process will just crash. It is up to the middleware to make sure that a reply is sent if something goes wrong.

Configuration

-
-

The middleware environment is defined as the env protocol option. -In the previous chapters we saw it briefly when we needed to pass -the routing information. It is a list of tuples with the first -element being an atom and the second any Erlang term.

-

Two values in the environment are reserved:

-
    -
  • -

    -listener contains the name of the listener -

    +

    The middleware environment is defined as the env protocol option. In the previous chapters we saw it briefly when we needed to pass the routing information. It is a list of tuples with the first element being an atom and the second any Erlang term.

    +

    Two values in the environment are reserved:

    +
    • listener contains the name of the listener
    • -
    • -

      -result contains the result of the processing -

      +
    • result contains the result of the processing
    • -
-

The listener value is always defined. The result value can be -set by any middleware. If set to anything other than ok, Cowboy -will not process any subsequent requests on this connection.

-

The middlewares that come with Cowboy may define or require other -environment values to perform.

-

You can update the environment by calling the cowboy:set_env/3 -convenience function, adding or replacing a value in the environment.

-
-
-
+ +

The listener value is always defined. The result value can be set by any middleware. If set to anything other than ok, Cowboy will not process any subsequent requests on this connection.

+

The middlewares that come with Cowboy may define or require other environment values to perform.

+

You can update the environment by calling the cowboy:set_env/3 convenience function, adding or replacing a value in the environment.

Routing middleware

-
-

The routing middleware requires the dispatch value. If routing -succeeds, it will put the handler name and options in the handler -and handler_opts values of the environment, respectively.

-
-
-
+

The routing middleware requires the dispatch value. If routing succeeds, it will put the handler name and options in the handler and handler_opts values of the environment, respectively.

Handler middleware

-
-

The handler middleware requires the handler and handler_opts -values. It puts the result of the request handling into result.

-
-
+

The handler middleware requires the handler and handler_opts values. It puts the result of the request handling into result.

+ diff --git a/docs/en/cowboy/2.1/guide/migrating_from_1.0/index.html b/docs/en/cowboy/2.1/guide/migrating_from_1.0/index.html index e2ae159d..6a6cd794 100644 --- a/docs/en/cowboy/2.1/guide/migrating_from_1.0/index.html +++ b/docs/en/cowboy/2.1/guide/migrating_from_1.0/index.html @@ -62,388 +62,120 @@

Migrating from Cowboy 1.0 to 2.0

-

A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req -interface in particular has seen a massive revamp. Hooks are -gone, their functionality can now be achieved via stream -handlers.

-

The documentation has seen great work, in particular the -manual. Each module and each function now has its own dedicated -manual page with full details and examples.

-
+

A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req interface in particular has seen a massive revamp. Hooks are gone, their functionality can now be achieved via stream handlers.

+

The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples.

Compatibility

-
-

Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. -Erlang/OTP 19.0 or above is required. It is non-trivial to -make Cowboy 2.0 work with older Erlang/OTP versions.

-

Cowboy 2.0 is not compatible with Cowlib versions older than -2.0. It should be compatible with Ranch 1.0 or above, however -it has not been tested with Ranch versions older than 1.4.

-

Cowboy 2.0 is tested on Arch Linux, Ubuntu, FreeBSD, Windows -and OSX. It is tested with every point release (latest patch -release) and also with HiPE on the most recent release.

-

Cowboy 2.0 now comes with Erlang.mk templates.

-
-
-
+

Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. Erlang/OTP 19.0 or above is required. It is non-trivial to make Cowboy 2.0 work with older Erlang/OTP versions.

+

Cowboy 2.0 is not compatible with Cowlib versions older than 2.0. It should be compatible with Ranch 1.0 or above, however it has not been tested with Ranch versions older than 1.4.

+

Cowboy 2.0 is tested on Arch Linux, Ubuntu, FreeBSD, Windows and OSX. It is tested with every point release (latest patch release) and also with HiPE on the most recent release.

+

Cowboy 2.0 now comes with Erlang.mk templates.

Features added

-
-
    -
  • -

    -The HTTP/2 protocol is now supported. -

    -
  • -
  • -

    -Cowboy no longer uses only one process per connection. - It now uses one process per connection plus one process - per request by default. This is necessary for HTTP/2. - There might be a slight drop in performance for HTTP/1.1 - connections due to this change. -

    -
  • -
  • -

    -Cowboy internals have largely been reworked in order to - support HTTP/2. This opened the way to stream handlers, - which are a chain of modules that are called whenever - something happens relating to a request/response. -

    -
  • -
  • -

    -The cowboy_stream_h stream handler has been added. - It provides most of Cowboy’s default behavior. -

    -
  • -
  • -

    -The cowboy_compress_h stream handler has been added. - It compresses responses when possible. It’s worth noting - that it compresses in more cases than Cowboy 1.0 ever did. -

    -
  • -
  • -

    -Because of the many changes in the internals of Cowboy, - many options have been added or modified. Of note is that - the Websocket options are now given per handler rather - than for the entire listener. -

    -
  • -
  • -

    -Websocket permessage-deflate compression is now supported - via the compress option. -

    -
  • -
  • -

    -Static file handlers will now correctly find files found - in .ez archives. -

    -
  • -
  • -

    -Constraints have been generalized and are now used not only - in the router but also in some cowboy_req functions. Their - interface has also been modified to allow for reverse - operations and formatting of errors. -

    -
  • -
-
-
-
+
  • The HTTP/2 protocol is now supported. +
  • +
  • Cowboy no longer uses only one process per connection. It now uses one process per connection plus one process per request by default. This is necessary for HTTP/2. There might be a slight drop in performance for HTTP/1.1 connections due to this change. +
  • +
  • Cowboy internals have largely been reworked in order to support HTTP/2. This opened the way to stream handlers, which are a chain of modules that are called whenever something happens relating to a request/response. +
  • +
  • The cowboy_stream_h stream handler has been added. It provides most of Cowboy's default behavior. +
  • +
  • The cowboy_compress_h stream handler has been added. It compresses responses when possible. It's worth noting that it compresses in more cases than Cowboy 1.0 ever did. +
  • +
  • Because of the many changes in the internals of Cowboy, many options have been added or modified. Of note is that the Websocket options are now given per handler rather than for the entire listener. +
  • +
  • Websocket permessage-deflate compression is now supported via the compress option. +
  • +
  • Static file handlers will now correctly find files found in .ez archives. +
  • +
  • Constraints have been generalized and are now used not only in the router but also in some cowboy_req functions. Their interface has also been modified to allow for reverse operations and formatting of errors. +
  • +

Features removed

-
-
    -
  • -

    -SPDY support has been removed. Use HTTP/2 instead. -

    -
  • -
  • -

    -Hooks have been removed. Use stream handlers instead. -

    -
  • -
  • -

    -The undocumented waiting_stream hack has been removed. - It allowed disabling chunked transfer-encoding for HTTP/1.1. - It has no equivalent in Cowboy 2.0. Open a ticket if necessary. -

    -
  • -
  • -

    -Sub protocols still exist, but their interface has largely changed - and they are no longer documented for the time being. -

    -
  • -
-
-
-
+
  • SPDY support has been removed. Use HTTP/2 instead. +
  • +
  • Hooks have been removed. Use stream handlers instead. +
  • +
  • The undocumented waiting_stream hack has been removed. It allowed disabling chunked transfer-encoding for HTTP/1.1. It has no equivalent in Cowboy 2.0. Open a ticket if necessary. +
  • +
  • Sub protocols still exist, but their interface has largely changed and they are no longer documented for the time being. +
  • +

Changed behaviors

-
-
    -
  • -

    -The handler behaviors have been renamed and are now cowboy_handler, - cowboy_loop, cowboy_rest and cowboy_websocket. -

    -
  • -
  • -

    -Plain HTTP, loop, REST and Websocket handlers have had their - init and terminate callbacks unified. They now all use the - init/2 and terminate/3 callbacks. The latter is now optional. - The terminate reason has now been documented for all handlers. -

    -
  • -
  • -

    -The tuple returned to switch to a different handler type has - changed. It now takes the form {Module, Req, State} or - {Module, Req, State, Opts}, where Opts is a map of options - to configure the handler. The timeout and hibernate options - must now be specified using this map, where applicable. -

    -
  • -
  • -

    -All behaviors that used to accept halt or shutdown tuples - as a return value no longer do so. The return value is now - a stop tuple, consistent across Cowboy. -

    -
  • -
  • -

    -Middlewares can no longer return an error tuple. They have - to send the response and return a stop tuple instead. -

    -
  • -
  • -

    -The known_content_type REST handler callback has been removed - as it was found unnecessary. -

    -
  • -
  • -

    -Websocket handlers have both the normal init/2 and - an optional websocket_init/1 function. The reason for - that exception is that the websocket_* callbacks execute - in a separate process from the init/2 callback, and it - was therefore not obvious how timers or monitors should - be setup properly. They are effectively initializing the - handler before and after the HTTP/1.1 upgrade. -

    -
  • -
  • -

    -Websocket handlers can now send frames directly from - websocket_init/1. The frames will be sent immediately - after the handshake. -

    -
  • -
  • -

    -Websocket handler callbacks no longer receive the Req - argument. The init/2 callback still receives it and - can be used to extract relevant information. The terminate/3 - callback, if implemented, may still receive the Req - (see next bullet point). -

    -
  • -
  • -

    -Websocket handlers have a new req_filter option that - can be used to customize how much information should be - discarded from the Req object after the handshake. Note - that the Req object is only available in terminate/3 - past that point. -

    -
  • -
  • -

    -Websocket handlers have their timeout default changed - from infinity to 60 seconds. -

    -
  • -
-
-
-
+
  • The handler behaviors have been renamed and are now cowboy_handler, cowboy_loop, cowboy_rest and cowboy_websocket. +
  • +
  • Plain HTTP, loop, REST and Websocket handlers have had their init and terminate callbacks unified. They now all use the init/2 and terminate/3 callbacks. The latter is now optional. The terminate reason has now been documented for all handlers. +
  • +
  • The tuple returned to switch to a different handler type has changed. It now takes the form {Module, Req, State} or {Module, Req, State, Opts}, where Opts is a map of options to configure the handler. The timeout and hibernate options must now be specified using this map, where applicable. +
  • +
  • All behaviors that used to accept halt or shutdown tuples as a return value no longer do so. The return value is now a stop tuple, consistent across Cowboy. +
  • +
  • Middlewares can no longer return an error tuple. They have to send the response and return a stop tuple instead. +
  • +
  • The known_content_type REST handler callback has been removed as it was found unnecessary. +
  • +
  • Websocket handlers have both the normal init/2 and an optional websocket_init/1 function. The reason for that exception is that the websocket_* callbacks execute in a separate process from the init/2 callback, and it was therefore not obvious how timers or monitors should be setup properly. They are effectively initializing the handler before and after the HTTP/1.1 upgrade. +
  • +
  • Websocket handlers can now send frames directly from websocket_init/1. The frames will be sent immediately after the handshake. +
  • +
  • Websocket handler callbacks no longer receive the Req argument. The init/2 callback still receives it and can be used to extract relevant information. The terminate/3 callback, if implemented, may still receive the Req (see next bullet point). +
  • +
  • Websocket handlers have a new req_filter option that can be used to customize how much information should be discarded from the Req object after the handshake. Note that the Req object is only available in terminate/3 past that point. +
  • +
  • Websocket handlers have their timeout default changed from infinity to 60 seconds. +
  • +

New functions

-
-
    -
  • -

    -The cowboy_req:scheme/1 function has been added. -

    -
  • -
  • -

    -The cowboy_req:uri/1,2 function has been added, replacing the - less powerful functions cowboy_req:url/1 and cowboy_req:host_url/1. -

    -
  • -
  • -

    -The functions cowboy_req:match_qs/2 and cowboy_req:match_cookies/2 - allow matching query string and cookies against constraints. -

    -
  • -
  • -

    -The function cowboy_req:set_resp_cookie/3 has been added to - complement cowboy_req:set_resp_cookie/4. -

    -
  • -
  • -

    -The functions cowboy_req:resp_header/2,3 and cowboy_req:resp_headers/1 - have been added. They can be used to retrieve response headers - that were previously set. -

    -
  • -
  • -

    -The function cowboy_req:set_resp_headers/2 has been added. It - allows setting many response headers at once. -

    -
  • -
  • -

    -The functions cowboy_req:push/3,4 can be used to push resources - for protocols that support it (by default only HTTP/2). -

    -
  • -
-
-
-
+
  • The cowboy_req:scheme/1 function has been added. +
  • +
  • The cowboy_req:uri/1,2 function has been added, replacing the less powerful functions cowboy_req:url/1 and cowboy_req:host_url/1. +
  • +
  • The functions cowboy_req:match_qs/2 and cowboy_req:match_cookies/2 allow matching query string and cookies against constraints. +
  • +
  • The function cowboy_req:set_resp_cookie/3 has been added to complement cowboy_req:set_resp_cookie/4. +
  • +
  • The functions cowboy_req:resp_header/2,3 and cowboy_req:resp_headers/1 have been added. They can be used to retrieve response headers that were previously set. +
  • +
  • The function cowboy_req:set_resp_headers/2 has been added. It allows setting many response headers at once. +
  • +
  • The functions cowboy_req:push/3,4 can be used to push resources for protocols that support it (by default only HTTP/2). +
  • +

Changed functions

-
-
    -
  • -

    -The cowboy:start_http/4 function was renamed to cowboy:start_clear/3. -

    -
  • -
  • -

    -The cowboy:start_https/4 function was renamed to cowboy:start_tls/3. -

    -
  • -
  • -

    -Most, if not all, functions in the cowboy_req module have been modified. - Please consult the changelog of each individual functions. The changes - are mainly about simplifying and clarifying the interface. The Req is no - longer returned when not necessary, maps are used wherever possible, - and some functions have been renamed. -

    -
  • -
  • -

    -The position of the Opts argument for cowboy_req:set_resp_cookie/4 - has changed to improve consistency. It is now the last argument. -

    -
  • -
-
-
-
+
  • The cowboy:start_http/4 function was renamed to cowboy:start_clear/3. +
  • +
  • The cowboy:start_https/4 function was renamed to cowboy:start_tls/3. +
  • +
  • Most, if not all, functions in the cowboy_req module have been modified. Please consult the changelog of each individual functions. The changes are mainly about simplifying and clarifying the interface. The Req is no longer returned when not necessary, maps are used wherever possible, and some functions have been renamed. +
  • +
  • The position of the Opts argument for cowboy_req:set_resp_cookie/4 has changed to improve consistency. It is now the last argument. +
  • +

Removed functions

-
-
    -
  • -

    -The functions cowboy_req:url/1 and cowboy_req:host_url/1 have been - removed in favor of the new function cowboy_req:uri/1,2. -

    -
  • -
  • -

    -The functions cowboy_req:meta/2,3 and cowboy_req:set_meta/3 have - been removed. The Req object is now a public map, therefore they became - unnecessary. -

    -
  • -
  • -

    -The functions cowboy_req:set_resp_body_fun/2,3 have been removed. - For sending files, the function cowboy_req:set_resp_body/2 can now - take a sendfile tuple. -

    -
  • -
  • -

    -Remove many undocumented functions from cowboy_req, including the - functions cowboy_req:get/2 and cowboy_req:set/3. -

    -
  • -
-
-
-
+
  • The functions cowboy_req:url/1 and cowboy_req:host_url/1 have been removed in favor of the new function cowboy_req:uri/1,2. +
  • +
  • The functions cowboy_req:meta/2,3 and cowboy_req:set_meta/3 have been removed. The Req object is now a public map, therefore they became unnecessary. +
  • +
  • The functions cowboy_req:set_resp_body_fun/2,3 have been removed. For sending files, the function cowboy_req:set_resp_body/2 can now take a sendfile tuple. +
  • +
  • Remove many undocumented functions from cowboy_req, including the functions cowboy_req:get/2 and cowboy_req:set/3. +
  • +

Other changes

-
-
    -
  • -

    -The correct percent-decoding algorithm is now used for path elements - during routing. It will no longer decode + characters. -

    -
  • -
  • -

    -The router will now properly handle path segments . and ... -

    -
  • -
  • -

    -Routing behavior has changed for URIs containing latin1 characters. - They are no longer allowed. URIs are expected to be in UTF-8 once - they are percent-decoded. -

    -
  • -
  • -

    -Clients that send multiple headers of the same name - will have the values of those headers concatenated into a - comma-separated list. This is of special importance in the - case of the content-type header, as previously only the - first value was used in the content_types_accepted/2 step - in REST handlers. -

    -
  • -
  • -

    -Etag comparison in REST handlers has been fixed. Some requests may - now fail when they succeeded in the past. -

    -
  • -
  • -

    -The If-*-Since headers are now ignored in REST handlers if - the corresponding If*-Match header exist. The former is - largely a backward compatible header and this shouldn’t create - any issue. The new behavior follows the current RFCs more closely. -

    -
  • -
  • -

    -The static file handler has been improved to handle more special - characters on systems that accept them. -

    -
  • -
-
-
+
  • The correct percent-decoding algorithm is now used for path elements during routing. It will no longer decode + characters. +
  • +
  • The router will now properly handle path segments . and ... +
  • +
  • Routing behavior has changed for URIs containing latin1 characters. They are no longer allowed. URIs are expected to be in UTF-8 once they are percent-decoded. +
  • +
  • Clients that send multiple headers of the same name will have the values of those headers concatenated into a comma-separated list. This is of special importance in the case of the content-type header, as previously only the first value was used in the content_types_accepted/2 step in REST handlers. +
  • +
  • Etag comparison in REST handlers has been fixed. Some requests may now fail when they succeeded in the past. +
  • +
  • The If-*-Since headers are now ignored in REST handlers if the corresponding If*-Match header exist. The former is largely a backward compatible header and this shouldn't create any issue. The new behavior follows the current RFCs more closely. +
  • +
  • The static file handler has been improved to handle more special characters on systems that accept them. +
  • +
+ diff --git a/docs/en/cowboy/2.1/guide/migrating_from_2.0/index.html b/docs/en/cowboy/2.1/guide/migrating_from_2.0/index.html index dcae7395..4124c49a 100644 --- a/docs/en/cowboy/2.1/guide/migrating_from_2.0/index.html +++ b/docs/en/cowboy/2.1/guide/migrating_from_2.0/index.html @@ -62,188 +62,55 @@

Migrating from Cowboy 2.0 to 2.1

-

Cowboy 2.1 focused on adding features that were temporarily -removed in Cowboy 2.0. A number of bugs found in the 2.0 -release were also fixed.

-
+

Cowboy 2.1 focused on adding features that were temporarily removed in Cowboy 2.0. A number of bugs found in the 2.0 release were also fixed.

Features added

-
-
    -
  • -

    -It is now possible to obtain the client TLS certificate - and the local IP/port for the connection from the Req object. -

    +
    • It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object.
    • -
    • -

      -Informational responses (1XX responses) can now be sent. - They must be sent before initiating the final response. -

      +
    • Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response.
    • -
    • -

      -The expect: 100-continue header is now handled - automatically. The 100 response will be sent on the - first cowboy_req:read_body/2,3,4 call. This only applies - when using the default cowboy_stream_h stream handler. -

      +
    • The expect: 100-continue header is now handled automatically. The 100 response will be sent on the first cowboy_req:read_body/2,3,4 call. This only applies when using the default cowboy_stream_h stream handler.
    • -
-
-
-
+

Experimental features added

-
-

Experimental features are previews of features that will be -added in a future release. They are not documented and their -interface may change at any time. You are welcome to try them -and provide feedback.

-
    -
  • -

    -The cowboy_metrics_h stream handler can be used to - extract metrics out of Cowboy. It must be used first in - the list of stream handlers, and will record all events - related to requests, responses and spawned processes. - When the stream terminates it will pass this information - to a user-defined callback. -

    +

    Experimental features are previews of features that will be added in a future release. They are not documented and their interface may change at any time. You are welcome to try them and provide feedback.

    +
    • The cowboy_metrics_h stream handler can be used to extract metrics out of Cowboy. It must be used first in the list of stream handlers, and will record all events related to requests, responses and spawned processes. When the stream terminates it will pass this information to a user-defined callback.
    • -
    • -

      -The cowboy_tracer_h stream handler can be used to setup - automatic tracing of specific requests. You can conditionally - enable tracing based on a function, header, path or any other - element from the request and the trace will apply to the - entire connection and any processes created by it. This is - meant to be used for debugging both in tests and production. -

      +
    • The cowboy_tracer_h stream handler can be used to setup automatic tracing of specific requests. You can conditionally enable tracing based on a function, header, path or any other element from the request and the trace will apply to the entire connection and any processes created by it. This is meant to be used for debugging both in tests and production.
    • -
-
-
-
+

Changed behaviors

-
-
    -
  • -

    -The cowboy_rest handler now implements a mechanism for - switching to a different type of handler from any callback - where stop is also allowed. Switch by returning - {switch_handler, Module} or {switch_handler, Module, Opts}. - This is especially useful for switching to cowboy_loop - for streaming the request or response body. -

    +
    • The cowboy_rest handler now implements a mechanism for switching to a different type of handler from any callback where stop is also allowed. Switch by returning {switch_handler, Module} or {switch_handler, Module, Opts}. This is especially useful for switching to cowboy_loop for streaming the request or response body.
    • -
    • -

      -REST callbacks that do not allow stop as a return value - are now explicitly listed in the documentation. -

      +
    • REST callbacks that do not allow stop as a return value are now explicitly listed in the documentation.
    • -
-
-
-
+

New functions

-
-
    -
  • -

    -The function cowboy_req:sock/1 returns the IP/port - of the local socket. -

    +
    • The function cowboy_req:sock/1 returns the IP/port of the local socket.
    • -
    • -

      -The function cowboy_req:cert/1 returns the client - TLS certificate or undefined if it isn’t available. -

      +
    • The function cowboy_req:cert/1 returns the client TLS certificate or undefined if it isn't available.
    • -
    • -

      -The function cowboy_req:inform/2,3 sends an - informational response. -

      +
    • The function cowboy_req:inform/2,3 sends an informational response.
    • -
-
-
-
+

Bugs fixed

-
-
    -
  • -

    -Ensure HTTP/2 connections are not closed prematurely - when the user code does not read the request body. -

    +
    • Ensure HTTP/2 connections are not closed prematurely when the user code does not read the request body.
    • -
    • -

      -Ensure HTTP/1.1 streams are not terminated too early. - Their behavior is now consistent with the HTTP/2 code - where the stream handler is only terminated when the - stop command is returned. -

      +
    • Ensure HTTP/1.1 streams are not terminated too early. Their behavior is now consistent with the HTTP/2 code where the stream handler is only terminated when the stop command is returned.
    • -
    • -

      -Sending zero-sized data from stream handlers or from - cowboy_req:stream_body/3 could lead to issues with - HTTP/1.1. This has been fixed. -

      +
    • Sending zero-sized data from stream handlers or from cowboy_req:stream_body/3 could lead to issues with HTTP/1.1. This has been fixed.
    • -
    • -

      -The final chunk sent by Cowboy when it terminates a - chunked body after the handler process exits was not - passed through stream handlers, which could lead to - issues when cowboy_compress_h was being used. This - is now corrected. -

      +
    • The final chunk sent by Cowboy when it terminates a chunked body after the handler process exits was not passed through stream handlers, which could lead to issues when cowboy_compress_h was being used. This is now corrected.
    • -
    • -

      -The stream handler state was discarded in some cases - where Cowboy had to send a response or response data - automatically when ending a stream. This has now - been corrected. -

      +
    • The stream handler state was discarded in some cases where Cowboy had to send a response or response data automatically when ending a stream. This has now been corrected.
    • -
    • -

      -The stream handler callback terminate/3 will now be - called when switching to another protocol using the - command switch_protocol. This doesn’t apply when - doing upgrades to HTTP/2 as those occur before the - stream is initialized. -

      +
    • The stream handler callback terminate/3 will now be called when switching to another protocol using the command switch_protocol. This doesn't apply when doing upgrades to HTTP/2 as those occur before the stream is initialized.
    • -
    • -

      -Cowlib has been updated to 2.0.1 to fix an issue with - Websocket compression when using Erlang/OTP 20.1. Note - that at the time of writing all 20.1 versions (from - 20.1 to 20.1.4) have issues when compression is enabled. - It is expected to work properly from 20.1.5 onward. In - the meantime it is recommended to run the plain 20.1 - release and disable Websocket compression, or use a - release before 20.1. -

      +
    • Cowlib has been updated to 2.0.1 to fix an issue with Websocket compression when using Erlang/OTP 20.1. Note that at the time of writing all 20.1 versions (from 20.1 to 20.1.4) have issues when compression is enabled. It is expected to work properly from 20.1.5 onward. In the meantime it is recommended to run the plain 20.1 release and disable Websocket compression, or use a release before 20.1.
    • -
    • -

      -Cowboy will no longer crash when the cowboy_clock - process is not running. This can happen when Cowboy - is being restarted during upgrades, for example. -

      +
    • Cowboy will no longer crash when the cowboy_clock process is not running. This can happen when Cowboy is being restarted during upgrades, for example.
    • -
-
-
+ + diff --git a/docs/en/cowboy/2.1/guide/modern_web/index.html b/docs/en/cowboy/2.1/guide/modern_web/index.html index 3c793fb7..4f31995c 100644 --- a/docs/en/cowboy/2.1/guide/modern_web/index.html +++ b/docs/en/cowboy/2.1/guide/modern_web/index.html @@ -62,115 +62,38 @@

The modern Web

-

Cowboy is a server for the modern Web. This chapter explains -what it means and details all the standards involved.

-

Cowboy supports all the standards listed in this document.

-
+

Cowboy is a server for the modern Web. This chapter explains what it means and details all the standards involved.

+

Cowboy supports all the standards listed in this document.

HTTP/2

-
-

HTTP/2 is the most efficient protocol for consuming Web -services. It enables clients to keep a connection open -for long periods of time; to send requests concurrently; -to reduce the size of requests through HTTP headers -compression; and more. The protocol is binary, greatly -reducing the resources needed to parse it.

-

HTTP/2 also enables the server to push messages to the -client. This can be used for various purposes, including -the sending of related resources before the client requests -them, in an effort to reduce latency. This can also be used -to enable bidirectional communication.

-

Cowboy provides transparent support for HTTP/2. Clients -that know it can use it; others fall back to HTTP/1.1 -automatically.

-

HTTP/2 is compatible with the HTTP/1.1 semantics.

-

HTTP/2 is defined by RFC 7540 and RFC 7541.

-
-
-
+

HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. The protocol is binary, greatly reducing the resources needed to parse it.

+

HTTP/2 also enables the server to push messages to the client. This can be used for various purposes, including the sending of related resources before the client requests them, in an effort to reduce latency. This can also be used to enable bidirectional communication.

+

Cowboy provides transparent support for HTTP/2. Clients that know it can use it; others fall back to HTTP/1.1 automatically.

+

HTTP/2 is compatible with the HTTP/1.1 semantics.

+

HTTP/2 is defined by RFC 7540 and RFC 7541.

HTTP/1.1

-
-

HTTP/1.1 is the previous version of the HTTP protocol. -The protocol itself is text-based and suffers from numerous -issues and limitations. In particular it is not possible -to execute requests concurrently (though pipelining is -sometimes possible), and it’s also sometimes difficult -to detect that a client disconnected.

-

HTTP/1.1 does provide very good semantics for interacting -with Web services. It defines the standard methods, headers -and status codes used by HTTP/1.1 and HTTP/2 clients and -servers.

-

HTTP/1.1 also defines compatibility with an older version -of the protocol, HTTP/1.0, which was never really standardized -across implementations.

-

The core of HTTP/1.1 is defined by RFC 7230, RFC 7231, -RFC 7232, RFC 7233, RFC 7234 and RFC 7235. Numerous RFCs -and other specifications exist defining additional HTTP -methods, status codes, headers or semantics.

-
-
-
+

HTTP/1.1 is the previous version of the HTTP protocol. The protocol itself is text-based and suffers from numerous issues and limitations. In particular it is not possible to execute requests concurrently (though pipelining is sometimes possible), and it's also sometimes difficult to detect that a client disconnected.

+

HTTP/1.1 does provide very good semantics for interacting with Web services. It defines the standard methods, headers and status codes used by HTTP/1.1 and HTTP/2 clients and servers.

+

HTTP/1.1 also defines compatibility with an older version of the protocol, HTTP/1.0, which was never really standardized across implementations.

+

The core of HTTP/1.1 is defined by RFC 7230, RFC 7231, RFC 7232, RFC 7233, RFC 7234 and RFC 7235. Numerous RFCs and other specifications exist defining additional HTTP methods, status codes, headers or semantics.

Websocket

-
-

Websocket is a protocol built on top of HTTP/1.1 -that provides a two-ways communication channel between the client and -the server. Communication is asynchronous and can occur concurrently.

-

It consists of a Javascript object allowing setting up a -Websocket connection to the server, and a binary based -protocol for sending data to the server or the client.

-

Websocket connections can transfer either UTF-8 encoded text -data or binary data. The protocol also includes support for -implementing a ping/pong mechanism, allowing the server and -the client to have more confidence that the connection is still -alive.

-

A Websocket connection can be used to transfer any kind of data, -small or big, text or binary. Because of this Websocket is -sometimes used for communication between systems.

-

Websocket messages have no semantics on their own. Websocket -is closer to TCP in that aspect, and requires you to design -and implement your own protocol on top of it; or adapt an -existing protocol to Websocket.

-

Cowboy provides an interface known as Websocket handlers -that gives complete control over a Websocket connection.

-

The Websocket protocol is defined by RFC 6455.

-
-
-
+

Websocket is a protocol built on top of HTTP/1.1 that provides a two-ways communication channel between the client and the server. Communication is asynchronous and can occur concurrently.

+

It consists of a Javascript object allowing setting up a Websocket connection to the server, and a binary based protocol for sending data to the server or the client.

+

Websocket connections can transfer either UTF-8 encoded text data or binary data. The protocol also includes support for implementing a ping/pong mechanism, allowing the server and the client to have more confidence that the connection is still alive.

+

A Websocket connection can be used to transfer any kind of data, small or big, text or binary. Because of this Websocket is sometimes used for communication between systems.

+

Websocket messages have no semantics on their own. Websocket is closer to TCP in that aspect, and requires you to design and implement your own protocol on top of it; or adapt an existing protocol to Websocket.

+

Cowboy provides an interface known as Websocket handlers that gives complete control over a Websocket connection.

+

The Websocket protocol is defined by RFC 6455.

Long-lived requests

-
-

Cowboy provides an interface that can be used to support -long-polling or to stream large amounts of data reliably, -including using Server-Sent Events.

-

Long-polling is a mechanism in which the client performs -a request which may not be immediately answered by the -server. It allows clients to request resources that may -not currently exist, but are expected to be created soon, -and which will be returned as soon as they are.

-

Long-polling is essentially a hack, but it is widely used -to overcome limitations on older clients and servers.

-

Server-Sent Events is a small protocol defined as a media -type, text/event-stream, along with a new HTTP header, -Last-Event-ID. It is defined in the EventSource W3C -specification.

-

Cowboy provides an interface known as loop handlers -that facilitates the implementation of long-polling or stream -mechanisms. It works regardless of the underlying protocol.

-
-
-
+

Cowboy provides an interface that can be used to support long-polling or to stream large amounts of data reliably, including using Server-Sent Events.

+

Long-polling is a mechanism in which the client performs a request which may not be immediately answered by the server. It allows clients to request resources that may not currently exist, but are expected to be created soon, and which will be returned as soon as they are.

+

Long-polling is essentially a hack, but it is widely used to overcome limitations on older clients and servers.

+

Server-Sent Events is a small protocol defined as a media type, text/event-stream, along with a new HTTP header, Last-Event-ID. It is defined in the EventSource W3C specification.

+

Cowboy provides an interface known as loop handlers that facilitates the implementation of long-polling or stream mechanisms. It works regardless of the underlying protocol.

REST

-
-

REST, or REpresentational State Transfer, -is a style of architecture for loosely connected distributed -systems. It can easily be implemented on top of HTTP.

-

REST is essentially a set of constraints to be followed. -Many of these constraints are purely architectural and -solved by simply using HTTP. Some constraints must be -explicitly followed by the developer.

-

Cowboy provides an interface known as REST handlers -that simplifies the implementation of a REST API on top of -the HTTP protocol.

-
-
+

REST, or REpresentational State Transfer, is a style of architecture for loosely connected distributed systems. It can easily be implemented on top of HTTP.

+

REST is essentially a set of constraints to be followed. Many of these constraints are purely architectural and solved by simply using HTTP. Some constraints must be explicitly followed by the developer.

+

Cowboy provides an interface known as REST handlers that simplifies the implementation of a REST API on top of the HTTP protocol.

+ diff --git a/docs/en/cowboy/2.1/guide/multipart/index.html b/docs/en/cowboy/2.1/guide/multipart/index.html index ddc9f4ef..ee825e25 100644 --- a/docs/en/cowboy/2.1/guide/multipart/index.html +++ b/docs/en/cowboy/2.1/guide/multipart/index.html @@ -62,169 +62,107 @@

Multipart requests

-

Multipart originates from MIME, an Internet standard that -extends the format of emails.

-

A multipart message is a list of parts. A part contains -headers and a body. The body of the parts may be -of any media type, and contain text or binary data. -It is possible for parts to contain a multipart media -type.

-

In the context of HTTP, multipart is most often used -with the multipart/form-data media type. It is what -browsers use to upload files through HTML forms.

-

The multipart/byteranges is also common. It is the -media type used to send arbitrary bytes from a resource, -enabling clients to resume downloads.

-
+

Multipart originates from MIME, an Internet standard that extends the format of emails.

+

A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type.

+

In the context of HTTP, multipart is most often used with the multipart/form-data media type. It is what browsers use to upload files through HTML forms.

+

The multipart/byteranges is also common. It is the media type used to send arbitrary bytes from a resource, enabling clients to resume downloads.

Form-data

-
-

In the normal case, when a form is submitted, the -browser will use the application/x-www-form-urlencoded -content-type. This type is just a list of keys and -values and is therefore not fit for uploading files.

-

That’s where the multipart/form-data content-type -comes in. When the form is configured to use this -content-type, the browser will create a multipart -message where each part corresponds to a field on -the form. For files, it also adds some metadata in -the part headers, like the file name.

-

A form with a text input, a file input and a select -choice box will result in a multipart message with -three parts, one for each field.

-

The browser does its best to determine the media type -of the files it sends this way, but you should not -rely on it for determining the contents of the file. -Proper investigation of the contents is recommended.

-
-
-
+

In the normal case, when a form is submitted, the browser will use the application/x-www-form-urlencoded content-type. This type is just a list of keys and values and is therefore not fit for uploading files.

+

That's where the multipart/form-data content-type comes in. When the form is configured to use this content-type, the browser will create a multipart message where each part corresponds to a field on the form. For files, it also adds some metadata in the part headers, like the file name.

+

A form with a text input, a file input and a select choice box will result in a multipart message with three parts, one for each field.

+

The browser does its best to determine the media type of the files it sends this way, but you should not rely on it for determining the contents of the file. Proper investigation of the contents is recommended.

Checking for multipart messages

-
-

The content-type header indicates the presence of -a multipart message:

-
-
-
{<<"multipart">>, <<"form-data">>, _}
-    = cowboy_req:parse_header(<<"content-type">>, Req).
-
-
-
+
{<<"multipart">>, <<"form-data">>, _}
+    = cowboy_req:parse_header(<<"content-type">>, Req).
+

Reading a multipart message

-
-

Cowboy provides two sets of functions for reading -request bodies as multipart messages.

-

The cowboy_req:read_part/1,2 functions return the -next part’s headers, if any.

-

The cowboy_req:read_part_body/1,2 functions return -the current part’s body. For large bodies you may -need to call the function multiple times.

-

To read a multipart message you need to iterate over -all its parts:

-
-
-
multipart(Req0) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, _Headers, Req1} ->
-            {ok, _Body, Req} = cowboy_req:read_part_body(Req1),
-            multipart(Req);
-        {done, Req} ->
-            Req
-    end.
-

When part bodies are too large, Cowboy will return -a more tuple, and allow you to loop until the part -body has been fully read.

-

The function cow_multipart:form_data/1 can be used -to quickly obtain information about a part from a -multipart/form-data message. The function returns -a data or a file tuple depending on whether this -is a normal field or a file being uploaded.

-

The following snippet will use this function and -use different strategies depending on whether the -part is a file:

-
-
-
multipart(Req0) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, Headers, Req1} ->
-            Req = case cow_multipart:form_data(Headers) of
-                {data, _FieldName} ->
-                    {ok, _Body, Req2} = cowboy_req:read_part_body(Req1),
-                    Req2;
-                {file, _FieldName, _Filename, _CType} ->
-                    stream_file(Req1)
-            end,
-            multipart(Req);
-        {done, Req} ->
-            Req
-    end.
-
-stream_file(Req0) ->
-    case cowboy_req:read_part_body(Req0) of
-        {ok, _LastBodyChunk, Req} ->
-            Req;
-        {more, _BodyChunk, Req} ->
-            stream_file(Req)
-    end.
-

Both the part header and body reading functions can take -options that will be given to the request body reading -functions. By default, cowboy_req:read_part/1 reads -up to 64KB for up to 5 seconds. cowboy_req:read_part_body/1 -has the same defaults as cowboy_req:read_body/1.

-

To change the defaults for part headers:

-
-
-
cowboy_req:read_part(Req, #{length => 128000}).
-

And for part bodies:

-
-
-
cowboy_req:read_part_body(Req, #{length => 1000000, period => 7000}).
-
- -
+
cowboy_req:read_part_body(Req, #{length => 1000000, period => 7000}).
+

Skipping unwanted parts

-
-

Part bodies do not have to be read. Cowboy will automatically -skip it when you request the next part’s body.

-

The following snippet reads all part headers and skips -all bodies:

-
-
-
multipart(Req0) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, _Headers, Req} ->
-            multipart(Req);
-        {done, Req} ->
-            Req
-    end.
-

Similarly, if you start reading the body and it ends up -being too big, you can simply continue with the next part. -Cowboy will automatically skip what remains.

-

While Cowboy can skip part bodies automatically, the read -rate is not configurable. Depending on your application -you may want to skip manually, in particular if you observe -poor performance while skipping.

-

You do not have to read all parts either. You can stop -reading as soon as you find the data you need.

-
- +
multipart(Req0) ->
+    case cowboy_req:read_part(Req0) of
+        {ok, _Headers, Req} ->
+            multipart(Req);
+        {done, Req} ->
+            Req
+    end.
+ +

Similarly, if you start reading the body and it ends up being too big, you can simply continue with the next part. Cowboy will automatically skip what remains.

+

While Cowboy can skip part bodies automatically, the read rate is not configurable. Depending on your application you may want to skip manually, in particular if you observe poor performance while skipping.

+

You do not have to read all parts either. You can stop reading as soon as you find the data you need.

+ + diff --git a/docs/en/cowboy/2.1/guide/req/index.html b/docs/en/cowboy/2.1/guide/req/index.html index 640eb075..7ecf8bc5 100644 --- a/docs/en/cowboy/2.1/guide/req/index.html +++ b/docs/en/cowboy/2.1/guide/req/index.html @@ -62,407 +62,283 @@

The Req object

-

The Req object is a variable used for obtaining information -about a request, read its body or send a response.

-

It is not really an object in the object-oriented sense. -It is a simple map that can be directly accessed or -used when calling functions from the cowboy_req module.

-

The Req object is the subject of a few different chapters. -In this chapter we will learn about the Req object and -look at how to retrieve information about the request.

-
+

The Req object is a variable used for obtaining information about a request, read its body or send a response.

+

It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module.

+

The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request.

Direct access

-
-

The Req map contains a number of fields which are documented -and can be accessed directly. They are the fields that have -a direct mapping to HTTP: the request method; the HTTP -version used; the effective URI components scheme, -host, port, path and qs; the request headers; -and the connection peer address and port.

-

Note that the version field can be used to determine -whether a connection is using HTTP/2.

-

To access a field, you can simply match in the function -head. The following example sends a simple "Hello world!" -response when the method is GET, and a 405 error -otherwise.

-
-
-
init(Req0=#{method := <<"GET">>}, State) ->
-    Req = cowboy_req:reply(200, #{
-        <<"content-type">> => <<"text/plain">>
-    }, <<"Hello world!">>, Req0),
-    {ok, Req, State};
-init(Req0, State) ->
-    Req = cowboy_req:reply(405, #{
-        <<"allow">> => <<"GET">>
-    }, Req0),
-    {ok, Req, State}.
-

Any other field is internal and should not be accessed. -They may change in future releases, including maintenance -releases, without notice.

-

Modifying the Req object, while allowed, is not recommended -unless strictly necessary. If adding new fields, make sure -to namespace the field names so that no conflict can occur -with future Cowboy updates or third party projects.

-
-
-
+
init(Req0=#{method := <<"GET">>}, State) ->
+    Req = cowboy_req:reply(200, #{
+        <<"content-type">> => <<"text/plain">>
+    }, <<"Hello world!">>, Req0),
+    {ok, Req, State};
+init(Req0, State) ->
+    Req = cowboy_req:reply(405, #{
+        <<"allow">> => <<"GET">>
+    }, Req0),
+    {ok, Req, State}.
+
+

Any other field is internal and should not be accessed. They may change in future releases, including maintenance releases, without notice.

+

Modifying the Req object, while allowed, is not recommended unless strictly necessary. If adding new fields, make sure to namespace the field names so that no conflict can occur with future Cowboy updates or third party projects.

+

Introduction to the cowboy_req interface

-
-

Functions in the cowboy_req module provide access to -the request information but also various operations that -are common when dealing with HTTP requests.

-

All the functions that begin with a verb indicate an action. -Other functions simply return the corresponding value -(sometimes that value does need to be built, but the -cost of the operation is equivalent to retrieving a value).

-

Some of the cowboy_req functions return an updated Req -object. They are the read, reply, set and delete functions. -While ignoring the returned Req will not cause incorrect -behavior for some of them, it is highly recommended to -always keep and use the last returned Req object. The -manual for cowboy_req details these functions and what -modifications are done to the Req object.

-

Some of the calls to cowboy_req have side effects. This -is the case of the read and reply functions. Cowboy reads -the request body or replies immediately when the function -is called.

-

All functions will crash if something goes wrong. There -is usually no need to catch these errors, Cowboy will -send the appropriate 4xx or 5xx response depending on -where the crash occurred.

-
- -
+ +

Functions in the cowboy_req module provide access to the request information but also various operations that are common when dealing with HTTP requests.

+

All the functions that begin with a verb indicate an action. Other functions simply return the corresponding value (sometimes that value does need to be built, but the cost of the operation is equivalent to retrieving a value).

+

Some of the cowboy_req functions return an updated Req object. They are the read, reply, set and delete functions. While ignoring the returned Req will not cause incorrect behavior for some of them, it is highly recommended to always keep and use the last returned Req object. The manual for cowboy_req details these functions and what modifications are done to the Req object.

+

Some of the calls to cowboy_req have side effects. This is the case of the read and reply functions. Cowboy reads the request body or replies immediately when the function is called.

+

All functions will crash if something goes wrong. There is usually no need to catch these errors, Cowboy will send the appropriate 4xx or 5xx response depending on where the crash occurred.

Request method

-
-

The request method can be retrieved directly:

-
-
-
#{method := Method} = Req.
-

Or using a function:

-
-
-
Method = cowboy_req:method(Req).
-

The method is a case sensitive binary string. Standard -methods include GET, HEAD, OPTIONS, PATCH, POST, PUT -or DELETE.

-
-
-
+
Method = cowboy_req:method(Req).
+
+

The method is a case sensitive binary string. Standard methods include GET, HEAD, OPTIONS, PATCH, POST, PUT or DELETE.

HTTP version

-
-

The HTTP version is informational. It does not indicate that -the client implements the protocol well or fully.

-

There is typically no need to change behavior based on the -HTTP version: Cowboy already does it for you.

-

It can be useful in some cases, though. For example, one may -want to redirect HTTP/1.1 clients to use Websocket, while HTTP/2 -clients keep using HTTP/2.

-

The HTTP version can be retrieved directly:

-
-
-
#{version := Version} = Req.
-

Or using a function:

-
-
-
Version = cowboy_req:version(Req).
-

Cowboy defines the 'HTTP/1.0', 'HTTP/1.1' and 'HTTP/2' -versions. Custom protocols can define their own values as -atoms.

-
- -
+
Version = cowboy_req:version(Req).
+
+

Cowboy defines the 'HTTP/1.0', 'HTTP/1.1' and 'HTTP/2' versions. Custom protocols can define their own values as atoms.

Effective request URI

-
-

The scheme, host, port, path and query string components -of the effective request URI can all be retrieved directly:

-
-
#{
-    scheme := Scheme,
-    host := Host,
-    port := Port,
-    path := Path,
-    qs := Qs
-} = Req.
-

Or using the related functions:

-
-
-
Scheme = cowboy_req:scheme(Req),
-Host = cowboy_req:host(Req),
-Port = cowboy_req:port(Req),
-Path = cowboy_req:path(Req).
-Qs = cowboy_req:qs(Req).
-

The scheme and host are lowercased case insensitive binary -strings. The port is an integer representing the port number. -The path and query string are case sensitive binary strings.

-

Cowboy defines only the <<"http">> and <<"https">> schemes. -They are chosen so that the scheme will only be <<"https">> -for requests on secure HTTP/1.1 or HTTP/2 connections.

-

The effective request URI itself can be reconstructed with -the cowboy_req:uri/1,2 function. By default, an absolute -URI is returned:

-
-
+

The effective request URI itself can be reconstructed with the cowboy_req:uri/1,2 function. By default, an absolute URI is returned:

+
-
%% scheme://host[:port]/path[?qs]
-URI = cowboy_req:uri(Req).
-

Options are available to either disable or replace some -or all of the components. Various URIs or URI formats can -be generated this way, including the origin form:

-
-
-
%% /path[?qs]
-URI = cowboy_req:uri(Req, #{host => undefined}).
-

The protocol relative form:

-
-
-
%% //host[:port]/path[?qs]
-URI = cowboy_req:uri(Req, #{scheme => undefined}).
-

The absolute URI without a query string:

-
-
-
URI = cowboy_req:uri(Req, #{qs => undefined}).
-

A different host:

-
-
-
URI = cowboy_req:uri(Req, #{host => <<"example.org">>}).
-

And any other combination.

-
-
-
+
URI = cowboy_req:uri(Req, #{host => <<"example.org">>}).
+
+

And any other combination.

Bindings

-
-

Bindings are the host and path components that you chose -to extract when defining the routes of your application. -They are only available after the routing.

-

Cowboy provides functions to retrieve one or all bindings.

-

To retrieve a single value:

-
-
-
Value = cowboy_req:binding(userid, Req).
-

When attempting to retrieve a value that was not bound, -undefined will be returned. A different default value -can be provided:

-
-
-
Value = cowboy_req:binding(userid, Req, 42).
-

To retrieve everything that was bound:

-
-
-
Bindings = cowboy_req:bindings(Req).
-

They are returned as a map, with keys being atoms.

-

The Cowboy router also allows you to capture many host -or path segments at once using the ... qualifier.

-

To retrieve the segments captured from the host name:

-
-
-
HostInfo = cowboy_req:host_info(Req).
-

And the path segments:

-
-
-
PathInfo = cowboy_req:path_info(Req).
-

Cowboy will return undefined if ... was not used -in the route.

-
- -
+
PathInfo = cowboy_req:path_info(Req).
+
+

Cowboy will return undefined if ... was not used in the route.

Query parameters

-
-

Cowboy provides two functions to access query parameters. -You can use the first to get the entire list of parameters.

-
-
-
QsVals = cowboy_req:parse_qs(Req),
-{_, Lang} = lists:keyfind(<<"lang">>, 1, QsVals).
-

Cowboy will only parse the query string, and not do any -transformation. This function may therefore return duplicates, -or parameter names without an associated value. The order of -the list returned is undefined.

-

When a query string is key=1&key=2, the list returned will -contain two parameters of name key.

-

The same is true when trying to use the PHP-style suffix []. -When a query string is key[]=1&key[]=2, the list returned will -contain two parameters of name key[].

-

When a query string is simply key, Cowboy will return the -list [{<<"key">>, true}], using true to indicate that the -parameter key was defined, but with no value.

-

The second function Cowboy provides allows you to match out -only the parameters you are interested in, and at the same -time do any post processing you require using constraints. -This function returns a map.

-
-
-
#{id := ID, lang := Lang} = cowboy_req:match_qs([id, lang], Req).
-

Constraints can be applied automatically. The following -snippet will crash when the id parameter is not an integer, -or when the lang parameter is empty. At the same time, the -value for id will be converted to an integer term:

-
-
-
QsMap = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req).
-

A default value may also be provided. The default will be used -if the lang key is not found. It will not be used if -the key is found but has an empty value.

-
-
-
#{lang := Lang} = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
-

If no default is provided and the value is missing, the -query string is deemed invalid and the process will crash.

-

When the query string is key=1&key=2, the value for key -will be the list [1, 2]. Parameter names do not need to -include the PHP-style suffix. Constraints may be used to -ensure that only one value was passed through.

-
- -
+
#{lang := Lang} = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
+
+

If no default is provided and the value is missing, the query string is deemed invalid and the process will crash.

+

When the query string is key=1&key=2, the value for key will be the list [1, 2]. Parameter names do not need to include the PHP-style suffix. Constraints may be used to ensure that only one value was passed through.

Headers

-
-

Header values can be retrieved either as a binary string -or parsed into a more meaningful representation.

-

The get the raw value:

-
-
-
HeaderVal = cowboy_req:header(<<"content-type">>, Req).
-

Cowboy expects all header names to be provided as lowercase -binary strings. This is true for both requests and responses, -regardless of the underlying protocol.

-

When the header is missing from the request, undefined -will be returned. A different default can be provided:

-
-
-
HeaderVal = cowboy_req:header(<<"content-type">>, Req, <<"text/plain">>).
-

All headers can be retrieved at once, either directly:

-
-
-
#{headers := AllHeaders} = Req.
-

Or using a function:

-
-
-
AllHeaders = cowboy_req:headers(Req).
-

Cowboy provides equivalent functions to parse individual -headers. There is no function to parse all headers at once.

-

To parse a specific header:

-
-
-
ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req).
-

An exception will be thrown if it doesn’t know how to parse the -given header, or if the value is invalid. The list of known headers -and default values can be found in the manual.

-

When the header is missing, undefined is returned. You can -change the default value. Note that it should be the parsed value -directly:

-
-
-
ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req,
-    {<<"text">>, <<"plain">>, []}).
-
- -
+
ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req,
+    {<<"text">>, <<"plain">>, []}).
+

Peer

-
-

The peer address and port number for the connection can be -retrieved either directly or using a function.

-

To retrieve the peer directly:

-
-
-
#{peer := {IP, Port}} = Req.
-

And using a function:

-
-
-
{IP, Port} = cowboy_req:peer(Req).
-

Note that the peer corresponds to the remote end of the -connection to the server, which may or may not be the -client itself. It may also be a proxy or a gateway.

-
- +
{IP, Port} = cowboy_req:peer(Req).
+ +

Note that the peer corresponds to the remote end of the connection to the server, which may or may not be the client itself. It may also be a proxy or a gateway.

+ diff --git a/docs/en/cowboy/2.1/guide/req_body/index.html b/docs/en/cowboy/2.1/guide/req_body/index.html index 6589675c..f9dca81e 100644 --- a/docs/en/cowboy/2.1/guide/req_body/index.html +++ b/docs/en/cowboy/2.1/guide/req_body/index.html @@ -62,144 +62,93 @@

Reading the request body

-

The request body can be read using the Req object.

-

Cowboy will not attempt to read the body until requested. -You need to call the body reading functions in order to -retrieve it.

-

Cowboy will not cache the body, it is therefore only -possible to read it once.

-

You are not required to read it, however. If a body is -present and was not read, Cowboy will either cancel or -skip its download, depending on the protocol.

-

Cowboy provides functions for reading the body raw, -and read and parse form urlencoded or multipart bodies. -The latter is covered in its own chapter.

-
+

The request body can be read using the Req object.

+

Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it.

+

Cowboy will not cache the body, it is therefore only possible to read it once.

+

You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol.

+

Cowboy provides functions for reading the body raw, and read and parse form urlencoded or multipart bodies. The latter is covered in its own chapter.

Request body presence

-
-

Not all requests come with a body. You can check for -the presence of a request body with this function:

-
-
-
cowboy_req:has_body(Req).
-

It returns true if there is a body; false otherwise.

-

In practice, this function is rarely used. When the -method is POST, PUT or PATCH, the request body -is often required by the application, which should -just attempt to read it directly.

-
-
-
+
cowboy_req:has_body(Req).
+
+

It returns true if there is a body; false otherwise.

+

In practice, this function is rarely used. When the method is POST, PUT or PATCH, the request body is often required by the application, which should just attempt to read it directly.

Request body length

-
-

You can obtain the length of the body:

-
-
-
Length = cowboy_req:body_length(Req).
-

Note that the length may not be known in advance. In -that case undefined will be returned. This can happen -with HTTP/1.1’s chunked transfer-encoding, or HTTP/2 -when no content-length was provided.

-

Cowboy will update the body length in the Req object -once the body has been read completely. A length will -always be returned when attempting to call this function -after reading the body completely.

-
- -
+
Length = cowboy_req:body_length(Req).
+
+

Note that the length may not be known in advance. In that case undefined will be returned. This can happen with HTTP/1.1's chunked transfer-encoding, or HTTP/2 when no content-length was provided.

+

Cowboy will update the body length in the Req object once the body has been read completely. A length will always be returned when attempting to call this function after reading the body completely.

Reading the body

-
-

You can read the entire body with one function call:

-
-
-
{ok, Data, Req} = cowboy_req:read_body(Req0).
-

Cowboy returns an ok tuple when the body has been -read fully.

-

By default, Cowboy will attempt to read up to 8MB -of data, for up to 15 seconds. The call will return -once Cowboy has read at least 8MB of data, or at -the end of the 15 seconds period.

-

These values can be customized. For example, to read -only up to 1MB for up to 5 seconds:

-
-
-
{ok, Data, Req} = cowboy_req:read_body(Req0,
-    #{length => 1000000, period => 5000}).
-

You may also disable the length limit:

-
-
-
{ok, Data, Req} = cowboy_req:read_body(Req0, #{length => infinity}).
-

This makes the function wait 15 seconds and return with -whatever arrived during that period. This is not -recommended for public facing applications.

-

These two options can effectively be used to control -the rate of transmission of the request body.

-
- -
+
{ok, Data, Req} = cowboy_req:read_body(Req0, #{length => infinity}).
+
+

This makes the function wait 15 seconds and return with whatever arrived during that period. This is not recommended for public facing applications.

+

These two options can effectively be used to control the rate of transmission of the request body.

Streaming the body

-
-

When the body is too large, the first call will return -a more tuple instead of ok. You can call the -function again to read more of the body, reading -it one chunk at a time.

-
-
-
read_body_to_console(Req0) ->
-    case cowboy_req:read_body(Req0) of
-        {ok, Data, Req} ->
-            io:format("~s", [Data]),
-            Req;
-        {more, Data, Req} ->
-            io:format("~s", [Data]),
-            read_body_to_console(Req)
-    end.
-

The length and period options can also be used. -They need to be passed for every call.

-
- -
+
read_body_to_console(Req0) ->
+    case cowboy_req:read_body(Req0) of
+        {ok, Data, Req} ->
+            io:format("~s", [Data]),
+            Req;
+        {more, Data, Req} ->
+            io:format("~s", [Data]),
+            read_body_to_console(Req)
+    end.
+
+

The length and period options can also be used. They need to be passed for every call.

Reading a form urlencoded body

-
-

Cowboy provides a convenient function for reading and -parsing bodies sent as application/x-www-form-urlencoded.

-
-
-
{ok, KeyValues, Req} = cowboy_req:read_urlencoded_body(Req0).
-

This function returns a list of key/values, exactly like -the function cowboy_req:parse_qs/1.

-

The defaults for this function are different. Cowboy will -read for up to 64KB and up to 5 seconds. They can be modified:

-
-
-
{ok, KeyValues, Req} = cowboy_req:read_urlencoded_body(Req0,
-    #{length => 4096, period => 3000}).
-
- +
{ok, KeyValues, Req} = cowboy_req:read_urlencoded_body(Req0,
+    #{length => 4096, period => 3000}).
+ + diff --git a/docs/en/cowboy/2.1/guide/resource_design/index.html b/docs/en/cowboy/2.1/guide/resource_design/index.html index 6df3301e..5b13ead0 100644 --- a/docs/en/cowboy/2.1/guide/resource_design/index.html +++ b/docs/en/cowboy/2.1/guide/resource_design/index.html @@ -62,213 +62,66 @@

Designing a resource handler

-

This chapter aims to provide you with a list of questions -you must answer in order to write a good resource handler. -It is meant to be usable as a step by step guide.

-
+

This chapter aims to provide you with a list of questions you must answer in order to write a good resource handler. It is meant to be usable as a step by step guide.

The service

-
-

Can the service become unavailable, and when it does, can -we detect it? For example, database connectivity problems -may be detected early. We may also have planned outages -of all or parts of the system. Implement the -service_available callback.

-

What HTTP methods does the service implement? Do we need -more than the standard OPTIONS, HEAD, GET, PUT, POST, -PATCH and DELETE? Are we not using one of those at all? -Implement the known_methods callback.

-
-
-
+

Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. Implement the service_available callback.

+

What HTTP methods does the service implement? Do we need more than the standard OPTIONS, HEAD, GET, PUT, POST, PATCH and DELETE? Are we not using one of those at all? Implement the known_methods callback.

Type of resource handler

-
-

Am I writing a handler for a collection of resources, -or for a single resource?

-

The semantics for each of these are quite different. -You should not mix collection and single resource in -the same handler.

-
-
-
+

Am I writing a handler for a collection of resources, or for a single resource?

+

The semantics for each of these are quite different. You should not mix collection and single resource in the same handler.

Collection handler

-
-

Skip this section if you are not doing a collection.

-

Is the collection hardcoded or dynamic? For example, -if you use the route /users for the collection of -users then the collection is hardcoded; if you use -/forums/:category for the collection of threads -then it isn’t. When the collection is hardcoded you -can safely assume the resource always exists.

-

What methods should I implement?

-

OPTIONS is used to get some information about the -collection. It is recommended to allow it even if you -do not implement it, as Cowboy has a default -implementation built-in.

-

HEAD and GET are used to retrieve the collection. -If you allow GET, also allow HEAD as there’s no extra -work required to make it work.

-

POST is used to create a new resource inside the -collection. Creating a resource by using POST on -the collection is useful when resources may be -created before knowing their URI, usually because -parts of it are generated dynamically. A common -case is some kind of auto incremented integer -identifier.

-

The next methods are more rarely allowed.

-

PUT is used to create a new collection (when -the collection isn’t hardcoded), or replace -the entire collection.

-

DELETE is used to delete the entire collection.

-

PATCH is used to modify the collection using -instructions given in the request body. A PATCH -operation is atomic. The PATCH operation may -be used for such things as reordering; adding, -modifying or deleting parts of the collection.

-
-
-
+

Skip this section if you are not doing a collection.

+

Is the collection hardcoded or dynamic? For example, if you use the route /users for the collection of users then the collection is hardcoded; if you use /forums/:category for the collection of threads then it isn't. When the collection is hardcoded you can safely assume the resource always exists.

+

What methods should I implement?

+

OPTIONS is used to get some information about the collection. It is recommended to allow it even if you do not implement it, as Cowboy has a default implementation built-in.

+

HEAD and GET are used to retrieve the collection. If you allow GET, also allow HEAD as there's no extra work required to make it work.

+

POST is used to create a new resource inside the collection. Creating a resource by using POST on the collection is useful when resources may be created before knowing their URI, usually because parts of it are generated dynamically. A common case is some kind of auto incremented integer identifier.

+

The next methods are more rarely allowed.

+

PUT is used to create a new collection (when the collection isn't hardcoded), or replace the entire collection.

+

DELETE is used to delete the entire collection.

+

PATCH is used to modify the collection using instructions given in the request body. A PATCH operation is atomic. The PATCH operation may be used for such things as reordering; adding, modifying or deleting parts of the collection.

Single resource handler

-
-

Skip this section if you are doing a collection.

-

What methods should I implement?

-

OPTIONS is used to get some information about the -resource. It is recommended to allow it even if you -do not implement it, as Cowboy has a default -implementation built-in.

-

HEAD and GET are used to retrieve the resource. -If you allow GET, also allow HEAD as there’s no extra -work required to make it work.

-

POST is used to update the resource.

-

PUT is used to create a new resource (when it doesn’t -already exist) or replace the resource.

-

DELETE is used to delete the resource.

-

PATCH is used to modify the resource using -instructions given in the request body. A PATCH -operation is atomic. The PATCH operation may -be used for adding, removing or modifying specific -values in the resource.

-
-
-
+

Skip this section if you are doing a collection.

+

What methods should I implement?

+

OPTIONS is used to get some information about the resource. It is recommended to allow it even if you do not implement it, as Cowboy has a default implementation built-in.

+

HEAD and GET are used to retrieve the resource. If you allow GET, also allow HEAD as there's no extra work required to make it work.

+

POST is used to update the resource.

+

PUT is used to create a new resource (when it doesn't already exist) or replace the resource.

+

DELETE is used to delete the resource.

+

PATCH is used to modify the resource using instructions given in the request body. A PATCH operation is atomic. The PATCH operation may be used for adding, removing or modifying specific values in the resource.

The resource

-
-

Following the above discussion, implement the -allowed_methods callback.

-

Does the resource always exist? If it may not, implement -the resource_exists callback.

-

Do I need to authenticate the client before they can -access the resource? What authentication mechanisms -should I provide? This may include form-based, token-based -(in the URL or a cookie), HTTP basic, HTTP digest, -SSL certificate or any other form of authentication. -Implement the is_authorized callback.

-

Do I need fine-grained access control? How do I determine -that they are authorized access? Handle that in your -is_authorized callback.

-

Can access to a resource be forbidden regardless of access -being authorized? A simple example of that is censorship -of a resource. Implement the forbidden callback.

-

Are there any constraints on the length of the resource URI? -For example, the URI may be used as a key in storage and may -have a limit in length. Implement uri_too_long.

-
-
-
+

Following the above discussion, implement the allowed_methods callback.

+

Does the resource always exist? If it may not, implement the resource_exists callback.

+

Do I need to authenticate the client before they can access the resource? What authentication mechanisms should I provide? This may include form-based, token-based (in the URL or a cookie), HTTP basic, HTTP digest, SSL certificate or any other form of authentication. Implement the is_authorized callback.

+

Do I need fine-grained access control? How do I determine that they are authorized access? Handle that in your is_authorized callback.

+

Can access to a resource be forbidden regardless of access being authorized? A simple example of that is censorship of a resource. Implement the forbidden callback.

+

Are there any constraints on the length of the resource URI? For example, the URI may be used as a key in storage and may have a limit in length. Implement uri_too_long.

Representations

-
-

What media types do I provide? If text based, what charsets -are provided? What languages do I provide?

-

Implement the mandatory content_types_provided. Prefix -the callbacks with to_ for clarity. For example, to_html -or to_text.

-

Implement the languages_provided or charsets_provided -callbacks if applicable.

-

Is there any other header that may make the representation -of the resource vary? Implement the variances callback.

-

Depending on your choices for caching content, you may -want to implement one or more of the generate_etag, -last_modified and expires callbacks.

-

Do I want the user or user agent to actively choose a -representation available? Send a list of available -representations in the response body and implement -the multiple_choices callback.

-
-
-
+

What media types do I provide? If text based, what charsets are provided? What languages do I provide?

+

Implement the mandatory content_types_provided. Prefix the callbacks with to_ for clarity. For example, to_html or to_text.

+

Implement the languages_provided or charsets_provided callbacks if applicable.

+

Is there any other header that may make the representation of the resource vary? Implement the variances callback.

+

Depending on your choices for caching content, you may want to implement one or more of the generate_etag, last_modified and expires callbacks.

+

Do I want the user or user agent to actively choose a representation available? Send a list of available representations in the response body and implement the multiple_choices callback.

Redirections

-
-

Do I need to keep track of what resources were deleted? -For example, you may have a mechanism where moving a -resource leaves a redirect link to its new location. -Implement the previously_existed callback.

-

Was the resource moved, and is the move temporary? If -it is explicitly temporary, for example due to maintenance, -implement the moved_temporarily callback. Otherwise, -implement the moved_permanently callback.

-
-
-
+

Do I need to keep track of what resources were deleted? For example, you may have a mechanism where moving a resource leaves a redirect link to its new location. Implement the previously_existed callback.

+

Was the resource moved, and is the move temporary? If it is explicitly temporary, for example due to maintenance, implement the moved_temporarily callback. Otherwise, implement the moved_permanently callback.

The request

-
-

Do you need to read the query string? Individual headers? -Implement malformed_request and do all the parsing and -validation in this function. Note that the body should not -be read at this point.

-

May there be a request body? Will I know its size? -What’s the maximum size of the request body I’m willing -to accept? Implement valid_entity_length.

-

Finally, take a look at the sections corresponding to the -methods you are implementing.

-
-
-
+

Do you need to read the query string? Individual headers? Implement malformed_request and do all the parsing and validation in this function. Note that the body should not be read at this point.

+

May there be a request body? Will I know its size? What's the maximum size of the request body I'm willing to accept? Implement valid_entity_length.

+

Finally, take a look at the sections corresponding to the methods you are implementing.

OPTIONS method

-
-

Cowboy by default will send back a list of allowed methods. -Do I need to add more information to the response? Implement -the options method.

-
-
-
+

Cowboy by default will send back a list of allowed methods. Do I need to add more information to the response? Implement the options method.

GET and HEAD methods

-
-

If you implement the methods GET and/or HEAD, you must -implement one ProvideResource callback for each -content-type returned by the content_types_provided -callback.

-
-
-
-

PUT, POST and PATCH methods

-
-

If you implement the methods PUT, POST and/or PATCH, -you must implement the content_types_accepted callback, -and one AcceptCallback callback for each content-type -it returns. Prefix the AcceptCallback callback names -with from_ for clarity. For example, from_html or -from_json.

-

Do we want to allow the POST method to create individual -resources directly through their URI (like PUT)? Implement -the allow_missing_post callback. It is recommended to -explicitly use PUT in these cases instead.

-

May there be conflicts when using PUT to create or replace -a resource? Do we want to make sure that two updates around -the same time are not cancelling one another? Implement the -is_conflict callback.

-
-
-
+

If you implement the methods GET and/or HEAD, you must implement one ProvideResource callback for each content-type returned by the content_types_provided callback.

+

PUT, POST and PATCH methods

+

If you implement the methods PUT, POST and/or PATCH, you must implement the content_types_accepted callback, and one AcceptCallback callback for each content-type it returns. Prefix the AcceptCallback callback names with from_ for clarity. For example, from_html or from_json.

+

Do we want to allow the POST method to create individual resources directly through their URI (like PUT)? Implement the allow_missing_post callback. It is recommended to explicitly use PUT in these cases instead.

+

May there be conflicts when using PUT to create or replace a resource? Do we want to make sure that two updates around the same time are not cancelling one another? Implement the is_conflict callback.

DELETE methods

-
-

If you implement the method DELETE, you must implement -the delete_resource callback.

-

When delete_resource returns, is the resource completely -removed from the server, including from any caching service? -If not, and/or if the deletion is asynchronous and we have -no way of knowing it has been completed yet, implement the -delete_completed callback.

-
-
+

If you implement the method DELETE, you must implement the delete_resource callback.

+

When delete_resource returns, is the resource completely removed from the server, including from any caching service? If not, and/or if the deletion is asynchronous and we have no way of knowing it has been completed yet, implement the delete_completed callback.

+ diff --git a/docs/en/cowboy/2.1/guide/resp/index.html b/docs/en/cowboy/2.1/guide/resp/index.html index 129e304b..e884cd91 100644 --- a/docs/en/cowboy/2.1/guide/resp/index.html +++ b/docs/en/cowboy/2.1/guide/resp/index.html @@ -62,346 +62,231 @@

Sending a response

-

The response must be sent using the Req object.

-

Cowboy provides two different ways of sending responses: -either directly or by streaming the body. Response headers -and body may be set in advance. The response is sent as -soon as one of the reply or stream reply function is -called.

-

Cowboy also provides a simplified interface for sending -files. It can also send only specific parts of a file.

-

While only one response is allowed for every request, -HTTP/2 introduced a mechanism that allows the server -to push additional resources related to the response. -This chapter also describes how this feature works in -Cowboy.

-
+

The response must be sent using the Req object.

+

Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called.

+

Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file.

+

While only one response is allowed for every request, HTTP/2 introduced a mechanism that allows the server to push additional resources related to the response. This chapter also describes how this feature works in Cowboy.

Reply

-
-

Cowboy provides three functions for sending the entire reply, -depending on whether you need to set headers and body. In all -cases, Cowboy will add any headers required by the protocol -(for example the date header will always be sent).

-

When you need to set only the status code, -use cowboy_req:reply/2:

-
-
-
Req = cowboy_req:reply(200, Req0).
-

When you need to set response headers at the same time, -use cowboy_req:reply/3:

-
-
-
Req = cowboy_req:reply(303, #{
-    <<"location">> => <<"https://ninenines.eu">>
-}, Req0).
-

Note that the header name must always be a lowercase -binary.

-

When you also need to set the response body, -use cowboy_req:reply/4:

-
-
-
Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, "Hello world!", Req0).
-

You should always set the content-type header when the -response has a body. There is however no need to set -the content-length header; Cowboy does it automatically.

-

The response body and the header values must be either -a binary or an iolist. An iolist is a list containing -binaries, characters, strings or other iolists. This -allows you to build a response from different parts -without having to do any concatenation:

-
-
-
Title = "Hello world!",
-Body = <<"Hats off!">>,
-Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/html">>
-}, ["<html><head><title>", Title, "</title></head>",
-    "<body><p>", Body, "</p></body></html>"], Req0).
-

This method of building responses is more efficient than -concatenating. Behind the scenes, each element of the list -is simply a pointer, and those pointers are used directly -when writing to the socket.

-
-
-
+
Title = "Hello world!",
+Body = <<"Hats off!">>,
+Req = cowboy_req:reply(200, #{
+    <<"content-type">> => <<"text/html">>
+}, ["<html><head><title>", Title, "</title></head>",
+    "<body><p>", Body, "</p></body></html>"], Req0).
+
+

This method of building responses is more efficient than concatenating. Behind the scenes, each element of the list is simply a pointer, and those pointers are used directly when writing to the socket.

Stream reply

-
-

Cowboy provides two functions for initiating a response, -and an additional function for streaming the response body. -Cowboy will add any required headers to the response.

-

When you need to set only the status code, -use cowboy_req:stream_reply/2:

-
-
+

When you need to set only the status code, use cowboy_req:stream_reply/2:

+
-
Req = cowboy_req:stream_reply(200, Req0),
-
-cowboy_req:stream_body("Hello...", nofin, Req),
-cowboy_req:stream_body("chunked...", nofin, Req),
-cowboy_req:stream_body("world!!", fin, Req).
-

The second argument to cowboy_req:stream_body/3 indicates -whether this data terminates the body. Use fin for the -final flag, and nofin otherwise.

-

This snippet does not set a content-type header. This is -not recommended. All responses with a body should have -a content-type. The header can be set beforehand, or -using the cowboy_req:stream_reply/3:

-
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/html">>
-}, Req0),
-
-cowboy_req:stream_body("<html><head>Hello world!</head>", nofin, Req),
-cowboy_req:stream_body("<body><p>Hats off!</p></body></html>", fin, Req).
-

HTTP provides a few different ways to stream response bodies. -Cowboy will select the most appropriate one based on the HTTP -version and the request and response headers.

-

While not required by any means, it is recommended that you -set the content-length header in the response if you know it -in advance. This will ensure that the best response method -is selected and help clients understand when the response -is fully received.

-
-
-
+
Req = cowboy_req:stream_reply(200, #{
+    <<"content-type">> => <<"text/html">>
+}, Req0),
+
+cowboy_req:stream_body("<html><head>Hello world!</head>", nofin, Req),
+cowboy_req:stream_body("<body><p>Hats off!</p></body></html>", fin, Req).
+
+

HTTP provides a few different ways to stream response bodies. Cowboy will select the most appropriate one based on the HTTP version and the request and response headers.

+

While not required by any means, it is recommended that you set the content-length header in the response if you know it in advance. This will ensure that the best response method is selected and help clients understand when the response is fully received.

+

Preset response headers

-
-

Cowboy provides functions to set response headers without -immediately sending them. They are stored in the Req object -and sent as part of the response when a reply function is -called.

-

To set response headers:

-
-
-
Req = cowboy_req:set_resp_header(<<"allow">>, "GET", Req0).
-

Header names must be a lowercase binary.

-

Do not use this function for setting cookies. Refer to -the Cookies chapter for more information.

-

To check if a response header has already been set:

-
-
-
cowboy_req:has_resp_header(<<"allow">>, Req).
-

It returns true if the header was set, false otherwise.

-

To delete a response header that was set previously:

-
-
-
Req = cowboy_req:delete_resp_header(<<"allow">>, Req0).
-
- -
+
Req = cowboy_req:delete_resp_header(<<"allow">>, Req0).
+

Overriding headers

-
-

As Cowboy provides different ways of setting response -headers and body, clashes may occur, so it’s important -to understand what happens when a header is set twice.

-

Headers come from five different origins:

-
    -
  • -

    -Protocol-specific headers (for example HTTP/1.1’s connection header) -

    +

    As Cowboy provides different ways of setting response headers and body, clashes may occur, so it's important to understand what happens when a header is set twice.

    +

    Headers come from five different origins:

    +
    • Protocol-specific headers (for example HTTP/1.1's connection header)
    • -
    • -

      -Other required headers (for example the date header) -

      +
    • Other required headers (for example the date header)
    • -
    • -

      -Preset headers -

      +
    • Preset headers
    • -
    • -

      -Headers given to the reply function -

      +
    • Headers given to the reply function
    • -
    • -

      -Set-cookie headers -

      +
    • Set-cookie headers
    • -
-

Cowboy does not allow overriding protocol-specific headers.

-

Set-cookie headers will always be appended at the end of -the list of headers before sending the response.

-

Headers given to the reply function will always override -preset headers and required headers. If a header is found -in two or three of these, then the one in the reply function -is picked and the others are dropped.

-

Similarly, preset headers will always override required -headers.

-

To illustrate, look at the following snippet. Cowboy by -default sends the server header with the value "Cowboy". -We can override it:

-
-
-
Req = cowboy_req:reply(200, #{
-    <<"server">> => <<"yaws">>
-}, Req0).
-
- -
+
Req = cowboy_req:reply(200, #{
+    <<"server">> => <<"yaws">>
+}, Req0).
+

Preset response body

-
-

Cowboy provides functions to set the response body without -immediately sending it. It is stored in the Req object and -sent when the reply function is called.

-

To set the response body:

-
-
-
Req = cowboy_req:set_resp_body("Hello world!", Req0).
-

To check if a response body has already been set:

-
-
+ +

To check if a response body has already been set:

+
-
cowboy_req:has_resp_body(Req).
-

It returns true if the body was set and is non-empty, -false otherwise.

-

The preset response body is only sent if the reply function -used is cowboy_req:reply/2 or cowboy_req:reply/3.

-
-
-
+
cowboy_req:has_resp_body(Req).
+
+

It returns true if the body was set and is non-empty, false otherwise.

+ + + +

The preset response body is only sent if the reply function used is cowboy_req:reply/2 or cowboy_req:reply/3.

Sending files

-
-

Cowboy provides a shortcut for sending files. When -using cowboy_req:reply/4, or when presetting the -response header, you can give a sendfile tuple to -Cowboy:

-
-
-
{sendfile, Offset, Length, Filename}
-

Depending on the values for Offset or Length, the -entire file may be sent, or just a part of it.

-

The length is required even for sending the entire file. -Cowboy sends it in the content-length header.

-

To send a file while replying:

-
-
-
Req = cowboy_req:reply(200, #{
-    <<"content-type">> => "image/png"
-}, {sendfile, 0, 12345, "path/to/logo.png"}, Req0).
-
- -
+
Req = cowboy_req:reply(200, #{
+    <<"content-type">> => "image/png"
+}, {sendfile, 0, 12345, "path/to/logo.png"}, Req0).
+
+ + + + + + + + +

Informational responses

-
-

Cowboy allows you to send informational responses.

-

Informational responses are responses that have a status -code between 100 and 199. Any number can be sent before -the proper response. Sending an informational response -does not change the behavior of the proper response, and -clients are expected to ignore any informational response -they do not understand.

-

The following snippet sends a 103 informational response -with some headers that are expected to be in the final -response.

-
-
-
Req = cowboy_req:inform(103, #{
-    <<"link">> => <<"</style.css>; rel=preload; as=style">>,
-    <<"link">> => <<"</script.js>; rel=preload; as=script">>
-}, Req0).
-
- -
+
Req = cowboy_req:inform(103, #{
+    <<"link">> => <<"</style.css>; rel=preload; as=style">>,
+    <<"link">> => <<"</script.js>; rel=preload; as=script">>
+}, Req0).
+

Push

-
-

The HTTP/2 protocol introduced the ability to push resources -related to the one sent in the response. Cowboy provides two -functions for that purpose: cowboy_req:push/3,4.

-

Push is only available for HTTP/2. Cowboy will automatically -ignore push requests if the protocol doesn’t support it.

-

The push function must be called before any of the reply -functions. Doing otherwise will result in a crash.

-

To push a resource, you need to provide the same information -as a client performing a request would. This includes the -HTTP method, the URI and any necessary request headers.

-

Cowboy by default only requires you to give the path to -the resource and the request headers. The rest of the URI -is taken from the current request (excluding the query -string, set to empty) and the method is GET by default.

-

The following snippet pushes a CSS file that is linked to -in the response:

-
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, Req0),
-Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/html">>
-}, ["<html><head><title>My web page</title>",
-    "<link rel='stylesheet' type='text/css' href='/static/style.css'>",
-    "<body><p>Welcome to Erlang!</p></body></html>"], Req0).
-

To override the method, scheme, host, port or query string, -simply pass in a fourth argument. The following snippet -uses a different host name:

-
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, #{host => <<"cdn.example.org">>}, Req),
-

Pushed resources don’t have to be files. As long as the push -request is cacheable, safe and does not include a body, the -resource can be pushed.

-

Under the hood, Cowboy handles pushed requests the same as -normal requests: a different process is created which will -ultimately send a response to the client.

-
- +
cowboy_req:push("/static/style.css", #{
+    <<"accept">> => <<"text/css">>
+}, #{host => <<"cdn.example.org">>}, Req),
+ +

Pushed resources don't have to be files. As long as the push request is cacheable, safe and does not include a body, the resource can be pushed.

+

Under the hood, Cowboy handles pushed requests the same as normal requests: a different process is created which will ultimately send a response to the client.

+ diff --git a/docs/en/cowboy/2.1/guide/rest_flowcharts/index.html b/docs/en/cowboy/2.1/guide/rest_flowcharts/index.html index 87d33daa..7eb1edfb 100644 --- a/docs/en/cowboy/2.1/guide/rest_flowcharts/index.html +++ b/docs/en/cowboy/2.1/guide/rest_flowcharts/index.html @@ -62,244 +62,64 @@

REST flowcharts

-

This chapter will explain the REST handler state machine through -a number of different diagrams.

-

There are four main paths that requests may follow. One for the -method OPTIONS; one for the methods GET and HEAD; one for the -methods PUT, POST and PATCH; and one for the method DELETE.

-

All paths start with the "Start" diagram, and all paths excluding -the OPTIONS path go through the "Content negotiation" diagram -and optionally the "Conditional requests" diagram if the resource -exists.

-

The red squares refer to another diagram. The light green squares -indicate a response. Other squares may be either a callback or a -question answered by Cowboy itself. Green arrows tend to indicate -the default behavior if the callback is undefined.

-
+

This chapter will explain the REST handler state machine through a number of different diagrams.

+

There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE.

+

All paths start with the "Start" diagram, and all paths excluding the OPTIONS path go through the "Content negotiation" diagram and optionally the "Conditional requests" diagram if the resource exists.

+

The red squares refer to another diagram. The light green squares indicate a response. Other squares may be either a callback or a question answered by Cowboy itself. Green arrows tend to indicate the default behavior if the callback is undefined.

Start

-
-

All requests start from here.

-
-
-REST starting flowchart -
-
-

A series of callbacks are called in succession to perform -a general checkup of the service, the request line and -request headers.

-

The request body, if any, is not expected to have been -received for any of these steps. It is only processed -at the end of the "PUT, POST and PATCH methods" diagram, -when all conditions have been met.

-

The known_methods and allowed_methods callbacks -return a list of methods. Cowboy then checks if the request -method is in the list, and stops otherwise.

-

The is_authorized callback may be used to check that -access to the resource is authorized. Authentication -may also be performed as needed. When authorization is -denied, the return value from the callback must include -a challenge applicable to the requested resource, which -will be sent back to the client in the www-authenticate -header.

-

This diagram is immediately followed by either the -"OPTIONS method" diagram when the request method is -OPTIONS, or the "Content negotiation" diagram otherwise.

-
-
-
+

All requests start from here.

+REST starting flowchart

A series of callbacks are called in succession to perform a general checkup of the service, the request line and request headers.

+

The request body, if any, is not expected to have been received for any of these steps. It is only processed at the end of the "PUT, POST and PATCH methods" diagram, when all conditions have been met.

+

The known_methods and allowed_methods callbacks return a list of methods. Cowboy then checks if the request method is in the list, and stops otherwise.

+

The is_authorized callback may be used to check that access to the resource is authorized. Authentication may also be performed as needed. When authorization is denied, the return value from the callback must include a challenge applicable to the requested resource, which will be sent back to the client in the www-authenticate header.

+

This diagram is immediately followed by either the "OPTIONS method" diagram when the request method is OPTIONS, or the "Content negotiation" diagram otherwise.

OPTIONS method

-
-

This diagram only applies to OPTIONS requests.

-
-
-REST OPTIONS method flowchart -
-
-

The options callback may be used to add information -about the resource, such as media types or languages -provided; allowed methods; any extra information. A -response body may also be set, although clients should -not be expected to read it.

-

If the options callback is not defined, Cowboy will -send a response containing the list of allowed methods -by default.

-
-
-
+

This diagram only applies to OPTIONS requests.

+REST OPTIONS method flowchart

The options callback may be used to add information about the resource, such as media types or languages provided; allowed methods; any extra information. A response body may also be set, although clients should not be expected to read it.

+

If the options callback is not defined, Cowboy will send a response containing the list of allowed methods by default.

Content negotiation

-
-

This diagram applies to all request methods other than -OPTIONS. It is executed right after the "Start" diagram -is completed.

-
-
-REST content negotiation flowchart -
-
-

The purpose of these steps is to determine an appropriate -representation to be sent back to the client.

-

The request may contain any of the accept header; the -accept-language header; or the accept-charset header. -When present, Cowboy will parse the headers and then -call the corresponding callback to obtain the list -of provided content-type, language or charset for this -resource. It then automatically select the best match -based on the request.

-

If a callback is not defined, Cowboy will select the -content-type, language or charset that the client -prefers.

-

The content_types_provided also returns the name of -a callback for every content-type it accepts. This -callback will only be called at the end of the -"GET and HEAD methods" diagram, when all conditions -have been met.

-

The selected content-type, language and charset are -saved as meta values in the Req object. You should -use the appropriate representation if you set a -response body manually (alongside an error code, -for example).

-

This diagram is immediately followed by -the "GET and HEAD methods" diagram, -the "PUT, POST and PATCH methods" diagram, -or the "DELETE method" diagram, depending on the -method.

-
-
-
+

This diagram applies to all request methods other than OPTIONS. It is executed right after the "Start" diagram is completed.

+REST content negotiation flowchart

The purpose of these steps is to determine an appropriate representation to be sent back to the client.

+

The request may contain any of the accept header; the accept-language header; or the accept-charset header. When present, Cowboy will parse the headers and then call the corresponding callback to obtain the list of provided content-type, language or charset for this resource. It then automatically select the best match based on the request.

+

If a callback is not defined, Cowboy will select the content-type, language or charset that the client prefers.

+

The content_types_provided also returns the name of a callback for every content-type it accepts. This callback will only be called at the end of the "GET and HEAD methods" diagram, when all conditions have been met.

+

The selected content-type, language and charset are saved as meta values in the Req object. You should use the appropriate representation if you set a response body manually (alongside an error code, for example).

+

This diagram is immediately followed by the "GET and HEAD methods" diagram, the "PUT, POST and PATCH methods" diagram, or the "DELETE method" diagram, depending on the method.

GET and HEAD methods

-
-

This diagram only applies to GET and HEAD requests.

-

For a description of the cond step, please see -the "Conditional requests" diagram.

-
-
-REST GET/HEAD methods flowchart -
-
-

When the resource exists, and the conditional steps -succeed, the resource can be retrieved.

-

Cowboy prepares the response by first retrieving -metadata about the representation, then by calling -the ProvideResource callback. This is the callback -you defined for each content-types you returned from -content_types_provided. This callback returns the body -that will be sent back to the client, or a fun if the -body must be streamed.

-

When the resource does not exist, Cowboy will figure out -whether the resource existed previously, and if so whether -it was moved elsewhere in order to redirect the client to -the new URI.

-

The moved_permanently and moved_temporarily callbacks -must return the new location of the resource if it was in -fact moved.

-
-
-
-

PUT, POST and PATCH methods

-
-

This diagram only applies to PUT, POST and PATCH requests.

-

For a description of the cond step, please see -the "Conditional requests" diagram.

-
-
-REST PUT/POST/PATCH methods flowchart -
-
-

When the resource exists, first the conditional steps -are executed. When that succeeds, and the method is PUT, -Cowboy will call the is_conflict callback. This function -can be used to prevent potential race conditions, by locking -the resource for example.

-

Then all three methods reach the content_types_accepted -step that we will describe in a few paragraphs.

-

When the resource does not exist, and the method is PUT, -Cowboy will check for conflicts and then move on to the -content_types_accepted step. For other methods, Cowboy -will figure out whether the resource existed previously, -and if so whether it was moved elsewhere. If the resource -is truly non-existent, the method is POST and the call -for allow_missing_post returns true, then Cowboy will -move on to the content_types_accepted step. Otherwise -the request processing ends there.

-

The moved_permanently and moved_temporarily callbacks -must return the new location of the resource if it was in -fact moved.

-

The content_types_accepted returns a list of -content-types it accepts, but also the name of a callback -for each of them. Cowboy will select the appropriate -callback for processing the request body and call it.

-

This callback may return one of three different return -values.

-

If an error occurred while processing the request body, -it must return false and Cowboy will send an -appropriate error response.

-

If the method is POST, then you may return true with -an URI of where the resource has been created. This is -especially useful for writing handlers for collections.

-

Otherwise, return true to indicate success. Cowboy -will select the appropriate response to be sent depending -on whether a resource has been created, rather than -modified, and on the availability of a location header -or a body in the response.

-
-
-
+

This diagram only applies to GET and HEAD requests.

+

For a description of the cond step, please see the "Conditional requests" diagram.

+REST GET/HEAD methods flowchart

When the resource exists, and the conditional steps succeed, the resource can be retrieved.

+

Cowboy prepares the response by first retrieving metadata about the representation, then by calling the ProvideResource callback. This is the callback you defined for each content-types you returned from content_types_provided. This callback returns the body that will be sent back to the client, or a fun if the body must be streamed.

+

When the resource does not exist, Cowboy will figure out whether the resource existed previously, and if so whether it was moved elsewhere in order to redirect the client to the new URI.

+

The moved_permanently and moved_temporarily callbacks must return the new location of the resource if it was in fact moved.

+

PUT, POST and PATCH methods

+

This diagram only applies to PUT, POST and PATCH requests.

+

For a description of the cond step, please see the "Conditional requests" diagram.

+REST PUT/POST/PATCH methods flowchart

When the resource exists, first the conditional steps are executed. When that succeeds, and the method is PUT, Cowboy will call the is_conflict callback. This function can be used to prevent potential race conditions, by locking the resource for example.

+

Then all three methods reach the content_types_accepted step that we will describe in a few paragraphs.

+

When the resource does not exist, and the method is PUT, Cowboy will check for conflicts and then move on to the content_types_accepted step. For other methods, Cowboy will figure out whether the resource existed previously, and if so whether it was moved elsewhere. If the resource is truly non-existent, the method is POST and the call for allow_missing_post returns true, then Cowboy will move on to the content_types_accepted step. Otherwise the request processing ends there.

+

The moved_permanently and moved_temporarily callbacks must return the new location of the resource if it was in fact moved.

+

The content_types_accepted returns a list of content-types it accepts, but also the name of a callback for each of them. Cowboy will select the appropriate callback for processing the request body and call it.

+

This callback may return one of three different return values.

+

If an error occurred while processing the request body, it must return false and Cowboy will send an appropriate error response.

+

If the method is POST, then you may return true with an URI of where the resource has been created. This is especially useful for writing handlers for collections.

+

Otherwise, return true to indicate success. Cowboy will select the appropriate response to be sent depending on whether a resource has been created, rather than modified, and on the availability of a location header or a body in the response.

DELETE method

-
-

This diagram only applies to DELETE requests.

-

For a description of the cond step, please see -the "Conditional requests" diagram.

-
-
-REST DELETE method flowchart -
-
-

When the resource exists, and the conditional steps -succeed, the resource can be deleted.

-

Deleting the resource is a two steps process. First -the callback delete_resource is executed. Use this -callback to delete the resource.

-

Because the resource may be cached, you must also -delete all cached representations of this resource -in the system. This operation may take a while though, -so you may return before it finished.

-

Cowboy will then call the delete_completed callback. -If you know that the resource has been completely -deleted from your system, including from caches, then -you can return true. If any doubts persist, return -false. Cowboy will assume true by default.

-

To finish, Cowboy checks if you set a response body, -and depending on that, sends the appropriate response.

-

When the resource does not exist, Cowboy will figure out -whether the resource existed previously, and if so whether -it was moved elsewhere in order to redirect the client to -the new URI.

-

The moved_permanently and moved_temporarily callbacks -must return the new location of the resource if it was in -fact moved.

-
-
-
+

This diagram only applies to DELETE requests.

+

For a description of the cond step, please see the "Conditional requests" diagram.

+REST DELETE method flowchart

When the resource exists, and the conditional steps succeed, the resource can be deleted.

+

Deleting the resource is a two steps process. First the callback delete_resource is executed. Use this callback to delete the resource.

+

Because the resource may be cached, you must also delete all cached representations of this resource in the system. This operation may take a while though, so you may return before it finished.

+

Cowboy will then call the delete_completed callback. If you know that the resource has been completely deleted from your system, including from caches, then you can return true. If any doubts persist, return false. Cowboy will assume true by default.

+

To finish, Cowboy checks if you set a response body, and depending on that, sends the appropriate response.

+

When the resource does not exist, Cowboy will figure out whether the resource existed previously, and if so whether it was moved elsewhere in order to redirect the client to the new URI.

+

The moved_permanently and moved_temporarily callbacks must return the new location of the resource if it was in fact moved.

Conditional requests

-
-

This diagram applies to all request methods other than -OPTIONS. It is executed right after the resource_exists -callback, when the resource exists.

-
-
-REST conditional requests flowchart -
-
-

A request becomes conditional when it includes either of -the if-match header; the if-unmodified-since header; the -if-none-match header; or the if-modified-since header.

-

If the condition fails, the request ends immediately -without any retrieval or modification of the resource.

-

The generate_etag and last_modified are called as -needed. Cowboy will only call them once and then cache -the results for subsequent use.

-
-
+

This diagram applies to all request methods other than OPTIONS. It is executed right after the resource_exists callback, when the resource exists.

+REST conditional requests flowchart

A request becomes conditional when it includes either of the if-match header; the if-unmodified-since header; the if-none-match header; or the if-modified-since header.

+

If the condition fails, the request ends immediately without any retrieval or modification of the resource.

+

The generate_etag and last_modified are called as needed. Cowboy will only call them once and then cache the results for subsequent use.

+ diff --git a/docs/en/cowboy/2.1/guide/rest_handlers/index.html b/docs/en/cowboy/2.1/guide/rest_handlers/index.html index 9ec77e6b..76c32a51 100644 --- a/docs/en/cowboy/2.1/guide/rest_handlers/index.html +++ b/docs/en/cowboy/2.1/guide/rest_handlers/index.html @@ -62,287 +62,162 @@

REST handlers

-

REST is implemented in Cowboy as a sub protocol. The request -is handled as a state machine with many optional callbacks -describing the resource and modifying the machine’s behavior.

-

The REST handler is the recommended way to handle HTTP requests.

-
+

REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine's behavior.

+

The REST handler is the recommended way to handle HTTP requests.

Initialization

-
-

First, the init/2 callback is called. This callback is common -to all handlers. To use REST for the current request, this function -must return a cowboy_rest tuple.

-
-
-
init(Req, State) ->
-    {cowboy_rest, Req, State}.
-

Cowboy will then switch to the REST protocol and start executing -the state machine.

-

After reaching the end of the flowchart, the terminate/3 callback -will be called if it is defined.

-
-
-
+
init(Req, State) ->
+    {cowboy_rest, Req, State}.
+
+

Cowboy will then switch to the REST protocol and start executing the state machine.

+

After reaching the end of the flowchart, the terminate/3 callback will be called if it is defined.

Methods

-
-

The REST component has code for handling the following HTTP methods: -HEAD, GET, POST, PATCH, PUT, DELETE and OPTIONS.

-

Other methods can be accepted, however they have no specific callback -defined for them at this time.

-
- -
+

The REST component has code for handling the following HTTP methods: HEAD, GET, POST, PATCH, PUT, DELETE and OPTIONS.

+

Other methods can be accepted, however they have no specific callback defined for them at this time.

Callbacks

-
-

All callbacks are optional. Some may become mandatory depending -on what other defined callbacks return. The various flowcharts -in the next chapter should be a useful to determine which callbacks -you need.

-

All callbacks take two arguments, the Req object and the State, -and return a three-element tuple of the form {Value, Req, State}.

-

Nearly all callbacks can also return {stop, Req, State} to -stop execution of the request, and -{{switch_handler, Module}, Req, State} or -{{switch_handler, Module, Opts}, Req, State} to switch to -a different handler type. The exceptions are expires -generate_etag, last_modified and variances.

-

The following table summarizes the callbacks and their default values. -If the callback isn’t defined, then the default value will be used. -Please look at the flowcharts to find out the result of each return -value.

-

In the following table, "skip" means the callback is entirely skipped -if it is undefined, moving directly to the next step. Similarly, -"none" means there is no default value for this callback.

-
- --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +

All callbacks are optional. Some may become mandatory depending on what other defined callbacks return. The various flowcharts in the next chapter should be a useful to determine which callbacks you need.

+

All callbacks take two arguments, the Req object and the State, and return a three-element tuple of the form {Value, Req, State}.

+

Nearly all callbacks can also return {stop, Req, State} to stop execution of the request, and {{switch_handler, Module}, Req, State} or {{switch_handler, Module, Opts}, Req, State} to switch to a different handler type. The exceptions are expires generate_etag, last_modified and variances.

+

The following table summarizes the callbacks and their default values. If the callback isn't defined, then the default value will be used. Please look at the flowcharts to find out the result of each return value.

+

In the following table, "skip" means the callback is entirely skipped if it is undefined, moving directly to the next step. Similarly, "none" means there is no default value for this callback.

+
Callback name Default value

allowed_methods

[<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]

allow_missing_post

true

charsets_provided

skip

content_types_accepted

none

content_types_provided

[{{ <<"text">>, <<"html">>, '*'}, to_html}]

delete_completed

true

delete_resource

false

expires

undefined

forbidden

false

generate_etag

undefined

is_authorized

true

is_conflict

false

known_methods

[<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]

languages_provided

skip

last_modified

undefined

malformed_request

false

moved_permanently

false

moved_temporarily

false

multiple_choices

false

options

ok

previously_existed

false

resource_exists

true

service_available

true

uri_too_long

false

+ + + + - - - + + - - - + + - - - + + - -
Callback nameDefault value
allowed_methods[<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]

valid_content_headers

true

allow_missing_posttrue

valid_entity_length

true

charsets_providedskip

variances

[]

content_types_acceptednone
-
-

As you can see, Cowboy tries to move on with the request whenever -possible by using well thought out default values.

-

In addition to these, there can be any number of user-defined -callbacks that are specified through content_types_accepted/2 -and content_types_provided/2. They can take any name, however -it is recommended to use a separate prefix for the callbacks of -each function. For example, from_html and to_html indicate -in the first case that we’re accepting a resource given as HTML, -and in the second case that we send one as HTML.

-
-
-
+content_types_provided +[{{ <<"text">>, <<"html">>, '*'}, to_html}] + +delete_completed +true + +delete_resource +false + +expires +undefined + +forbidden +false + +generate_etag +undefined + +is_authorized +true + +is_conflict +false + +known_methods +[<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>] + +languages_provided +skip + +last_modified +undefined + +malformed_request +false + +moved_permanently +false + +moved_temporarily +false + +multiple_choices +false + +options +ok + +previously_existed +false + +resource_exists +true + +service_available +true + +uri_too_long +false + +valid_content_headers +true + +valid_entity_length +true + +variances +[] + + +

As you can see, Cowboy tries to move on with the request whenever possible by using well thought out default values.

+

In addition to these, there can be any number of user-defined callbacks that are specified through content_types_accepted/2 and content_types_provided/2. They can take any name, however it is recommended to use a separate prefix for the callbacks of each function. For example, from_html and to_html indicate in the first case that we're accepting a resource given as HTML, and in the second case that we send one as HTML.

Meta data

-
-

Cowboy will set informative values to the Req object at various -points of the execution. You can retrieve them by matching the -Req object directly. The values are defined in the following table:

-
- --- - - - - - - - - - - - - - - - - - - - -
Key Details

media_type

The content-type negotiated for the response entity.

language

The language negotiated for the response entity.

charset

The charset negotiated for the response entity.

-
-

They can be used to send a proper body with the response to a -request that used a method other than HEAD or GET.

-
-
-
+

Cowboy will set informative values to the Req object at various points of the execution. You can retrieve them by matching the Req object directly. The values are defined in the following table:

+ + + + + + + + + + + + +
KeyDetails
media_typeThe content-type negotiated for the response entity.
languageThe language negotiated for the response entity.
charsetThe charset negotiated for the response entity.
+

They can be used to send a proper body with the response to a request that used a method other than HEAD or GET.

Response headers

-
-

Cowboy will set response headers automatically over the execution -of the REST code. They are listed in the following table.

-
- --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Header name Details

content-language

Language used in the response body

content-type

Media type and charset of the response body

etag

Etag of the resource

expires

Expiration date of the resource

last-modified

Last modification date for the resource

location

Relative or absolute URI to the requested resource

vary

List of headers that may change the representation of the resource

-
-
-
+

Cowboy will set response headers automatically over the execution of the REST code. They are listed in the following table.

+ + + + + + + + + + + + + + + + + + + + + + + + +
Header nameDetails
content-languageLanguage used in the response body
content-typeMedia type and charset of the response body
etagEtag of the resource
expiresExpiration date of the resource
last-modifiedLast modification date for the resource
locationRelative or absolute URI to the requested resource
varyList of headers that may change the representation of the resource
+ diff --git a/docs/en/cowboy/2.1/guide/rest_principles/index.html b/docs/en/cowboy/2.1/guide/rest_principles/index.html index dddcb229..2df06a2c 100644 --- a/docs/en/cowboy/2.1/guide/rest_principles/index.html +++ b/docs/en/cowboy/2.1/guide/rest_principles/index.html @@ -62,153 +62,38 @@

REST principles

-

This chapter will attempt to define the concepts behind REST -and explain what makes a service RESTful.

-

REST is often confused with performing a distinct operation -depending on the HTTP method, while using more than the GET -and POST methods. That’s highly misguided at best.

-

We will first attempt to define REST and will look at what -it means in the context of HTTP and the Web. -For a more in-depth explanation of REST, you can read -Roy T. Fielding’s dissertation -as it does a great job explaining where it comes from and -what it achieves.

-
+

This chapter will attempt to define the concepts behind REST and explain what makes a service RESTful.

+

REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That's highly misguided at best.

+

We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. Fielding's dissertation as it does a great job explaining where it comes from and what it achieves.

REST architecture

-
-

REST is a client-server architecture. The client and the server -both have a different set of concerns. The server stores and/or -manipulates information and makes it available to the user in -an efficient manner. The client takes that information and -displays it to the user and/or uses it to perform subsequent -requests for information. This separation of concerns allows both -the client and the server to evolve independently as it only -requires that the interface stays the same.

-

REST is stateless. That means the communication between the -client and the server always contains all the information needed -to perform the request. There is no session state in the server, -it is kept entirely on the client’s side. If access to a resource -requires authentication, then the client needs to authenticate -itself with every request.

-

REST is cacheable. The client, the server and any intermediary -components can all cache resources in order to improve performance.

-

REST provides a uniform interface between components. This -simplifies the architecture, as all components follow the same -rules to speak to one another. It also makes it easier to understand -the interactions between the different components of the system. -A number of constraints are required to achieve this. They are -covered in the rest of the chapter.

-

REST is a layered system. Individual components cannot see -beyond the immediate layer with which they are interacting. This -means that a client connecting to an intermediate component, like -a proxy, has no knowledge of what lies beyond. This allows -components to be independent and thus easily replaceable or -extendable.

-

REST optionally provides code on demand. Code may be downloaded -to extend client functionality. This is optional however because -the client may not be able to download or run this code, and so -a REST component cannot rely on it being executed.

-
-
-
+

REST is a client-server architecture. The client and the server both have a different set of concerns. The server stores and/or manipulates information and makes it available to the user in an efficient manner. The client takes that information and displays it to the user and/or uses it to perform subsequent requests for information. This separation of concerns allows both the client and the server to evolve independently as it only requires that the interface stays the same.

+

REST is stateless. That means the communication between the client and the server always contains all the information needed to perform the request. There is no session state in the server, it is kept entirely on the client's side. If access to a resource requires authentication, then the client needs to authenticate itself with every request.

+

REST is cacheable. The client, the server and any intermediary components can all cache resources in order to improve performance.

+

REST provides a uniform interface between components. This simplifies the architecture, as all components follow the same rules to speak to one another. It also makes it easier to understand the interactions between the different components of the system. A number of constraints are required to achieve this. They are covered in the rest of the chapter.

+

REST is a layered system. Individual components cannot see beyond the immediate layer with which they are interacting. This means that a client connecting to an intermediate component, like a proxy, has no knowledge of what lies beyond. This allows components to be independent and thus easily replaceable or extendable.

+

REST optionally provides code on demand. Code may be downloaded to extend client functionality. This is optional however because the client may not be able to download or run this code, and so a REST component cannot rely on it being executed.

Resources and resource identifiers

-
-

A resource is an abstract concept. In a REST system, any information -that can be named may be a resource. This includes documents, images, -a collection of resources and any other information. Any information -that can be the target of an hypertext link can be a resource.

-

A resource is a conceptual mapping to a set of entities. The set of -entities evolves over time; a resource doesn’t. For example, a resource -can map to "users who have logged in this past month" and another -to "all users". At some point in time they may map to the same set of -entities, because all users logged in this past month. But they are -still different resources. Similarly, if nobody logged in recently, -then the first resource may map to the empty set. This resource exists -regardless of the information it maps to.

-

Resources are identified by uniform resource identifiers, also known -as URIs. Sometimes internationalized resource identifiers, or IRIs, -may also be used, but these can be directly translated into a URI.

-

In practice we will identify two kinds of resources. Individual -resources map to a set of one element, for example "user Joe". -Collection of resources map to a set of 0 to N elements, -for example "all users".

-
-
-
+

A resource is an abstract concept. In a REST system, any information that can be named may be a resource. This includes documents, images, a collection of resources and any other information. Any information that can be the target of an hypertext link can be a resource.

+

A resource is a conceptual mapping to a set of entities. The set of entities evolves over time; a resource doesn't. For example, a resource can map to "users who have logged in this past month" and another to "all users". At some point in time they may map to the same set of entities, because all users logged in this past month. But they are still different resources. Similarly, if nobody logged in recently, then the first resource may map to the empty set. This resource exists regardless of the information it maps to.

+

Resources are identified by uniform resource identifiers, also known as URIs. Sometimes internationalized resource identifiers, or IRIs, may also be used, but these can be directly translated into a URI.

+

In practice we will identify two kinds of resources. Individual resources map to a set of one element, for example "user Joe". Collection of resources map to a set of 0 to N elements, for example "all users".

Resource representations

-
-

The representation of a resource is a sequence of bytes associated -with metadata.

-

The metadata comes as a list of key-value pairs, where the name -corresponds to a standard that defines the value’s structure and -semantics. With HTTP, the metadata comes in the form of request -or response headers. The headers' structure and semantics are well -defined in the HTTP standard. Metadata includes representation -metadata, resource metadata and control data.

-

The representation metadata gives information about the -representation, such as its media type, the date of last -modification, or even a checksum.

-

Resource metadata could be link to related resources or -information about additional representations of the resource.

-

Control data allows parameterizing the request or response. -For example, we may only want the representation returned if -it is more recent than the one we have in cache. Similarly, -we may want to instruct the client about how it should cache -the representation. This isn’t restricted to caching. We may, -for example, want to store a new representation of a resource -only if it wasn’t modified since we first retrieved it.

-

The data format of a representation is also known as the media -type. Some media types are intended for direct rendering to the -user, while others are intended for automated processing. The -media type is a key component of the REST architecture.

-
-
-
+

The representation of a resource is a sequence of bytes associated with metadata.

+

The metadata comes as a list of key-value pairs, where the name corresponds to a standard that defines the value's structure and semantics. With HTTP, the metadata comes in the form of request or response headers. The headers' structure and semantics are well defined in the HTTP standard. Metadata includes representation metadata, resource metadata and control data.

+

The representation metadata gives information about the representation, such as its media type, the date of last modification, or even a checksum.

+

Resource metadata could be link to related resources or information about additional representations of the resource.

+

Control data allows parameterizing the request or response. For example, we may only want the representation returned if it is more recent than the one we have in cache. Similarly, we may want to instruct the client about how it should cache the representation. This isn't restricted to caching. We may, for example, want to store a new representation of a resource only if it wasn't modified since we first retrieved it.

+

The data format of a representation is also known as the media type. Some media types are intended for direct rendering to the user, while others are intended for automated processing. The media type is a key component of the REST architecture.

Self-descriptive messages

-
-

Messages must be self-descriptive. That means that the data -format of a representation must always come with its media -type (and similarly requesting a resource involves choosing -the media type of the representation returned). If you are -sending HTML, then you must say it is HTML by sending the -media type with the representation. In HTTP this is done -using the content-type header.

-

The media type is often an IANA registered media type, like -text/html or image/png, but does not need to be. Exactly -two things are important for respecting this constraint: that -the media type is well specified, and that the sender and -recipient agree about what the media type refers to.

-

This means that you can create your own media types, like -application/x-mine, and that as long as you write the -specifications for it and that both endpoints agree about -it then the constraint is respected.

-
-
-
+

Messages must be self-descriptive. That means that the data format of a representation must always come with its media type (and similarly requesting a resource involves choosing the media type of the representation returned). If you are sending HTML, then you must say it is HTML by sending the media type with the representation. In HTTP this is done using the content-type header.

+

The media type is often an IANA registered media type, like text/html or image/png, but does not need to be. Exactly two things are important for respecting this constraint: that the media type is well specified, and that the sender and recipient agree about what the media type refers to.

+

This means that you can create your own media types, like application/x-mine, and that as long as you write the specifications for it and that both endpoints agree about it then the constraint is respected.

Hypermedia as the engine of application state

-
-

The last constraint is generally where services that claim -to be RESTful fail. Interactions with a server must be -entirely driven by hypermedia. The client does not need -any prior knowledge of the service in order to use it, -other than an entry point and of course basic understanding -of the media type of the representations, at the very least -enough to find and identify hyperlinks and link relations.

-

To give a simple example, if your service only works with -the application/json media type then this constraint -cannot be respected (as there are no concept of links in -JSON) and thus your service isn’t RESTful. This is the case -for the majority of self-proclaimed REST services.

-

On the other hand if you create a JSON based media type -that has a concept of links and link relations, then -your service might be RESTful.

-

Respecting this constraint means that the entirety of the -service becomes self-discoverable, not only the resources -in it, but also the operations you can perform on it. This -makes clients very thin as there is no need to implement -anything specific to the service to operate on it.

-
-
+

The last constraint is generally where services that claim to be RESTful fail. Interactions with a server must be entirely driven by hypermedia. The client does not need any prior knowledge of the service in order to use it, other than an entry point and of course basic understanding of the media type of the representations, at the very least enough to find and identify hyperlinks and link relations.

+

To give a simple example, if your service only works with the application/json media type then this constraint cannot be respected (as there are no concept of links in JSON) and thus your service isn't RESTful. This is the case for the majority of self-proclaimed REST services.

+

On the other hand if you create a JSON based media type that has a concept of links and link relations, then your service might be RESTful.

+

Respecting this constraint means that the entirety of the service becomes self-discoverable, not only the resources in it, but also the operations you can perform on it. This makes clients very thin as there is no need to implement anything specific to the service to operate on it.

+ diff --git a/docs/en/cowboy/2.1/guide/routing/index.html b/docs/en/cowboy/2.1/guide/routing/index.html index 513a8b94..6080fa67 100644 --- a/docs/en/cowboy/2.1/guide/routing/index.html +++ b/docs/en/cowboy/2.1/guide/routing/index.html @@ -62,261 +62,181 @@

Routing

-

Cowboy does nothing by default.

-

To make Cowboy useful, you need to map URIs to Erlang modules that will -handle the requests. This is called routing.

-

When Cowboy receives a request, it tries to match the requested host and -path to the configured routes. When there’s a match, the route’s -associated handler is executed.

-

Routes need to be compiled before they can be used by Cowboy. -The result of the compilation is the dispatch rules.

-
+

Cowboy does nothing by default.

+

To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing.

+

When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there's a match, the route's associated handler is executed.

+

Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules.

Syntax

-
-

The general structure for the routes is defined as follow.

-
-
-
Routes = [Host1, Host2, ... HostN].
-

Each host contains matching rules for the host along with optional -constraints, and a list of routes for the path component.

-
-
-
Host1 = {HostMatch, PathsList}.
-Host2 = {HostMatch, Constraints, PathsList}.
-

The list of routes for the path component is defined similar to the -list of hosts.

-
-
-
PathsList = [Path1, Path2, ... PathN].
-

Finally, each path contains matching rules for the path along with -optional constraints, and gives us the handler module to be used -along with its initial state.

-
-
-
Path1 = {PathMatch, Handler, InitialState}.
-Path2 = {PathMatch, Constraints, Handler, InitialState}.
-

Continue reading to learn more about the match syntax and the optional -constraints.

-
-
-
+
Path1 = {PathMatch, Handler, InitialState}.
+Path2 = {PathMatch, Constraints, Handler, InitialState}.
+
+

Continue reading to learn more about the match syntax and the optional constraints.

Match syntax

-
-

The match syntax is used to associate host names and paths with their -respective handlers.

-

The match syntax is the same for host and path with a few subtleties. -Indeed, the segments separator is different, and the host is matched -starting from the last segment going to the first. All examples will -feature both host and path match rules and explain the differences -when encountered.

-

Excluding special values that we will explain at the end of this section, -the simplest match value is a host or a path. It can be given as either -a string() or a binary().

-
-
-
PathMatch1 = "/".
-PathMatch2 = "/path/to/resource".
-
-HostMatch1 = "cowboy.example.org".
-

As you can see, all paths defined this way must start with a slash -character. Note that these two paths are identical as far as routing -is concerned.

-
-
-
PathMatch2 = "/path/to/resource".
-PathMatch3 = "/path/to/resource/".
-

Hosts with and without a trailing dot are equivalent for routing. -Similarly, hosts with and without a leading dot are also equivalent.

-
-
-
HostMatch1 = "cowboy.example.org".
-HostMatch2 = "cowboy.example.org.".
-HostMatch3 = ".cowboy.example.org".
-

It is possible to extract segments of the host and path and to store -the values in the Req object for later use. We call these kind of -values bindings.

-

The syntax for bindings is very simple. A segment that begins with -the : character means that what follows until the end of the segment -is the name of the binding in which the segment value will be stored.

-
-
-
PathMatch = "/hats/:name/prices".
-HostMatch = ":subdomain.example.org".
-

If these two end up matching when routing, you will end up with two -bindings defined, subdomain and name, each containing the -segment value where they were defined. For example, the URL -http://test.example.org/hats/wild_cowboy_legendary/prices will -result in having the value test bound to the name subdomain -and the value wild_cowboy_legendary bound to the name name. -They can later be retrieved using cowboy_req:binding/{2,3}. The -binding name must be given as an atom.

-

There is a special binding name you can use to mimic the underscore -variable in Erlang. Any match against the _ binding will succeed -but the data will be discarded. This is especially useful for -matching against many domain names in one go.

-
-
-
HostMatch = "ninenines.:_".
-

Similarly, it is possible to have optional segments. Anything -between brackets is optional.

-
-
-
PathMatch = "/hats/[page/:number]".
-HostMatch = "[www.]ninenines.eu".
-

You can also have imbricated optional segments.

-
-
-
PathMatch = "/hats/[page/[:number]]".
-

You can retrieve the rest of the host or path using [...]. -In the case of hosts it will match anything before, in the case -of paths anything after the previously matched segments. It is -a special case of optional segments, in that it can have -zero, one or many segments. You can then find the segments using -cowboy_req:host_info/1 and cowboy_req:path_info/1 respectively. -They will be represented as a list of segments.

-
-
-
PathMatch = "/hats/[...]".
-HostMatch = "[...]ninenines.eu".
-

If a binding appears twice in the routing rules, then the match -will succeed only if they share the same value. This copies the -Erlang pattern matching behavior.

-
-
-
PathMatch = "/hats/:name/:name".
-

This is also true when an optional segment is present. In this -case the two values must be identical only if the segment is -available.

-
-
-
PathMatch = "/hats/:name/[:name]".
-

If a binding is defined in both the host and path, then they must -also share the same value.

-
-
-
PathMatch = "/:user/[...]".
-HostMatch = ":user.github.com".
-

Finally, there are two special match values that can be used. The -first is the atom '_' which will match any host or path.

-
-
-
PathMatch = '_'.
-HostMatch = '_'.
-

The second is the special host match "*" which will match the -wildcard path, generally used alongside the OPTIONS method.

-
-
-
HostMatch = "*".
-
- -
+
HostMatch = "*".
+

Constraints

-
-

After the matching has completed, the resulting bindings can be tested -against a set of constraints. Constraints are only tested when the -binding is defined. They run in the order you defined them. The match -will succeed only if they all succeed. If the match fails, then Cowboy -tries the next route in the list.

-

The format used for constraints is the same as match functions in -cowboy_req: they are provided as a list of fields which may have -one or more constraints. While the router accepts the same format, -it will skip fields with no constraints and will also ignore default -values, if any.

-

Read more about constraints.

-
- -
+

After the matching has completed, the resulting bindings can be tested against a set of constraints. Constraints are only tested when the binding is defined. They run in the order you defined them. The match will succeed only if they all succeed. If the match fails, then Cowboy tries the next route in the list.

+

The format used for constraints is the same as match functions in cowboy_req: they are provided as a list of fields which may have one or more constraints. While the router accepts the same format, it will skip fields with no constraints and will also ignore default values, if any.

+

Read more about constraints.

Compilation

-
-

The routes must be compiled before Cowboy can use them. The compilation -step normalizes the routes to simplify the code and speed up the -execution, but the routes are still looked up one by one in the end. -Faster compilation strategies could be to compile the routes directly -to Erlang code, but would require heavier dependencies.

-

To compile routes, just call the appropriate function:

-
-
-
Dispatch = cowboy_router:compile([
-    %% {HostMatch, list({PathMatch, Handler, InitialState})}
-    {'_', [{'_', my_handler, #{}}]}
+
Dispatch = cowboy_router:compile([
+    %% {HostMatch, list({PathMatch, Handler, InitialState})}
+    {'_', [{'_', my_handler, #{}}]}
 ]),
-%% Name, NbAcceptors, TransOpts, ProtoOpts
-cowboy:start_clear(my_http_listener,
-    [{port, 8080}],
-    #{env => #{dispatch => Dispatch}}
-).
-
-
-
+%% Name, NbAcceptors, TransOpts, ProtoOpts +cowboy:start_clear(my_http_listener, + [{port, 8080}], + #{env => #{dispatch => Dispatch}} +). +

Live update

-
-

You can use the cowboy:set_env/3 function for updating the dispatch -list used by routing. This will apply to all new connections accepted -by the listener:

-
-
-
Dispatch = cowboy_router:compile(Routes),
-cowboy:set_env(my_http_listener, dispatch, Dispatch).
-

Note that you need to compile the routes again before updating.

-
- +
Dispatch = cowboy_router:compile(Routes),
+cowboy:set_env(my_http_listener, dispatch, Dispatch).
+ +

Note that you need to compile the routes again before updating.

+ diff --git a/docs/en/cowboy/2.1/guide/specs/index.html b/docs/en/cowboy/2.1/guide/specs/index.html index a35ac154..4b24e97c 100644 --- a/docs/en/cowboy/2.1/guide/specs/index.html +++ b/docs/en/cowboy/2.1/guide/specs/index.html @@ -62,839 +62,337 @@

HTTP and other specifications

-

This chapter intends to list all the specification documents -for or related to HTTP.

-
+

This chapter intends to list all the specification documents for or related to HTTP.

HTTP

-
- -
+

Current

-
    -
  • -

    -CORS: Cross-Origin Resource Sharing -

    -
  • -
  • -

    -CSP2: Content Security Policy Level 2 -

    -
  • -
  • -

    -DNT: Tracking Preference Expression (DNT) -

    -
  • -
  • -

    -eventsource: Server-Sent Events -

    -
  • -
  • -

    -Form content types: Form content types -

    -
  • -
  • -

    -Preload: Preload -

    -
  • -
  • -

    -REST: Fielding’s Dissertation -

    -
  • -
  • -

    -RFC 1945: HTTP/1.0 -

    -
  • -
  • -

    -RFC 1951: DEFLATE Compressed Data Format Specification version 1.3 -

    -
  • -
  • -

    -RFC 1952: GZIP file format specification version 4.3 -

    -
  • -
  • -

    -RFC 2046: Multipart media type (in MIME Part Two: Media Types) -

    -
  • -
  • -

    -RFC 2295: Transparent Content Negotiation in HTTP -

    -
  • -
  • -

    -RFC 2296: HTTP Remote Variant Selection Algorithm: RVSA/1.0 -

    -
  • -
  • -

    -RFC 2817: Upgrading to TLS Within HTTP/1.1 -

    -
  • -
  • -

    -RFC 2818: HTTP Over TLS -

    -
  • -
  • -

    -RFC 3230: Instance Digests in HTTP -

    -
  • -
  • -

    -RFC 4559: SPNEGO-based Kerberos and NTLM HTTP Authentication in Microsoft Windows -

    -
  • -
  • -

    -RFC 5789: PATCH Method for HTTP -

    -
  • -
  • -

    -RFC 5843: Additional Hash Algorithms for HTTP Instance Digests -

    -
  • -
  • -

    -RFC 5861: HTTP Cache-Control Extensions for Stale Content -

    -
  • -
  • -

    -RFC 5988: Web Linking -

    -
  • -
  • -

    -RFC 6265: HTTP State Management Mechanism -

    -
  • -
  • -

    -RFC 6266: Use of the Content-Disposition Header Field -

    -
  • -
  • -

    -RFC 6454: The Web Origin Concept -

    -
  • -
  • -

    -RFC 6455: The WebSocket Protocol -

    -
  • -
  • -

    -RFC 6585: Additional HTTP Status Codes -

    -
  • -
  • -

    -RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage -

    -
  • -
  • -

    -RFC 6797: HTTP Strict Transport Security (HSTS) -

    -
  • -
  • -

    -RFC 6903: Additional Link Relation Types -

    -
  • -
  • -

    -RFC 7034: HTTP Header Field X-Frame-Options -

    -
  • -
  • -

    -RFC 7089: Time-Based Access to Resource States: Memento -

    -
  • -
  • -

    -RFC 7230: HTTP/1.1 Message Syntax and Routing -

    -
  • -
  • -

    -RFC 7231: HTTP/1.1 Semantics and Content -

    -
  • -
  • -

    -RFC 7232: HTTP/1.1 Conditional Requests -

    -
  • -
  • -

    -RFC 7233: HTTP/1.1 Range Requests -

    -
  • -
  • -

    -RFC 7234: HTTP/1.1 Caching -

    -
  • -
  • -

    -RFC 7235: HTTP/1.1 Authentication -

    -
  • -
  • -

    -RFC 7239: Forwarded HTTP Extension -

    -
  • -
  • -

    -RFC 7240: Prefer Header for HTTP -

    -
  • -
  • -

    -RFC 7469: Public Key Pinning Extension for HTTP -

    -
  • -
  • -

    -RFC 7486: HTTP Origin-Bound Authentication (HOBA) -

    -
  • -
  • -

    -RFC 7538: HTTP Status Code 308 (Permanent Redirect) -

    -
  • -
  • -

    -RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2) -

    -
  • -
  • -

    -RFC 7541: HPACK: Header Compression for HTTP/2 -

    -
  • -
  • -

    -RFC 7578: Returning Values from Forms: multipart/form-data -

    -
  • -
  • -

    -RFC 7615: HTTP Authentication-Info and Proxy-Authentication-Info Response Header Fields -

    -
  • -
  • -

    -RFC 7616: HTTP Digest Access Authentication -

    -
  • -
  • -

    -RFC 7617: The Basic HTTP Authentication Scheme -

    -
  • -
  • -

    -RFC 7639: The ALPN HTTP Header Field -

    -
  • -
  • -

    -RFC 7692: Compression Extensions for WebSocket -

    -
  • -
  • -

    -RFC 7694: HTTP Client-Initiated Content-Encoding -

    -
  • -
  • -

    -RFC 7725: An HTTP Status Code to Report Legal Obstacles -

    -
  • -
  • -

    -RFC 7804: Salted Challenge Response HTTP Authentication Mechanism -

    -
  • -
  • -

    -RFC 7838: HTTP Alternative Services -

    -
  • -
  • -

    -RFC 7932: Brotli Compressed Data Format -

    -
  • -
  • -

    -RFC 7936: Clarifying Registry Procedures for the WebSocket Subprotocol Name Registry -

    -
  • -
  • -

    -RFC 8053: HTTP Authentication Extensions for Interactive Clients -

    -
  • -
  • -

    -RFC 8164: Opportunistic Security for HTTP/2 -

    -
  • -
  • -

    -RFC 8187: Indicating Character Encoding and Language for HTTP Header Field Parameters -

    -
  • -
  • -

    -RFC 8188: Encrypted Content-Encoding for HTTP -

    -
  • -
  • -

    -RFC 8246: HTTP Immutable Responses -

    -
  • -
  • -

    -Webmention: Webmention -

    -
  • -
-
-
+
  • CORS: Cross-Origin Resource Sharing +
  • +
  • CSP2: Content Security Policy Level 2 +
  • +
  • DNT: Tracking Preference Expression (DNT) +
  • +
  • eventsource: Server-Sent Events +
  • +
  • Form content types: Form content types +
  • +
  • Preload: Preload +
  • +
  • REST: Fielding's Dissertation +
  • +
  • RFC 1945: HTTP/1.0 +
  • +
  • RFC 1951: DEFLATE Compressed Data Format Specification version 1.3 +
  • +
  • RFC 1952: GZIP file format specification version 4.3 +
  • +
  • RFC 2046: Multipart media type (in MIME Part Two: Media Types) +
  • +
  • RFC 2295: Transparent Content Negotiation in HTTP +
  • +
  • RFC 2296: HTTP Remote Variant Selection Algorithm: RVSA/1.0 +
  • +
  • RFC 2817: Upgrading to TLS Within HTTP/1.1 +
  • +
  • RFC 2818: HTTP Over TLS +
  • +
  • RFC 3230: Instance Digests in HTTP +
  • +
  • RFC 4559: SPNEGO-based Kerberos and NTLM HTTP Authentication in Microsoft Windows +
  • +
  • RFC 5789: PATCH Method for HTTP +
  • +
  • RFC 5843: Additional Hash Algorithms for HTTP Instance Digests +
  • +
  • RFC 5861: HTTP Cache-Control Extensions for Stale Content +
  • +
  • RFC 5988: Web Linking +
  • +
  • RFC 6265: HTTP State Management Mechanism +
  • +
  • RFC 6266: Use of the Content-Disposition Header Field +
  • +
  • RFC 6454: The Web Origin Concept +
  • +
  • RFC 6455: The WebSocket Protocol +
  • +
  • RFC 6585: Additional HTTP Status Codes +
  • +
  • RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage +
  • +
  • RFC 6797: HTTP Strict Transport Security (HSTS) +
  • +
  • RFC 6903: Additional Link Relation Types +
  • +
  • RFC 7034: HTTP Header Field X-Frame-Options +
  • +
  • RFC 7089: Time-Based Access to Resource States: Memento +
  • +
  • RFC 7230: HTTP/1.1 Message Syntax and Routing +
  • +
  • RFC 7231: HTTP/1.1 Semantics and Content +
  • +
  • RFC 7232: HTTP/1.1 Conditional Requests +
  • +
  • RFC 7233: HTTP/1.1 Range Requests +
  • +
  • RFC 7234: HTTP/1.1 Caching +
  • +
  • RFC 7235: HTTP/1.1 Authentication +
  • +
  • RFC 7239: Forwarded HTTP Extension +
  • +
  • RFC 7240: Prefer Header for HTTP +
  • +
  • RFC 7469: Public Key Pinning Extension for HTTP +
  • +
  • RFC 7486: HTTP Origin-Bound Authentication (HOBA) +
  • +
  • RFC 7538: HTTP Status Code 308 (Permanent Redirect) +
  • +
  • RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2) +
  • +
  • RFC 7541: HPACK: Header Compression for HTTP/2 +
  • +
  • RFC 7578: Returning Values from Forms: multipart/form-data +
  • +
  • RFC 7615: HTTP Authentication-Info and Proxy-Authentication-Info Response Header Fields +
  • +
  • RFC 7616: HTTP Digest Access Authentication +
  • +
  • RFC 7617: The Basic HTTP Authentication Scheme +
  • +
  • RFC 7639: The ALPN HTTP Header Field +
  • +
  • RFC 7692: Compression Extensions for WebSocket +
  • +
  • RFC 7694: HTTP Client-Initiated Content-Encoding +
  • +
  • RFC 7725: An HTTP Status Code to Report Legal Obstacles +
  • +
  • RFC 7804: Salted Challenge Response HTTP Authentication Mechanism +
  • +
  • RFC 7838: HTTP Alternative Services +
  • +
  • RFC 7932: Brotli Compressed Data Format +
  • +
  • RFC 7936: Clarifying Registry Procedures for the WebSocket Subprotocol Name Registry +
  • +
  • RFC 8053: HTTP Authentication Extensions for Interactive Clients +
  • +
  • RFC 8164: Opportunistic Security for HTTP/2 +
  • +
  • RFC 8187: Indicating Character Encoding and Language for HTTP Header Field Parameters +
  • +
  • RFC 8188: Encrypted Content-Encoding for HTTP +
  • +
  • RFC 8246: HTTP Immutable Responses +
  • +
  • Webmention: Webmention +
  • +

Upcoming

- -
-
+

Informative

-
    -
  • -

    -Architecture of the World Wide Web -

    -
  • -
  • -

    -RFC 2936: HTTP MIME Type Handler Detection -

    -
  • -
  • -

    -RFC 2964: Use of HTTP State Management -

    -
  • -
  • -

    -RFC 3143: Known HTTP Proxy/Caching Problems -

    -
  • -
  • -

    -RFC 6202: Known Issues and Best Practices for the Use of Long Polling and Streaming in Bidirectional HTTP -

    -
  • -
  • -

    -RFC 6838: Media Type Specifications and Registration Procedures -

    -
  • -
  • -

    -RFC 7478: Web Real-Time Communication Use Cases and Requirements -

    -
  • -
-
-
+
  • Architecture of the World Wide Web +
  • +
  • RFC 2936: HTTP MIME Type Handler Detection +
  • +
  • RFC 2964: Use of HTTP State Management +
  • +
  • RFC 3143: Known HTTP Proxy/Caching Problems +
  • +
  • RFC 6202: Known Issues and Best Practices for the Use of Long Polling and Streaming in Bidirectional HTTP +
  • +
  • RFC 6838: Media Type Specifications and Registration Procedures +
  • +
  • RFC 7478: Web Real-Time Communication Use Cases and Requirements +
  • +
-
-
-
+

Seemingly obsolete

-
    -
  • -

    -RFC 2227: Simple Hit-Metering and Usage-Limiting for HTTP -

    -
  • -
  • -

    -RFC 2310: The Safe Response Header Field -

    -
  • -
  • -

    -RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) -

    -
  • -
  • -

    -RFC 2660: The Secure HyperText Transfer Protocol -

    -
  • -
  • -

    -RFC 2774: An HTTP Extension Framework -

    -
  • -
  • -

    -RFC 2965: HTTP State Management Mechanism (Cookie2) -

    -
  • -
  • -

    -RFC 3229: Delta encoding in HTTP -

    -
  • -
  • -

    -RFC 7168: The Hyper Text Coffee Pot Control Protocol for Tea Efflux Appliances (HTCPCP-TEA) -

    -
  • -
  • -

    -SPDY: SPDY Protocol -

    -
  • -
  • -

    -x-webkit-deflate-frame: Deprecated Websocket compression -

    -
  • -
-
-
-
-
+
  • RFC 2227: Simple Hit-Metering and Usage-Limiting for HTTP +
  • +
  • RFC 2310: The Safe Response Header Field +
  • +
  • RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) +
  • +
  • RFC 2660: The Secure HyperText Transfer Protocol +
  • +
  • RFC 2774: An HTTP Extension Framework +
  • +
  • RFC 2965: HTTP State Management Mechanism (Cookie2) +
  • +
  • RFC 3229: Delta encoding in HTTP +
  • +
  • RFC 7168: The Hyper Text Coffee Pot Control Protocol for Tea Efflux Appliances (HTCPCP-TEA) +
  • +
  • SPDY: SPDY Protocol +
  • +
  • x-webkit-deflate-frame: Deprecated Websocket compression +
  • +

URL

-
-
-
-
-
+

WebDAV

-
-
    -
  • -

    -RFC 3253: Versioning Extensions to WebDAV -

    -
  • -
  • -

    -RFC 3648: WebDAV Ordered Collections Protocol -

    -
  • -
  • -

    -RFC 3744: WebDAV Access Control Protocol -

    -
  • -
  • -

    -RFC 4316: Datatypes for WebDAV Properties -

    -
  • -
  • -

    -RFC 4331: Quota and Size Properties for DAV Collections -

    -
  • -
  • -

    -RFC 4437: WebDAV Redirect Reference Resources -

    -
  • -
  • -

    -RFC 4709: Mounting WebDAV Servers -

    -
  • -
  • -

    -RFC 4791: Calendaring Extensions to WebDAV (CalDAV) -

    -
  • -
  • -

    -RFC 4918: HTTP Extensions for WebDAV -

    -
  • -
  • -

    -RFC 5323: WebDAV SEARCH -

    -
  • -
  • -

    -RFC 5397: WebDAV Current Principal Extension -

    -
  • -
  • -

    -RFC 5689: Extended MKCOL for WebDAV -

    -
  • -
  • -

    -RFC 5842: Binding Extensions to WebDAV -

    -
  • -
  • -

    -RFC 5995: Using POST to Add Members to WebDAV Collections -

    -
  • -
  • -

    -RFC 6352: CardDAV: vCard Extensions to WebDAV -

    -
  • -
  • -

    -RFC 6578: Collection Synchronization for WebDAV -

    -
  • -
  • -

    -RFC 6638: Scheduling Extensions to CalDAV -

    -
  • -
  • -

    -RFC 6764: Locating Services for Calendaring Extensions to WebDAV (CalDAV) and vCard Extensions to WebDAV (CardDAV) -

    -
  • -
  • -

    -RFC 7809: Calendaring Extensions to WebDAV (CalDAV): Time Zones by Reference -

    -
  • -
  • -

    -RFC 7953: Calendar Availability -

    -
  • -
  • -

    -RFC 8144: Use of the Prefer Header Field in WebDAV -

    -
  • -
-
-
-
+
  • RFC 3253: Versioning Extensions to WebDAV +
  • +
  • RFC 3648: WebDAV Ordered Collections Protocol +
  • +
  • RFC 3744: WebDAV Access Control Protocol +
  • +
  • RFC 4316: Datatypes for WebDAV Properties +
  • +
  • RFC 4331: Quota and Size Properties for DAV Collections +
  • +
  • RFC 4437: WebDAV Redirect Reference Resources +
  • +
  • RFC 4709: Mounting WebDAV Servers +
  • +
  • RFC 4791: Calendaring Extensions to WebDAV (CalDAV) +
  • +
  • RFC 4918: HTTP Extensions for WebDAV +
  • +
  • RFC 5323: WebDAV SEARCH +
  • +
  • RFC 5397: WebDAV Current Principal Extension +
  • +
  • RFC 5689: Extended MKCOL for WebDAV +
  • +
  • RFC 5842: Binding Extensions to WebDAV +
  • +
  • RFC 5995: Using POST to Add Members to WebDAV Collections +
  • +
  • RFC 6352: CardDAV: vCard Extensions to WebDAV +
  • +
  • RFC 6578: Collection Synchronization for WebDAV +
  • +
  • RFC 6638: Scheduling Extensions to CalDAV +
  • +
  • RFC 6764: Locating Services for Calendaring Extensions to WebDAV (CalDAV) and vCard Extensions to WebDAV (CardDAV) +
  • +
  • RFC 7809: Calendaring Extensions to WebDAV (CalDAV): Time Zones by Reference +
  • +
  • RFC 7953: Calendar Availability +
  • +
  • RFC 8144: Use of the Prefer Header Field in WebDAV +
  • +

CoAP

-
-
    -
  • -

    -RFC 7252: The Constrained Application Protocol (CoAP) -

    -
  • -
  • -

    -RFC 7390: Group Communication for CoAP -

    -
  • -
  • -

    -RFC 7641: Observing Resources in CoAP -

    -
  • -
  • -

    -RFC 7650: A CoAP Usage for REsource LOcation And Discovery (RELOAD) -

    -
  • -
  • -

    -RFC 7959: Block-Wise Transfers in CoAP -

    -
  • -
  • -

    -RFC 7967: CoAP Option for No Server Response -

    -
  • -
  • -

    -RFC 8075: Guidelines for Mapping Implementations: HTTP to CoAP -

    -
  • -
  • -

    -RFC 8132: PATCH and FETCH Methods for CoAP -

    -
  • -
-
-
+
  • RFC 7252: The Constrained Application Protocol (CoAP) +
  • +
  • RFC 7390: Group Communication for CoAP +
  • +
  • RFC 7641: Observing Resources in CoAP +
  • +
  • RFC 7650: A CoAP Usage for REsource LOcation And Discovery (RELOAD) +
  • +
  • RFC 7959: Block-Wise Transfers in CoAP +
  • +
  • RFC 7967: CoAP Option for No Server Response +
  • +
  • RFC 8075: Guidelines for Mapping Implementations: HTTP to CoAP +
  • +
  • RFC 8132: PATCH and FETCH Methods for CoAP +
  • +
+ diff --git a/docs/en/cowboy/2.1/guide/static_files/index.html b/docs/en/cowboy/2.1/guide/static_files/index.html index 40d70996..c0f10d1c 100644 --- a/docs/en/cowboy/2.1/guide/static_files/index.html +++ b/docs/en/cowboy/2.1/guide/static_files/index.html @@ -62,173 +62,101 @@

Static files

-

Cowboy comes with a ready to use handler for serving static -files. It is provided as a convenience for serving files -during development.

-

For systems in production, consider using one of the many -Content Distribution Network (CDN) available on the market, -as they are the best solution for serving files.

-

The static handler can serve either one file or all files -from a given directory. The etag generation and mime types -can be configured.

-
+

Cowboy comes with a ready to use handler for serving static files. It is provided as a convenience for serving files during development.

+

For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files.

+

The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured.

Serve one file

-
-

You can use the static handler to serve one specific file -from an application’s private directory. This is particularly -useful to serve an index.html file when the client requests -the / path, for example. The path configured is relative -to the given application’s private directory.

-

The following rule will serve the file static/index.html -from the application my_app's priv directory whenever the -path / is accessed:

-
-
-
{"/", cowboy_static, {priv_file, my_app, "static/index.html"}}
-

You can also specify the absolute path to a file, or the -path to the file relative to the current directory:

-
-
-
{"/", cowboy_static, {file, "/var/www/index.html"}}
-
-
-
+
{"/", cowboy_static, {file, "/var/www/index.html"}}
+

Serve all files from a directory

-
-

You can also use the static handler to serve all files that -can be found in the configured directory. The handler will -use the path_info information to resolve the file location, -which means that your route must end with a [...] pattern -for it to work. All files are served, including the ones that -may be found in subfolders.

-

You can specify the directory relative to an application’s -private directory.

-

The following rule will serve any file found in the application -my_app's priv directory inside the static/assets folder -whenever the requested path begins with /assets/:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets"}}
-

You can also specify the absolute path to the directory or -set it relative to the current directory:

-
-
-
{"/assets/[...]", cowboy_static, {dir, "/var/www/assets"}}
-
- -
+
{"/assets/[...]", cowboy_static, {dir, "/var/www/assets"}}
+

Customize the mimetype detection

-
-

By default, Cowboy will attempt to recognize the mimetype -of your static files by looking at the extension.

-

You can override the function that figures out the mimetype -of the static files. It can be useful when Cowboy is missing -a mimetype you need to handle, or when you want to reduce -the list to make lookups faster. You can also give a -hard-coded mimetype that will be used unconditionally.

-

Cowboy comes with two functions built-in. The default -function only handles common file types used when building -Web applications. The other function is an extensive list -of hundreds of mimetypes that should cover almost any need -you may have. You can of course create your own function.

-

To use the default function, you should not have to configure -anything, as it is the default. If you insist, though, the -following will do the job:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{mimetypes, cow_mimetypes, web}]}}
-

As you can see, there is an optional field that may contain -a list of less used options, like mimetypes or etag. All option -types have this optional field.

-

To use the function that will detect almost any mimetype, -the following configuration will do:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{mimetypes, cow_mimetypes, all}]}}
-

You probably noticed the pattern by now. The configuration -expects a module and a function name, so you can use any -of your own functions instead:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{mimetypes, Module, Function}]}}
-

The function that performs the mimetype detection receives -a single argument that is the path to the file on disk. It -is recommended to return the mimetype in tuple form, although -a binary string is also allowed (but will require extra -processing). If the function can’t figure out the mimetype, -then it should return {<<"application">>, <<"octet-stream">>, []}.

-

When the static handler fails to find the extension, -it will send the file as application/octet-stream. -A browser receiving such file will attempt to download it -directly to disk.

-

Finally, the mimetype can be hard-coded for all files. -This is especially useful in combination with the file -and priv_file options as it avoids needless computation:

-
-
-
{"/", cowboy_static, {priv_file, my_app, "static/index.html",
-    [{mimetypes, {<<"text">>, <<"html">>, []}}]}}
-
- -
+
{"/", cowboy_static, {priv_file, my_app, "static/index.html",
+    [{mimetypes, {<<"text">>, <<"html">>, []}}]}}
+

Generate an etag

-
-

By default, the static handler will generate an etag header -value based on the size and modified time. This solution -can not be applied to all systems though. It would perform -rather poorly over a cluster of nodes, for example, as the -file metadata will vary from server to server, giving a -different etag on each server.

-

You can however change the way the etag is calculated:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{etag, Module, Function}]}}
-

This function will receive three arguments: the path to the -file on disk, the size of the file and the last modification -time. In a distributed setup, you would typically use the -file path to retrieve an etag value that is identical across -all your servers.

-

You can also completely disable etag handling:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{etag, false}]}}
-
- +
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
+    [{etag, false}]}}
+ + diff --git a/docs/en/cowboy/2.1/guide/streams/index.html b/docs/en/cowboy/2.1/guide/streams/index.html index 152f413e..887ec381 100644 --- a/docs/en/cowboy/2.1/guide/streams/index.html +++ b/docs/en/cowboy/2.1/guide/streams/index.html @@ -62,61 +62,23 @@

Streams

-

A stream is the set of messages that form an HTTP -request/response pair.

-

The term stream comes from HTTP/2. In Cowboy, it is -also used when talking about HTTP/1.1 or HTTP/1.0. -It should not be confused with streaming the request -or response body.

-

All versions of HTTP allow clients to initiate -streams. HTTP/2 is the only one also allowing servers, -through its server push feature. Both client and -server-initiated streams go through the same process -in Cowboy.

-
+

A stream is the set of messages that form an HTTP request/response pair.

+

The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body.

+

All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy.

Stream handlers

-
-

Stream handlers must implement five different callbacks. -Four of them are directly related; one is special.

-

All callbacks receives the stream ID as first argument.

-

Most of them can return a list of commands to be executed -by Cowboy. When callbacks are chained, it is possible to -intercept and modify these commands. This can be useful -for modifying responses for example.

-

The init/3 callback is invoked when a new request -comes in. It receives the Req object and the protocol options -for this listener.

-

The data/4 callback is invoked when data from the request -body is received. It receives both this data and a flag -indicating whether more is to be expected.

-

The info/3 callback is invoked when an Erlang message is -received for this stream. They will typically be messages -sent by the request process.

-

Finally the terminate/3 callback is invoked with the -terminate reason for the stream. The return value is ignored. -Note that as with all terminate callbacks in Erlang, there -is no strong guarantee that it will be called.

-

The special callback early_error/5 is called when an error -occurs before the request headers were fully received and -Cowboy is sending a response. It receives the partial Req -object, the error reason, the protocol options and the response -Cowboy will send. This response must be returned, possibly -modified.

-
-
-
+

Stream handlers must implement five different callbacks. Four of them are directly related; one is special.

+

All callbacks receives the stream ID as first argument.

+

Most of them can return a list of commands to be executed by Cowboy. When callbacks are chained, it is possible to intercept and modify these commands. This can be useful for modifying responses for example.

+

The init/3 callback is invoked when a new request comes in. It receives the Req object and the protocol options for this listener.

+

The data/4 callback is invoked when data from the request body is received. It receives both this data and a flag indicating whether more is to be expected.

+

The info/3 callback is invoked when an Erlang message is received for this stream. They will typically be messages sent by the request process.

+

Finally the terminate/3 callback is invoked with the terminate reason for the stream. The return value is ignored. Note that as with all terminate callbacks in Erlang, there is no strong guarantee that it will be called.

+

The special callback early_error/5 is called when an error occurs before the request headers were fully received and Cowboy is sending a response. It receives the partial Req object, the error reason, the protocol options and the response Cowboy will send. This response must be returned, possibly modified.

Built-in handlers

-
-

Cowboy comes with two handlers.

-

cowboy_stream_h is the default stream handler. -It is the core of much of the functionality of Cowboy. -All chains of stream handlers should call it last.

-

cowboy_compress_h will automatically compress -responses when possible. It is not enabled by default. -It is a good example for writing your own handlers -that will modify responses.

-
-
+

Cowboy comes with two handlers.

+

cowboy_stream_h is the default stream handler. It is the core of much of the functionality of Cowboy. All chains of stream handlers should call it last.

+

cowboy_compress_h will automatically compress responses when possible. It is not enabled by default. It is a good example for writing your own handlers that will modify responses.

+ diff --git a/docs/en/cowboy/2.1/guide/ws_handlers/index.html b/docs/en/cowboy/2.1/guide/ws_handlers/index.html index 7abf9626..027e9d2d 100644 --- a/docs/en/cowboy/2.1/guide/ws_handlers/index.html +++ b/docs/en/cowboy/2.1/guide/ws_handlers/index.html @@ -62,271 +62,171 @@

Websocket handlers

-

Websocket handlers provide an interface for upgrading HTTP/1.1 -connections to Websocket and sending or receiving frames on -the Websocket connection.

-

As Websocket connections are established through the HTTP/1.1 -upgrade mechanism, Websocket handlers need to be able to first -receive the HTTP request for the upgrade, before switching to -Websocket and taking over the connection. They can then receive -or send Websocket frames, handle incoming Erlang messages or -close the connection.

-
+

Websocket handlers provide an interface for upgrading HTTP/1.1 connections to Websocket and sending or receiving frames on the Websocket connection.

+

As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection.

Upgrade

-
-

The init/2 callback is called when the request is received. -To establish a Websocket connection, you must switch to the -cowboy_websocket module:

-
-
-
init(Req, State) ->
-    {cowboy_websocket, Req, State}.
-

Cowboy will perform the Websocket handshake immediately. Note -that the handshake will fail if the client did not request an -upgrade to Websocket.

-

The Req object becomes unavailable after this function returns. -Any information required for proper execution of the Websocket -handler must be saved in the state.

-
-
-
-

Subprotocol

-
-

The client may provide a list of Websocket subprotocols it -supports in the sec-websocket-protocol header. The server must -select one of them and send it back to the client or the -handshake will fail.

-

For example, a client could understand both STOMP and MQTT over -Websocket, and provide the header:

-
-
-
sec-websocket-protocol: v12.stomp, mqtt
+
init(Req, State) ->
+    {cowboy_websocket, Req, State}.
-

If the server only understands MQTT it can return:

-
-
-
sec-websocket-protocol: mqtt
-
-

This selection must be done in init/2. An example usage could -be:

-
-
-
init(Req0, State) ->
-    case cowboy_req:parse_header(<<"sec-websocket-protocol">>, Req0) of
-        undefined ->
-            {cowboy_websocket, Req0, State};
-        Subprotocols ->
-            case lists:keymember(<<"mqtt">>, 1, Subprotocols) of
-                true ->
-                    Req = cowboy_req:set_resp_header(<<"sec-websocket-protocol">>,
-                        <<"mqtt">>, Req0),
-                    {cowboy_websocket, Req, State};
-                false ->
-                    Req = cowboy_req:reply(400, Req0),
-                    {ok, Req, State}
-            end
-    end.
-
-
-
+
init(Req0, State) ->
+    case cowboy_req:parse_header(<<"sec-websocket-protocol">>, Req0) of
+        undefined ->
+            {cowboy_websocket, Req0, State};
+        Subprotocols ->
+            case lists:keymember(<<"mqtt">>, 1, Subprotocols) of
+                true ->
+                    Req = cowboy_req:set_resp_header(<<"sec-websocket-protocol">>,
+                        <<"mqtt">>, Req0),
+                    {cowboy_websocket, Req, State};
+                false ->
+                    Req = cowboy_req:reply(400, Req0),
+                    {ok, Req, State}
+            end
+    end.
+

Post-upgrade initialization

-
-

Cowboy has separate processes for handling the connection -and requests. Because Websocket takes over the connection, -the Websocket protocol handling occurs in a different -process than the request handling.

-

This is reflected in the different callbacks Websocket -handlers have. The init/2 callback is called from the -temporary request process and the websocket_ callbacks -from the connection process.

-

This means that some initialization cannot be done from -init/2. Anything that would require the current pid, -or be tied to the current pid, will not work as intended. -The optional websocket_init/1 can be used instead:

-
-
-
websocket_init(State) ->
-    erlang:start_timer(1000, self(), <<"Hello!">>),
-    {ok, State}.
-

All Websocket callbacks share the same return values. This -means that we can send frames to the client right after -the upgrade:

-
-
-
websocket_init(State) ->
-    {reply, {text, <<"Hello!">>}, State}.
-
- -
+
websocket_init(State) ->
+    {reply, {text, <<"Hello!">>}, State}.
+

Receiving frames

-
-

Cowboy will call websocket_handle/2 whenever a text, binary, -ping or pong frame arrives from the client.

-

The handler can handle or ignore the frames. It can also -send frames back to the client or stop the connection.

-

The following snippet echoes back any text frame received and -ignores all others:

-
-
-
websocket_handle(Frame = {text, _}, State) ->
-    {reply, Frame, State};
-websocket_handle(_Frame, State) ->
-    {ok, State}.
-

Note that ping and pong frames require no action from the -handler as Cowboy will automatically reply to ping frames. -They are provided for informative purposes only.

-
- -
+
websocket_handle(Frame = {text, _}, State) ->
+    {reply, Frame, State};
+websocket_handle(_Frame, State) ->
+    {ok, State}.
+
+

Note that ping and pong frames require no action from the handler as Cowboy will automatically reply to ping frames. They are provided for informative purposes only.

Receiving Erlang messages

-
-

Cowboy will call websocket_info/2 whenever an Erlang message -arrives.

-

The handler can handle or ignore the messages. It can also -send frames to the client or stop the connection.

-

The following snippet forwards log messages to the client -and ignores all others:

-
-
-
websocket_info({log, Text}, State) ->
-    {reply, {text, Text}, State};
-websocket_info(_Info, State) ->
-    {ok, State}.
-
- -
+
websocket_info({log, Text}, State) ->
+    {reply, {text, Text}, State};
+websocket_info(_Info, State) ->
+    {ok, State}.
+

Sending frames

-
-

All websocket_ callbacks share return values. They may -send zero, one or many frames to the client.

-

To send nothing, just return an ok tuple:

-
-
+ + +

All websocket_ callbacks share return values. They may send zero, one or many frames to the client.

+

To send nothing, just return an ok tuple:

+
-
websocket_info(_Info, State) ->
-    {ok, State}.
-

To send one frame, return a reply tuple with the frame to send:

-
-
-
websocket_info(_Info, State) ->
-    {reply, {text, <<"Hello!">>}, State}.
-

You can send frames of any type: text, binary, ping, pong -or close frames.

-

To send many frames at once, return a reply tuple with the -list of frames to send:

-
-
-
websocket_info(_Info, State) ->
-    {reply, [
-        {text, "Hello"},
-        {text, <<"world!">>},
-        {binary, <<0:8000>>}
-    ], State}.
-

They are sent in the given order.

-
-
-
+
websocket_info(_Info, State) ->
+    {reply, [
+        {text, "Hello"},
+        {text, <<"world!">>},
+        {binary, <<0:8000>>}
+    ], State}.
+
+

They are sent in the given order.

Keeping the connection alive

-
-

Cowboy will automatically respond to ping frames sent by -the client. They are still forwarded to the handler for -informative purposes, but no further action is required.

-

Cowboy does not send ping frames itself. The handler can -do it if required. A better solution in most cases is to -let the client handle pings. Doing it from the handler -would imply having an additional timer per connection and -this can be a considerable cost for servers that need to -handle large numbers of connections.

-

Cowboy can be configured to close idle connections -automatically. It is highly recommended to configure -a timeout here, to avoid having processes linger longer -than needed.

-

The init/2 callback can set the timeout to be used -for the connection. For example, this would make Cowboy -close connections idle for more than 30 seconds:

-
-
-
init(Req, State) ->
-    {cowboy_websocket, Req, State, #{
-        idle_timeout => 30000}}.
-

This value cannot be changed once it is set. It defaults to -60000.

-
- -
+
init(Req, State) ->
+    {cowboy_websocket, Req, State, #{
+        idle_timeout => 30000}}.
+
+

This value cannot be changed once it is set. It defaults to 60000.

Saving memory

-
-

The Websocket connection process can be set to hibernate -after the callback returns.

-

Simply add an hibernate field to the ok or reply tuples:

-
-
-
websocket_init(State) ->
-    {ok, State, hibernate}.
-
-websocket_handle(_Frame, State) ->
-    {ok, State, hibernate}.
-
-websocket_info(_Info, State) ->
-    {reply, {text, <<"Hello!">>}, State, hibernate}.
-

It is highly recommended to write your handlers with -hibernate enabled, as this allows to greatly reduce the -memory usage. Do note however that an increase in the -CPU usage or latency can be observed instead, in particular -for the more busy connections.

-
- -
+
websocket_init(State) ->
+    {ok, State, hibernate}.
+
+websocket_handle(_Frame, State) ->
+    {ok, State, hibernate}.
+
+websocket_info(_Info, State) ->
+    {reply, {text, <<"Hello!">>}, State, hibernate}.
+
+

It is highly recommended to write your handlers with hibernate enabled, as this allows to greatly reduce the memory usage. Do note however that an increase in the CPU usage or latency can be observed instead, in particular for the more busy connections.

Closing the connection

-
-

The connection can be closed at any time, either by telling -Cowboy to stop it or by sending a close frame.

-

To tell Cowboy to close the connection, use a stop tuple:

-
-
-
websocket_info(_Info, State) ->
-    {stop, State}.
-

Sending a close frame will immediately initiate the closing -of the Websocket connection. Note that when sending a list of -frames that include a close frame, any frame found after the -close frame will not be sent.

-
- +
websocket_info(_Info, State) ->
+    {stop, State}.
+ +

Sending a close frame will immediately initiate the closing of the Websocket connection. Note that when sending a list of frames that include a close frame, any frame found after the close frame will not be sent.

+ diff --git a/docs/en/cowboy/2.1/guide/ws_protocol/index.html b/docs/en/cowboy/2.1/guide/ws_protocol/index.html index f840e46c..aa5705d1 100644 --- a/docs/en/cowboy/2.1/guide/ws_protocol/index.html +++ b/docs/en/cowboy/2.1/guide/ws_protocol/index.html @@ -62,70 +62,22 @@

The Websocket protocol

-

This chapter explains what Websocket is and why it is -a vital component of soft realtime Web applications.

-
+

This chapter explains what Websocket is and why it is a vital component of soft realtime Web applications.

Description

-
-

Websocket is an extension to HTTP that emulates plain TCP -connections between the client, typically a Web browser, -and the server. It uses the HTTP Upgrade mechanism to -establish the connection.

-

Websocket connections are fully asynchronous, unlike -HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the -server can only initiate streams in response to requests). -With Websocket, the client and the server can both send -frames at any time without any restriction. It is closer -to TCP than any of the HTTP protocols.

-

Websocket is an IETF standard. Cowboy supports the standard -and all drafts that were previously implemented by browsers, -excluding the initial flawed draft sometimes known as -"version 0".

-
-
-
+

Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection.

+

Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). With Websocket, the client and the server can both send frames at any time without any restriction. It is closer to TCP than any of the HTTP protocols.

+

Websocket is an IETF standard. Cowboy supports the standard and all drafts that were previously implemented by browsers, excluding the initial flawed draft sometimes known as "version 0".

Websocket vs HTTP/2

-
-

For a few years Websocket was the only way to have a -bidirectional asynchronous connection with the server. -This changed when HTTP/2 was introduced. While HTTP/2 -requires the client to first perform a request before -the server can push data, this is only a minor restriction -as the client can do so just as it connects.

-

Websocket was designed as a kind-of-TCP channel to a -server. It only defines the framing and connection -management and lets the developer implement a protocol -on top of it. For example you could implement IRC over -Websocket and use a Javascript IRC client to speak to -the server.

-

HTTP/2 on the other hand is just an improvement over -the HTTP/1.1 connection and request/response mechanism. -It has the same semantics as HTTP/1.1.

-

If all you need is to access an HTTP API, then HTTP/2 -should be your first choice. On the other hand, if what -you need is a different protocol, then you can use -Websocket to implement it.

-
-
-
+

For a few years Websocket was the only way to have a bidirectional asynchronous connection with the server. This changed when HTTP/2 was introduced. While HTTP/2 requires the client to first perform a request before the server can push data, this is only a minor restriction as the client can do so just as it connects.

+

Websocket was designed as a kind-of-TCP channel to a server. It only defines the framing and connection management and lets the developer implement a protocol on top of it. For example you could implement IRC over Websocket and use a Javascript IRC client to speak to the server.

+

HTTP/2 on the other hand is just an improvement over the HTTP/1.1 connection and request/response mechanism. It has the same semantics as HTTP/1.1.

+

If all you need is to access an HTTP API, then HTTP/2 should be your first choice. On the other hand, if what you need is a different protocol, then you can use Websocket to implement it.

Implementation

-
-

Cowboy implements Websocket as a protocol upgrade. Once the -upgrade is performed from the init/2 callback, Cowboy -switches to Websocket. Please consult the next chapter for -more information on initiating and handling Websocket -connections.

-

The implementation of Websocket in Cowboy is validated using -the Autobahn test suite, which is an extensive suite of tests -covering all aspects of the protocol. Cowboy passes the -suite with 100% success, including all optional tests.

-

Cowboy’s Websocket implementation also includes the -permessage-deflate and x-webkit-deflate-frame compression -extensions.

-

Cowboy will automatically use compression when the -compress option is returned from the init/2 function.

-
-
+

Cowboy implements Websocket as a protocol upgrade. Once the upgrade is performed from the init/2 callback, Cowboy switches to Websocket. Please consult the next chapter for more information on initiating and handling Websocket connections.

+

The implementation of Websocket in Cowboy is validated using the Autobahn test suite, which is an extensive suite of tests covering all aspects of the protocol. Cowboy passes the suite with 100% success, including all optional tests.

+

Cowboy's Websocket implementation also includes the permessage-deflate and x-webkit-deflate-frame compression extensions.

+

Cowboy will automatically use compression when the compress option is returned from the init/2 function.

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy.set_env/index.html b/docs/en/cowboy/2.1/manual/cowboy.set_env/index.html index 94ab14c2..684e90a7 100644 --- a/docs/en/cowboy/2.1/manual/cowboy.set_env/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy.set_env/index.html @@ -62,117 +62,59 @@

cowboy:set_env(3)

-

Name

-
-

cowboy:set_env - Update a listener’s environment value

-
-
-
+

cowboy:set_env - Update a listener's environment value

Description

-
-
-
-
set_env(Name  :: ranch:ref(),
-        Key   :: atom(),
-        Value :: any())
-    -> ok
-

Set or update an environment value for a previously started -listener.

-

This is most useful for updating the routes dynamically, -without having to restart the listener.

-

The new value will only be available to new connections. -Pre-existing connections will still use the old value.

-
-
-
+
set_env(Name  :: ranch:ref(),
+        Key   :: atom(),
+        Value :: any())
+    -> ok
+
+

Set or update an environment value for a previously started listener.

+

This is most useful for updating the routes dynamically, without having to restart the listener.

+

The new value will only be available to new connections. Pre-existing connections will still use the old value.

Arguments

-
-
-
-Name -
-
-

-The name of the listener to update. -

-

The name of the listener is the first argument given to the -cowboy:start_clear(3), -cowboy:start_tls(3) or -ranch:start_listener(3) function.

+
Name
+

The name of the listener to update.

+

The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function.

-
-Key -
-
-

-The key in the environment map. Common keys include dispatch -and middlewares. -

+
Key
+

The key in the environment map. Common keys include dispatch and middlewares.

-
-Value -
-
-

-The new value. -

-

The type of the value differs depending on the key.

+
Value
+

The new value.

+

The type of the value differs depending on the key.

-
-
- -
+

Return value

-
-

The atom ok is returned on success.

-

An exit:badarg exception is thrown when the listener does -not exist.

-
-
-
+

The atom ok is returned on success.

+

An exit:badarg exception is thrown when the listener does not exist.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Update a listener’s routes
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []},
-        {"/ws", websocket_h, []}
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []},
+        {"/ws", websocket_h, []}
     ]}
 ]),
 
-cowboy:set_env(example, dispatch, Dispatch).
-
-
-
+cowboy:set_env(example, dispatch, Dispatch). +

See also

- - +

cowboy(3), cowboy:start_clear(3), cowboy:start_tls(3), ranch:set_protocol_options(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy.start_clear/index.html b/docs/en/cowboy/2.1/manual/cowboy.start_clear/index.html index b5268e08..d20c97c5 100644 --- a/docs/en/cowboy/2.1/manual/cowboy.start_clear/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy.start_clear/index.html @@ -62,148 +62,77 @@

cowboy:start_clear(3)

-

Name

-
-

cowboy:start_clear - Listen for connections using plain TCP

-
-
-
+

cowboy:start_clear - Listen for connections using plain TCP

Description

-
-
-
-
start_clear(Name          :: ranch:ref(),
-            TransportOpts :: ranch_tcp:opts(),
-            ProtocolOpts  :: opts())
-    -> {ok, ListenerPid :: pid()}
-     | {error, any()}
-

Start listening for connections over a clear TCP channel.

-

Both HTTP/1.1 and HTTP/2 are supported on this listener. -HTTP/2 has two methods of establishing a connection over -a clear TCP channel. Both the upgrade and the prior knowledge -methods are supported.

-
-
-
+
start_clear(Name          :: ranch:ref(),
+            TransportOpts :: ranch_tcp:opts(),
+            ProtocolOpts  :: opts())
+    -> {ok, ListenerPid :: pid()}
+     | {error, any()}
+
+

Start listening for connections over a clear TCP channel.

+

Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported.

Arguments

-
-
-
-Name -
-
-

-The listener name is used to refer to this listener in -future calls, for example when stopping it or when -updating the routes defined. -

-

It can be any Erlang term. An atom is generally good enough, -for example api, my_app_clear or my_app_tls.

+
Name
+

The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined.

+

It can be any Erlang term. An atom is generally good enough, for example api, my_app_clear or my_app_tls.

-
-TransportOpts -
-
-

-The transport options are where the TCP options, including -the listener’s port number, are defined. Transport options -are provided as a list of keys and values, for example -[{port, 8080}]. -

-

The available options are documented in the -ranch_tcp(3) manual.

+
TransportOpts
+

The transport options are where the TCP options, including the listener's port number, are defined. Transport options are provided as a list of keys and values, for example [{port, 8080}].

+

The available options are documented in the ranch_tcp(3) manual.

-
-ProtocolOpts -
-
-

-The protocol options are in a map containing all the options for -the different protocols that may be involved when connecting -to the listener, including HTTP/1.1 and HTTP/2. -

-

The HTTP/1.1 options are documented in the -cowboy_http(3) manual; -and the HTTP/2 options in -cowboy_http2(3).

+
ProtocolOpts
+

The protocol options are in a map containing all the options for the different protocols that may be involved when connecting to the listener, including HTTP/1.1 and HTTP/2.

+

The HTTP/1.1 options are documented in the cowboy_http(3) manual; and the HTTP/2 options in cowboy_http2(3).

-
-
- -
+

Return value

-
-

An ok tuple is returned on success. It contains the pid of -the top-level supervisor for the listener.

-

An error tuple is returned on error. The error reason may -be any Erlang term.

-

A common error is eaddrinuse. It indicates that the port -configured for Cowboy is already in use.

-
-
-
+

An ok tuple is returned on success. It contains the pid of the top-level supervisor for the listener.

+

An error tuple is returned on error. The error reason may be any Erlang term.

+

A common error is eaddrinuse. It indicates that the port configured for Cowboy is already in use.

Changelog

-
-
    -
  • -

    -2.0: HTTP/2 support added. -

    +
    • 2.0: HTTP/2 support added.
    • -
    • -

      -2.0: Function introduced. Replaces cowboy:start_http/4. -

      +
    • 2.0: Function introduced. Replaces cowboy:start_http/4.
    • -
-
-
-
+

Examples

-
-
-
Start a listener
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []}
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []}
     ]}
 ]),
 
-{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{
-    env => #{dispatch => Dispatch}
-}).
-
-
Start a listener on a random port
-
-
Name = example,
+
Name = example,
 
-{ok, _} = cowboy:start_clear(Name, [], #{
-    env => #{dispatch => Dispatch}
+{ok, _} = cowboy:start_clear(Name, [], #{
+    env => #{dispatch => Dispatch}
 }),
 
-Port = ranch:get_port(Name).
-
-
-
+Port = ranch:get_port(Name). +

See also

- - +

cowboy(3), cowboy:start_tls(3), cowboy:stop_listener(3), ranch(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy.start_tls/index.html b/docs/en/cowboy/2.1/manual/cowboy.start_tls/index.html index 63b6227a..33469ef1 100644 --- a/docs/en/cowboy/2.1/manual/cowboy.start_tls/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy.start_tls/index.html @@ -62,153 +62,82 @@

cowboy:start_tls(3)

-

Name

-
-

cowboy:start_tls - Listen for connections using TLS

-
-
-
+

cowboy:start_tls - Listen for connections using TLS

Description

-
-
-
-
start_tls(Name          :: ranch:ref(),
-          TransportOpts :: ranch_ssl:opts(),
-          ProtocolOpts  :: opts())
-    -> {ok, ListenerPid :: pid()}
-     | {error, any()}
-

Start listening for connections over a secure TLS channel.

-

Both HTTP/1.1 and HTTP/2 are supported on this listener. -The ALPN TLS extension must be used to initiate an HTTP/2 -connection.

-
-
-
+
start_tls(Name          :: ranch:ref(),
+          TransportOpts :: ranch_ssl:opts(),
+          ProtocolOpts  :: opts())
+    -> {ok, ListenerPid :: pid()}
+     | {error, any()}
+
+

Start listening for connections over a secure TLS channel.

+

Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection.

Arguments

-
-
-
-Name -
-
-

-The listener name is used to refer to this listener in -future calls, for example when stopping it or when -updating the routes defined. -

-

It can be any Erlang term. An atom is generally good enough, -for example api, my_app_clear or my_app_tls.

+
Name
+

The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined.

+

It can be any Erlang term. An atom is generally good enough, for example api, my_app_clear or my_app_tls.

-
-TransportOpts -
-
-

-The transport options are where the TCP options, including -the listener’s port number, are defined. They also contain -the TLS options, like the server’s certificate. Transport options -are provided as a list of keys and values, for example -[{port, 8443}, {certfile, "path/to/cert.pem"}]. -

-

The available options are documented in the -ranch_ssl(3) manual.

+
TransportOpts
+

The transport options are where the TCP options, including the listener's port number, are defined. They also contain the TLS options, like the server's certificate. Transport options are provided as a list of keys and values, for example [{port, 8443}, {certfile, "path/to/cert.pem"}].

+

The available options are documented in the ranch_ssl(3) manual.

-
-ProtocolOpts -
-
-

-The protocol options are in a map containing all the options for -the different protocols that may be involved when connecting -to the listener, including HTTP/1.1 and HTTP/2. -

-

The HTTP/1.1 options are documented in the -cowboy_http(3) manual; -and the HTTP/2 options in -cowboy_http2(3).

+
ProtocolOpts
+

The protocol options are in a map containing all the options for the different protocols that may be involved when connecting to the listener, including HTTP/1.1 and HTTP/2.

+

The HTTP/1.1 options are documented in the cowboy_http(3) manual; and the HTTP/2 options in cowboy_http2(3).

-
-
- -
+

Return value

-
-

An ok tuple is returned on success. It contains the pid of -the top-level supervisor for the listener.

-

An error tuple is returned on error. The error reason may -be any Erlang term.

-

A common error is eaddrinuse. It indicates that the port -configured for Cowboy is already in use.

-
-
-
+

An ok tuple is returned on success. It contains the pid of the top-level supervisor for the listener.

+

An error tuple is returned on error. The error reason may be any Erlang term.

+

A common error is eaddrinuse. It indicates that the port configured for Cowboy is already in use.

Changelog

-
-
    -
  • -

    -2.0: HTTP/2 support added. -

    +
    • 2.0: HTTP/2 support added.
    • -
    • -

      -2.0: Function introduced. Replaces cowboy:start_https/4. -

      +
    • 2.0: Function introduced. Replaces cowboy:start_https/4.
    • -
-
-
-
+

Examples

-
-
-
Start a listener
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []}
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []}
     ]}
 ]),
 
-{ok, _} = cowboy:start_tls(example, [
-    {port, 8443},
-    {cert, "path/to/cert.pem"}
+{ok, _} = cowboy:start_tls(example, [
+    {port, 8443},
+    {cert, "path/to/cert.pem"}
 ], #{
-    env => #{dispatch => Dispatch}
-}).
-
-
Start a listener on a random port
-
-
Name = example,
+
Name = example,
 
-{ok, _} = cowboy:start_tls(Name, [
-    {cert, "path/to/cert.pem"}
+{ok, _} = cowboy:start_tls(Name, [
+    {cert, "path/to/cert.pem"}
 ], #{
-    env => #{dispatch => Dispatch}
+    env => #{dispatch => Dispatch}
 }),
 
-Port = ranch:get_port(Name).
-
-
-
+Port = ranch:get_port(Name). +

See also

- - +

cowboy(3), cowboy:start_clear(3), cowboy:stop_listener(3), ranch(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy.stop_listener/index.html b/docs/en/cowboy/2.1/manual/cowboy.stop_listener/index.html index 52b2bacc..7274f27c 100644 --- a/docs/en/cowboy/2.1/manual/cowboy.stop_listener/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy.stop_listener/index.html @@ -62,87 +62,42 @@

cowboy:stop_listener(3)

-

Name

-
-

cowboy:stop_listener - Stop the given listener

-
-
-
+

cowboy:stop_listener - Stop the given listener

Description

-
-
-
-
stop_listener(Name :: ranch:ref())
-    -> ok | {error, not_found}.
-

Stop a previously started listener.

- -
-
-
+
stop_listener(Name :: ranch:ref())
+    -> ok | {error, not_found}.
+
+

Stop a previously started listener.

+

Alias of ranch:stop_listener(3).

Arguments

-
-
-
-Name -
-
-

-The name of the listener to be stopped. -

-

The name of the listener is the first argument given to the -cowboy:start_clear(3), -cowboy:start_tls(3) or -ranch:start_listener(3) function.

+
Name
+

The name of the listener to be stopped.

+

The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function.

-
-
- -
+

Return value

-
-

The atom ok is returned on success.

-

The {error, not_found} tuple is returned when the listener -does not exist.

-
-
-
+

The atom ok is returned on success.

+

The {error, not_found} tuple is returned when the listener does not exist.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Stop a listener
-
-
ok = cowboy:stop_listener(example).
-
-
-
+
ok = cowboy:stop_listener(example).
+

See also

- - +

cowboy(3), cowboy:start_clear(3), cowboy:start_tls(3), ranch(3), ranch:start_listener(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy/index.html b/docs/en/cowboy/2.1/manual/cowboy/index.html index 7caa8dc0..078f560f 100644 --- a/docs/en/cowboy/2.1/manual/cowboy/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy/index.html @@ -62,129 +62,76 @@

cowboy(3)

-

Name

-
-

cowboy - HTTP server

-
-
-
+

cowboy - HTTP server

Description

-
-

The module cowboy provides convenience functions for -manipulating Ranch listeners.

-
-
-
+

The module cowboy provides convenience functions for manipulating Ranch listeners.

Exports

-
-
-
-
-
+

Types

-
-

fields()

-
-
-
fields() :: [Name
-           | {Name, Constraints}
-           | {Name, Constraints, Default}]
-
-Name        :: atom()
-Constraints :: Constraint | [Constraint]
-Constraint  :: cowboy_constraints:constraint()
-Default     :: any()
-

Fields description for match operations.

-

This type is used in cowboy_router(3) -for matching bindings and in the match functions found in -cowboy_req(3).

-
-
+
fields() :: [Name
+           | {Name, Constraints}
+           | {Name, Constraints, Default}]
+
+Name        :: atom()
+Constraints :: Constraint | [Constraint]
+Constraint  :: cowboy_constraints:constraint()
+Default     :: any()
+
+

Fields description for match operations.

+

This type is used in cowboy_router(3) for matching bindings and in the match functions found in cowboy_req(3).

http_headers()

-
-
-
http_headers() :: #{binary() => iodata()}
-

HTTP headers.

-
-
+
http_headers() :: #{binary() => iodata()}
+
+

HTTP headers.

http_status()

-
-
-
http_status() :: non_neg_integer() | binary()
-

HTTP response status.

-

A binary status can be used to set a reason phrase. Note -however that HTTP/2 only sends the status code and drops -the reason phrase entirely.

- -
+
http_status() :: non_neg_integer() | binary()
+
+

HTTP response status.

+

A binary status can be used to set a reason phrase. Note however that HTTP/2 only sends the status code and drops the reason phrase entirely.

http_version()

-
-
-
http_version() :: 'HTTP/2' | 'HTTP/1.1' | 'HTTP/1.0'
-

HTTP version.

-

Note that semantically, HTTP/1.1 and HTTP/2 are equivalent.

- -
+
http_version() :: 'HTTP/2' | 'HTTP/1.1' | 'HTTP/1.0'
+
+

HTTP version.

+

Note that semantically, HTTP/1.1 and HTTP/2 are equivalent.

opts()

-
-
-
opts() :: map()
-

Options for the HTTP/1.1, HTTP/2 and Websocket protocols.

-

The protocol options are in a map containing all the options for -the different protocols that may be involved when connecting -to the listener, including HTTP/1.1 and HTTP/2.

-

The HTTP/1.1 options are documented in the -cowboy_http(3) manual -and the HTTP/2 options in -cowboy_http2(3).

- - - -
+
opts() :: map()
+
+

Options for the HTTP/1.1, HTTP/2 and Websocket protocols.

+

The protocol options are in a map containing all the options for the different protocols that may be involved when connecting to the listener, including HTTP/1.1 and HTTP/2.

+

The HTTP/1.1 options are documented in the cowboy_http(3) manual and the HTTP/2 options in cowboy_http2(3).

See also

- - +

cowboy(7), ranch(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_app/index.html b/docs/en/cowboy/2.1/manual/cowboy_app/index.html index b3ae0707..44c4d65d 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_app/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_app/index.html @@ -62,171 +62,77 @@

cowboy(7)

-

Name

-
-

cowboy - Small, fast, modern HTTP server for Erlang/OTP

-
-
-
+

cowboy - Small, fast, modern HTTP server for Erlang/OTP

Description

-
-

Cowboy is an HTTP server for Erlang/OTP with support for the -HTTP/1.1, HTTP/2 and Websocket protocols.

-

Cowboy aims to provide a complete HTTP stack. This includes -the implementation of the HTTP RFCs but also any directly -related standards, like Websocket or Server-Sent Events.

-
-
-
+

Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols.

+

Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events.

Modules

-
-

Functions:

-
-

Protocols:

-
+

Protocols:

+
-

Handlers:

-
+

Handlers:

+
-

Behaviors:

-
+

Behaviors:

+
-

Middlewares:

-
+

Middlewares:

+
-
-
-
+ +

Dependencies

-
-
    -
  • -

    -ranch(7) - Socket acceptor pool for TCP protocols -

    +
    • ranch(7) - Socket acceptor pool for TCP protocols
    • -
    • -

      -cowlib(7) - Support library for manipulating Web protocols -

      +
    • cowlib(7) - Support library for manipulating Web protocols
    • -
    • -

      -ssl - Secure communication over sockets -

      +
    • ssl - Secure communication over sockets
    • -
    • -

      -crypto - Crypto functions -

      +
    • crypto - Crypto functions
    • -
-

All these applications must be started before the cowboy -application. To start Cowboy and all dependencies at once:

-
-
-
{ok, _} = application:ensure_all_started(cowboy).
-
-
-
+
{ok, _} = application:ensure_all_started(cowboy).
+

Environment

-
-

The cowboy application does not define any application -environment configuration parameters.

-
- -
+

The cowboy application does not define any application environment configuration parameters.

See also

- -
+

ranch(7), cowlib(7)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_constraints.int/index.html b/docs/en/cowboy/2.1/manual/cowboy_constraints.int/index.html index 5d35efd4..a4dd8866 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_constraints.int/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_constraints.int/index.html @@ -62,92 +62,52 @@

cowboy_constraints:int(3)

-

Name

-
-

cowboy_constraints:int - Integer constraint

-
-
-
+

cowboy_constraints:int - Integer constraint

Description

-
-

Constraint functions implement a number of different operations.

-
-
-
int(forward, Bin) -> {ok, Int} | {error, not_an_integer}
+
int(forward, Bin) -> {ok, Int} | {error, not_an_integer}
 
-Bin :: binary()
-Int :: integer()
-

Validate and convert the text representation of an integer.

-
-
-
int(reverse, Int) -> {ok, Bin} | {error, not_an_integer}
-

Convert an integer back to its text representation.

-
-
-
int(format_error, Error) -> HumanReadable
+
int(format_error, Error) -> HumanReadable
 
-Error         :: {not_an_integer, Bin | Int}
-HumanReadable :: iolist()
-

Generate a human-readable error message.

-
-
-
+Error :: {not_an_integer, Bin | Int} +HumanReadable :: iolist() +
+

Generate a human-readable error message.

Arguments

-
-

Arguments vary depending on the operation. Constraint -functions always take the operation type as first argument, -and the value as second argument.

-
- -
+

Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument.

Return value

-
-

The return value varies depending on the operation.

-
-
-
+

The return value varies depending on the operation.

Changelog

-
-
    -
  • -

    -2.0: Interface modified to allow for a variety of operations. -

    +
    • 2.0: Interface modified to allow for a variety of operations.
    • -
    • -

      -1.0: Constraint introduced. -

      +
    • 1.0: Constraint introduced.
    • -
-
-
-
+

Examples

-
-

This function is not meant to be called directly.

-
-
-
+

This function is not meant to be called directly.

See also

- -
+

cowboy_constraints(3), cowboy_constraints:nonempty(3), cowboy_router(3), cowboy_req:match_cookies(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_constraints.nonempty/index.html b/docs/en/cowboy/2.1/manual/cowboy_constraints.nonempty/index.html index 6134e88f..fed24ccc 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_constraints.nonempty/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_constraints.nonempty/index.html @@ -62,91 +62,51 @@

cowboy_constraints:nonempty(3)

-

Name

-
-

cowboy_constraints:nonempty - Non-empty constraint

-
-
-
+

cowboy_constraints:nonempty - Non-empty constraint

Description

-
-

Constraint functions implement a number of different operations.

-
-
-
nonempty(forward | reverse, <<>>) -> {error, empty}
-

Reject empty values.

-
-
-
nonempty(forward | reverse, Bin) -> {ok, Bin}
+
nonempty(forward | reverse, Bin) -> {ok, Bin}
 
-Bin :: binary()
-

Accept any other binary values.

-
-
-
nonempty(format_error, Error) -> HumanReadable
+
nonempty(format_error, Error) -> HumanReadable
 
-Error         :: {empty, Bin}
-HumanReadable :: iolist()
-

Generate a human-readable error message.

-
-
-
+Error :: {empty, Bin} +HumanReadable :: iolist() +
+

Generate a human-readable error message.

Arguments

-
-

Arguments vary depending on the operation. Constraint -functions always take the operation type as first argument, -and the value as second argument.

-
- -
+

Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument.

Return value

-
-

The return value varies depending on the operation.

-
-
-
+

The return value varies depending on the operation.

Changelog

-
-
    -
  • -

    -2.0: Interface modified to allow for a variety of operations. -

    +
    • 2.0: Interface modified to allow for a variety of operations.
    • -
    • -

      -1.0: Constraint introduced. -

      +
    • 1.0: Constraint introduced.
    • -
-
-
-
+

Examples

-
-

This function is not meant to be called directly.

-
-
-
+

This function is not meant to be called directly.

See also

- -
+

cowboy_constraints(3), cowboy_constraints:int(3), cowboy_router(3), cowboy_req:match_cookies(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_constraints/index.html b/docs/en/cowboy/2.1/manual/cowboy_constraints/index.html index 9776040e..20892d27 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_constraints/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_constraints/index.html @@ -62,84 +62,43 @@

cowboy_constraints(3)

-

Name

-
-

cowboy_constraints - Constraints

-
-
-
+

cowboy_constraints - Constraints

Description

-
-

The module cowboy_constraints defines the built-in -constraints in Cowboy and provides an interface for -manipulating these constraints.

-

Constraints are functions that define what type of -input is allowed. They are used throughout Cowboy, -from the router to query strings to cookies.

-
-
-
+

The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints.

+

Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies.

Exports

-
-

Built-in constraints:

-
-
-
-
+

Types

-
-

constraint()

-
-
-
constraint() :: int | nonempty | fun()
-

A constraint function.

-

The atom constraints are built-in, see the corresponding -function in the exports list above.

-
-
+
constraint() :: int | nonempty | fun()
+
+

A constraint function.

+

The atom constraints are built-in, see the corresponding function in the exports list above.

reason()

-
-
-
reason() :: {constraint(), Reason, Value}
-
-Reason :: any()
-Value  :: any()
-

Reason for the constraint failure.

-

It includes the constraint function in question, -a machine-readable error reason and the value that -made the constraint fail.

-
- - -
+
reason() :: {constraint(), Reason, Value}
+
+Reason :: any()
+Value  :: any()
+
+

Reason for the constraint failure.

+

It includes the constraint function in question, a machine-readable error reason and the value that made the constraint fail.

See also

- - +

cowboy(7), cowboy(3), cowboy_router(3), cowboy_req:match_cookies(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_handler.terminate/index.html b/docs/en/cowboy/2.1/manual/cowboy_handler.terminate/index.html index 9a6092ff..97ff596b 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_handler.terminate/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_handler.terminate/index.html @@ -62,109 +62,54 @@

cowboy_handler:terminate(3)

-

Name

-
-

cowboy_handler:terminate - Terminate the handler

-
-
-
+

cowboy_handler:terminate - Terminate the handler

Description

-
-
-
-
terminate(Reason, PartialReq, State, Handler) -> ok
-
-Reason     :: any()
-PartialReq :: map()
-State      :: any()
-Handler    :: module()
-

Call the optional terminate callback if it is defined.

-

Make sure to use this function at the end of the execution -of modules that implement custom handler behaviors.

-
-
-
+
terminate(Reason, PartialReq, State, Handler) -> ok
+
+Reason     :: any()
+PartialReq :: map()
+State      :: any()
+Handler    :: module()
+
+

Call the optional terminate callback if it is defined.

+

Make sure to use this function at the end of the execution of modules that implement custom handler behaviors.

Arguments

-
-
-
-Reason -
-
-

-Reason for termination. -

+
Reason
+

Reason for termination.

-
-PartialReq -
-
-

-The Req object. -

-

It is possible to remove fields from the Req object to save memory -when the handler has no concept of requests/responses. The only -requirement is that a map is provided.

+
PartialReq
+

The Req object.

+

It is possible to remove fields from the Req object to save memory when the handler has no concept of requests/responses. The only requirement is that a map is provided.

-
-State -
-
-

-Handler state. -

+
State
+

Handler state.

-
-Handler -
-
-

-Handler module. -

+
Handler
+

Handler module.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Terminate a handler normally
-
-
cowboy_handler:terminate(normal, Req, State, Handler).
-
-
-
+
cowboy_handler:terminate(normal, Req, State, Handler).
+

See also

- - +

cowboy_handler(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_handler/index.html b/docs/en/cowboy/2.1/manual/cowboy_handler/index.html index b1fa30ee..1d1f3185 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_handler/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_handler/index.html @@ -62,96 +62,46 @@

cowboy_handler(3)

-

Name

-
-

cowboy_handler - Plain HTTP handlers

-
-
-
+

cowboy_handler - Plain HTTP handlers

Description

-
-

The cowboy_handler middleware executes the handler selected -by the router or any other preceding middleware.

-

This middleware takes the handler module and initial state -from the handler and handler_opts environment values, -respectively. On completion, it adds a result value to -the middleware environment, containing the return value -of the terminate/3 callback (if defined) and ok otherwise.

-

This module also defines a callback interface for handling -HTTP requests.

-
-
-
+

The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware.

+

This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise.

+

This module also defines a callback interface for handling HTTP requests.

Callbacks

-
-

Plain HTTP handlers implement the following interface:

-
-
-
init(Req, State) -> {ok, Req, State}
-
-terminate(Reason, Req, State) -> ok  %% optional
-
-Req    :: cowboy_req:req()
-State  :: any()
-Reason :: normal
-        | {crash, error | exit | throw, any()}
-

These two callbacks are common to all handlers.

-

Plain HTTP handlers do all their work in the init/2 -callback. Returning ok terminates the handler. If no -response is sent, Cowboy will send a 204 No Content.

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the handler. -Cowboy will terminate the process right after this. There -is no need to perform any cleanup in this callback.

-

The following terminate reasons are defined for plain HTTP -handlers:

-
-
-normal -
-
-

- The connection was closed normally. -

+
init(Req, State) -> {ok, Req, State}
+
+terminate(Reason, Req, State) -> ok  %% optional
+
+Req    :: cowboy_req:req()
+State  :: any()
+Reason :: normal
+        | {crash, error | exit | throw, any()}
+
+

These two callbacks are common to all handlers.

+

Plain HTTP handlers do all their work in the init/2 callback. Returning ok terminates the handler. If no response is sent, Cowboy will send a 204 No Content.

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the handler. Cowboy will terminate the process right after this. There is no need to perform any cleanup in this callback.

+

The following terminate reasons are defined for plain HTTP handlers:

+
normal
+

The connection was closed normally.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
- - -
+

Exports

-
-

The following function should be called by modules implementing -custom handlers to execute the optional terminate callback:

-
-
-
-
+

See also

- -
+

cowboy(7)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_http/index.html b/docs/en/cowboy/2.1/manual/cowboy_http/index.html index 3d6bf3d3..f05ff949 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_http/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_http/index.html @@ -62,240 +62,110 @@

cowboy_http(3)

-

Name

-
-

cowboy_http - HTTP/1.1

-
-
-
+

cowboy_http - HTTP/1.1

Description

-
-

The module cowboy_http implements HTTP/1.1 and HTTP/1.0 -as a Ranch protocol.

-
-
-
+

The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol.

Options

-
-
-
+ +
-
opts() :: #{
-    connection_type         => worker | supervisor,
-    env                     => cowboy_middleware:env(),
-    idle_timeout            => timeout(),
-    inactivity_timeout      => timeout(),
-    max_empty_lines         => non_neg_integer(),
-    max_header_name_length  => non_neg_integer(),
-    max_header_value_length => non_neg_integer(),
-    max_headers             => non_neg_integer(),
-    max_keepalive           => non_neg_integer(),
-    max_method_length       => non_neg_integer(),
-    max_request_line_length => non_neg_integer(),
-    middlewares             => [module()],
-    request_timeout         => timeout(),
-    shutdown_timeout        => timeout(),
-    stream_handlers         => [module()]
-}
-

Configuration for the HTTP/1.1 protocol.

-

This configuration is passed to Cowboy when starting listeners -using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

-

It can be updated without restarting listeners using the -Ranch functions ranch:get_protocol_options/1 and -ranch:set_protocol_options/2.

-

The default value is given next to the option name:

-
-
-connection_type (supervisor) -
-
-

- Whether the connection process also acts as a supervisor. -

+
opts() :: #{
+    connection_type         => worker | supervisor,
+    env                     => cowboy_middleware:env(),
+    idle_timeout            => timeout(),
+    inactivity_timeout      => timeout(),
+    max_empty_lines         => non_neg_integer(),
+    max_header_name_length  => non_neg_integer(),
+    max_header_value_length => non_neg_integer(),
+    max_headers             => non_neg_integer(),
+    max_keepalive           => non_neg_integer(),
+    max_method_length       => non_neg_integer(),
+    max_request_line_length => non_neg_integer(),
+    middlewares             => [module()],
+    request_timeout         => timeout(),
+    shutdown_timeout        => timeout(),
+    stream_handlers         => [module()]
+}
+
+

Configuration for the HTTP/1.1 protocol.

+

This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

+

It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2.

+

The default value is given next to the option name:

+
connection_type (supervisor)
+

Whether the connection process also acts as a supervisor.

-
-env (#{}) -
-
-

- Middleware environment. -

+
env (#{})
+

Middleware environment.

-
-idle_timeout (60000) -
-
-

- Time in ms with no data received before Cowboy closes the connection. -

+
idle_timeout (60000)
+

Time in ms with no data received before Cowboy closes the connection.

-
-inactivity_timeout (300000) -
-
-

- Time in ms with nothing received at all before Cowboy closes the connection. -

+
inactivity_timeout (300000)
+

Time in ms with nothing received at all before Cowboy closes the connection.

-
-max_empty_lines (5) -
-
-

- Maximum number of empty lines before a request. -

+
max_empty_lines (5)
+

Maximum number of empty lines before a request.

-
-max_header_name_length (64) -
-
-

- Maximum length of header names. -

+
max_header_name_length (64)
+

Maximum length of header names.

-
-max_header_value_length (4096) -
-
-

- Maximum length of header values. -

+
max_header_value_length (4096)
+

Maximum length of header values.

-
-max_headers (100) -
-
-

- Maximum number of headers allowed per request. -

+
max_headers (100)
+

Maximum number of headers allowed per request.

-
-max_keepalive (100) -
-
-

- Maximum number of requests allowed per connection. -

+
max_keepalive (100)
+

Maximum number of requests allowed per connection.

-
-max_method_length (32) -
-
-

- Maximum length of the method. -

+
max_method_length (32)
+

Maximum length of the method.

-
-max_request_line_length (8000) -
-
-

- Maximum length of the request line. -

+
max_request_line_length (8000)
+

Maximum length of the request line.

-
-middlewares ([cowboy_router, cowboy_handler]) -
-
-

- Middlewares to run for every request. -

+
middlewares ([cowboy_router, cowboy_handler])
+

Middlewares to run for every request.

-
-request_timeout (5000) -
-
-

- Time in ms with no requests before Cowboy closes the connection. -

+
request_timeout (5000)
+

Time in ms with no requests before Cowboy closes the connection.

-
-shutdown_timeout (5000) -
-
-

- Time in ms Cowboy will wait for child processes to shut down before killing them. -

+
shutdown_timeout (5000)
+

Time in ms Cowboy will wait for child processes to shut down before killing them.

-
-stream_handlers ([cowboy_stream_h]) -
-
-

- Ordered list of stream handlers that will handle all stream events. -

+
stream_handlers ([cowboy_stream_h])
+

Ordered list of stream handlers that will handle all stream events.

-
-
-
-
+

Changelog

-
-
    -
  • -

    -2.0: The timeout option was renamed request_timeout. -

    +
    • 2.0: The timeout option was renamed request_timeout.
    • -
    • -

      -2.0: The idle_timeout, inactivity_timeout and shutdown_timeout options were added. -

      +
    • 2.0: The idle_timeout, inactivity_timeout and shutdown_timeout options were added.
    • -
    • -

      -2.0: The max_method_length option was added. -

      +
    • 2.0: The max_method_length option was added.
    • -
    • -

      -2.0: The max_request_line_length default was increased from 4096 to 8000. -

      +
    • 2.0: The max_request_line_length default was increased from 4096 to 8000.
    • -
    • -

      -2.0: The connection_type option was added. -

      +
    • 2.0: The connection_type option was added.
    • -
    • -

      -2.0: The env option is now a map instead of a proplist. -

      +
    • 2.0: The env option is now a map instead of a proplist.
    • -
    • -

      -2.0: The stream_handlers option was added. -

      +
    • 2.0: The stream_handlers option was added.
    • -
    • -

      -2.0: The compress option was removed in favor of the cowboy_compress_h stream handler. -

      +
    • 2.0: The compress option was removed in favor of the cowboy_compress_h stream handler.
    • -
    • -

      -2.0: Options are now a map instead of a proplist. -

      +
    • 2.0: Options are now a map instead of a proplist.
    • -
    • -

      -2.0: Protocol introduced. Replaces cowboy_protocol. -

      +
    • 2.0: Protocol introduced. Replaces cowboy_protocol.
    • -
-
-
- +

cowboy(7), cowboy_http2(3), cowboy_websocket(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_http2/index.html b/docs/en/cowboy/2.1/manual/cowboy_http2/index.html index 29016fa0..2a48eec9 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_http2/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_http2/index.html @@ -62,123 +62,60 @@

cowboy_http2(3)

-

Name

-
-

cowboy_http2 - HTTP/2

-
-
-
+

cowboy_http2 - HTTP/2

Description

-
-

The module cowboy_http2 implements HTTP/2 -as a Ranch protocol.

-
-
-
+

The module cowboy_http2 implements HTTP/2 as a Ranch protocol.

Options

-
-
-
+ +
-
opts() :: #{
-    connection_type    => worker | supervisor,
-    env                => cowboy_middleware:env(),
-    inactivity_timeout => timeout(),
-    middlewares        => [module()],
-    preface_timeout    => timeout(),
-    shutdown_timeout   => timeout(),
-    stream_handlers    => [module()]
-}
-

Configuration for the HTTP/2 protocol.

-

This configuration is passed to Cowboy when starting listeners -using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

-

It can be updated without restarting listeners using the -Ranch functions ranch:get_protocol_options/1 and -ranch:set_protocol_options/2.

-

The default value is given next to the option name:

-
-
-connection_type (supervisor) -
-
-

- Whether the connection process also acts as a supervisor. -

+
opts() :: #{
+    connection_type    => worker | supervisor,
+    env                => cowboy_middleware:env(),
+    inactivity_timeout => timeout(),
+    middlewares        => [module()],
+    preface_timeout    => timeout(),
+    shutdown_timeout   => timeout(),
+    stream_handlers    => [module()]
+}
+
+

Configuration for the HTTP/2 protocol.

+

This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

+

It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2.

+

The default value is given next to the option name:

+
connection_type (supervisor)
+

Whether the connection process also acts as a supervisor.

-
-env (#{}) -
-
-

- Middleware environment. -

+
env (#{})
+

Middleware environment.

-
-inactivity_timeout (300000) -
-
-

- Time in ms with nothing received at all before Cowboy closes the connection. -

+
inactivity_timeout (300000)
+

Time in ms with nothing received at all before Cowboy closes the connection.

-
-middlewares ([cowboy_router, cowboy_handler]) -
-
-

- Middlewares to run for every request. -

+
middlewares ([cowboy_router, cowboy_handler])
+

Middlewares to run for every request.

-
-preface_timeout (5000) -
-
-

- Time in ms Cowboy is willing to wait for the connection preface. -

+
preface_timeout (5000)
+

Time in ms Cowboy is willing to wait for the connection preface.

-
-shutdown_timeout (5000) -
-
-

- Time in ms Cowboy will wait for child processes to shut down before killing them. -

+
shutdown_timeout (5000)
+

Time in ms Cowboy will wait for child processes to shut down before killing them.

-
-stream_handlers ([cowboy_stream_h]) -
-
-

- Ordered list of stream handlers that will handle all stream events. -

+
stream_handlers ([cowboy_stream_h])
+

Ordered list of stream handlers that will handle all stream events.

-
-
-
-
+

Changelog

-
-
    -
  • -

    -2.0: Protocol introduced. -

    +
    • 2.0: Protocol introduced.
    • -
-
-
- +

cowboy(7), cowboy_http(3), cowboy_websocket(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_loop/index.html b/docs/en/cowboy/2.1/manual/cowboy_loop/index.html index f287b2c4..7f0469c6 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_loop/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_loop/index.html @@ -62,120 +62,60 @@

cowboy_loop(3)

-

Name

-
-

cowboy_loop - Loop handlers

-
-
-
+

cowboy_loop - Loop handlers

Description

-
-

The module cowboy_loop defines a callback interface for -long running HTTP connections.

-

You should switch to this behavior for long polling, -server-sent events and similar long-running requests.

-

There are generally two usage patterns:

-
    -
  • -

    -Loop until receiving a specific message, then send - a response and stop execution (for example long polling); -

    +

    The module cowboy_loop defines a callback interface for long running HTTP connections.

    +

    You should switch to this behavior for long polling, server-sent events and similar long-running requests.

    +

    There are generally two usage patterns:

    +
    • Loop until receiving a specific message, then send a response and stop execution (for example long polling);
    • -
    • -

      -Or initiate a response in init/2 and stream the - body in info/3 as necessary (for example server-sent events). -

      +
    • Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events).
    • -
-
-
-
+

Callbacks

-
-

Loop handlers implement the following interface:

-
-
-
init(Req, State)
-    -> {cowboy_loop, Req, State}
-     | {cowboy_loop, Req, State, hibernate}
-
-info(Info, Req, State)
-    -> {ok, Req, State}
-     | {ok, Req, State, hibernate}
-     | {stop, Req, State}
-
-terminate(Reason, Req, State) -> ok  %% optional
-
-Req    :: cowboy_req:req()
-State  :: any()
-Info   :: any()
-Reason :: stop
-        | {crash, error | exit | throw, any()}
-

The init/2 callback is common to all handlers. To switch -to the loop behavior, it must return cowboy_loop as the -first element of the tuple.

-

The info/3 callback will be called for every Erlang message -received. It may choose to continue the receive loop or stop -it.

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the handler. -Cowboy will terminate the process right after this. There -is no need to perform any cleanup in this callback.

-

The following terminate reasons are defined for loop handlers:

-
-
-stop -
-
-

- The handler requested to close the connection by returning - a stop tuple. -

+
init(Req, State)
+    -> {cowboy_loop, Req, State}
+     | {cowboy_loop, Req, State, hibernate}
+
+info(Info, Req, State)
+    -> {ok, Req, State}
+     | {ok, Req, State, hibernate}
+     | {stop, Req, State}
+
+terminate(Reason, Req, State) -> ok  %% optional
+
+Req    :: cowboy_req:req()
+State  :: any()
+Info   :: any()
+Reason :: stop
+        | {crash, error | exit | throw, any()}
+
+

The init/2 callback is common to all handlers. To switch to the loop behavior, it must return cowboy_loop as the first element of the tuple.

+

The info/3 callback will be called for every Erlang message received. It may choose to continue the receive loop or stop it.

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the handler. Cowboy will terminate the process right after this. There is no need to perform any cleanup in this callback.

+

The following terminate reasons are defined for loop handlers:

+
stop
+

The handler requested to close the connection by returning a stop tuple.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
- - -
+

Changelog

-
-
    -
  • -

    -2.0: Loop handlers no longer need to handle overflow/timeouts. -

    +
    • 2.0: Loop handlers no longer need to handle overflow/timeouts.
    • -
    • -

      -1.0: Behavior introduced. -

      +
    • 1.0: Behavior introduced.
    • -
-
-
-
+

See also

- -
+

cowboy(7), cowboy_handler(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_middleware/index.html b/docs/en/cowboy/2.1/manual/cowboy_middleware/index.html index bc744f5c..4bbd9847 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_middleware/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_middleware/index.html @@ -62,115 +62,56 @@

cowboy_middleware(3)

-

Name

-
-

cowboy_middleware - Middlewares

-
-
-
+

cowboy_middleware - Middlewares

Description

-
-

The module cowboy_middleware defines a callback interface for -Cowboy middlewares.

-

Middlewares process the request sequentially in the order they -are configured.

-
-
-
+

The module cowboy_middleware defines a callback interface for Cowboy middlewares.

+

Middlewares process the request sequentially in the order they are configured.

Callbacks

-
-

Middlewares implement the following interface:

-
-
-
execute(Req, Env)
-    -> {ok, Req, Env}
-     | {suspend, module(), atom(), [any()]}
-     | {stop, Req}
-
-Req :: cowboy_req:req()
-Env :: cowboy_middleware:env()
-

The execute/2 is the only callback that needs to be -implemented. It must execute the middleware and return -with instructions for Cowboy.

-
-
-ok -
-
-

-Cowboy should continue processing the request using the -returned Req object and environment. -

+
execute(Req, Env)
+    -> {ok, Req, Env}
+     | {suspend, module(), atom(), [any()]}
+     | {stop, Req}
+
+Req :: cowboy_req:req()
+Env :: cowboy_middleware:env()
+
+

The execute/2 is the only callback that needs to be implemented. It must execute the middleware and return with instructions for Cowboy.

+
ok
+

Cowboy should continue processing the request using the returned Req object and environment.

-
-suspend -
-
-

-Cowboy will hibernate the process. When resuming, Cowboy -will apply the returned module, function and arguments. -

+
suspend
+

Cowboy will hibernate the process. When resuming, Cowboy will apply the returned module, function and arguments.

-
-stop -
-
-

-Cowboy will stop middleware execution. No other middleware -will be executed. This effectively ends the processing of -the request. -

+
stop
+

Cowboy will stop middleware execution. No other middleware will be executed. This effectively ends the processing of the request.

-
- - -
+

Types

-
-

env()

-
-
-
env() :: #{atom() => any()}
-

Middleware environment.

-

A new environment is created for every request. The initial -environment contained the user configured environment values -(like dispatch for example) plus the listener value which -contains the name of the listener for this connection.

-

Middlewares may modify the environment as necessary.

-
-
-
-
+
env() :: #{atom() => any()}
+
+

Middleware environment.

+

A new environment is created for every request. The initial environment contained the user configured environment values (like dispatch for example) plus the listener value which contains the name of the listener for this connection.

+

Middlewares may modify the environment as necessary.

Changelog

-
-
    -
  • -

    -2.0: The env type is now a map instead of a proplist. -

    +
    • 2.0: The env type is now a map instead of a proplist.
    • -
    • -

      -1.0: Behavior introduced. -

      +
    • 1.0: Behavior introduced.
    • -
-
- -
+

See also

- -
+

cowboy(7)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.binding/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.binding/index.html index 81d081ff..4c1ad4d1 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.binding/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.binding/index.html @@ -62,116 +62,60 @@

cowboy_req:binding(3)

-

Name

-
-

cowboy_req:binding - Access a value bound from the route

-
-
-
+

cowboy_req:binding - Access a value bound from the route

Description

-
-
-
-
binding(Name, Req)          -> binding(Name, Req, undefined)
-binding(Name, Req, Default) -> any() | Default
-
-Name    :: atom()
-Req     :: cowboy_req:req()
-Default :: any()
-

Return the value for the given binding.

-
-
-
+
binding(Name, Req)          -> binding(Name, Req, undefined)
+binding(Name, Req, Default) -> any() | Default
+
+Name    :: atom()
+Req     :: cowboy_req:req()
+Default :: any()
+
+

Return the value for the given binding.

Arguments

-
-
-
-Name -
-
-

-Desired binding name as an atom. -

+
Name
+

Desired binding name as an atom.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the binding is missing. -

+
Default
+

Default value returned when the binding is missing.

-
-
- -
+

Return value

-
-

By default the value is a case sensitive binary string, however -constraints may change the type of this value (for example -automatically converting numbers to integer).

-
-
-
+

By default the value is a case sensitive binary string, however constraints may change the type of this value (for example automatically converting numbers to integer).

Changelog

-
-
    -
  • -

    -2.0: Only the value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the username from the path
-
-
%% Route is "/users/:user"
-Username = cowboy_req:binding(user, Req).
-
-
Get the branch name, with a default
-
-
%% Route is "/log[/:branch]"
-Branch = cowboy_req:binding(branch, Req, <<"master">>)
-
-
-
+
%% Route is "/log[/:branch]"
+Branch = cowboy_req:binding(branch, Req, <<"master">>)
+

See also

- - +

cowboy_req(3), cowboy_req:bindings(3), cowboy_req:host_info(3), cowboy_req:path_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.bindings/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.bindings/index.html index 41e74c3d..ae727c9b 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.bindings/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.bindings/index.html @@ -62,86 +62,40 @@

cowboy_req:bindings(3)

-

Name

-
-

cowboy_req:bindings - Access all values bound from the route

-
-
-
+

cowboy_req:bindings - Access all values bound from the route

Description

-
-
-
-
bindings(Req :: cowboy_req:req()) -> cowboy_router:bindings()
-

Return a map containing all bindings.

-
-
-
+
bindings(Req :: cowboy_req:req()) -> cowboy_router:bindings()
+
+

Return a map containing all bindings.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

By default values are case sensitive binary strings, however -constraints may change the type of this value (for example -automatically converting numbers to integer).

-
-
-
+

By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer).

Changelog

-
-
    -
  • -

    -2.0: Only the values are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the values are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get all bindings
-
-
Bindings = cowboy_req:bindings(Req).
-
-
-
+
Bindings = cowboy_req:bindings(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:host_info(3), cowboy_req:path_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.body_length/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.body_length/index.html index 9a55ee32..51e1a831 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.body_length/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.body_length/index.html @@ -62,89 +62,41 @@

cowboy_req:body_length(3)

-

Name

-
-

cowboy_req:body_length - Body length

-
-
-
+

cowboy_req:body_length - Body length

Description

-
-
-
-
body_length(Req :: cowboy_req:req()) -> undefined | non_neg_integer()
-

Return the length of the request body.

-

The length is not always known before reading the body. -In those cases Cowboy will return undefined. The body -length is available after the body has been fully read.

-
-
-
+
body_length(Req :: cowboy_req:req()) -> undefined | non_neg_integer()
+
+

Return the length of the request body.

+

The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The length of the request body, or undefined if it is -not known.

-
-
-
+

The length of the request body, or undefined if it is not known.

Changelog

-
-
    -
  • -

    -2.0: Only the length is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the length is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the body length
-
-
Length = cowboy_req:body_length(Req).
-
-
-
+
Length = cowboy_req:body_length(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.cert/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.cert/index.html index a297fbbe..6514040f 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.cert/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.cert/index.html @@ -62,104 +62,60 @@

cowboy_req:cert(3)

-

Name

-
-

cowboy_req:cert - Client TLS certificate

-
-
-
+

cowboy_req:cert - Client TLS certificate

Description

-
-
-
-
cert(Req :: cowboy_req:req()) -> binary() | undefined
-

Return the peer’s TLS certificate.

-

Using the default configuration this function will always return -undefined. You need to explicitly configure Cowboy to request -the client certificate. To do this you need to set the verify -transport option to verify_peer:

-
-
-
{ok, _} = cowboy:start_tls(example, [
-    {port, 8443},
-    {cert, "path/to/cert.pem"},
-    {verify, verify_peer}
+
{ok, _} = cowboy:start_tls(example, [
+    {port, 8443},
+    {cert, "path/to/cert.pem"},
+    {verify, verify_peer}
 ], #{
-    env => #{dispatch => Dispatch}
-}).
-

You may also want to customize the verify_fun function. Please -consult the ssl application’s manual for more details.

-

TCP connections do not allow a certificate and this function -will therefore always return undefined.

-

The certificate can also be obtained using pattern matching:

-
-
-
#{cert := Cert} = Req.
-
-
-
+
#{cert := Cert} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The client TLS certificate.

-
-
-
+

The client TLS certificate.

Changelog

-
-
    -
  • -

    -2.1: Function introduced. -

    +
    • 2.1: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the client TLS certificate.
-
-
Cert = cowboy_req:cert(Req).
-
-
-
+
Cert = cowboy_req:cert(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:peer(3), cowboy_req:sock(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.delete_resp_header/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.delete_resp_header/index.html index 0efb2d46..96223e98 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.delete_resp_header/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.delete_resp_header/index.html @@ -62,95 +62,45 @@

cowboy_req:delete_resp_header(3)

-

Name

-
-

cowboy_req:delete_resp_header - Delete a response header

-
-
-
+

cowboy_req:delete_resp_header - Delete a response header

Description

-
-
-
-
delete_resp_header(Name, Req :: cowboy_req:req()) -> Req
+
delete_resp_header(Name, Req :: cowboy_req:req()) -> Req
 
-Name :: binary()  %% lowercase; case insensitive
-

Delete the given response header.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+Name :: binary() %% lowercase; case insensitive +
+

Delete the given response header.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Name -
-
-

-Header name as a lowercase binary string. -

+
Name
+

Header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the header will still be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the header will still be sent in the response.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Remove the content-type header from the response
-
-
Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),
-
-
-
+
Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:has_resp_header(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.has_body/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.has_body/index.html index 3524e2c0..7739e636 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.has_body/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.has_body/index.html @@ -62,80 +62,38 @@

cowboy_req:has_body(3)

-

Name

-
-

cowboy_req:has_body - Is there a request body?

-
-
-
+

cowboy_req:has_body - Is there a request body?

Description

-
-
-
-
has_body(Req :: cowboy_req:req()) -> boolean()
-

Return whether the request has a body.

-
-
-
+
has_body(Req :: cowboy_req:req()) -> boolean()
+
+

Return whether the request has a body.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A boolean indicating whether the request has a body.

-
-
-
+

A boolean indicating whether the request has a body.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Ensure the request has a body
-
-
true = cowboy_req:has_body(Req).
-
-
-
+
true = cowboy_req:has_body(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.has_resp_body/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.has_resp_body/index.html index a2bd881f..6bfc1ff3 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.has_resp_body/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.has_resp_body/index.html @@ -62,82 +62,43 @@

cowboy_req:has_resp_body(3)

-

Name

-
-

cowboy_req:has_resp_body - Is there a response body?

-
-
-
+

cowboy_req:has_resp_body - Is there a response body?

Description

-
-
-
-
has_resp_body(Req :: cowboy_req:req()) -> boolean()
-

Return whether a response body has been set.

-
-
-
+
has_resp_body(Req :: cowboy_req:req()) -> boolean()
+
+

Return whether a response body has been set.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A boolean indicating whether a response body has been set.

-

This function will return false when an empty response -body has been set.

-
-
-
+

A boolean indicating whether a response body has been set.

+

This function will return false when an empty response body has been set.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Check whether a body has been set
-
-
false = cowboy_req:has_resp_body(Req0),
-Req1 = cowboy_req:set_resp_body(<<"Hello!">>, Req0),
-true = cowboy_req:has_resp_body(Req1),
-Req = cowboy_req:set_resp_body(<<>>, Req1),
-false = cowboy_req:has_resp_body(Req).
-
-
-
+
false = cowboy_req:has_resp_body(Req0),
+Req1 = cowboy_req:set_resp_body(<<"Hello!">>, Req0),
+true = cowboy_req:has_resp_body(Req1),
+Req = cowboy_req:set_resp_body(<<>>, Req1),
+false = cowboy_req:has_resp_body(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_body(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.has_resp_header/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.has_resp_header/index.html index 0f56b764..edb18ee4 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.has_resp_header/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.has_resp_header/index.html @@ -62,95 +62,46 @@

cowboy_req:has_resp_header(3)

-

Name

-
-

cowboy_req:has_resp_header - Is the given response header set?

-
-
-
+

cowboy_req:has_resp_header - Is the given response header set?

Description

-
-
-
-
has_resp_header(Name, Req :: cowboy_req:req()) -> boolean()
+
has_resp_header(Name, Req :: cowboy_req:req()) -> boolean()
 
-Name :: binary()  %% lowercase; case insensitive
-

Return whether the given response header has been set.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+Name :: binary() %% lowercase; case insensitive +
+

Return whether the given response header has been set.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Name -
-
-

-Header name as a lowercase binary string. -

+
Name
+

Header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A boolean indicating whether the given response header has been set.

-
-
-
+

A boolean indicating whether the given response header has been set.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Check whether the content-type header has been set
-
-
false = cowboy_req:has_resp_header(<<"content-type">>, Req0),
-Req = cowboy_req:set_resp_header(<<"content-type">>, <<"text/html">>, Req0),
-true = cowboy_req:has_resp_header(<<"content-type">>, Req).
-
-
-
+
false = cowboy_req:has_resp_header(<<"content-type">>, Req0),
+Req = cowboy_req:set_resp_header(<<"content-type">>, <<"text/html">>, Req0),
+true = cowboy_req:has_resp_header(<<"content-type">>, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3), cowboy_req:delete_resp_header(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.header/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.header/index.html index 477c5c26..1b1a3995 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.header/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.header/index.html @@ -62,122 +62,67 @@

cowboy_req:header(3)

-

Name

-
-

cowboy_req:header - HTTP header

-
-
-
+

cowboy_req:header - HTTP header

Description

-
-
-
-
header(Name, Req)          -> header(Name, Req, undefined)
-header(Name, Req, Default) -> binary() | Default
-
-Name    :: binary()          %% lowercase; case insensitive
-Req     :: cowboy_req:req()
-Default :: any()
-

Return the value for the given HTTP header.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Headers can also be obtained using pattern matching:

-
-
-
#{headers := #{Name := Value}} = Req.
-

Note that this snippet will crash if the header is missing.

-
-
-
+
#{headers := #{Name := Value}} = Req.
+
+

Note that this snippet will crash if the header is missing.

Arguments

-
-
-
-Name -
-
-

-Desired HTTP header name as a lowercase binary string. -

+
Name
+

Desired HTTP header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the header is missing. -

+
Default
+

Default value returned when the header is missing.

-
-
- -
+

Return value

-
-

The header value is returned as a binary string. When the -header is missing, the default argument is returned.

-
-
-
+

The header value is returned as a binary string. When the header is missing, the default argument is returned.

Changelog

-
-
    -
  • -

    -2.0: Only the header value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the header value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the accept header
-
-
Accept = cowboy_req:header(<<"accept">>, Req).
-
-
Get the content-length header with a default value
-
-
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).
-
-
-
+
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).
+

See also

- - +

cowboy_req(3), cowboy_req:headers(3), cowboy_req:parse_header(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.headers/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.headers/index.html index 59aa63b5..9fe39b2a 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.headers/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.headers/index.html @@ -62,90 +62,47 @@

cowboy_req:headers(3)

-

Name

-
-

cowboy_req:headers - HTTP headers

-
-
-
+

cowboy_req:headers - HTTP headers

Description

-
-
-
-
headers(Req :: cowboy_req:req()) -> cowboy:http_headers()
-

Return all request headers.

-

Request headers can also be obtained using pattern matching:

-
-
-
#{headers := Headers} = Req.
-
-
-
+
#{headers := Headers} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Headers are returned as a map with keys being lowercase -binary strings, and values as binary strings.

-
-
-
+

Headers are returned as a map with keys being lowercase binary strings, and values as binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the headers are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the headers are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get all headers
-
-
Headers = cowboy_req:headers(Req).
-
-
-
+
Headers = cowboy_req:headers(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:header(3), cowboy_req:parse_header(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.host/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.host/index.html index 4875e476..e561dd87 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.host/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.host/index.html @@ -62,91 +62,47 @@

cowboy_req:host(3)

-

Name

-
-

cowboy_req:host - URI host name

-
-
-
+

cowboy_req:host - URI host name

Description

-
-
-
-
host(Req :: cowboy_req:req()) -> Host :: binary()
-

Return the host name of the effective request URI.

-

The host name can also be obtained using pattern matching:

-
-
-
#{host := Host} = Req.
-
-
-
+
#{host := Host} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The host name is returned as a lowercase binary string. -It is case insensitive.

-
-
-
+

The host name is returned as a lowercase binary string. It is case insensitive.

Changelog

-
-
    -
  • -

    -2.0: Only the host name is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the host name is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s host name
-
-
Host = cowboy_req:host(Req).
-
-
-
+
Host = cowboy_req:host(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:host_info(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.host_info/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.host_info/index.html index b5c53d33..9ef585bd 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.host_info/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.host_info/index.html @@ -62,87 +62,41 @@

cowboy_req:host_info(3)

-

Name

-
-

cowboy_req:host_info - Access the route’s heading host segments

-
-
-
+

cowboy_req:host_info - Access the route's heading host segments

Description

-
-
-
-
host_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
-

Return the tokens for the heading host segments.

-

This is the part of the host name that was matched using -the ... notation.

-
-
-
+
host_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
+
+

Return the tokens for the heading host segments.

+

This is the part of the host name that was matched using the ... notation.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The tokens are returned as a list of case insensitive -binary strings.

-
-
-
+

The tokens are returned as a list of case insensitive binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the tokens are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the host_info tokens
-
-
HostInfo = cowboy_req:host_info(Req).
-
-
-
+
HostInfo = cowboy_req:host_info(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:path_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.inform/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.inform/index.html index 4a753810..142b57e8 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.inform/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.inform/index.html @@ -62,125 +62,66 @@

cowboy_req:inform(3)

-

Name

-
-

cowboy_req:inform - Send an informational response

-
-
-
+

cowboy_req:inform - Send an informational response

Description

-
-
-
-
inform(Status, Req :: cowboy_req:req())
-    -> inform(StatusCode, #{}, Req)
-
-inform(Status, Headers, Req :: cowboy_req:req())
-    -> ok
-
-Status  :: cowboy:http_status()
-Headers :: cowboy:http_headers()
-

Send an informational response.

-

Informational responses use a status code between 100 and 199. -They cannot include a body. This function will not use any -of the previously set headers. All headers to be sent must -be given directly.

-

Any number of informational responses can be sent as long as -they are sent before the proper response. Attempting to use -this function after sending a normal response will result -in an error.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+
inform(Status, Req :: cowboy_req:req())
+    -> inform(StatusCode, #{}, Req)
+
+inform(Status, Headers, Req :: cowboy_req:req())
+    -> ok
+
+Status  :: cowboy:http_status()
+Headers :: cowboy:http_headers()
+
+

Send an informational response.

+

Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly.

+

Any number of informational responses can be sent as long as they are sent before the proper response. Attempting to use this function after sending a normal response will result in an error.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Status -
-
-

-The status code for the response. -

+
Status
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Req -
-
-

-The Req object. -

+
+

Header names must be given as lowercase binary strings.

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.1: Function introduced. -

    +
    • 2.1: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Send an informational response
-
-
Req = cowboy_req:inform(102, Req0).
-
-
Send an informational response with headers
-
-
Req = cowboy_req:inform(103, #{
-    <<"link">> => <<"</style.css>; rel=preload; as=style">>,
-    <<"link">> => <<"</script.js>; rel=preload; as=script">>
-}, Req0).
-
-
-
+
Req = cowboy_req:inform(103, #{
+    <<"link">> => <<"</style.css>; rel=preload; as=style">>,
+    <<"link">> => <<"</script.js>; rel=preload; as=script">>
+}, Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:reply(3), cowboy_req:stream_reply(3), cowboy_req:push(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.match_cookies/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.match_cookies/index.html index 5847531a..4317a623 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.match_cookies/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.match_cookies/index.html @@ -62,123 +62,67 @@

cowboy_req:match_cookies(3)

-

Name

-
-

cowboy_req:match_cookies - Match cookies against constraints

-
-
-
+

cowboy_req:match_cookies - Match cookies against constraints

Description

-
-
-
-
match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req())
-    -> #{atom() => any()}
-

Parse the cookies and match specific values against -constraints.

-

Cowboy will only return the cookie values specified in the -fields list, and ignore all others. Fields can be either -the name of the cookie requested; the name along with a -list of constraints; or the name, a list of constraints -and a default value in case the cookie is missing.

-

This function will crash if the cookie is missing and no -default value is provided. This function will also crash -if a constraint fails.

-

The name of the cookie must be provided as an atom. The -key of the returned map will be that atom. The value may -be converted through the use of constraints, making this -function able to extract, validate and convert values all -in one step.

-
-
-
+
match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req())
+    -> #{atom() => any()}
+
+

Parse the cookies and match specific values against constraints.

+

Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing.

+

This function will crash if the cookie is missing and no default value is provided. This function will also crash if a constraint fails.

+

The name of the cookie must be provided as an atom. The key of the returned map will be that atom. The value may be converted through the use of constraints, making this function able to extract, validate and convert values all in one step.

Arguments

-
-
-
-Fields -
-
-

-Cookies to retrieve. -

-

See cowboy(3) for a complete description.

+
Fields
+

Cookies to retrieve.

+

See cowboy(3) for a complete description.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Desired values are returned as a map. The key is the atom -that was given in the list of fields, and the value is the -optionally converted value after applying constraints.

-

The map contains the same keys that were given in the fields.

-

An exception is triggered when the match fails.

-
-
-
+

Desired values are returned as a map. The key is the atom that was given in the list of fields, and the value is the optionally converted value after applying constraints.

+

The map contains the same keys that were given in the fields.

+

An exception is triggered when the match fails.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Match fields
-
-
%% ID and Lang are binaries.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_cookies([id, lang], Req).
-
-
Match fields and apply constraints
-
-
%% ID is an integer and Lang a non-empty binary.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_cookies([{id, int}, {lang, nonempty}], Req).
-
-
Match fields with default values
-
-
#{lang := Lang}
-    = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
-
-
-
+
#{lang := Lang}
+    = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
+

See also

- - +

cowboy_req(3), cowboy_req:parse_cookies(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.match_qs/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.match_qs/index.html index ac39045e..d592d036 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.match_qs/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.match_qs/index.html @@ -62,123 +62,67 @@

cowboy_req:match_qs(3)

-

Name

-
-

cowboy_req:match_qs - Match the query string against constraints

-
-
-
+

cowboy_req:match_qs - Match the query string against constraints

Description

-
-
-
-
match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req())
-    -> #{atom() => any()}
-

Parse the query string and match specific values against -constraints.

-

Cowboy will only return the query string values specified -in the fields list, and ignore all others. Fields can be -either the key requested; the key along with a list of -constraints; or the key, a list of constraints and a -default value in case the key is missing.

-

This function will crash if the key is missing and no -default value is provided. This function will also crash -if a constraint fails.

-

The key must be provided as an atom. The key of the -returned map will be that atom. The value may be converted -through the use of constraints, making this function able -to extract, validate and convert values all in one step.

-
-
-
+
match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req())
+    -> #{atom() => any()}
+
+

Parse the query string and match specific values against constraints.

+

Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing.

+

This function will crash if the key is missing and no default value is provided. This function will also crash if a constraint fails.

+

The key must be provided as an atom. The key of the returned map will be that atom. The value may be converted through the use of constraints, making this function able to extract, validate and convert values all in one step.

Arguments

-
-
-
-Fields -
-
-

-Fields to retrieve from the query string. -

-

See cowboy(3) for a complete description.

+
Fields
+

Fields to retrieve from the query string.

+

See cowboy(3) for a complete description.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Desired values are returned as a map. The key is the atom -that was given in the list of fields, and the value is the -optionally converted value after applying constraints.

-

The map contains the same keys that were given in the fields.

-

An exception is triggered when the match fails.

-
-
-
+

Desired values are returned as a map. The key is the atom that was given in the list of fields, and the value is the optionally converted value after applying constraints.

+

The map contains the same keys that were given in the fields.

+

An exception is triggered when the match fails.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Match fields
-
-
%% ID and Lang are binaries.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_qs([id, lang], Req).
-
-
Match fields and apply constraints
-
-
%% ID is an integer and Lang a non-empty binary.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req).
-
-
Match fields with default values
-
-
#{lang := Lang}
-    = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
-
-
-
+
#{lang := Lang}
+    = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
+

See also

- - +

cowboy_req(3), cowboy_req:qs(3), cowboy_req:parse_qs(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.method/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.method/index.html index d58a364b..d0a6a414 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.method/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.method/index.html @@ -62,100 +62,58 @@

cowboy_req:method(3)

-

Name

-
-

cowboy_req:method - HTTP method

-
-
-
+

cowboy_req:method - HTTP method

Description

-
-
-
-
method(Req :: cowboy_req:req()) -> Method :: binary()
-

Return the request’s HTTP method.

-

The method can also be obtained using pattern matching:

-
-
-
#{method := Method} = Req.
-
-
-
+
#{method := Method} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The request’s HTTP method is returned as a binary string. -While methods are case sensitive, standard methods are -always uppercase.

-
-
-
+

The request's HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase.

Changelog

-
-
    -
  • -

    -2.0: Only the method is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the method is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Ensure the request’s method is GET
-
-
<<"GET">> = cowboy_req:method(Req).
-
-
Allow methods from list
-
-
init(Req, State) ->
-    case lists:member(cowboy_req:method(Req), [<<"GET">>, <<"POST">>]) of
-        true -> handle(Req, State);
-        false -> method_not_allowed(Req, State)
-    end.
-
-
-
+
init(Req, State) ->
+    case lists:member(cowboy_req:method(Req), [<<"GET">>, <<"POST">>]) of
+        true -> handle(Req, State);
+        false -> method_not_allowed(Req, State)
+    end.
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.parse_cookies/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.parse_cookies/index.html index 5405fa1d..d2b8c356 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.parse_cookies/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.parse_cookies/index.html @@ -62,91 +62,47 @@

cowboy_req:parse_cookies(3)

-

Name

-
-

cowboy_req:parse_cookies - Parse cookie headers

-
-
-
+

cowboy_req:parse_cookies - Parse cookie headers

Description

-
-
-
-
parse_cookies(Req) -> [{Name, Value}]
-
-Name  :: binary() %% case sensitive
-Value :: binary() %% case sensitive
-

Parse cookie headers.

- -

When the cookie header is missing, [] is returned.

-

While an empty cookie header is not valid, some clients do -send it. Cowboy will in this case also return [].

-
-
-
+
parse_cookies(Req) -> [{Name, Value}]
+
+Name  :: binary() %% case sensitive
+Value :: binary() %% case sensitive
+
+

Parse cookie headers.

+

Alias for cowboy_req:parse_header(<<"cookie">>, Req).

+

When the cookie header is missing, [] is returned.

+

While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return [].

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The cookies are returned as a list of key/values. Keys and -values are case sensitive binary strings.

-
-
-
+

The cookies are returned as a list of key/values. Keys and values are case sensitive binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces cookie/2,3 and cookies/1. -

      +
    • 2.0: Function introduced. Replaces cookie/2,3 and cookies/1.
    • -
-
-
-
+

Examples

-
-
-
Look for a specific cookie
-
-
Cookies = cowboy_req:parse_cookies(Req),
-{_, Token} = lists:keyfind(token, 1, Cookies).
-
-
-
+
Cookies = cowboy_req:parse_cookies(Req),
+{_, Token} = lists:keyfind(token, 1, Cookies).
+

See also

- - +

cowboy_req(3), cowboy_req:parse_header(3), cowboy_req:match_cookies(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.parse_header/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.parse_header/index.html index 6ad50b43..4b245860 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.parse_header/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.parse_header/index.html @@ -62,283 +62,218 @@

cowboy_req:parse_header(3)

-

Name

-
-

cowboy_req:parse_header - Parse the given HTTP header

-
-
-
+

cowboy_req:parse_header - Parse the given HTTP header

Description

-
-
-
-
parse_header(Name, Req)          -> ParsedValue | Default
-parse_header(Name, Req, Default) -> ParsedValue | Default
-
-Name        :: binary()
-Req         :: cowboy_req:req()
-ParsedValue :: any()
-Default     :: any()
-

Parse the given HTTP header.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

The type of the parsed value varies depending on -the header. Similarly, the default value when calling -cowboy_req:parse_header/2 differs depending on the -header.

-
-
-
+
parse_header(Name, Req)          -> ParsedValue | Default
+parse_header(Name, Req, Default) -> ParsedValue | Default
+
+Name        :: binary()
+Req         :: cowboy_req:req()
+ParsedValue :: any()
+Default     :: any()
+
+

Parse the given HTTP header.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

The type of the parsed value varies depending on the header. Similarly, the default value when calling cowboy_req:parse_header/2 differs depending on the header.

Arguments

-
-
-
-Name -
-
-

-Desired HTTP header name as a lowercase binary string. -

+
Name
+

Desired HTTP header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the header is missing. -

+
Default
+

Default value returned when the header is missing.

-
-
- -
+

Return value

-
-

The parsed header value varies depending on the header. -When the header is missing, the default argument is returned.

-
-
-
+

The parsed header value varies depending on the header. When the header is missing, the default argument is returned.

Headers

-
-

The following snippets detail the types returned by the -different headers. Unless mentioned otherwise, the -default value when the header is missing will be undefined:

-
-
accept
-
-
parse_header(<<"accept">>, Req)
-    -> [{{Type, SubType, Params}, Quality, AcceptExt}]
-
-Type      :: binary()               %% case insensitive
-SubType   :: binary()               %% case insensitive
-Params    :: [{Key, Value}]
-Quality   :: 0..1000
-AcceptExt :: [Key | {Key, Value}]
-Key       :: binary()               %% case insensitive
-Value     :: binary()               %% case sensitive
-
-
accept-charset, accept-encoding and accept-language
-
-
parse_header(Name, Req) -> [{Value, Quality}]
-
-Name    :: <<"accept-charset">>
-         | <<"accept-encoding">>
-         | <<"accept-language">>
-Value   :: binary()                 %% case insensitive
-Quality :: 0..1000
-
-
authorization
-
-
parse_header(<<"authorization">>, Req)
-    -> {basic, Username :: binary(), Password :: binary()}
-     | {bearer, Token :: binary()}
-     | {digest, [{Key :: binary(), Value :: binary()}]}
-
-
content-length
-
+
content-length
+
-
parse_header(<<"content-length">>, Req) -> non_neg_integer()
-

When the content-length header is missing, 0 is returned.

-
-
content-type
-
-
parse_header(<<"content-type">>, Req)
-    -> {Type, SubType, Params}
-
-Type      :: binary()               %% case insensitive
-SubType   :: binary()               %% case insensitive
-Params    :: [{Key, Value}]
-Key       :: binary()               %% case insensitive
-Value     :: binary()               %% case sensitive;
-

Note that the value for the charset parameter is case insensitive -and returned as a lowercase binary string.

-
-
cookie
-
-
parse_header(<<"cookie">>, Req) -> [{Name, Value}]
-
-Name  :: binary()                   %% case sensitive
-Value :: binary()                   %% case sensitive
-

When the cookie header is missing, [] is returned.

-

While an empty cookie header is not valid, some clients do -send it. Cowboy will in this case also return [].

-
-
expect
-
-
parse_header(<<"expect">>, Req) -> continue
-
-
if-match and if-none-match
-
-
parse_header(Name, Req)
-    -> '*' | [{weak | strong, OpaqueTag}]
-
-Name      :: <<"if-match">>
-           | <<"if-none-match">>
-OpaqueTag :: binary()               %% case sensitive
-
-
if-modified-since and if-unmodified-since
-
-
parse_header(Name, Req) -> calendar:datetime()
-
-
range
-
-
parse_header(<<"range">>, Req) -> {From, To} | Final
-
-From  :: non_neg_integer()
-To    :: non_neg_integer() | infinity
-Final :: neg_integer()
-
-
sec-websocket-extensions
-
-
parse_header(<<"sec-websocket-extensions">>, Req)
-    -> [{Extension, Params}]
-
-Extension :: binary()               %% case sensitive
-Params    :: [Key | {Key, Value}]
-Key       :: binary()               %% case sensitive
-Value     :: binary()               %% case sensitive
-
-
sec-websocket-protocol and upgrade
-
-
parse_header(Name, Req) -> [Token]
-
-Name  :: <<"sec-websocket-protocol">>
-       | <<"upgrade">>
-Token :: binary()                   %% case insensitive
-
-
x-forwarded-for
-
-
parse_header(<<"x-forwarded-for">>, Req) -> [Token]
+
parse_header(<<"x-forwarded-for">>, Req) -> [Token]
 
-Token :: binary()                   %% case sensitive
-
-
Unknown headers
-
-
parse_header(_, Req) -> {undefined, RawValue}
-
-
-
+
parse_header(_, Req) -> {undefined, RawValue}
+

Changelog

-
-
    -
  • -

    -2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Parse the accept header with a custom default value
-
-
%% Accept everything when header is missing.
-Accept = cowboy_req:parse_header(<<"accept">>, Req,
-    [{{ <<"*">>, <<"*">>, []}, 1000, []}]).
-
-
Parse the content-length header
-
-
%% Default content-length is 0.
-Length = cowboy_req:header(<<"content-length">>, Req).
-
-
-
+
%% Default content-length is 0.
+Length = cowboy_req:header(<<"content-length">>, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:header(3), cowboy_req:headers(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.parse_qs/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.parse_qs/index.html index 63e09f33..74e787fe 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.parse_qs/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.parse_qs/index.html @@ -62,117 +62,55 @@

cowboy_req:parse_qs(3)

-

Name

-
-

cowboy_req:parse_qs - Parse the query string

-
-
-
+

cowboy_req:parse_qs - Parse the query string

Description

-
-
-
-
parse_qs(Req :: cowboy_req:req())
-    -> [{Key :: binary(), Value :: binary() | true}]
-

Parse the query string as a list of key/value pairs.

-
-
-
+
parse_qs(Req :: cowboy_req:req())
+    -> [{Key :: binary(), Value :: binary() | true}]
+
+

Parse the query string as a list of key/value pairs.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The parsed query string is returned as a list of key/value pairs. -The key is a binary string. The value is either a binary string, -or the atom true. Both key and value are case sensitive.

-

The atom true is returned when a key is present in the query -string without a value. For example, in the following URIs -the key <<"edit">> will always have the value true:

-
    -
  • -

    -/posts/42?edit -

    +

    The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. Both key and value are case sensitive.

    +

    The atom true is returned when a key is present in the query string without a value. For example, in the following URIs the key <<"edit">> will always have the value true:

    +
    • /posts/42?edit
    • -
    • -

      -/posts/42?edit&exclusive=1 -

      +
    • /posts/42?edit&exclusive=1
    • -
    • -

      -/posts/42?exclusive=1&edit -

      +
    • /posts/42?exclusive=1&edit
    • -
    • -

      -/posts/42?exclusive=1&edit&from=web -

      +
    • /posts/42?exclusive=1&edit&from=web
    • -
-
-
-
+

Changelog

-
-
    -
  • -

    -2.0: The parsed value is not longer cached in the Req object. -

    +
    • 2.0: The parsed value is not longer cached in the Req object.
    • -
    • -

      -2.0: Only the parsed query string is returned, it is no longer wrapped in a tuple. -

      +
    • 2.0: Only the parsed query string is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces qs_val/1 and qs_vals/1. -

      +
    • 2.0: Function introduced. Replaces qs_val/1 and qs_vals/1.
    • -
-
-
-
+

Examples

-
-
-
Parse the query string and convert the keys to atoms
-
-
ParsedQs = cowboy_req:parse_qs(Req),
-AtomsQs = [{binary_to_existing_atom(K, latin1), V}
-    || {K, V} <- ParsedQs].
-
-
-
+
ParsedQs = cowboy_req:parse_qs(Req),
+AtomsQs = [{binary_to_existing_atom(K, latin1), V}
+    || {K, V} <- ParsedQs].
+

See also

- - +

cowboy_req(3), cowboy_req:qs(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.path/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.path/index.html index 73aecfc8..5edd85e1 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.path/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.path/index.html @@ -62,90 +62,47 @@

cowboy_req:path(3)

-

Name

-
-

cowboy_req:path - URI path

-
-
-
+

cowboy_req:path - URI path

Description

-
-
-
-
path(Req :: cowboy_req:req()) -> Path :: binary()
-

Return the path of the effective request URI.

-

The path can also be obtained using pattern matching:

-
-
-
#{path := Path} = Req.
-
-
-
+
#{path := Path} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The path is returned as a binary string. It is case sensitive.

-
-
-
+

The path is returned as a binary string. It is case sensitive.

Changelog

-
-
    -
  • -

    -2.0: Only the path is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the path is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s path
-
-
Path = cowboy_req:path(Req).
-
-
-
+
Path = cowboy_req:path(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:path_info(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.path_info/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.path_info/index.html index 68320b5e..ac35e9e9 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.path_info/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.path_info/index.html @@ -62,87 +62,41 @@

cowboy_req:path_info(3)

-

Name

-
-

cowboy_req:path_info - Access the route’s trailing path segments

-
-
-
+

cowboy_req:path_info - Access the route's trailing path segments

Description

-
-
-
-
path_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
-

Return the tokens for the trailing path segments.

-

This is the part of the host name that was matched using -the ... notation.

-
-
-
+
path_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
+
+

Return the tokens for the trailing path segments.

+

This is the part of the host name that was matched using the ... notation.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The tokens are returned as a list of case sensitive -binary strings.

-
-
-
+

The tokens are returned as a list of case sensitive binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the tokens are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the path_info tokens
-
-
PathInfo = cowboy_req:path_info(Req).
-
-
-
+
PathInfo = cowboy_req:path_info(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:host_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.peer/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.peer/index.html index 3155feb3..00420d92 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.peer/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.peer/index.html @@ -62,98 +62,51 @@

cowboy_req:peer(3)

-

Name

-
-

cowboy_req:peer - Peer address and port

-
-
-
+

cowboy_req:peer - Peer address and port

Description

-
-
-
-
peer(Req :: cowboy_req:req()) -> Info
+
peer(Req :: cowboy_req:req()) -> Info
 
-Info :: {inet:ip_address(), inet:port_number()}
-

Return the peer’s IP address and port number.

-

The peer information can also be obtained using pattern matching:

-
-
-
#{peer := {IP, Port}} = Req.
-
-
-
+
#{peer := {IP, Port}} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The peer’s IP address and port number.

-

The peer is not necessarily the client’s IP address and port. -It is the IP address of the endpoint connecting directly to -the server, which may be a gateway or a proxy.

-

The forwarded header can be used to get better information -about the different endpoints from the client to the server. -Note however that it is only informative; there is no reliable -way of determining the source of an HTTP request.

-
-
-
+

The peer's IP address and port number.

+

The peer is not necessarily the client's IP address and port. It is the IP address of the endpoint connecting directly to the server, which may be a gateway or a proxy.

+

The forwarded header can be used to get better information about the different endpoints from the client to the server. Note however that it is only informative; there is no reliable way of determining the source of an HTTP request.

Changelog

-
-
    -
  • -

    -2.0: Only the peer is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the peer is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the peer IP address and port number.
-
-
{IP, Port} = cowboy_req:peer(Req).
-
-
-
+
{IP, Port} = cowboy_req:peer(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:sock(3), cowboy_req:cert(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.port/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.port/index.html index 19ecfaef..91f92659 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.port/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.port/index.html @@ -62,90 +62,48 @@

cowboy_req:port(3)

-

Name

-
-

cowboy_req:port - URI port number

-
-
-
+

cowboy_req:port - URI port number

Description

-
-
-
-
port(Req :: cowboy_req:req()) -> Port :: inet:port_number()
-

Return the port number of the effective request URI.

-

Note that the port number returned by this function is obtained -by parsing the host header. It may be different from the port -the peer used to connect to Cowboy.

-

The port number can also be obtained using pattern matching:

-
-
-
#{port := Port} = Req.
-
-
-
+
#{port := Port} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The port number is returned as an integer.

-
-
-
+

The port number is returned as an integer.

Changelog

-
-
    -
  • -

    -2.0: Only the port number is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the port number is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s port number
-
-
Port = cowboy_req:port(Req).
-
-
-
+
Port = cowboy_req:port(Req).
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.push/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.push/index.html index bdf4fd06..bbe96982 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.push/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.push/index.html @@ -62,142 +62,74 @@

cowboy_req:push(3)

-

Name

-
-

cowboy_req:push - Push a resource to the client

-
-
-
+

cowboy_req:push - Push a resource to the client

Description

-
-
-
-
push(Path, Headers, Req :: cowboy_req:req())
-    -> push(Path, Headers, Req, #{})
-
-push(Path, Headers, Req :: cowboy_req:req(), Opts)
-    -> ok
-
-Path    :: iodata()                %% case sensitive
-Headers :: cowboy:http_headers()
-Opts    :: cowboy_req:push_opts()
-

Push a resource to the client.

-

Cowboy handles push requests the same way as if they came -from the client, including the creation of a request handling -process, routing and middlewares and so on.

-

This function does nothing when the HTTP/1.1 protocol is -used. You may call it safely without first checking whether -the connection uses HTTP/2.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Note that the headers must be the headers the client is expected -to send if it were to perform the request. They are therefore -request headers, and not response headers.

-

By default, Cowboy will use the GET method, an empty query string, -and take the scheme, host and port directly from the current -request’s URI. You can override them by passing options.

-

It is not possible to push resources after sending a response. -Any attempt will result in an error.

-
-
-
+
push(Path, Headers, Req :: cowboy_req:req())
+    -> push(Path, Headers, Req, #{})
+
+push(Path, Headers, Req :: cowboy_req:req(), Opts)
+    -> ok
+
+Path    :: iodata()                %% case sensitive
+Headers :: cowboy:http_headers()
+Opts    :: cowboy_req:push_opts()
+
+

Push a resource to the client.

+

Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on.

+

This function does nothing when the HTTP/1.1 protocol is used. You may call it safely without first checking whether the connection uses HTTP/2.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Note that the headers must be the headers the client is expected to send if it were to perform the request. They are therefore request headers, and not response headers.

+

By default, Cowboy will use the GET method, an empty query string, and take the scheme, host and port directly from the current request's URI. You can override them by passing options.

+

It is not possible to push resources after sending a response. Any attempt will result in an error.

Arguments

-
-
-
-Path -
-
-

-The status code for the response. -

+
Path
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Req -
-
-

-The Req object. -

+
+

Header names must be given as lowercase binary strings.

+
Req
+

The Req object.

-
-Opts -
-
-

-Customize the HTTP method or the URI scheme, host, port -or query string. -

+
Opts
+

Customize the HTTP method or the URI scheme, host, port or query string.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Push a resource
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, Req),
-
-
Push a resource with a custom host
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, #{host => <<"cdn.example.org">>}, Req),
-
-
-
+
cowboy_req:push("/static/style.css", #{
+    <<"accept">> => <<"text/css">>
+}, #{host => <<"cdn.example.org">>}, Req),
+

See also

- - +

cowboy_req(3), cowboy_req:inform(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.qs/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.qs/index.html index 097df763..d8b52154 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.qs/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.qs/index.html @@ -62,89 +62,47 @@

cowboy_req:qs(3)

-

Name

-
-

cowboy_req:qs - URI query string

-
-
-
+

cowboy_req:qs - URI query string

Description

-
-
-
-
qs(Req :: cowboy_req:req()) -> Qs :: binary()
-

Return the query string of the effective request URI.

-

The query string can also be obtained using pattern matching:

-
-
-
#{qs := Qs} = Req.
-
-
-
+
#{qs := Qs} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The query string is returned as a binary string. It is case sensitive.

-
-
-
+

The query string is returned as a binary string. It is case sensitive.

Changelog

-
-
    -
  • -

    -2.0: Only the query string is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the query string is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s query string
-
-
Qs = cowboy_req:qs(Req).
-
-
-
+
Qs = cowboy_req:qs(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:parse_qs(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.read_body/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.read_body/index.html index 28eec5ba..a04fa945 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.read_body/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.read_body/index.html @@ -62,143 +62,72 @@

cowboy_req:read_body(3)

-

Name

-
-

cowboy_req:read_body - Read the request body

-
-
-
+

cowboy_req:read_body - Read the request body

Description

-
-
-
-
read_body(Req :: cowboy_req:req())
-    -> read_body(Req, #{})
-
-read_body(Req :: cowboy_req:req(), Opts)
-    -> {ok,   Data :: binary(), Req}
-     | {more, Data :: binary(), Req}
-
-Opts :: cowboy_req:read_body_opts()
-

Read the request body.

-

This function reads a chunk of the request body. A more tuple -is returned when more data remains to be read. Call the function -repeatedly until an ok tuple is returned to read the entire body.

-

An ok tuple with empty data is returned when the request has no body, -or when calling this function again after the body has already -been read. It is therefore safe to call this function directly. -Note that the body can only be read once.

-

This function reads the request body from the connection process. -The connection process is responsible for reading from the socket. -The exact behavior varies depending on the protocol.

-

The options therefore are only related to the communication -between the request process and the connection process.

-

Cowboy will automatically handle protocol details including -the expect header, chunked transfer-encoding and others.

-

Once the body has been read fully, Cowboy sets the content-length -header if it was not previously provided.

-
-
-
+
read_body(Req :: cowboy_req:req())
+    -> read_body(Req, #{})
+
+read_body(Req :: cowboy_req:req(), Opts)
+    -> {ok,   Data :: binary(), Req}
+     | {more, Data :: binary(), Req}
+
+Opts :: cowboy_req:read_body_opts()
+
+

Read the request body.

+

This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body.

+

An ok tuple with empty data is returned when the request has no body, or when calling this function again after the body has already been read. It is therefore safe to call this function directly. Note that the body can only be read once.

+

This function reads the request body from the connection process. The connection process is responsible for reading from the socket. The exact behavior varies depending on the protocol.

+

The options therefore are only related to the communication between the request process and the connection process.

+

Cowboy will automatically handle protocol details including the expect header, chunked transfer-encoding and others.

+

Once the body has been read fully, Cowboy sets the content-length header if it was not previously provided.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. -

-

The length option can be used to request smaller or bigger -chunks of data to be sent. It is a best effort approach, Cowboy -may send more data than configured on occasions. It defaults -to 8MB.

-

The period indicates how long the connection process will wait -before it provides us with the data it received. It defaults -to 15 seconds.

-

The connection process sends data to the request process when -either the length of data or the period of time is reached.

-

The timeout option is a safeguard in case the connection -process becomes unresponsive. The function will crash if no -message was received in that interval. The timeout should be -larger than the period. It defaults to the period + 1 second.

+
Opts
+

A map of body reading options.

+

The length option can be used to request smaller or bigger chunks of data to be sent. It is a best effort approach, Cowboy may send more data than configured on occasions. It defaults to 8MB.

+

The period indicates how long the connection process will wait before it provides us with the data it received. It defaults to 15 seconds.

+

The connection process sends data to the request process when either the length of data or the period of time is reached.

+

The timeout option is a safeguard in case the connection process becomes unresponsive. The function will crash if no message was received in that interval. The timeout should be larger than the period. It defaults to the period
1 second.

-
-
- -
+

Return value

-
-

A more tuple is returned when there are more data to be read.

-

An ok tuple is returned when there are no more data to be read, -either because this is the last chunk of data, the body has already -been read, or there was no body to begin with.

-

The data is always returned as a binary.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

A more tuple is returned when there are more data to be read.

+

An ok tuple is returned when there are no more data to be read, either because this is the last chunk of data, the body has already been read, or there was no body to begin with.

+

The data is always returned as a binary.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces body/1,2. -

    +
    • 2.0: Function introduced. Replaces body/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read the entire body
-
-
read_body(Req0, Acc) ->
-    case cowboy_req:read_body(Req0) of
-        {ok, Data, Req} -> {ok, << Acc/binary, Data/binary >>, Req};
-        {more, Data, Req} -> read_body(Req, << Acc/binary, Data/binary >>)
-    end.
-
-
Read the body in small chunks
-
-
cowboy_req:read_body(Req, #{length => 64000}).
-
-
-
+
cowboy_req:read_body(Req, #{length => 64000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.read_part/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.read_part/index.html index 1c8c632d..a4afda73 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.read_part/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.read_part/index.html @@ -62,162 +62,94 @@

cowboy_req:read_part(3)

-

Name

-
-

cowboy_req:read_part - Read the next multipart headers

-
-
-
+

cowboy_req:read_part - Read the next multipart headers

Description

-
-
-
-
read_part(Req :: cowboy_req:req())
-    -> read_part(Req, #{})
-
-read_part(Req :: cowboy_req:req(), Opts)
-    -> {ok, Headers, Req} | {done, Req}
-
-Opts    :: cowboy_req:read_body_opts()
-Headers :: #{binary() => binary()}
-

Read the next part of a multipart body.

-

This function reads the request body and parses it as -multipart. Each parts of a multipart representation have -their own headers and body. This function parses and returns -headers. Examples of multipart media types are -multipart/form-data and multipart/byteranges.

-

Cowboy will skip any data remaining until the beginning of -the next part. This includes the preamble to the multipart -message but also the body of a previous part if it hasn’t -been read. Both are skipped automatically when calling this -function.

-

Cowboy will read the body before parsing in chunks of size -up to 64KB, with a period of 5 seconds. This is tailored for -reading part headers and might not be the most efficient for -skipping the previous part’s body.

-

The headers returned are MIME headers, NOT HTTP headers. -They can be parsed using the functions from the cow_multipart -module. In addition, the cow_multipart:form_data/1 function -can be used to quickly extract information from multipart/form-data -representations.

-

Once a part has been read, it can not be read again.

-

Once the body has been read, Cowboy sets the content-length -header if it was not previously provided.

-
-
-
+
read_part(Req :: cowboy_req:req())
+    -> read_part(Req, #{})
+
+read_part(Req :: cowboy_req:req(), Opts)
+    -> {ok, Headers, Req} | {done, Req}
+
+Opts    :: cowboy_req:read_body_opts()
+Headers :: #{binary() => binary()}
+
+

Read the next part of a multipart body.

+

This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. Examples of multipart media types are multipart/form-data and multipart/byteranges.

+

Cowboy will skip any data remaining until the beginning of the next part. This includes the preamble to the multipart message but also the body of a previous part if it hasn't been read. Both are skipped automatically when calling this function.

+

Cowboy will read the body before parsing in chunks of size up to 64KB, with a period of 5 seconds. This is tailored for reading part headers and might not be the most efficient for skipping the previous part's body.

+

The headers returned are MIME headers, NOT HTTP headers. They can be parsed using the functions from the cow_multipart module. In addition, the cow_multipart:form_data/1 function can be used to quickly extract information from multipart/form-data representations.

+ +

Once a part has been read, it can not be read again.

+

Once the body has been read, Cowboy sets the content-length header if it was not previously provided.

+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. Please refer to -cowboy_req:read_body(3) -for details about each option. -

-

This function defaults the length to 64KB and the period -to 5 seconds.

+
Opts
+

A map of body reading options. Please refer to cowboy_req:read_body(3) for details about each option.

+

This function defaults the length to 64KB and the period to 5 seconds.

-
-
- -
+

Return value

-
-

An ok tuple is returned containing the next part’s headers -as a map.

-

A done tuple is returned if there are no more parts to read.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

An ok tuple is returned containing the next part's headers as a map.

+

A done tuple is returned if there are no more parts to read.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces part/1,2. -

    +
    • 2.0: Function introduced. Replaces part/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read all parts
-
-
acc_multipart(Req0, Acc) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, Headers, Req1} ->
-            {ok, Body, Req} = stream_body(Req1, <<>>),
-            acc_multipart(Req, [{Headers, Body}|Acc]);
-        {done, Req} ->
-            {lists:reverse(Acc), Req}
-    end.
-
-stream_body(Req0, Acc) ->
-    case cowboy_req:read_part_body(Req0) of
-        {more, Data, Req} ->
-            stream_body(Req, << Acc/binary, Data/binary >>);
-        {ok, Data, Req} ->
-            {ok, << Acc/binary, Data/binary >>, Req}
-    end.
-
-
Read all part headers, skipping bodies
-
-
skip_body_multipart(Req0, Acc) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, Headers, Req} ->
-            skip_body_multipart(Req, [Headers|Acc]);
-        {done, Req} ->
-            {lists:reverse(Acc), Req}
-    end.
-
-
Read a part header in larger chunks
-
-
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).
-
-
-
+
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.read_part_body/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.read_part_body/index.html index 058903a0..c3b898a0 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.read_part_body/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.read_part_body/index.html @@ -62,130 +62,70 @@

cowboy_req:read_part_body(3)

-

Name

-
-

cowboy_req:read_part_body - Read the current part’s body

-
-
-
+

cowboy_req:read_part_body - Read the current part's body

Description

-
-
-
-
read_part_body(Req :: cowboy_req:req())
-    -> read_part_body(Req, #{})
-
-read_part_body(Req :: cowboy_req:req(), Opts)
-    -> {ok,   Data :: binary(), Req}
-     | {more, Data :: binary(), Req}
-
-Opts :: cowboy_req:read_body_opts()
-

Read the body of the current part of the multipart message.

-

This function reads the request body and parses it as -multipart. Each parts of a multipart representation have -their own headers and body. This function returns the -body of the current part. Examples of multipart media types -are multipart/form-data and multipart/byteranges.

-

This function reads a chunk of the part’s body. A more tuple -is returned when more data remains to be read. Call the function -repeatedly until an ok tuple is returned to read the entire body.

-

Once a part has been read, it can not be read again.

-

Once the body has been read, Cowboy sets the content-length -header if it was not previously provided.

-
-
-
+
read_part_body(Req :: cowboy_req:req())
+    -> read_part_body(Req, #{})
+
+read_part_body(Req :: cowboy_req:req(), Opts)
+    -> {ok,   Data :: binary(), Req}
+     | {more, Data :: binary(), Req}
+
+Opts :: cowboy_req:read_body_opts()
+
+

Read the body of the current part of the multipart message.

+

This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function returns the body of the current part. Examples of multipart media types are multipart/form-data and multipart/byteranges.

+

This function reads a chunk of the part's body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body.

+

Once a part has been read, it can not be read again.

+

Once the body has been read, Cowboy sets the content-length header if it was not previously provided.

+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. Please refer to -cowboy_req:read_body(3) -for details about each option. -

-

This function uses the same default options as the -cowboy_req:read_body(3) -function.

+
Opts
+

A map of body reading options. Please refer to cowboy_req:read_body(3) for details about each option.

+

This function uses the same default options as the cowboy_req:read_body(3) function.

-
-
- -
+

Return value

-
-

A more tuple is returned when there are more data to be read.

-

An ok tuple is returned when there are no more data to be read.

-

The data is always returned as a binary.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

A more tuple is returned when there are more data to be read.

+

An ok tuple is returned when there are no more data to be read.

+

The data is always returned as a binary.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces part_body/1,2. -

    +
    • 2.0: Function introduced. Replaces part_body/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read a full part’s body
-
-
stream_body(Req0, Acc) ->
-    case cowboy_req:read_part_body(Req0) of
-        {more, Data, Req} ->
-            stream_body(Req, << Acc/binary, Data/binary >>);
-        {ok, Data, Req} ->
-            {ok, << Acc/binary, Data/binary >>, Req}
-    end.
-
-
Ensure a part’s body is smaller than 64KB
-
-
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).
-
-
-
+
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.read_urlencoded_body/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.read_urlencoded_body/index.html index 70bd0d48..19a2058f 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.read_urlencoded_body/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.read_urlencoded_body/index.html @@ -62,126 +62,64 @@

cowboy_req:read_urlencoded_body(3)

-

Name

-
-

cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body

-
-
-
+

cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body

Description

-
-
-
-
read_urlencoded_body(Req :: cowboy_req:req())
-    -> read_urlencoded_body(Req, #{})
-
-read_urlencoded_body(Req :: cowboy_req:req(), Opts)
-    -> {ok, Body, Req}
-
-Opts :: cowboy_req:read_body_opts()
-Body :: [{Key :: binary(), Value :: binary() | true}]
-

Read and parse a urlencoded request body.

-

This function reads the request body and parses it as -application/x-www-form-urlencoded. It returns a list -of key/values.

-

The urlencoded media type is used by Web browsers when -submitting HTML forms using the POST method.

-

Cowboy needs to read the full body before parsing. By default -it will read bodies of size up to 64KB. It is possible to -provide options to read larger bodies if required.

-

Cowboy will automatically handle protocol details including -the expect header, chunked transfer-encoding and others.

-

Once the body has been read, Cowboy sets the content-length -header if it was not previously provided.

-

This function can only be called once. Calling it again will -result in undefined behavior.

-
-
-
+
read_urlencoded_body(Req :: cowboy_req:req())
+    -> read_urlencoded_body(Req, #{})
+
+read_urlencoded_body(Req :: cowboy_req:req(), Opts)
+    -> {ok, Body, Req}
+
+Opts :: cowboy_req:read_body_opts()
+Body :: [{Key :: binary(), Value :: binary() | true}]
+
+

Read and parse a urlencoded request body.

+

This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values.

+

The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method.

+

Cowboy needs to read the full body before parsing. By default it will read bodies of size up to 64KB. It is possible to provide options to read larger bodies if required.

+

Cowboy will automatically handle protocol details including the expect header, chunked transfer-encoding and others.

+

Once the body has been read, Cowboy sets the content-length header if it was not previously provided.

+

This function can only be called once. Calling it again will result in undefined behavior.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. Please refer to -cowboy_req:read_body(3) -for details about each option. -

-

This function defaults the length to 64KB and the period -to 5 seconds.

+
Opts
+

A map of body reading options. Please refer to cowboy_req:read_body(3) for details about each option.

+

This function defaults the length to 64KB and the period to 5 seconds.

-
-
- -
+

Return value

-
-

An ok tuple is returned containing a list of key/values found -in the body.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

An ok tuple is returned containing a list of key/values found in the body.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces body_qs/1,2. -

    +
    • 2.0: Function introduced. Replaces body_qs/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read a urlencoded body
-
-
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0),
-{_, Lang} = lists:keyfind(<<"lang">>, 1, Body).
-
-
Allow large urlencoded bodies
-
-
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).
-
-
-
+
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.reply/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.reply/index.html index ae3ba450..f5c3f8ed 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.reply/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.reply/index.html @@ -62,165 +62,87 @@

cowboy_req:reply(3)

-

Name

-
-

cowboy_req:reply - Send the response

-
-
-
+

cowboy_req:reply - Send the response

Description

-
-
-
-
reply(Status, Req :: cowboy_req:req())
-    -> reply(StatusCode, #{}, Req)
-
-reply(Status, Headers, Req :: cowboy_req:req())
-    -> Req
-
-reply(Status, Headers, Body, Req :: cowboy_req:req())
-    -> Req
-
-Status  :: cowboy:http_status()
-Headers :: cowboy:http_headers()
-Body    :: cowboy_req:resp_body()
-

Send the response.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may overwrite those set by set_resp_header/3 -and set_resp_headers/2.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-

The reply/2,3 functions will send the body set previously, -if any. The reply/4 function always sends the given body, -overriding any previously set.

-

You do not need to set the content-length header when -sending a response body. Cowboy takes care of it automatically. -You should however provide a content-type header.

-

No further data can be transmitted after this function -returns. This includes the push mechanism. Attempting to -send two replies, or to push resources after a reply has -been sent, will result in an error.

-
-
-
+
reply(Status, Req :: cowboy_req:req())
+    -> reply(StatusCode, #{}, Req)
+
+reply(Status, Headers, Req :: cowboy_req:req())
+    -> Req
+
+reply(Status, Headers, Body, Req :: cowboy_req:req())
+    -> Req
+
+Status  :: cowboy:http_status()
+Headers :: cowboy:http_headers()
+Body    :: cowboy_req:resp_body()
+
+

Send the response.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3 and set_resp_headers/2.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

+

The reply/2,3 functions will send the body set previously, if any. The reply/4 function always sends the given body, overriding any previously set.

+

You do not need to set the content-length header when sending a response body. Cowboy takes care of it automatically. You should however provide a content-type header.

+

No further data can be transmitted after this function returns. This includes the push mechanism. Attempting to send two replies, or to push resources after a reply has been sent, will result in an error.

Arguments

-
-
-
-Status -
-
-

-The status code for the response. -

+
Status
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Body -
-
-

-The body can be either a binary value, an iolist or a -sendfile tuple telling Cowboy to send the contents of -a file. -

+
+

Header names must be given as lowercase binary strings.

+
Body
+

The body can be either a binary value, an iolist or a sendfile tuple telling Cowboy to send the contents of a file.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object should be used from that point onward -as it contains updated information about the state of the request.

-
-
-
+

A new Req object is returned.

+

The returned Req object should be used from that point onward as it contains updated information about the state of the request.

Changelog

-
-
    -
  • -

    -2.0: Only the Req is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the Req is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Reply
-
-
Req = cowboy_req:reply(404, Req0).
-
-
Reply with custom headers
-
-
Req = cowboy_req:reply(401, #{
-    <<"www-authenticate">> => <<"Basic realm=\"erlang.org\"">>
-}, Req0).
-
-
Reply with custom headers and a body
-
-
Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, "Hello world!", Req0).
-
-
-
+
Req = cowboy_req:reply(200, #{
+    <<"content-type">> => <<"text/plain">>
+}, "Hello world!", Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:set_resp_body(3), cowboy_req:inform(3), cowboy_req:stream_reply(3), cowboy_req:push(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.resp_header/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.resp_header/index.html index 8633fcc7..53a0bb00 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.resp_header/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.resp_header/index.html @@ -62,113 +62,58 @@

cowboy_req:resp_header(3)

-

Name

-
-

cowboy_req:resp_header - Response header

-
-
-
+

cowboy_req:resp_header - Response header

Description

-
-
-
-
resp_header(Name, Req)          -> resp_header(Name, Req, undefined)
-resp_header(Name, Req, Default) -> binary() | Default
-
-Name    :: binary()          %% lowercase; case insensitive
-Req     :: cowboy_req:req()
-Default :: any()
-

Return the value for the given response header.

-

The response header must have been set previously using -cowboy_req:set_resp_header(3) or -cowboy_req:set_resp_headers(3).

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+
resp_header(Name, Req)          -> resp_header(Name, Req, undefined)
+resp_header(Name, Req, Default) -> binary() | Default
+
+Name    :: binary()          %% lowercase; case insensitive
+Req     :: cowboy_req:req()
+Default :: any()
+
+

Return the value for the given response header.

+

The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3).

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Name -
-
-

-Desired response header name as a lowercase binary string. -

+
Name
+

Desired response header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the header is missing. -

+
Default
+

Default value returned when the header is missing.

-
-
- -
+

Return value

-
-

The header value is returned as a binary string. When the -header is missing, the default argument is returned.

-
-
-
+

The header value is returned as a binary string. When the header is missing, the default argument is returned.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the content-type response header
-
-
Type = cowboy_req:resp_header(<<"content-type">>, Req).
-
-
Get the content-type response header with a default value
-
-
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).
-
-
-
+
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).
+

See also

- - +

cowboy_req(3), cowboy_req:resp_headers(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.resp_headers/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.resp_headers/index.html index b228ad28..d7be7452 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.resp_headers/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.resp_headers/index.html @@ -62,79 +62,38 @@

cowboy_req:resp_headers(3)

-

Name

-
-

cowboy_req:resp_headers - Response headers

-
-
-
+

cowboy_req:resp_headers - Response headers

Description

-
-
-
-
resp_headers(Req :: cowboy_req:req()) -> cowboy:http_headers()
-

Return all response headers.

-
-
-
+
resp_headers(Req :: cowboy_req:req()) -> cowboy:http_headers()
+
+

Return all response headers.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Headers are returned as a map with keys being lowercase -binary strings, and values as binary strings.

-
-
-
+

Headers are returned as a map with keys being lowercase binary strings, and values as binary strings.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get all response headers
-
-
Headers = cowboy_req:resp_headers(Req).
-
-
-
+
Headers = cowboy_req:resp_headers(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:resp_header(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.scheme/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.scheme/index.html index a1937174..ca4c8f1a 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.scheme/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.scheme/index.html @@ -62,89 +62,52 @@

cowboy_req:scheme(3)

-

Name

-
-

cowboy_req:scheme - URI scheme

-
-
-
+

cowboy_req:scheme - URI scheme

Description

-
-
-
-
scheme(Req :: cowboy_req:req()) -> Scheme :: binary()
-

Return the scheme of the effective request URI.

-

The scheme can also be obtained using pattern matching:

-
-
-
#{scheme := Scheme} = Req.
-
-
-
+
#{scheme := Scheme} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The scheme is returned as a binary. It is case insensitive.

-

Cowboy will only set the scheme to <<"http">> or <<"https">>.

-
-
-
+

The scheme is returned as a binary. It is case insensitive.

+

Cowboy will only set the scheme to <<"http">> or <<"https">>.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Redirect HTTP to HTTPS
-
-
init(Req0=#{scheme := <<"http">>}, State) ->
-    Req = cowboy_req:reply(302, #{
-        <<"location">> => cowboy_req:uri(Req, #{scheme => <<"https">>})
-    }, Req0),
-    {ok, Req, State};
-init(Req, State) ->
-    {cowboy_rest, Req, State}.
-
-
-
+
init(Req0=#{scheme := <<"http">>}, State) ->
+    Req = cowboy_req:reply(302, #{
+        <<"location">> => cowboy_req:uri(Req, #{scheme => <<"https">>})
+    }, Req0),
+    {ok, Req, State};
+init(Req, State) ->
+    {cowboy_rest, Req, State}.
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_body/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_body/index.html index 537bdd40..c2fc5186 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_body/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_body/index.html @@ -62,138 +62,79 @@

cowboy_req:set_resp_body(3)

-

Name

-
-

cowboy_req:set_resp_body - Set the response body

-
-
-
+

cowboy_req:set_resp_body - Set the response body

Description

-
-
-
-
set_resp_body(Body, Req :: cowboy_req:req())
-        -> Req
-
-Body :: cowboy_req:resp_body()
-

Set the response body.

-

The response body will be sent when a reply is initiated. -Note that the functions stream_reply/2,3 and reply/4 -will override the body set by this function.

-

This function can also be used to remove a response body -that was set previously. To do so, simply call this function -with an empty body.

-
-
-
+
set_resp_body(Body, Req :: cowboy_req:req())
+	-> Req
+
+Body :: cowboy_req:resp_body()
+
+

Set the response body.

+

The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function.

+

This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body.

Arguments

-
-
-
-Body -
-
-

-The body can be either a binary value, an iolist or a -sendfile tuple telling Cowboy to send the contents of -a file. -

+
Body
+

The body can be either a binary value, an iolist or a sendfile tuple telling Cowboy to send the contents of a file.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the body will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the body will not be sent in the response.

Changelog

-
-
    -
  • -

    -2.0: The function now accepts a sendfile tuple. -

    +
    • 2.0: The function now accepts a sendfile tuple.
    • -
    • -

      -2.0: The set_resp_body_fun/2,3 functions were removed. -

      +
    • 2.0: The set_resp_body_fun/2,3 functions were removed.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set the response body
-
-
Req = cowboy_req:set_resp_body(<<"Hello world!">>, Req0).
-
-
Set the response body as an iolist
-
-
Req = cowboy_req:set_resp_body([
-    "<html><head><title>",
-    page_title(),
-    "</title></head><body>",
-    page_body(),
-    "</body></html>"
-], Req0).
-
-
Tell Cowboy to send data from a file
-
-
{ok, #file_info{size=Size}} = file:read_file_info(Filename),
-Req = cowboy_req:set_resp_body({sendfile, 0, Size, Filename}, Req0).
-
-
Clear any previously set response body
-
-
Req = cowboy_req:set_resp_body(<<>>, Req0).
-
-
-
+
Req = cowboy_req:set_resp_body(<<>>, Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_cookie/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_cookie/index.html index d251b22c..d816604c 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_cookie/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_cookie/index.html @@ -62,167 +62,104 @@

cowboy_req:set_resp_cookie(3)

-

Name

-
-

cowboy_req:set_resp_cookie - Set a cookie

-
-
-
+

cowboy_req:set_resp_cookie - Set a cookie

Description

-
-
-
-
set_resp_cookie(Name, Value, Req :: cowboy_req:req())
-    -> set_resp_cookie(Name, Value, [], Req)
-
-set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts)
-    -> Req
-
-Name  :: binary()                  %% case sensitive
-Value :: iodata()                  %% case sensitive
-Opts  :: cow_cookie:cookie_opts()
-

Set a cookie to be sent with the response.

-

Note that cookie names are case sensitive.

-
-
-
+
set_resp_cookie(Name, Value, Req :: cowboy_req:req())
+    -> set_resp_cookie(Name, Value, [], Req)
+
+set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts)
+    -> Req
+
+Name  :: binary()                  %% case sensitive
+Value :: iodata()                  %% case sensitive
+Opts  :: cow_cookie:cookie_opts()
+
+

Set a cookie to be sent with the response.

+

Note that cookie names are case sensitive.

Arguments

-
-
-
-Name -
-
-

-Cookie name. -

+
Name
+

Cookie name.

-
-Value -
-
-

-Cookie value. -

+
Value
+

Cookie value.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-Cookie options. -

+
Opts
+

Cookie options.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the cookie will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the cookie will not be sent in the response.

Changelog

-
-
    -
  • -

    -2.0: set_resp_cookie/3 introduced as an alias to set_resp_cookie/4 with no options. -

    +
    • 2.0: set_resp_cookie/3 introduced as an alias to set_resp_cookie/4 with no options.
    • -
    • -

      -2.0: The first argument type is now binary() instead of iodata(). -

      +
    • 2.0: The first argument type is now binary() instead of iodata().
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set a session cookie
-
-
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0).
-
-
Set a cookie with an expiration time
-
-
Req = cowboy_req:set_resp_cookie(<<"lang">>, <<"fr-FR">>,
-    Req0, #{max_age => 3600}).
-
-
Delete a cookie
-
-
Req = cowboy_req:set_resp_cookie(<<"sessionid">>, <<>>,
-    Req0, #{max_age => 0}).
-
-
Set a cookie for a specific domain and path
-
-
Req = cowboy_req:set_resp_cookie(<<"inaccount">>, <<"1">>,
-    Req0, #{domain => "my.example.org", path => "/account"}).
-
-
Restrict a cookie to HTTPS
-
-
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID,
-    Req0, #{secure => true}).
-
-
Restrict a cookie to HTTP
-
-
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID,
-    Req0, #{http_only => true}).
-
-
-
+
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
+Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID,
+    Req0, #{http_only => true}).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_header/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_header/index.html index ee6fcf2c..57e6e8d7 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_header/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_header/index.html @@ -62,121 +62,60 @@

cowboy_req:set_resp_header(3)

-

Name

-
-

cowboy_req:set_resp_header - Set a response header

-
-
-
+

cowboy_req:set_resp_header - Set a response header

Description

-
-
-
-
set_resp_header(Name, Value, Req :: cowboy_req:req())
-        -> Req
-
-Name  :: binary()  %% lowercase; case insensitive
-Value :: iodata()  %% case depends on header
-

Set a header to be sent with the response.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may be overwritten by those set from the -reply functions.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-
-
-
+
set_resp_header(Name, Value, Req :: cowboy_req:req())
+	-> Req
+
+Name  :: binary()  %% lowercase; case insensitive
+Value :: iodata()  %% case depends on header
+
+

Set a header to be sent with the response.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

Arguments

-
-
-
-Name -
-
-

-Header name as a lowercase binary string. -

+
Name
+

Header name as a lowercase binary string.

-
-Value -
-
-

-Header value. -

+
Value
+

Header value.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the header will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the header will not be sent in the response.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set a header in the response
-
-
Req = cowboy_req:set_resp_header(<<"allow">>, "GET", Req0).
-
-
Construct a header using iolists
-
-
Req = cowboy_req:set_resp_header(<<"allow">>,
-    [allowed_methods(), ", OPTIONS"], Req0).
-
-
-
+
Req = cowboy_req:set_resp_header(<<"allow">>,
+    [allowed_methods(), ", OPTIONS"], Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_headers(3), cowboy_req:has_resp_header(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3), cowboy_req:delete_resp_header(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_headers/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_headers/index.html index 8b73363d..5545ea15 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_headers/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_headers/index.html @@ -62,109 +62,51 @@

cowboy_req:set_resp_headers(3)

-

Name

-
-

cowboy_req:set_resp_headers - Set several response headers

-
-
-
+

cowboy_req:set_resp_headers - Set several response headers

Description

-
-
-
-
set_resp_headers(Headers, Req :: cowboy_req:req())
-    -> Req
-
-Headers :: cowboy:http_headers()
-

Set several headers to be sent with the response.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may be overwritten by those set from the -reply functions. Likewise, headers set by this function may -overwrite headers that were set previously.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-
-
-
+
set_resp_headers(Headers, Req :: cowboy_req:req())
+    -> Req
+
+Headers :: cowboy:http_headers()
+
+

Set several headers to be sent with the response.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. Likewise, headers set by this function may overwrite headers that were set previously.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

Arguments

-
-
-
-Headers -
-
-

-Headers as a map with keys being lowercase binary strings, -and values as binary strings. -

+
Headers
+

Headers as a map with keys being lowercase binary strings, and values as binary strings.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the headers will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the headers will not be sent in the response.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set several response headers
-
-
Req = cowboy_req:set_resp_headers(#{
-    <<"content-type">>     => <<"text/html">>,
-    <<"content-encoding">> => <<"gzip">>
-}, Req0).
-
-
-
+
Req = cowboy_req:set_resp_headers(#{
+    <<"content-type">>     => <<"text/html">>,
+    <<"content-encoding">> => <<"gzip">>
+}, Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_header(3), cowboy_req:has_resp_header(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3), cowboy_req:delete_resp_header(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.sock/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.sock/index.html index 7395c134..3281d9b6 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.sock/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.sock/index.html @@ -62,86 +62,47 @@

cowboy_req:sock(3)

-

Name

-
-

cowboy_req:sock - Socket address and port

-
-
-
+

cowboy_req:sock - Socket address and port

Description

-
-
-
-
sock(Req :: cowboy_req:req()) -> Info
+
sock(Req :: cowboy_req:req()) -> Info
 
-Info :: {inet:ip_address(), inet:port_number()}
-

Return the socket’s IP address and port number.

-

The socket information can also be obtained using pattern matching:

-
-
-
#{sock := {IP, Port}} = Req.
-
-
-
+
#{sock := {IP, Port}} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The socket’s local IP address and port number.

-
-
-
+

The socket's local IP address and port number.

Changelog

-
-
    -
  • -

    -2.1: Function introduced. -

    +
    • 2.1: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the socket’s IP address and port number.
-
-
{IP, Port} = cowboy_req:sock(Req).
-
-
-
+
{IP, Port} = cowboy_req:sock(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:peer(3), cowboy_req:cert(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.stream_body/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.stream_body/index.html index f1f341f8..9b35540b 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.stream_body/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.stream_body/index.html @@ -62,116 +62,56 @@

cowboy_req:stream_body(3)

-

Name

-
-

cowboy_req:stream_body - Stream the response body

-
-
-
+

cowboy_req:stream_body - Stream the response body

Description

-
-
-
-
stream_body(Data, IsFin, Req :: cowboy_req:req()) -> ok
-
-Data  :: iodata()
-IsFin :: fin | nofin
-

Stream the response body.

-

This function may be called as many times as needed after -initiating a response using the -cowboy_req:stream_reply(3) -function.

-

The second argument indicates if this call is the final -call. Use the nofin value until you know no more data -will be sent. The final call should use fin (possibly -with an empty data value).

-

Note that not using fin for the final call is not an -error; Cowboy will take care of it when the request -handler terminates if needed. Depending on the resource -it may however be more efficient to do it as early as -possible.

-

You do not need to handle HEAD requests specifically as -Cowboy will ensure no data is sent when you call this function.

-
-
-
+
stream_body(Data, IsFin, Req :: cowboy_req:req()) -> ok
+
+Data  :: iodata()
+IsFin :: fin | nofin
+
+

Stream the response body.

+

This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function.

+

The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. The final call should use fin (possibly with an empty data value).

+

Note that not using fin for the final call is not an error; Cowboy will take care of it when the request handler terminates if needed. Depending on the resource it may however be more efficient to do it as early as possible.

+

You do not need to handle HEAD requests specifically as Cowboy will ensure no data is sent when you call this function.

Arguments

-
-
-
-Data -
-
-

-The data to be sent. -

+
Data
+

The data to be sent.

-
-IsFin -
-
-

-A flag indicating whether this is the final piece of data -to be sent. -

+
IsFin
+

A flag indicating whether this is the final piece of data to be sent.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces chunk/2. -

    +
    • 2.0: Function introduced. Replaces chunk/2.
    • -
-
-
-
+

Examples

-
-
-
Stream the response body
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, Req0),
-cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
-timer:sleep(1000),
-cowboy_req:stream_body(<<"World!\n">>, fin, Req).
-
-
-
+
Req = cowboy_req:stream_reply(200, #{
+    <<"content-type">> => <<"text/plain">>
+}, Req0),
+cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
+timer:sleep(1000),
+cowboy_req:stream_body(<<"World!\n">>, fin, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.stream_reply/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.stream_reply/index.html index 1f4accbd..53d5066c 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.stream_reply/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.stream_reply/index.html @@ -62,149 +62,76 @@

cowboy_req:stream_reply(3)

-

Name

-
-

cowboy_req:stream_reply - Send the response headers

-
-
-
+

cowboy_req:stream_reply - Send the response headers

Description

-
-
-
-
stream_reply(Status, Req :: cowboy_req:req())
-    -> stream_reply(StatusCode, #{}, Req)
-
-stream_reply(Status, Headers, Req :: cowboy_req:req())
-    -> Req
-
-Status  :: cowboy:http_status()
-Headers :: cowboy:http_headers()
-

Send the response headers.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may overwrite those set by set_resp_header/3.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-

If a response body was set before calling this function, -it will not be sent.

-

Use cowboy_req:stream_body(3) -to stream the response body.

-

You may want to set the content-length header when using -this function, if it is known in advance. This will allow -clients using HTTP/2 and HTTP/1.0 to process the response -more efficiently.

-

The streaming method varies depending on the protocol being -used. HTTP/2 will use the usual DATA frames. HTTP/1.1 will -use chunked transfer-encoding. HTTP/1.0 will send the body -unmodified and close the connection at the end if no -content-length was set.

-

It is not possible to push resources after this function -returns. Any attempt will result in an error.

-
-
-
+
stream_reply(Status, Req :: cowboy_req:req())
+    -> stream_reply(StatusCode, #{}, Req)
+
+stream_reply(Status, Headers, Req :: cowboy_req:req())
+    -> Req
+
+Status  :: cowboy:http_status()
+Headers :: cowboy:http_headers()
+
+

Send the response headers.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

+

If a response body was set before calling this function, it will not be sent.

+

Use cowboy_req:stream_body(3) to stream the response body.

+

You may want to set the content-length header when using this function, if it is known in advance. This will allow clients using HTTP/2 and HTTP/1.0 to process the response more efficiently.

+

The streaming method varies depending on the protocol being used. HTTP/2 will use the usual DATA frames. HTTP/1.1 will use chunked transfer-encoding. HTTP/1.0 will send the body unmodified and close the connection at the end if no content-length was set.

+

It is not possible to push resources after this function returns. Any attempt will result in an error.

Arguments

-
-
-
-Status -
-
-

-The status code for the response. -

+
Status
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Req -
-
-

-The Req object. -

+
+

Header names must be given as lowercase binary strings.

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward -in order to be able to stream the response body.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward in order to be able to stream the response body.

Changelog

-
-
    -
  • -

    -2.0: Only the Req is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the Req is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces chunked_reply/1,2. -

      +
    • 2.0: Function introduced. Replaces chunked_reply/1,2.
    • -
-
-
-
+

Examples

-
-
-
Initiate the response
-
-
Req = cowboy_req:stream_reply(200, Req0).
-
-
Stream the response with custom headers
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, Req0),
-cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
-timer:sleep(1000),
-cowboy_req:stream_body(<<"World!\n">>, fin, Req).
-
-
-
+
Req = cowboy_req:stream_reply(200, #{
+    <<"content-type">> => <<"text/plain">>
+}, Req0),
+cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
+timer:sleep(1000),
+cowboy_req:stream_body(<<"World!\n">>, fin, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:inform(3), cowboy_req:reply(3), cowboy_req:stream_body(3), cowboy_req:push(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.uri/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.uri/index.html index 329f721a..feb1c1c7 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.uri/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.uri/index.html @@ -62,177 +62,106 @@

cowboy_req:uri(3)

-

Name

-
-

cowboy_req:uri - Reconstructed URI

-
-
-
+

cowboy_req:uri - Reconstructed URI

Description

-
-
-
-
uri(Req :: cowboy_req:req())       -> uri(Req, #{})
-uri(Req :: cowboy_req:req(), Opts) -> URI :: iodata()
-
-Opts :: #{
-    scheme   => iodata()           | undefined,
-    host     => iodata()           | undefined,
-    port     => inet:port_number() | undefined,
-    path     => iodata()           | undefined,
-    qs       => iodata()           | undefined,
-    fragment => iodata()           | undefined
-}
-

Reconstruct the effective request URI, optionally modifying components.

-

By default Cowboy will build a URI using the components found -in the request. Options allow disabling or replacing individual -components.

-
-
-
+
uri(Req :: cowboy_req:req())       -> uri(Req, #{})
+uri(Req :: cowboy_req:req(), Opts) -> URI :: iodata()
+
+Opts :: #{
+    scheme   => iodata()           | undefined,
+    host     => iodata()           | undefined,
+    port     => inet:port_number() | undefined,
+    path     => iodata()           | undefined,
+    qs       => iodata()           | undefined,
+    fragment => iodata()           | undefined
+}
+
+

Reconstruct the effective request URI, optionally modifying components.

+

By default Cowboy will build a URI using the components found in the request. Options allow disabling or replacing individual components.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-Map for overriding individual components. -

-

To replace a component, provide its new value as a binary -string or an iolist. To disable a component, set its value -to undefined.

-

As this function always returns a valid URI, there are some -things to note:

-
    -
  • -

    -Disabling the host also disables the scheme and port. -

    +
    Opts
    +

    Map for overriding individual components.

    +

    To replace a component, provide its new value as a binary string or an iolist. To disable a component, set its value to undefined.

    +

    As this function always returns a valid URI, there are some things to note:

    +
    • Disabling the host also disables the scheme and port.
    • -
    • -

      -There is no fragment component by default as these are - not sent with the request. -

      +
    • There is no fragment component by default as these are not sent with the request.
    • -
    • -

      -The port number may not appear in the resulting URI if - it is the default port for the given scheme (http: 80; https: 443). -

      +
    • The port number may not appear in the resulting URI if it is the default port for the given scheme (http: 80; https: 443).
    • -
+
-
-
- -
+

Return value

-
-

The reconstructed URI is returned as an iolist or a binary string.

-
-
-
+

The reconstructed URI is returned as an iolist or a binary string.

Changelog

-
-
    -
  • -

    -2.0: Individual components can be replaced or disabled. -

    +
    • 2.0: Individual components can be replaced or disabled.
    • -
    • -

      -2.0: Only the URI is returned, it is no longer wrapped in a tuple. -

      +
    • 2.0: Only the URI is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces host_url/1 and url/1. -

      +
    • 2.0: Function introduced. Replaces host_url/1 and url/1.
    • -
-
-
-
+

Examples

-
-

With an effective request URI http://example.org/path/to/res?edit=1 -we can have:

-
-
Protocol relative form
-
-
%% //example.org/path/to/res?edit=1
-cowboy_req:uri(Req, #{scheme => undefined}).
-
-
Serialized origin for use in the origin header
-
-
%% http://example.org
-cowboy_req:uri(Req, #{path => undefined, qs => undefined}).
-
-
HTTP/1.1 origin form (path and query string only)
-
-
%% /path/to/res?edit=1
-cowboy_req:uri(Req, #{host => undefined}).
-
-
Add a fragment to the URI
-
-
%% http://example.org/path/to/res?edit=1#errors
-cowboy_req:uri(Req, #{fragment => <<"errors">>}).
-
-
Ensure the scheme is HTTPS
-
-
%% https://example.org/path/to/res?edit=1
-cowboy_req:uri(Req, #{scheme => <<"https">>}).
-
-
Convert the URI to a binary string
-
-
iolist_to_binary(cowboy_req:uri(Req)).
-
-
-
+
iolist_to_binary(cowboy_req:uri(Req)).
+

See also

- - +

cowboy_req(3), cowboy_req:scheme(3), cowboy_req:host(3), cowboy_req:port(3), cowboy_req:path(3), cowboy_req:qs(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req.version/index.html b/docs/en/cowboy/2.1/manual/cowboy_req.version/index.html index bce5f980..d17b908f 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req.version/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req.version/index.html @@ -62,88 +62,47 @@

cowboy_req:version(3)

-

Name

-
-

cowboy_req:version - HTTP version

-
-
-
+

cowboy_req:version - HTTP version

Description

-
-
-
-
version(Req :: cowboy_req:req()) -> Version :: cowboy:http_version()
-

Return the HTTP version used for the request.

-

The version can also be obtained using pattern matching:

-
-
-
#{version := Version} = Req.
-
-
-
+
#{version := Version} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The HTTP version used for the request is returned as an -atom. It is provided for informative purposes only.

-
-
-
+

The HTTP version used for the request is returned as an atom. It is provided for informative purposes only.

Changelog

-
-
    -
  • -

    -2.0: Only the version is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the version is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the HTTP version
-
-
Version = cowboy_req:version(Req).
-
-
-
+
Version = cowboy_req:version(Req).
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_req/index.html b/docs/en/cowboy/2.1/manual/cowboy_req/index.html index e228b025..7bd20a2f 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_req/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_req/index.html @@ -62,409 +62,216 @@

cowboy_req(3)

-

Name

-
-

cowboy_req - HTTP request and response

-
-
-
+

cowboy_req - HTTP request and response

Description

-
-

The module cowboy_req provides functions to access, manipulate -and respond to requests.

-

There are four types of functions in this module. They can be -differentiated by their name and their return type:

-
- ---- - - - - +

The module cowboy_req provides functions to access, manipulate and respond to requests.

+

There are four types of functions in this module. They can be differentiated by their name and their return type:

+
Type Name pattern Return type
+ + + + + + - - - - - - + + + - - - - + + + - - - - + + + - - - - - - -
TypeName patternReturn type
accessno verb, parse_*, match_*Value

access

no verb, parse_*, match_*

Value

questionhas_*boolean()

question

has_*

boolean()

modificationset_*Req

modification

set_*

Req

actionany other verbok | {Result, Value, Req}

action

any other verb

ok | {Result, Value, Req}

-
-

Any Req returned must be used in place of the one passed as -argument. Functions that perform an action in particular write -state in the Req object to make sure you are using the function -correctly. For example, it’s only possible to send one response, -and to read the body once.

-
-
-
+ +

Any Req returned must be used in place of the one passed as argument. Functions that perform an action in particular write state in the Req object to make sure you are using the function correctly. For example, it's only possible to send one response, and to read the body once.

Exports

-
-

Connection:

-
-

Raw request:

-
-

Processed request:

-
-

Request body:

-
-

Response:

-
-
-
-
+

Connection:

+ +

Raw request:

+ +

Processed request:

+ +

Request body:

+ +

Response:

+

Types

-
-

push_opts()

-
-
-
push_opts() :: #{
-    method => binary(),            %% case sensitive
-    scheme => binary(),            %% lowercase; case insensitive
-    host   => binary(),            %% lowercase; case insensitive
-    port   => inet:port_number(),
-    qs     => binary()             %% case sensitive
-}
-

Push options.

-

By default, Cowboy will use the GET method, an empty query string, -and take the scheme, host and port directly from the current -request’s URI.

-
-
+
push_opts() :: #{
+    method => binary(),            %% case sensitive
+    scheme => binary(),            %% lowercase; case insensitive
+    host   => binary(),            %% lowercase; case insensitive
+    port   => inet:port_number(),
+    qs     => binary()             %% case sensitive
+}
+
+

Push options.

+

By default, Cowboy will use the GET method, an empty query string, and take the scheme, host and port directly from the current request's URI.

read_body_opts()

-
-
-
read_body_opts() :: #{
-    length  => non_neg_integer(),
-    period  => non_neg_integer(),
-    timeout => timeout()
-}
-

Body reading options.

-

The defaults are function-specific.

-
-
+
read_body_opts() :: #{
+    length  => non_neg_integer(),
+    period  => non_neg_integer(),
+    timeout => timeout()
+}
+
+

Body reading options.

+

The defaults are function-specific.

req()

-
-
-
req() :: #{
-    method  := binary(),               %% case sensitive
-    version := cowboy:http_version() | atom(),
-    scheme  := binary(),               %% lowercase; case insensitive
-    host    := binary(),               %% lowercase; case insensitive
-    port    := inet:port_number(),
-    path    := binary(),               %% case sensitive
-    qs      := binary(),               %% case sensitive
-    headers := cowboy:http_headers(),
-    peer    := {inet:ip_address(), inet:port_number()},
-    sock    := {inet:ip_address(), inet:port_number()},
-    cert    := binary() | undefined
-}
-

The Req object.

-

Contains information about the request and response. While -some fields are publicly documented, others aren’t and shouldn’t -be used.

-

You may add custom fields if required. Make sure to namespace -them by prepending an underscore and the name of your application:

-
-
Setting a custom field
-
-
Req#{_myapp_auth_method => pubkey}.
- -
+
Req#{_myapp_auth_method => pubkey}.
+

resp_body()

-
-
-
resp_body() :: iodata()
-    | {sendfile, Offset, Length, Filename}
+
resp_body() :: iodata()
+    | {sendfile, Offset, Length, Filename}
 
-Offset   :: non_neg_integer()
-Length   :: non_neg_integer()
-Filename :: file:name_all()
-

Response body.

-

It can take two forms: the actual data to be sent or a -tuple indicating which file to send.

-

When sending data directly, the type is either a binary or -an iolist. Iolists are an efficient way to build output. -Instead of concatenating strings or binaries, you can simply -build a list containing the fragments you want to send in the -order they should be sent:

-
-
Example iolists usage
-
-
1> RespBody = ["Hello ", [<<"world">>, $!]].
-["Hello ",[<<"world">>,33]]
-2> io:format("~s~n", [RespBody]).
-Hello world!
-

Note that the length must be greater than zero for any data -to be sent. Cowboy will send an empty body when the length -is zero.

- - - -
+
1> RespBody = ["Hello ", [<<"world">>, $!]].
+["Hello ",[<<"world">>,33]]
+2> io:format("~s~n", [RespBody]).
+Hello world!
+
+

Note that the length must be greater than zero for any data to be sent. Cowboy will send an empty body when the length is zero.

See also

- - +

cowboy(7)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_rest/index.html b/docs/en/cowboy/2.1/manual/cowboy_rest/index.html index 6ee7e059..ed98dd95 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_rest/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_rest/index.html @@ -62,668 +62,475 @@

cowboy_rest(3)

-

Name

-
-

cowboy_rest - REST handlers

-
-
-
+

cowboy_rest - REST handlers

Description

-
-

The module cowboy_rest implements the HTTP state machine.

-

Implementing REST handlers is not enough to provide a REST -interface; this interface must also follow the REST -constraints including HATEOAS (hypermedia as the engine -of application state).

-
-
-
+

The module cowboy_rest implements the HTTP state machine.

+

Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state).

Callbacks

-
-

REST handlers implement the following interface:

-
-
-
init(Req, State)
-    -> {cowboy_rest, Req, State}
-
-Callback(Req, State)
-    -> {Result, Req, State}
-     | {stop, Req, State}
-     | {{switch_handler, Module}, Req, State}
-     | {{switch_handler, Module, Opts}, Req, State}
-
-terminate(Reason, Req, State) -> ok  %% optional
-
-Req    :: cowboy_req:req()
-State  :: any()
-Module :: module()
-Opts   :: any()
-Reason :: normal
-        | {crash, error | exit | throw, any()}
-
-Callback - see below
-Result   - see below
-Default  - see below
-

The init/2 callback is common to all handlers. To switch -to the REST handler behavior, it must return cowboy_rest -as the first element of the tuple.

-

The Callback/2 above represents all the REST-specific -callbacks. They are described in the following section -of this manual. REST-specific callbacks differ by their -name, semantics, result and default values. The default -value is the one used when the callback has not been -implemented. They otherwise all follow the same interface.

-

The stop tuple can be returned to stop REST processing. -If no response was sent before then, Cowboy will send a -204 No Content. The stop tuple can be returned from -any callback, excluding expires, generate_etag, -last_modified and variances.

-

A switch_handler tuple can be returned from these same -callbacks to stop REST processing and switch to a different -handler type. This is very useful to, for example, to stream -the response body.

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the handler. -Cowboy will terminate the process right after this. There -is no need to perform any cleanup in this callback.

-

The following terminate reasons are defined for loop handlers:

-
-
-normal -
-
-

- The handler terminated normally. -

+

REST handlers implement the following interface:

+
+
init(Req, State)
+    -> {cowboy_rest, Req, State}
+
+Callback(Req, State)
+    -> {Result, Req, State}
+     | {stop, Req, State}
+     | {{switch_handler, Module}, Req, State}
+     | {{switch_handler, Module, Opts}, Req, State}
+
+terminate(Reason, Req, State) -> ok  %% optional
+
+Req    :: cowboy_req:req()
+State  :: any()
+Module :: module()
+Opts   :: any()
+Reason :: normal
+        | {crash, error | exit | throw, any()}
+
+Callback - see below
+Result   - see below
+Default  - see below
+
+

The init/2 callback is common to all handlers. To switch to the REST handler behavior, it must return cowboy_rest as the first element of the tuple.

+

The Callback/2 above represents all the REST-specific callbacks. They are described in the following section of this manual. REST-specific callbacks differ by their name, semantics, result and default values. The default value is the one used when the callback has not been implemented. They otherwise all follow the same interface.

+

The stop tuple can be returned to stop REST processing. If no response was sent before then, Cowboy will send a 204 No Content. The stop tuple can be returned from any callback, excluding expires, generate_etag, last_modified and variances.

+

A switch_handler tuple can be returned from these same callbacks to stop REST processing and switch to a different handler type. This is very useful to, for example, to stream the response body.

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the handler. Cowboy will terminate the process right after this. There is no need to perform any cleanup in this callback.

+

The following terminate reasons are defined for loop handlers:

+
normal
+

The handler terminated normally.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
-
-
-
+

REST callbacks

-
-

AcceptCallback

-
-
-
AcceptCallback(Req, State) -> {Result, Req, State}
-
-Result  :: true | {true, URI :: iodata()} | false}
-Default  - crash
-

Process the request body.

-

This function should create or update the resource using the -request body.

-

For PUT requests, the body is a representation of the resource -that is being created or replaced.

-

For POST requests, the body is typically application-specific -instructions on how to process the request, but it may also -be a representation of the resource. When creating a new -resource with POST at a different location, return {true, URI} -with URI the new location.

-

For PATCH requests, the body is a series of instructions on -how to update the resource. Patch files or JSON Patch are -examples of such media types.

-

A response body may be sent. The appropriate media type, charset -and language for the response can be retrieved from the Req -object using the media_type, charset and language keys, -respectively. The body can be set using -cowboy_req:set_resp_body(3).

-
-
+
+
AcceptCallback(Req, State) -> {Result, Req, State}
+
+Result  :: true | {true, URI :: iodata()} | false}
+Default  - crash
+
+

Process the request body.

+

This function should create or update the resource using the request body.

+

For PUT requests, the body is a representation of the resource that is being created or replaced.

+

For POST requests, the body is typically application-specific instructions on how to process the request, but it may also be a representation of the resource. When creating a new resource with POST at a different location, return {true, URI} with URI the new location.

+

For PATCH requests, the body is a series of instructions on how to update the resource. Patch files or JSON Patch are examples of such media types.

+

A response body may be sent. The appropriate media type, charset and language for the response can be retrieved from the Req object using the media_type, charset and language keys, respectively. The body can be set using cowboy_req:set_resp_body(3).

allowed_methods

-
-
-
allowed_methods(Req, State) -> {Result, Req, State}
+
allowed_methods(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% case sensitive
-Default :: [<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]
-

Return the list of allowed methods.

-
-
+Result :: [binary()] %% case sensitive +Default :: [<<"GET">>, <<"HEAD">>, <<"OPTIONS">>] +
+

Return the list of allowed methods.

allow_missing_post

-
-
-
allow_missing_post(Req, State) -> {Result, Req, State}
+
allow_missing_post(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether POST is allowed when the resource doesn’t exist.

-

Returning true here means that a new resource will be -created. The URI for the newly created resource should be -returned from the AcceptCallback function.

-
-
+Result :: boolean() +Default :: true +
+

Return whether POST is allowed when the resource doesn't exist.

+

Returning true here means that a new resource will be created. The URI for the newly created resource should be returned from the AcceptCallback function.

charsets_provided

-
-
-
charsets_provided(Req, State) -> {Result, Req, State}
+
charsets_provided(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% lowercase; case insensitive
-Default  - skip this step
-

Return the list of charsets the resource provides in order -of preference.

-

During content negotiation Cowboy will pick the most -appropriate charset for the client. The client advertises -charsets it prefers with the accept-charset header. When -that header is missing, Cowboy picks the first charset -from the resource.

-

Cowboy will add the negotiated charset to the Req object -after this step completes:

-
-
+

Cowboy will add the negotiated charset to the Req object after this step completes:

+
-
req() :: #{
-    charset => binary()  %% lowercase; case insensitive
-}
-
-
+
req() :: #{
+    charset => binary()  %% lowercase; case insensitive
+}
+

content_types_accepted

-
-
-
content_types_accepted(Req, State) -> {Result, Req, State}
-
-Result     :: [{binary() | ParsedMime, AcceptCallback :: atom()}]
-ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-
-Default     - crash
-

Return the list of media types the resource accepts in -order of preference.

-

A media type is made of different parts. The media type -text/html;charset=utf-8 is of type text, subtype html -and has a single parameter charset with value utf-8.

-

Cowboy will match the content-type request header against -the media types the server accepts and select the appropriate -callback. When that header is missing, or when the server does not -accept this media type, the request fails and an error response -is returned. Cowboy will execute the callback immediately otherwise.

-

An empty parameters list [] means that no parameters will be -accepted. When any parameter is acceptable, the tuple form -should be used with parameters as the atom '*'.

-

Cowboy treats all parameters as case sensitive, except for the -charset parameter, which is known to be case insensitive. You -should therefore always provide the charset as a lowercase -binary string.

- -
+
+
content_types_accepted(Req, State) -> {Result, Req, State}
+
+Result     :: [{binary() | ParsedMime, AcceptCallback :: atom()}]
+ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+Default     - crash
+
+ +

Return the list of media types the resource accepts in order of preference.

+

A media type is made of different parts. The media type text/html;charset=utf-8 is of type text, subtype html and has a single parameter charset with value utf-8.

+ + + +

Cowboy will match the content-type request header against the media types the server accepts and select the appropriate callback. When that header is missing, or when the server does not accept this media type, the request fails and an error response is returned. Cowboy will execute the callback immediately otherwise.

+ +

An empty parameters list [] means that no parameters will be accepted. When any parameter is acceptable, the tuple form should be used with parameters as the atom '*'.

+

Cowboy treats all parameters as case sensitive, except for the charset parameter, which is known to be case insensitive. You should therefore always provide the charset as a lowercase binary string.

+ + + + + +

content_types_provided

-
-
-
content_types_provided(Req, State) -> {Result, Req, State}
-
-Result     :: [{binary() | ParsedMime, ProvideCallback :: atom()}]
-ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-
-Default     - [{{ <<"text">>, <<"html">>, '*'}, to_html}]
-

Return the list of media types the resource provides in -order of preference.

-

A media type is made of different parts. The media type -text/html;charset=utf-8 is of type text, subtype html -and has a single parameter charset with value utf-8.

-

During content negotiation Cowboy will pick the most appropriate -media type for the client. The client advertises media types it -prefers with the accept header. When that header is missing, -the content negotiation fails and an error response is returned.

-

The callback given for the selected media type will be called -at the end of the execution of GET and HEAD requests when a -representation must be sent to the client.

-

An empty parameters list [] means that no parameters will be -accepted. When any parameter is acceptable, the tuple form -should be used with parameters as the atom '*'.

-

Cowboy treats all parameters as case sensitive, except for the -charset parameter, which is known to be case insensitive. You -should therefore always provide the charset as a lowercase -binary string.

-

Cowboy will add the negotiated media_type to the Req object -after this step completes:

-
-
-
req() :: #{
-    media_type => ParsedMime
-}
-
-
+
+
content_types_provided(Req, State) -> {Result, Req, State}
+
+Result     :: [{binary() | ParsedMime, ProvideCallback :: atom()}]
+ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+Default     - [{{ <<"text">>, <<"html">>, '*'}, to_html}]
+
+ + +

Return the list of media types the resource provides in order of preference.

+

A media type is made of different parts. The media type text/html;charset=utf-8 is of type text, subtype html and has a single parameter charset with value utf-8.

+ + + +

During content negotiation Cowboy will pick the most appropriate media type for the client. The client advertises media types it prefers with the accept header. When that header is missing, the content negotiation fails and an error response is returned.

+

The callback given for the selected media type will be called at the end of the execution of GET and HEAD requests when a representation must be sent to the client.

+ +

An empty parameters list [] means that no parameters will be accepted. When any parameter is acceptable, the tuple form should be used with parameters as the atom '*'.

+

Cowboy treats all parameters as case sensitive, except for the charset parameter, which is known to be case insensitive. You should therefore always provide the charset as a lowercase binary string.

+

Cowboy will add the negotiated media_type to the Req object after this step completes:

+
+
req() :: #{
+    media_type => ParsedMime
+}
+
+

delete_completed

-
-
-
delete_completed(Req, State) -> {Result, Req, State}
+
delete_completed(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the resource has been fully deleted from the -system, including from any internal cache.

-

Returning false will result in a 202 Accepted response -being sent instead of a 200 OK or 204 No Content.

-
-
+Result :: boolean() +Default :: true +
+

Return whether the resource has been fully deleted from the system, including from any internal cache.

+

Returning false will result in a 202 Accepted response being sent instead of a 200 OK or 204 No Content.

delete_resource

-
-
-
delete_resource(Req, State) -> {Result, Req, State}
+
delete_resource(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Delete the resource.

-

Cowboy will send an error response when this function -returns false.

- -
+Result :: boolean() +Default :: false +
+

Delete the resource.

+

Cowboy will send an error response when this function returns false.

expires

-
-
-
expires(Req, State) -> {Result, Req, State}
+
expires(Req, State) -> {Result, Req, State}
 
-Result  :: calendar:datetime() | binary() | undefined
-Default :: undefined
-

Return the resource’s expiration date.

- -
+Result :: calendar:datetime() | binary() | undefined +Default :: undefined +
+

Return the resource's expiration date.

forbidden

-
-
-
forbidden(Req, State) -> {Result, Req, State}
+
forbidden(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether access to the resource is forbidden.

-

A 403 Forbidden response will be sent if this -function returns true. This status code means that -access is forbidden regardless of authentication, -and that the request shouldn’t be repeated.

- -
+Result :: boolean() +Default :: false +
+

Return whether access to the resource is forbidden.

+

A 403 Forbidden response will be sent if this function returns true. This status code means that access is forbidden regardless of authentication, and that the request shouldn't be repeated.

generate_etag

-
-
-
generate_etag(Req, State) -> {Result, Req, State}
+
generate_etag(Req, State) -> {Result, Req, State}
 
-Result  :: binary() | {weak | strong, binary()}
-Default  - no etag value
-

Return the entity tag of the resource.

-

When a binary is returned, the value is automatically -parsed to a tuple. The binary must be in the same -format as the etag header, including quotes.

- -
+Result :: binary() | {weak | strong, binary()} +Default - no etag value +
+

Return the entity tag of the resource.

+

When a binary is returned, the value is automatically parsed to a tuple. The binary must be in the same format as the etag header, including quotes.

is_authorized

-
-
-
is_authorized(Req, State) -> {Result, Req, State}
+
is_authorized(Req, State) -> {Result, Req, State}
 
-Result  :: true | {false, AuthHeader :: iodata()}
-Default  - true
-

Return whether the user is authorized to perform the action.

-

This function should be used to perform any necessary -authentication of the user before attempting to perform -any action on the resource.

-

When authentication fails, the AuthHeader value will -be sent in the www-authenticate header for the -401 Unauthorized response.

- -
+Result :: true | {false, AuthHeader :: iodata()} +Default - true +
+

Return whether the user is authorized to perform the action.

+

This function should be used to perform any necessary authentication of the user before attempting to perform any action on the resource.

+

When authentication fails, the AuthHeader value will be sent in the www-authenticate header for the 401 Unauthorized response.

is_conflict

-
-
-
is_conflict(Req, State) -> {Result, Req, State}
+
is_conflict(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the PUT request results in a conflict.

-

A 409 Conflict response is sent when true.

- -
+Result :: boolean() +Default :: false +
+

Return whether the PUT request results in a conflict.

+

A 409 Conflict response is sent when true.

known_methods

-
-
-
known_methods(Req, State) -> {Result, Req, State}
+
known_methods(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% case sensitive
-Default :: [<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>,
-            <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]
-

Return the list of known methods.

-

The full list of methods known by the server should be -returned, regardless of their use in the resource.

-

The default value lists the methods Cowboy knows and -implement in cowboy_rest.

- -
+Result :: [binary()] %% case sensitive +Default :: [<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, + <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>] +
+

Return the list of known methods.

+

The full list of methods known by the server should be returned, regardless of their use in the resource.

+

The default value lists the methods Cowboy knows and implement in cowboy_rest.

languages_provided

-
-
-
languages_provided(Req, State) -> {Result, Req, State}
+
languages_provided(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% lowercase; case insensitive
-Default  - skip this step
-

Return the list of languages the resource provides in order -of preference.

-

During content negotiation Cowboy will pick the most -appropriate language for the client. The client advertises -languages it prefers with the accept-language header. When -that header is missing, Cowboy picks the first language -from the resource.

-

Cowboy will add the negotiated language to the Req object -after this step completes:

-
-
+

Cowboy will add the negotiated language to the Req object after this step completes:

+
-
req() :: #{
-    language => binary()  %% lowercase; case insensitive
-}
-
-
+
req() :: #{
+    language => binary()  %% lowercase; case insensitive
+}
+

last_modified

-
-
-
last_modified(Req, State) -> {Result, Req, State}
+
last_modified(Req, State) -> {Result, Req, State}
 
-Result  :: calendar:datetime()
-Default  - no last modified value
-

Return the resource’s last modification date.

-

This date will be used to test against the if-modified-since -and if-unmodified-since headers, and sent as the last-modified -header in the response to GET and HEAD requests.

- -
+Result :: calendar:datetime() +Default - no last modified value +
+

Return the resource's last modification date.

+

This date will be used to test against the if-modified-since and if-unmodified-since headers, and sent as the last-modified header in the response to GET and HEAD requests.

malformed_request

-
-
-
malformed_request(Req, State) -> {Result, Req, State}
+
malformed_request(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the request is malformed.

-

A request is malformed when a component required by the -resource is invalid. This may include the query string -or individual headers. They should be parsed and validated -in this function. The body should not be read at this point.

- -
+Result :: boolean() +Default :: false +
+

Return whether the request is malformed.

+

A request is malformed when a component required by the resource is invalid. This may include the query string or individual headers. They should be parsed and validated in this function. The body should not be read at this point.

moved_permanently

-
-
-
moved_permanently(Req, State) -> {Result, Req, State}
+
moved_permanently(Req, State) -> {Result, Req, State}
 
-Result  :: {true, URI :: iodata()} | false
-Default :: false
-

Return whether the resource was permanently moved, and -what its new location is.

- -
+Result :: {true, URI :: iodata()} | false +Default :: false +
+

Return whether the resource was permanently moved, and what its new location is.

moved_temporarily

-
-
-
moved_temporarily(Req, State) -> {Result, Req, State}
+
moved_temporarily(Req, State) -> {Result, Req, State}
 
-Result  :: {true, URI :: iodata()} | false
-Default :: false
-

Return whether the resource was temporarily moved, and -what its new location is.

- -
+Result :: {true, URI :: iodata()} | false +Default :: false +
+

Return whether the resource was temporarily moved, and what its new location is.

multiple_choices

-
-
-
multiple_choices(Req, State) -> {Result, Req, State}
-
-Result  :: boolean()
-Default :: false
-

Return whether the client should engage in reactive -negotiation.

-

Return true when the server has multiple representations -of a resource, each with their specific identifier, but is -unable to determine which is best for the client. For -example an image might have different sizes and the server -is unable to determine the capabilities of the client.

-

When returning true the server should send a body with -links to the different representations. If the server has -a preferred representation it can send its link inside a -location header.

- -
+
+
multiple_choices(Req, State) -> {Result, Req, State}
+
+Result  :: boolean()
+Default :: false
+
+

Return whether the client should engage in reactive negotiation.

+

Return true when the server has multiple representations of a resource, each with their specific identifier, but is unable to determine which is best for the client. For example an image might have different sizes and the server is unable to determine the capabilities of the client.

+

When returning true the server should send a body with links to the different representations. If the server has a preferred representation it can send its link inside a location header.

options

-
-
-
options(Req, State) -> {ok, Req, State}
-

Respond to an OPTIONS request.

-

The response should inform the client the communication -options available for this resource. By default Cowboy -will send a 200 OK response with the allow header set.

-
-
+
options(Req, State) -> {ok, Req, State}
+
+

Respond to an OPTIONS request.

+

The response should inform the client the communication options available for this resource. By default Cowboy will send a 200 OK response with the allow header set.

previously_existed

-
-
-
previously_existed(Req, State) -> {Result, Req, State}
+
previously_existed(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the resource existed previously.

- -
+Result :: boolean() +Default :: false +
+

Return whether the resource existed previously.

ProvideCallback

-
-
-
ProvideCallback(Req, State) -> {Result, Req, State}
+
ProvideCallback(Req, State) -> {Result, Req, State}
 
-Result  :: cowboy_req:resp_body()
-Default  - crash
-

Return the response body.

-

The response body can be provided either as the actual data -to be sent or a tuple indicating which file to send.

-

This function is called for both GET and HEAD requests. For -the latter the body is not sent, however.

-

Note that there used to be a way to stream the response body. -It was temporarily removed and will be added back in a later -release.

- -
+Result :: cowboy_req:resp_body() +Default - crash +
+

Return the response body.

+

The response body can be provided either as the actual data to be sent or a tuple indicating which file to send.

+

This function is called for both GET and HEAD requests. For the latter the body is not sent, however.

+ + + +

Note that there used to be a way to stream the response body. It was temporarily removed and will be added back in a later release.

+

resource_exists

-
-
-
resource_exists(Req, State) -> {Result, Req, State}
+
resource_exists(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the resource exists.

- -
+Result :: boolean() +Default :: true +
+

Return whether the resource exists.

service_available

-
-
-
service_available(Req, State) -> {Result, Req, State}
+
service_available(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the service is available.

-

A 503 Service Unavailable response will be sent when this -function returns false.

- -
+Result :: boolean() +Default :: true +
+

Return whether the service is available.

+

A 503 Service Unavailable response will be sent when this function returns false.

uri_too_long

-
-
-
uri_too_long(Req, State) -> {Result, Req, State}
+
uri_too_long(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the requested URI is too long.

-

This function can be used to further restrict the length -of the URI for this specific resource.

- -
+Result :: boolean() +Default :: false +
+

Return whether the requested URI is too long.

+

This function can be used to further restrict the length of the URI for this specific resource.

valid_content_headers

-
-
-
valid_content_headers(Req, State) -> {Result, Req, State}
+
valid_content_headers(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the content headers are valid.

-

This callback can be used to reject requests that have -invalid content header values, for example an unsupported -content-encoding.

- -
+Result :: boolean() +Default :: true +
+

Return whether the content headers are valid.

+

This callback can be used to reject requests that have invalid content header values, for example an unsupported content-encoding.

valid_entity_length

-
-
-
valid_entity_length(Req, State) -> {Result, Req, State}
+
valid_entity_length(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the request body length is within acceptable boundaries.

-

A 413 Request Entity Too Large response will be sent if this -function returns false.

- -
+Result :: boolean() +Default :: true +
+

Return whether the request body length is within acceptable boundaries.

+

A 413 Request Entity Too Large response will be sent if this function returns false.

variances

-
-
-
variances(Req, State) -> {Result, Req, State}
+
variances(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% case insensitive
-Default :: []
-

Return the list of request headers that affect the -representation of the resource.

-

Cowboy automatically adds the accept, accept-charset and -accept-language headers when necessary.

- - - -
+Result :: [binary()] %% case insensitive +Default :: [] +
+

Return the list of request headers that affect the representation of the resource.

+

Cowboy automatically adds the accept, accept-charset and accept-language headers when necessary.

Changelog

-
-
    -
  • -

    -2.1: The switch_handler return value was added. -

    +
    • 2.1: The switch_handler return value was added.
    • -
    • -

      -1.0: Behavior introduced. -

      +
    • 1.0: Behavior introduced.
    • -
-
- -
+

See also

- -
+

cowboy(7), cowboy_handler(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_router.compile/index.html b/docs/en/cowboy/2.1/manual/cowboy_router.compile/index.html index abdeecbd..2eb79d71 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_router.compile/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_router.compile/index.html @@ -62,87 +62,48 @@

cowboy_router:compile(3)

-

Name

-
-

cowboy_router:compile - Compile routes to the resources

-
-
-
+

cowboy_router:compile - Compile routes to the resources

Description

-
-
-
-
compile(cowboy_router:routes()) -> cowboy_router:dispatch_rules()
-

Compile routes to the resources.

-

Takes a human readable list of routes and transforms it -into a form more efficient to process.

-
-
-
+
compile(cowboy_router:routes()) -> cowboy_router:dispatch_rules()
+
+

Compile routes to the resources.

+

Takes a human readable list of routes and transforms it into a form more efficient to process.

Arguments

-
-
-
-Routes -
-
-

-Human readable list of routes. -

+
Routes
+

Human readable list of routes.

-
-
- -
+

Return value

-
-

An opaque dispatch rules value is returned. This value -must be given to Cowboy as a middleware environment value.

-
-
-
+

An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Compile routes and start a listener
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []},
-        {"/[...], cowboy_static, {priv_dir, my_example_app, ""}}
-    ]}
-]),
-
-{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{
-    env => #{dispatch => Dispatch}
-}).
-
-
-
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []},
+        {"/[...], cowboy_static, {priv_dir, my_example_app, ""}}
+    ]}
+]),
+
+{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{
+    env => #{dispatch => Dispatch}
+}).
+

See also

- - +

cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_router/index.html b/docs/en/cowboy/2.1/manual/cowboy_router/index.html index 9f7da3de..a6732ddf 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_router/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_router/index.html @@ -62,110 +62,65 @@

cowboy_router(3)

-

Name

-
-

cowboy_router - Router middleware

-
-
-
+

cowboy_router - Router middleware

Description

-
-

The cowboy_router middleware maps the requested host and -path to the handler to be used for processing the request.

-

The router takes the dispatch rules as input from the -middleware environment. Dispatch rules are generated by -calling the -cowboy_router:compile(3) -function.

-

When a route matches, the router sets the handler and -handler_opts middleware environment values containing -the handler module and initial state, respectively.

-

The router will stop execution when no route matches. -It will send a 400 response if no host was found, and -a 404 response otherwise.

-
-
-
+

The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request.

+

The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function.

+

When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively.

+

The router will stop execution when no route matches. It will send a 400 response if no host was found, and a 404 response otherwise.

Exports

-
-
-
-
-
+

Types

-
-

bindings()

-
-
-
bindings() :: #{atom() => any()}
-

Bindings found during routing.

-
-
+
bindings() :: #{atom() => any()}
+
+

Bindings found during routing.

dispatch_rules()

-

Opaque type containing the compiled routes.

-
-
+

Opaque type containing the compiled routes.

routes()

-
-
-
routes() = [
-    {Host, PathList} |
-    {Host, Fields, PathList}
+
routes() = [
+    {Host, PathList} |
+    {Host, Fields, PathList}
 ]
 
-PathList :: [
-    {Path, Handler, InitialState} |
-    {Path, Fields, Handler, InitialState}
+PathList :: [
+    {Path, Handler, InitialState} |
+    {Path, Fields, Handler, InitialState}
 ]
 
-Host         :: '_' | iodata()
-Path         :: '_' | iodata()
-Fields       :: cowboy:fields()
-Handler      :: module()
-InitialState :: any()
-

Human readable list of routes to handlers.

-

Cowboy uses this list to map hosts and paths, optionally -augmented with constraints applied to the bindings, to -handler modules.

-

The syntax for routes is currently defined in the user guide.

-
-
+Host :: '_' | iodata() +Path :: '_' | iodata() +Fields :: cowboy:fields() +Handler :: module() +InitialState :: any() +
+

Human readable list of routes to handlers.

+

Cowboy uses this list to map hosts and paths, optionally augmented with constraints applied to the bindings, to handler modules.

+

The syntax for routes is currently defined in the user guide.

+ +

tokens()

-
-
-
tokens() :: [binary()]
-

List of host_info and path_info tokens that were found -using the ... syntax.

- - - -
+
tokens() :: [binary()]
+
+

List of host_info and path_info tokens that were found using the ... syntax.

See also

- - +

cowboy(7), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:host_info(3), cowboy_req:path_info(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_static/index.html b/docs/en/cowboy/2.1/manual/cowboy_static/index.html index b830e580..8ce3f0b1 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_static/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_static/index.html @@ -62,175 +62,110 @@

cowboy_static(3)

-

Name

-
-

cowboy_static - Static file handler

-
-
-
+

cowboy_static - Static file handler

Description

-
-

The module cowboy_static implements file serving capabilities -using the REST semantics provided by cowboy_rest.

-

The static file handler is a pre-written handler coming with -Cowboy. To serve files, use it in your routes.

-
-
-
+

The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest.

+

The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes.

Options

-
-
-
-
opts() :: {priv_file, App, Path}
-        | {priv_file, App, Path, Extra}
-        | {file, Path}
-        | {file, Path, Extra}
-        | {priv_dir, App, Path}
-        | {priv_dir, App, Path, Extra}
-        | {dir, Path}
-        | {dir, Path, Extra}
-
-App        :: atom()
-Path       :: binary() | string()
-Extra      :: [Etag | Mimetypes]
-
-Etag       :: {etag, module(), function()}
-            | {etag, false}
-
-Mimetypes  :: {mimetypes, module(), function()}
-            | {mimetypes, binary() | ParsedMime}
-
-ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-

Static handler configuration.

-
-
-priv_file -
-
-

-Send a file. -

-

The path is relative to the given application’s private -directory.

+
opts() :: {priv_file, App, Path}
+        | {priv_file, App, Path, Extra}
+        | {file, Path}
+        | {file, Path, Extra}
+        | {priv_dir, App, Path}
+        | {priv_dir, App, Path, Extra}
+        | {dir, Path}
+        | {dir, Path, Extra}
+
+App        :: atom()
+Path       :: binary() | string()
+Extra      :: [Etag | Mimetypes]
+
+Etag       :: {etag, module(), function()}
+            | {etag, false}
+
+Mimetypes  :: {mimetypes, module(), function()}
+            | {mimetypes, binary() | ParsedMime}
+
+ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+

Static handler configuration.

+
priv_file
+

Send a file.

+

The path is relative to the given application's private directory.

-
-file -
-
-

-Send a file. -

-

The path is either absolute or relative to the Erlang node’s -current directory.

+
file
+

Send a file.

+

The path is either absolute or relative to the Erlang node's current directory.

-
-priv_dir -
-
-

-Recursively serve files from a directory. -

-

The path is relative to the given application’s private -directory.

+
priv_dir
+

Recursively serve files from a directory.

+

The path is relative to the given application's private directory.

-
-dir -
-
-

-Recursively serve files from a directory. -

-

The path is either absolute or relative to the Erlang node’s -current directory.

+
dir
+

Recursively serve files from a directory.

+

The path is either absolute or relative to the Erlang node's current directory.

-
-

The extra options allow you to define how the etag should be -calculated and how the MIME type of files should be detected.

-

By default the static handler will generate an etag based -on the size and modification time of the file. You may disable -the etag entirely with {etag, false} or provide a module -and function that will be called when needed:

-
-
-
generate_etag(Path, Size, Mtime) -> {strong | weak, binary()}
-
-Path  :: binary()
-Size  :: non_neg_integer()
-Mtime :: file:date_time()
-

By default the static handler will detect Web-related MIME types -by looking at the file extension. You can provide a specific -MIME type that will always be used, or a module and function that -will be called when needed:

-
-
-
detect_mimetype(Path) -> ParsedMime
-
-Path       :: binary()
-ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-

Cowboy comes with two such functions; the default function -cow_mimetypes:web/1, and a second function generated from -the Apache mime.types file, cow_mimetypes:all/1.

-

The MIME type function should return -{<<"application">>, <<"octet-stream">>, []} -when it fails to detect a file’s MIME type.

- - -
+
detect_mimetype(Path) -> ParsedMime
+
+Path       :: binary()
+ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+ +

Cowboy comes with two such functions; the default function cow_mimetypes:web/1, and a second function generated from the Apache mime.types file, cow_mimetypes:all/1.

+

The MIME type function should return {<<"application">>, <<"octet-stream">>, []} when it fails to detect a file's MIME type.

Changelog

-
-
    -
  • -

    -1.0: Handler introduced. -

    +
    • 1.0: Handler introduced.
    • -
-
- -
+

Examples

-
-
-
Custom etag function
-
-
generate_etag(Path, Size, Mtime) ->
-    {strong, integer_to_binary(
-        erlang:phash2({Path, Size, Mtime}, 16#ffffffff))}.
-
-
Custom MIME type function
-
-
always_octet_stream(_Path) ->
-    case filename:extension(Path) of
-        <<".erl">> -> {<<"text">>, <<"plain">>, []};
-        _ -> {<<"application">>, <<"octet-stream">>, []}
-    end.
-
-
-
+
always_octet_stream(_Path) ->
+    case filename:extension(Path) of
+        <<".erl">> -> {<<"text">>, <<"plain">>, []};
+        _ -> {<<"application">>, <<"octet-stream">>, []}
+    end.
+

See also

- - +

cowboy(7), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_stream/index.html b/docs/en/cowboy/2.1/manual/cowboy_stream/index.html index a4c41e30..52702c01 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_stream/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_stream/index.html @@ -62,411 +62,282 @@

cowboy_stream(3)

-

Name

-
-

cowboy_handler - Stream handlers

-
-
-
+

cowboy_handler - Stream handlers

Description

-
-

The module cowboy_stream defines a callback interface -and a protocol for handling HTTP streams.

-

An HTTP request and its associated response is called -a stream. A connection may have many streams. In HTTP/1.1 -they are executed sequentially, while in HTTP/2 they are -executed concurrently.

-

Cowboy calls the stream handler for nearly all events -related to a stream. Exceptions vary depending on the -protocol.

-

Extra care must be taken when implementing stream handlers -to ensure compatibility. While some modification of the -events and commands is allowed, it is generally not a good -idea to completely omit them.

-
-
-
+

The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams.

+

An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently.

+

Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol.

+

Extra care must be taken when implementing stream handlers to ensure compatibility. While some modification of the events and commands is allowed, it is generally not a good idea to completely omit them.

Callbacks

-
-

Stream handlers must implement the following interface:

-
-
-
init(StreamID, Req, Opts) -> {Commands, State}
-data(StreamID, IsFin, Data, State) -> {Commands, State}
-info(StreamID, Info, State) -> {Commands, State}
-terminate(StreamID, Reason, State) -> any()
-early_error(StreamID, Reason, PartialReq, Resp, Opts) -> Resp
-
-StreamID   :: cowboy_stream:streamid()
-Req        :: cowboy_req:req()
-Opts       :: cowboy:opts()
-Commands   :: cowboy_stream:commands()
-State      :: any()
-IsFin      :: cowboy_stream:fin()
-Data       :: binary()
-Info       :: any()
-Reason     :: cowboy_stream:reason()
-PartialReq  - cowboy_req:req(), except all fields are optional
-Resp       :: cowboy_stream:resp_command()
-

HTTP/1.1 will initialize a stream only when the request-line -and all headers have been received. When errors occur before -that point Cowboy will call the callback early_error/5 -with a partial request, the error reason and the response -Cowboy intends to send. All other events go throuh the -stream handler using the normal callbacks.

-

HTTP/2 will initialize the stream when the HEADERS block has -been fully received and decoded. Any protocol error occuring -before that will not result in a response being sent and -will therefore not go through the stream handler. In addition -Cowboy may terminate streams without sending an HTTP response -back.

-

The stream is initialized by calling init/3. All streams -that are initialized will eventually be terminated by calling -terminate/3.

-

When Cowboy receives data for the stream it will call data/4. -The data given is the request body after any transfer decoding -has been applied.

-

When Cowboy receives a message addressed to a stream, or when -Cowboy needs to inform the stream handler that an internal -event has occurred, it will call info/3.

-
-
-
+
init(StreamID, Req, Opts) -> {Commands, State}
+data(StreamID, IsFin, Data, State) -> {Commands, State}
+info(StreamID, Info, State) -> {Commands, State}
+terminate(StreamID, Reason, State) -> any()
+early_error(StreamID, Reason, PartialReq, Resp, Opts) -> Resp
+
+StreamID   :: cowboy_stream:streamid()
+Req        :: cowboy_req:req()
+Opts       :: cowboy:opts()
+Commands   :: cowboy_stream:commands()
+State      :: any()
+IsFin      :: cowboy_stream:fin()
+Data       :: binary()
+Info       :: any()
+Reason     :: cowboy_stream:reason()
+PartialReq  - cowboy_req:req(), except all fields are optional
+Resp       :: cowboy_stream:resp_command()
+
+

HTTP/1.1 will initialize a stream only when the request-line and all headers have been received. When errors occur before that point Cowboy will call the callback early_error/5 with a partial request, the error reason and the response Cowboy intends to send. All other events go throuh the stream handler using the normal callbacks.

+

HTTP/2 will initialize the stream when the HEADERS block has been fully received and decoded. Any protocol error occuring before that will not result in a response being sent and will therefore not go through the stream handler. In addition Cowboy may terminate streams without sending an HTTP response back.

+

The stream is initialized by calling init/3. All streams that are initialized will eventually be terminated by calling terminate/3.

+

When Cowboy receives data for the stream it will call data/4. The data given is the request body after any transfer decoding has been applied.

+

When Cowboy receives a message addressed to a stream, or when Cowboy needs to inform the stream handler that an internal event has occurred, it will call info/3.

Commands

-
-

Stream handlers can return a list of commands to be executed -from the init/3, data/4 and info/3 callbacks. In addition, -the early_error/5 callback must return a response command.

-

The following commands are defined:

-
+

Stream handlers can return a list of commands to be executed from the init/3, data/4 and info/3 callbacks. In addition, the early_error/5 callback must return a response command.

+ + + + + +

The following commands are defined:

response

-

Send a response to the client.

-
-
-
{response, cowboy:http_status(), cowboy:http_headers(),
-    cowboy_req:resp_body()}
-

No more data can be sent after this command.

-
-
+
{response, cowboy:http_status(), cowboy:http_headers(),
+    cowboy_req:resp_body()}
+
+

No more data can be sent after this command.

headers

-

Initiate a response to the client.

-
-
-
{headers, cowboy:http_status(), cowboy:http_headers()}
-

This initiates a response to the client. The stream -will end when a data command with the fin flag is -returned.

- -
+
{headers, cowboy:http_status(), cowboy:http_headers()}
+
+

This initiates a response to the client. The stream will end when a data command with the fin flag is returned.

data

-

Send data to the client.

-
-
-
{data, fin(), iodata()}
- -
+
{data, fin(), iodata()}
+

push

-

Push a resource to the client.

-
-
-
{push, Method, Scheme, Host, inet:port_number(),
-    Path, Qs, cowboy:http_headers()}
+
{push, Method, Scheme, Host, inet:port_number(),
+    Path, Qs, cowboy:http_headers()}
 
-Method = Scheme = Host = Path = Qs = binary()
-

The command will be ignored if the protocol does not provide -any server push mechanism.

- -
+Method = Scheme = Host = Path = Qs = binary() +
+

The command will be ignored if the protocol does not provide any server push mechanism.

flow

-
-
-
{flow, pos_integer()}
-

Request more data to be read from the request body. The -exact behavior depends on the protocol.

- -
+
{flow, pos_integer()}
+
+

Request more data to be read from the request body. The exact behavior depends on the protocol.

spawn

-

Inform Cowboy that a process was spawned and should be -supervised.

-
-
-
{spawn, pid(), timeout()}
- -
+
{spawn, pid(), timeout()}
+

error_response

-

Send an error response if no response was sent previously.

-
-
-
{error_response, cowboy:http_status(), cowboy:http_headers(), iodata()}
- -
+
{error_response, cowboy:http_status(), cowboy:http_headers(), iodata()}
+

switch_protocol

-

Switch to a different protocol.

-
-
-
{switch_protocol, cowboy:http_headers(), module(), state()}
-

Contains the headers that will be sent in the 101 response, -along with the module implementing the protocol we are -switching to and its initial state.

- -
+
{switch_protocol, cowboy:http_headers(), module(), state()}
+
+

Contains the headers that will be sent in the 101 response, along with the module implementing the protocol we are switching to and its initial state.

stop

-

Stop the stream.

-
-
-
stop
-

While no more data can be sent after the fin flag was set, -the stream is still tracked by Cowboy until it is stopped by -the handler.

-

The behavior when stopping a stream for which no response -has been sent will vary depending on the protocol. The stream -will end successfully as far as the client is concerned.

-

To indicate that an error occurred, either use error_response -before stopping, or use internal_error.

- -
+
stop
+
+

While no more data can be sent after the fin flag was set, the stream is still tracked by Cowboy until it is stopped by the handler.

+

The behavior when stopping a stream for which no response has been sent will vary depending on the protocol. The stream will end successfully as far as the client is concerned.

+

To indicate that an error occurred, either use error_response before stopping, or use internal_error.

internal_error

-

Stop the stream with an error.

-
-
-
{internal_error, Reason, HumanReadable}
-
-Reason        = any()
-HumanReadable = atom()
-

This command should be used when the stream cannot continue -because of an internal error. An error_response command -may be sent before that to advertise to the client why the -stream is dropped.

- - - -
+
{internal_error, Reason, HumanReadable}
+
+Reason        = any()
+HumanReadable = atom()
+
+

This command should be used when the stream cannot continue because of an internal error. An error_response command may be sent before that to advertise to the client why the stream is dropped.

Predefined events

-
-

Cowboy will forward all messages sent to the stream to -the info/3 callback. To send a message to a stream, -send a message to the connection process with the form -{{Pid, StreamID}, Msg}. The connection process will -then forward Msg to the stream handlers.

-

Cowboy will also forward the exit signals for the -processes that the stream spawned.

-
+

Cowboy will forward all messages sent to the stream to the info/3 callback. To send a message to a stream, send a message to the connection process with the form {{Pid, StreamID}, Msg}. The connection process will then forward Msg to the stream handlers.

+

Cowboy will also forward the exit signals for the processes that the stream spawned.

EXIT

-

A process spawned by this stream has exited.

-
-
+ + +

A process spawned by this stream has exited.

+
-
{'EXIT', pid(), any()}
-

This is the raw exit message without any modification.

-
-
+
{'EXIT', pid(), any()}
+
+

This is the raw exit message without any modification.

+ + + + + + + + + + + + + + + + +

response

-

Same as the response command.

-

Usually sent when the request process replies to the client. -May also be sent by Cowboy internally.

-
-
+

Same as the response command.

+

Usually sent when the request process replies to the client. May also be sent by Cowboy internally.

headers

-

Same as the headers command.

-

Sent when the request process starts replying to the client.

-
-
+

Same as the headers command.

+

Sent when the request process starts replying to the client.

data

-

Same as the data command.

-

Sent when the request process streams data to the client.

-
-
+

Same as the data command.

+

Sent when the request process streams data to the client.

push

-

Same as the push command.

-

Sent when the request process pushes a resource to the client.

-
-
+

Same as the push command.

+

Sent when the request process pushes a resource to the client.

switch_protocol

- -

Sent when switching to the HTTP/2 or Websocket protocol.

-
-
- -
+

Same as the switch_protocol command.

+ +

Sent when switching to the HTTP/2 or Websocket protocol.

Exports

-
-

The following function should be called by modules implementing -stream handlers to execute the next stream handler in the list:

-
-
-
-
+

Types

-
-

commands()

-
-
-
commands() :: [Command]
-

See the list of commands for details.

-
-
+
commands() :: [Command]
+
+

See the list of commands for details.

fin()

-
-
-
fin() :: fin | nofin
-

Used in commands and events to indicate that this is -the end of the stream.

-
-
+
fin() :: fin | nofin
+
+

Used in commands and events to indicate that this is the end of the stream.

partial_req()

-
-
-
req() :: #{
-    method  => binary(),               %% case sensitive
-    version => cowboy:http_version() | atom(),
-    scheme  => binary(),               %% lowercase; case insensitive
-    host    => binary(),               %% lowercase; case insensitive
-    port    => inet:port_number(),
-    path    => binary(),               %% case sensitive
-    qs      => binary(),               %% case sensitive
-    headers => cowboy:http_headers(),
-    peer    => {inet:ip_address(), inet:port_number()}
-}
-

Partial request information received when an early error is -detected.

- -
+
req() :: #{
+    method  => binary(),               %% case sensitive
+    version => cowboy:http_version() | atom(),
+    scheme  => binary(),               %% lowercase; case insensitive
+    host    => binary(),               %% lowercase; case insensitive
+    port    => inet:port_number(),
+    path    => binary(),               %% case sensitive
+    qs      => binary(),               %% case sensitive
+    headers => cowboy:http_headers(),
+    peer    => {inet:ip_address(), inet:port_number()}
+}
+
+

Partial request information received when an early error is detected.

reason()

-
-
-
reason() :: normal | switch_protocol
-    | {internal_error, timeout | {error | exit | throw, any()}, HumanReadable}
-    | {socket_error, closed | atom(), HumanReadable}
-    | {stream_error, Error, HumanReadable}
-    | {connection_error, Error, HumanReadable}
-    | {stop, cow_http2:frame(), HumanReadable}
-
-Error         = atom()
-HumanReadable = atom()
-

Reason for the stream termination.

- -
+
reason() :: normal | switch_protocol
+    | {internal_error, timeout | {error | exit | throw, any()}, HumanReadable}
+    | {socket_error, closed | atom(), HumanReadable}
+    | {stream_error, Error, HumanReadable}
+    | {connection_error, Error, HumanReadable}
+    | {stop, cow_http2:frame(), HumanReadable}
+
+Error         = atom()
+HumanReadable = atom()
+
+

Reason for the stream termination.

resp_command()

-
-
-
resp_command() :: {response, cowboy:http_status(),
-    cowboy:http_headers(), cowboy_req:resp_body()}
-

See the response command for details.

- -
+
resp_command() :: {response, cowboy:http_status(),
+    cowboy:http_headers(), cowboy_req:resp_body()}
+
+

See the response command for details.

streamid()

-
-
-
streamid() :: any()
-

The identifier for this stream.

-

The identifier is unique over the connection process. -It is possible to form a unique identifier node-wide and -cluster-wide by wrapping it in a {self(), StreamID} -tuple.

- - - -
+
streamid() :: any()
+
+

The identifier for this stream.

+

The identifier is unique over the connection process. It is possible to form a unique identifier node-wide and cluster-wide by wrapping it in a {self(), StreamID} tuple.

Changelog

-
-
    -
  • -

    -2.0: Module introduced. -

    +
    • 2.0: Module introduced.
    • -
-
- - +

cowboy(7), cowboy_http(3), cowboy_http2(3)

+ diff --git a/docs/en/cowboy/2.1/manual/cowboy_websocket/index.html b/docs/en/cowboy/2.1/manual/cowboy_websocket/index.html index c7c9cef5..e4729fc1 100644 --- a/docs/en/cowboy/2.1/manual/cowboy_websocket/index.html +++ b/docs/en/cowboy/2.1/manual/cowboy_websocket/index.html @@ -62,295 +62,144 @@

cowboy_websocket(3)

-

Name

-
-

cowboy_websocket - Websocket

-
-
-
+

cowboy_websocket - Websocket

Description

-
-

The module cowboy_websocket implements Websocket -as a Ranch protocol. It also defines a callback interface -for handling Websocket connections.

-
-
-
+

The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections.

Callbacks

-
-

Websocket handlers must implement the following callback -interface:

-
-
-
init(Req, State)
-    -> {cowboy_websocket, Req, State}
-     | {cowboy_websocket, Req, State, Opts}
-
-websocket_init(State)            -> CallResult  %% optional
-websocket_handle(InFrame, State) -> CallResult
-websocket_info(Info, State)      -> CallResult
-
-terminate(Reason, PartialReq, State) -> ok      %% optional
-
-Req        :: cowboy_req:req()
-PartialReq :: map()
-State      :: any()
-Opts       :: cowboy_websocket:opts()
-InFrame    :: {text | binary | ping | pong, binary()}
-OutFrame   :: cow_ws:frame()                    %% see types below
-Info       :: any()
-
-CallResult :: {ok, State}
-            | {ok, State, hibernate}
-            | {reply, OutFrame | [OutFrame], State}
-            | {reply, OutFrame | [OutFrame], State, hibernate}
-            | {stop, State}
-
-Reason     :: normal | stop | timeout
-            | remote | {remote, cow_ws:close_code(), binary()}
-            | {error, badencoding | badframe | closed | atom()}
-            | {crash, error | exit | throw, any()}
-

The init/2 callback is common to all handlers. To upgrade -the connection to Websocket, it must return cowboy_websocket -as the first element of the tuple.

-

Any operation requiring the HTTP request must be done in the -init/2 function, as the Req object will not be available -after it returns. Websocket sub-protocol selection should -therefore be done in this function.

-

The optional websocket_init/1 callback will be called once -the connection has been upgraded to Websocket. It can be used -to perform any required initialization of the handler.

-

Note that the init/2 function does not run in the same -process as the Websocket callbacks. Any Websocket-specific -initialization must be done in websocket_init/1.

-

The websocket_handle/2 callback will be called for every -frame received. The websocket_info/2 callback will be -called for every Erlang message received.

-

All three Websocket callbacks may send one or more frames -back to the client (by returning a reply tuple) or terminate -the connection (by sending a close frame or returning a stop -tuple).

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the connection. This -callback is common to all handlers. Note that Websocket will -not provide the full Req object by default, to save memory.

-

Cowboy will terminate the process right after closing the -Websocket connection. This means that there is no need to -perform any cleanup in the terminate/3 callback.

-

The following terminate reasons are defined for Websocket -connections:

-
-
-normal -
-
-

- The connection was closed normally before establishing a Websocket - connection. This typically happens if an ok tuple is returned - from the init/2 callback. -

+
init(Req, State)
+    -> {cowboy_websocket, Req, State}
+     | {cowboy_websocket, Req, State, Opts}
+
+websocket_init(State)            -> CallResult  %% optional
+websocket_handle(InFrame, State) -> CallResult
+websocket_info(Info, State)      -> CallResult
+
+terminate(Reason, PartialReq, State) -> ok      %% optional
+
+Req        :: cowboy_req:req()
+PartialReq :: map()
+State      :: any()
+Opts       :: cowboy_websocket:opts()
+InFrame    :: {text | binary | ping | pong, binary()}
+OutFrame   :: cow_ws:frame()                    %% see types below
+Info       :: any()
+
+CallResult :: {ok, State}
+            | {ok, State, hibernate}
+            | {reply, OutFrame | [OutFrame], State}
+            | {reply, OutFrame | [OutFrame], State, hibernate}
+            | {stop, State}
+
+Reason     :: normal | stop | timeout
+            | remote | {remote, cow_ws:close_code(), binary()}
+            | {error, badencoding | badframe | closed | atom()}
+            | {crash, error | exit | throw, any()}
+
+

The init/2 callback is common to all handlers. To upgrade the connection to Websocket, it must return cowboy_websocket as the first element of the tuple.

+

Any operation requiring the HTTP request must be done in the init/2 function, as the Req object will not be available after it returns. Websocket sub-protocol selection should therefore be done in this function.

+

The optional websocket_init/1 callback will be called once the connection has been upgraded to Websocket. It can be used to perform any required initialization of the handler.

+

Note that the init/2 function does not run in the same process as the Websocket callbacks. Any Websocket-specific initialization must be done in websocket_init/1.

+

The websocket_handle/2 callback will be called for every frame received. The websocket_info/2 callback will be called for every Erlang message received.

+

All three Websocket callbacks may send one or more frames back to the client (by returning a reply tuple) or terminate the connection (by sending a close frame or returning a stop tuple).

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the connection. This callback is common to all handlers. Note that Websocket will not provide the full Req object by default, to save memory.

+

Cowboy will terminate the process right after closing the Websocket connection. This means that there is no need to perform any cleanup in the terminate/3 callback.

+

The following terminate reasons are defined for Websocket connections:

+
normal
+

The connection was closed normally before establishing a Websocket connection. This typically happens if an ok tuple is returned from the init/2 callback.

-
-remote -
-
-

- The remote endpoint closed the connection without giving any - further details. -

+
remote
+

The remote endpoint closed the connection without giving any further details.

-
-{remote, Code, Payload} -
-
-

- The remote endpoint closed the connection with the given - Code and Payload as the reason. -

+
{remote, Code, Payload}
+

The remote endpoint closed the connection with the given Code and Payload as the reason.

-
-stop -
-
-

- The handler requested to close the connection, either by returning - a stop tuple or by sending a close frame. -

+
stop
+

The handler requested to close the connection, either by returning a stop tuple or by sending a close frame.

-
-timeout -
-
-

- The connection has been closed due to inactivity. The timeout - value can be configured from init/2. -

+
timeout
+

The connection has been closed due to inactivity. The timeout value can be configured from init/2.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
-{error, badencoding} -
-
-

- A text frame was sent by the client with invalid encoding. All - text frames must be valid UTF-8. -

+
{error, badencoding}
+

A text frame was sent by the client with invalid encoding. All text frames must be valid UTF-8.

-
-{error, badframe} -
-
-

- A protocol error has been detected. -

+
{error, badframe}
+

A protocol error has been detected.

-
-{error, closed} -
-
-

- The socket has been closed brutally without a close frame being - received first. -

+
{error, closed}
+

The socket has been closed brutally without a close frame being received first.

-
-{error, Reason} -
-
-

- A socket error ocurred. -

+
{error, Reason}
+

A socket error ocurred.

-
- - -
+

Types

-
-

cow_ws:frame()

-
-
-
frame() :: {text, iodata()}
-    | {binary, iodata()}
-    | ping | {ping, iodata()}
-    | pong | {pong, iodata()}
-    | close | {close, iodata()} | {close, close_code(), iodata()}
-
-close_code() :: 1000..1003 | 1006..1011 | 3000..4999
-

Websocket frames that can be sent as a response.

-

Note that there is no need to send pong frames back as -Cowboy does it automatically for you.

-
-
+
frame() :: {text, iodata()}
+    | {binary, iodata()}
+    | ping | {ping, iodata()}
+    | pong | {pong, iodata()}
+    | close | {close, iodata()} | {close, close_code(), iodata()}
+
+close_code() :: 1000..1003 | 1006..1011 | 3000..4999
+
+

Websocket frames that can be sent as a response.

+

Note that there is no need to send pong frames back as Cowboy does it automatically for you.

opts()

-
-
-
opts() :: #{
-    compress => boolean(),
-    idle_timeout => timeout(),
-    req_filter => fun((cowboy_req:req()) -> map())
-}
-

Websocket handler options.

-

This configuration is passed to Cowboy from the init/2 -function:

-
-
-
init(Req, State) ->
-    Opts = #{compress => true},
-    {cowboy_websocket, Req, State, Opts}.
-

The default value is given next to the option name:

-
-
-compress (false) -
-
-

- Whether to enable the Websocket frame compression - extension. Frames will only be compressed for the - clients that support this extension. -

+
init(Req, State) ->
+    Opts = #{compress => true},
+    {cowboy_websocket, Req, State, Opts}.
+
+

The default value is given next to the option name:

+
compress (false)
+

Whether to enable the Websocket frame compression extension. Frames will only be compressed for the clients that support this extension.

-
-idle_timeout (60000) -
-
-

- Time in milliseconds that Cowboy will keep the - connection open without receiving anything from - the client. -

+
idle_timeout (60000)
+

Time in milliseconds that Cowboy will keep the connection open without receiving anything from the client.

-
-req_filter -
-
-

- A function applied to the Req to compact it and - only keep required information. The Req is only - given back in the terminate/3 callback. By default - it keeps the method, version, URI components and peer - information. -

+
req_filter
+

A function applied to the Req to compact it and only keep required information. The Req is only given back in the terminate/3 callback. By default it keeps the method, version, URI components and peer information.

-
- - - -
+

Changelog

-
-
    -
  • -

    -2.0: The Req object is no longer passed to Websocket callbacks. -

    +
    • 2.0: The Req object is no longer passed to Websocket callbacks.
    • -
    • -

      -2.0: The callback websocket_terminate/3 was removed in favor of terminate/3. -

      +
    • 2.0: The callback websocket_terminate/3 was removed in favor of terminate/3.
    • -
    • -

      -1.0: Protocol introduced. -

      +
    • 1.0: Protocol introduced.
    • -
-
-
- +

cowboy(7), cowboy_handler(3), cowboy_http(3), cowboy_http2(3)

+ diff --git a/docs/en/cowboy/2.1/manual/http_status_codes/index.html b/docs/en/cowboy/2.1/manual/http_status_codes/index.html index 99344691..2a947413 100644 --- a/docs/en/cowboy/2.1/manual/http_status_codes/index.html +++ b/docs/en/cowboy/2.1/manual/http_status_codes/index.html @@ -62,271 +62,92 @@

HTTP status codes(7)

-

Name

-
-

HTTP status codes - status codes used by Cowboy

-
-
-
+

HTTP status codes - status codes used by Cowboy

Description

-
-

This chapter aims to list all HTTP status codes that Cowboy -may return, with details on the reasons why. The list given -here only includes the replies that Cowboy sends, not user -replies.

-
-
-
+

This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies.

100 Continue

-
-

When the client sends an expect: 100-continue header, -Cowboy automatically sends a this status code before -trying to read the request body. This behavior can be -disabled using the appropriate body option.

-
-
-
+

When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. This behavior can be disabled using the appropriate body option.

101 Switching Protocols

-
-

This is the status code sent when switching to the -Websocket protocol.

-
-
-
+

This is the status code sent when switching to the Websocket protocol.

200 OK

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

201 Created

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

202 Accepted

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

204 No Content

-
-

This status code is sent when the processing of a request -ends without any reply having been sent. It may also be -sent by cowboy_rest under normal conditions.

-
-
-
+

This status code is sent when the processing of a request ends without any reply having been sent. It may also be sent by cowboy_rest under normal conditions.

300 Multiple Choices

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

301 Moved Permanently

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

303 See Other

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

304 Not Modified

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

307 Temporary Redirect

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

400 Bad Request

-
-

Cowboy will send this status code for any of the -following reasons:

-
    -
  • -

    -Too many empty lines were sent before the request. -

    +

    Cowboy will send this status code for any of the following reasons:

    +
    • Too many empty lines were sent before the request.
    • -
    • -

      -The request-line could not be parsed. -

      +
    • The request-line could not be parsed.
    • -
    • -

      -Too many headers were sent. -

      +
    • Too many headers were sent.
    • -
    • -

      -A header name was too long. -

      +
    • A header name was too long.
    • -
    • -

      -A header value was too long. -

      +
    • A header value was too long.
    • -
    • -

      -The host header was missing from an HTTP/1.1 request. -

      +
    • The host header was missing from an HTTP/1.1 request.
    • -
    • -

      -The host header could not be parsed. -

      +
    • The host header could not be parsed.
    • -
    • -

      -The requested host was not found. -

      +
    • The requested host was not found.
    • -
    • -

      -The requested path could not be parsed. -

      +
    • The requested path could not be parsed.
    • -
    • -

      -The accept header could not be parsed when using REST. -

      +
    • The accept header could not be parsed when using REST.
    • -
    • -

      -REST under normal conditions. -

      +
    • REST under normal conditions.
    • -
    • -

      -A Websocket upgrade failed. -

      +
    • A Websocket upgrade failed.
    • -
-
-
-
+

401 Unauthorized

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

403 Forbidden

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

404 Not Found

-
-

This status code is sent when the router successfully -resolved the host but didn’t find a matching path for -the request. It may also be sent by cowboy_rest under -normal conditions.

-
-
-
+

This status code is sent when the router successfully resolved the host but didn't find a matching path for the request. It may also be sent by cowboy_rest under normal conditions.

405 Method Not Allowed

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

406 Not Acceptable

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

408 Request Timeout

-
-

Cowboy will send this status code to the client if the -client started to send a request, indicated by the -request-line being received fully, but failed to send -all headers in a reasonable time.

-
-
-
+

Cowboy will send this status code to the client if the client started to send a request, indicated by the request-line being received fully, but failed to send all headers in a reasonable time.

409 Conflict

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

410 Gone

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

412 Precondition Failed

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

413 Request Entity Too Large

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

414 Request-URI Too Long

-
-

Cowboy will send this status code to the client if the -request-line is too long. It may also be sent by -cowboy_rest under normal conditions.

-
-
-
+

Cowboy will send this status code to the client if the request-line is too long. It may also be sent by cowboy_rest under normal conditions.

415 Unsupported Media Type

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

500 Internal Server Error

-
-

This status code is sent when a crash occurs in HTTP, loop -or REST handlers, or when an invalid return value is -returned. It may also be sent by cowboy_rest under -normal conditions.

-
-
-
+

This status code is sent when a crash occurs in HTTP, loop or REST handlers, or when an invalid return value is returned. It may also be sent by cowboy_rest under normal conditions.

501 Not Implemented

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

503 Service Unavailable

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

505 HTTP Version Not Supported

-
-

Cowboy only supports the versions 1.0 and 1.1 of HTTP. -In all other cases this status code is sent back to the -client and the connection is closed.

-
-
+

Cowboy only supports the versions 1.0 and 1.1 of HTTP. In all other cases this status code is sent back to the client and the connection is closed.

+ diff --git a/docs/en/cowboy/2.1/manual/index.html b/docs/en/cowboy/2.1/manual/index.html index 7ad969d9..5cd833a0 100644 --- a/docs/en/cowboy/2.1/manual/index.html +++ b/docs/en/cowboy/2.1/manual/index.html @@ -62,171 +62,77 @@

Cowboy Function Reference

-

Name

-
-

cowboy - Small, fast, modern HTTP server for Erlang/OTP

-
-
-
+

cowboy - Small, fast, modern HTTP server for Erlang/OTP

Description

-
-

Cowboy is an HTTP server for Erlang/OTP with support for the -HTTP/1.1, HTTP/2 and Websocket protocols.

-

Cowboy aims to provide a complete HTTP stack. This includes -the implementation of the HTTP RFCs but also any directly -related standards, like Websocket or Server-Sent Events.

-
-
-
+

Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols.

+

Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events.

Modules

-
-

Functions:

-
-

Protocols:

-
+

Protocols:

+
-

Handlers:

-
+

Handlers:

+
-

Behaviors:

-
+

Behaviors:

+
-

Middlewares:

-
+

Middlewares:

+
-
-
-
+ +

Dependencies

-
-
    -
  • -

    -ranch(7) - Socket acceptor pool for TCP protocols -

    +
    • ranch(7) - Socket acceptor pool for TCP protocols
    • -
    • -

      -cowlib(7) - Support library for manipulating Web protocols -

      +
    • cowlib(7) - Support library for manipulating Web protocols
    • -
    • -

      -ssl - Secure communication over sockets -

      +
    • ssl - Secure communication over sockets
    • -
    • -

      -crypto - Crypto functions -

      +
    • crypto - Crypto functions
    • -
-

All these applications must be started before the cowboy -application. To start Cowboy and all dependencies at once:

-
-
-
{ok, _} = application:ensure_all_started(cowboy).
-
-
-
+
{ok, _} = application:ensure_all_started(cowboy).
+

Environment

-
-

The cowboy application does not define any application -environment configuration parameters.

-
- -
+

The cowboy application does not define any application environment configuration parameters.

See also

- -
+

ranch(7), cowlib(7)

+ diff --git a/docs/en/cowboy/2.2/guide/constraints/index.html b/docs/en/cowboy/2.2/guide/constraints/index.html index 39e56d64..8ec722ab 100644 --- a/docs/en/cowboy/2.2/guide/constraints/index.html +++ b/docs/en/cowboy/2.2/guide/constraints/index.html @@ -62,141 +62,86 @@

Constraints

-

Constraints are validation and conversion functions applied -to user input.

-

They are used in various places in Cowboy, including the -router and the cowboy_req match functions.

-
+

Constraints are validation and conversion functions applied to user input.

+

They are used in various places in Cowboy, including the router and the cowboy_req match functions.

Syntax

-
-

Constraints are provided as a list of fields. For each field -in the list, specific constraints can be applied, as well as -a default value if the field is missing.

-

A field can take the form of an atom field, a tuple with -constraints {field, Constraints} or a tuple with constraints -and a default value {field, Constraints, Default}. -The field form indicates the field is mandatory.

-

Note that when used with the router, only the second form -makes sense, as it does not use the default and the field -is always defined.

-

Constraints for each field are provided as an ordered list -of atoms or funs to apply. Built-in constraints are provided -as atoms, while custom constraints are provided as funs.

-

When multiple constraints are provided, they are applied in -the order given. If the value has been modified by a constraint -then the next one receives the new value.

-

For example, the following constraints will first validate -and convert the field my_value to an integer, and then -check that the integer is positive:

-
-
-
PositiveFun = fun
-    (_, V) when V > 0 ->
-        {ok, V};
-    (_, _) ->
-        {error, not_positive}
-end,
-{my_value, [int, PositiveFun]}.
-

We ignore the first fun argument in this snippet. We shouldn’t. -We will simply learn what it is later in this chapter.

-

When there’s only one constraint, it can be provided directly -without wrapping it into a list:

-
-
-
{my_value, int}
-
-
-
+
{my_value, int}
+

Built-in constraints

-
-

Built-in constraints are specified as an atom:

-
- --- - - - - - - - - - +

Built-in constraints are specified as an atom:

+
Constraint Description

int

Converts binary value to integer.

+ + + + - - - + + - -
ConstraintDescription
intConverts binary value to integer.

nonempty

Ensures the binary value is non-empty.

nonemptyEnsures the binary value is non-empty.
-
-
- -
+

Custom constraints

-
-

Custom constraints are specified as a fun. This fun takes -two arguments. The first argument indicates the operation -to be performed, and the second is the value. What the -value is and what must be returned depends on the operation.

-

Cowboy currently defines three operations. The operation -used for validating and converting user input is the forward -operation.

-
-
-
int(forward, Value) ->
-    try
-        {ok, binary_to_integer(Value)}
-    catch _:_ ->
-        {error, not_an_integer}
-    end;
-

The value must be returned even if it is not converted -by the constraint.

-

The reverse operation does the opposite: it -takes a converted value and changes it back to what the -user input would have been.

-
-
-
int(reverse, Value) ->
-        try
-                {ok, integer_to_binary(Value)}
-        catch _:_ ->
-                {error, not_an_integer}
-        end;
-

Finally, the format_error operation takes an error -returned by any other operation and returns a formatted -human-readable error message.

-
-
-
int(format_error, {not_an_integer, Value}) ->
-        io_lib:format("The value ~p is not an integer.", [Value]).
-

Notice that for this case you get both the error and -the value that was given to the constraint that produced -this error.

-

Cowboy will not catch exceptions coming from constraint -functions. They should be written to not emit any exceptions.

-
-
+
int(format_error, {not_an_integer, Value}) ->
+	io_lib:format("The value ~p is not an integer.", [Value]).
+ +

Notice that for this case you get both the error and the value that was given to the constraint that produced this error.

+

Cowboy will not catch exceptions coming from constraint functions. They should be written to not emit any exceptions.

+ diff --git a/docs/en/cowboy/2.2/guide/cookies/index.html b/docs/en/cowboy/2.2/guide/cookies/index.html index 39863979..e545d2e5 100644 --- a/docs/en/cowboy/2.2/guide/cookies/index.html +++ b/docs/en/cowboy/2.2/guide/cookies/index.html @@ -62,144 +62,103 @@

Using cookies

-

Cookies are a mechanism allowing applications to maintain -state on top of the stateless HTTP protocol.

-

Cookies are a name/value store where the names and values are -stored in plain text. They expire either after a delay -or when the browser closes. They can be configured on a -specific domain name or path, and restricted to secure -resources (sent or downloaded over HTTPS), or restricted -to the server (disallowing access from client-side scripts).

-

Cookie names are de facto case sensitive.

-

Cookies are stored client-side and sent with every subsequent -request that matches the domain and path for which they were -stored, until they expire. This can create a non-negligible -cost.

-

Cookies should not be considered secure. They are stored on -the user’s computer in plain text, and can be read by any -program. They can also be read by proxies when using clear -connections. Always validate the value before using it, -and never store any sensitive information inside it.

-

Cookies set by the server are only available in requests -following the client reception of the response containing -them.

-

Cookies may be sent repeatedly. This is often useful to -update the expiration time and avoid losing a cookie.

-
+

Cookies are a mechanism allowing applications to maintain state on top of the stateless HTTP protocol.

+

Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts).

+

Cookie names are de facto case sensitive.

+

Cookies are stored client-side and sent with every subsequent request that matches the domain and path for which they were stored, until they expire. This can create a non-negligible cost.

+

Cookies should not be considered secure. They are stored on the user's computer in plain text, and can be read by any program. They can also be read by proxies when using clear connections. Always validate the value before using it, and never store any sensitive information inside it.

+

Cookies set by the server are only available in requests following the client reception of the response containing them.

+

Cookies may be sent repeatedly. This is often useful to update the expiration time and avoid losing a cookie.

Setting cookies

-
-

By default cookies are defined for the duration of the session:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0).
-

They can also be set for a duration in seconds:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{max_age => 3600}).
-

To delete cookies, set max_age to 0:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{max_age => 0}).
-

To restrict cookies to a specific domain and path, the options -of the same name can be used:

-
-
-
Req = cowboy_req:set_resp_cookie(<<"inaccount">>, <<"1">>, Req0,
-    #{domain => "my.example.org", path => "/account"}).
-

Cookies will be sent with requests to this domain and all -its subdomains, and to resources on this path or deeper -in the path hierarchy.

-

To restrict cookies to secure channels (typically resources -available over HTTPS):

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{secure => true}).
-

To prevent client-side scripts from accessing a cookie:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{http_only => true}).
-

Cookies may also be set client-side, for example using -Javascript.

-
-
-
+
SessionID = generate_session_id(),
+Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
+    #{http_only => true}).
+
+

Cookies may also be set client-side, for example using Javascript.

Reading cookies

-
-

The client only ever sends back the cookie name and value. -All other options that can be set are never sent back.

-

Cowboy provides two functions for reading cookies. Both -involve parsing the cookie header(s) and so should not -be called repeatedly.

-

You can get all cookies as a key/value list:

-
-
-
Cookies = cowboy_req:parse_cookies(Req),
-{_, Lang} = lists:keyfind(<<"lang">>, 1, Cookies).
-

Or you can perform a match against cookies and retrieve -only the ones you need, while at the same time doing -any required post processing using constraints. -This function returns a map:

-
-
-
#{id := ID, lang := Lang} = cowboy_req:match_cookies([id, lang], Req).
-

You can use constraints to validate the values while matching -them. The following snippet will crash if the id cookie is -not an integer number or if the lang cookie is empty. Additionally -the id cookie value will be converted to an integer term:

-
-
-
CookiesMap = cowboy_req:match_cookies([{id, int}, {lang, nonempty}], Req).
-

Note that if two cookies share the same name, then the map value -will be a list of the two cookie values.

-

A default value can be provided. The default will be used -if the lang cookie is not found. It will not be used if -the cookie is found but has an empty value:

-
-
-
#{lang := Lang} = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
-

If no default is provided and the value is missing, an -exception is thrown.

-
- +
#{lang := Lang} = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
+ +

If no default is provided and the value is missing, an exception is thrown.

+ diff --git a/docs/en/cowboy/2.2/guide/erlang_web/index.html b/docs/en/cowboy/2.2/guide/erlang_web/index.html index 23d64428..5804baf9 100644 --- a/docs/en/cowboy/2.2/guide/erlang_web/index.html +++ b/docs/en/cowboy/2.2/guide/erlang_web/index.html @@ -62,194 +62,52 @@

Erlang and the Web

-

Erlang is the ideal platform for writing Web applications. -Its features are a perfect match for the requirements of -modern Web applications.

-
+

Erlang is the ideal platform for writing Web applications. Its features are a perfect match for the requirements of modern Web applications.

The Web is concurrent

-
-

When you access a website there is little concurrency -involved. A few connections are opened and requests -are sent through these connections. Then the web page -is displayed on your screen. Your browser will only -open up to 4 or 8 connections to the server, depending -on your settings. This isn’t much.

-

But think about it. You are not the only one accessing -the server at the same time. There can be hundreds, if -not thousands, if not millions of connections to the -same server at the same time.

-

Even today a lot of systems used in production haven’t -solved the C10K problem (ten thousand concurrent connections). -And the ones who did are trying hard to get to the next -step, C100K, and are pretty far from it.

-

Erlang meanwhile has no problem handling millions of -connections. At the time of writing there are application -servers written in Erlang that can handle more than two -million connections on a single server in a real production -application, with spare memory and CPU!

-

The Web is concurrent, and Erlang is a language designed -for concurrency, so it is a perfect match.

-

Of course, various platforms need to scale beyond a few -million connections. This is where Erlang’s built-in -distribution mechanisms come in. If one server isn’t -enough, add more! Erlang allows you to use the same code -for talking to local processes or to processes in other -parts of your cluster, which means you can scale very -quickly if the need arises.

-

The Web has large userbases, and the Erlang platform was -designed to work in a distributed setting, so it is a -perfect match.

-

Or is it? Surely you can find solutions to handle that many -concurrent connections with your favorite language… But all -these solutions will break down in the next few years. Why? -Firstly because servers don’t get any more powerful, they -instead get a lot more cores and memory. This is only useful -if your application can use them properly, and Erlang is -light-years away from anything else in that area. Secondly, -today your computer and your phone are online, tomorrow your -watch, goggles, bike, car, fridge and tons of other devices -will also connect to various applications on the Internet.

-

Only Erlang is prepared to deal with what’s coming.

-
-
-
+

When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. This isn't much.

+

But think about it. You are not the only one accessing the server at the same time. There can be hundreds, if not thousands, if not millions of connections to the same server at the same time.

+

Even today a lot of systems used in production haven't solved the C10K problem (ten thousand concurrent connections). And the ones who did are trying hard to get to the next step, C100K, and are pretty far from it.

+

Erlang meanwhile has no problem handling millions of connections. At the time of writing there are application servers written in Erlang that can handle more than two million connections on a single server in a real production application, with spare memory and CPU!

+

The Web is concurrent, and Erlang is a language designed for concurrency, so it is a perfect match.

+

Of course, various platforms need to scale beyond a few million connections. This is where Erlang's built-in distribution mechanisms come in. If one server isn't enough, add more! Erlang allows you to use the same code for talking to local processes or to processes in other parts of your cluster, which means you can scale very quickly if the need arises.

+

The Web has large userbases, and the Erlang platform was designed to work in a distributed setting, so it is a perfect match.

+

Or is it? Surely you can find solutions to handle that many concurrent connections with your favorite language... But all these solutions will break down in the next few years. Why? Firstly because servers don't get any more powerful, they instead get a lot more cores and memory. This is only useful if your application can use them properly, and Erlang is light-years away from anything else in that area. Secondly, today your computer and your phone are online, tomorrow your watch, goggles, bike, car, fridge and tons of other devices will also connect to various applications on the Internet.

+

Only Erlang is prepared to deal with what's coming.

The Web is soft real time

-
-

What does soft real time mean, you ask? It means we want the -operations done as quickly as possible, and in the case of -web applications, it means we want the data propagated fast.

-

In comparison, hard real time has a similar meaning, but also -has a hard time constraint, for example an operation needs to -be done in under N milliseconds otherwise the system fails -entirely.

-

Users aren’t that needy yet, they just want to get access -to their content in a reasonable delay, and they want the -actions they make to register at most a few seconds after -they submitted them, otherwise they’ll start worrying about -whether it successfully went through.

-

The Web is soft real time because taking longer to perform an -operation would be seen as bad quality of service.

-

Erlang is a soft real time system. It will always run -processes fairly, a little at a time, switching to another -process after a while and preventing a single process to -steal resources from all others. This means that Erlang -can guarantee stable low latency of operations.

-

Erlang provides the guarantees that the soft real time Web -requires.

-
-
-
+

What does soft real time mean, you ask? It means we want the operations done as quickly as possible, and in the case of web applications, it means we want the data propagated fast.

+

In comparison, hard real time has a similar meaning, but also has a hard time constraint, for example an operation needs to be done in under N milliseconds otherwise the system fails entirely.

+

Users aren't that needy yet, they just want to get access to their content in a reasonable delay, and they want the actions they make to register at most a few seconds after they submitted them, otherwise they'll start worrying about whether it successfully went through.

+

The Web is soft real time because taking longer to perform an operation would be seen as bad quality of service.

+

Erlang is a soft real time system. It will always run processes fairly, a little at a time, switching to another process after a while and preventing a single process to steal resources from all others. This means that Erlang can guarantee stable low latency of operations.

+

Erlang provides the guarantees that the soft real time Web requires.

The Web is asynchronous

-
-

Long ago, the Web was synchronous because HTTP was synchronous. -You fired a request, and then waited for a response. Not anymore. -It all began when XmlHttpRequest started being used. It allowed -the client to perform asynchronous calls to the server.

-

Then Websocket appeared and allowed both the server and the client -to send data to the other endpoint completely asynchronously. The -data is contained within frames and no response is necessary.

-

Erlang processes work the same. They send each other data contained -within messages and then continue running without needing a response. -They tend to spend most of their time inactive, waiting for a new -message, and the Erlang VM happily activate them when one is received.

-

It is therefore quite easy to imagine Erlang being good at receiving -Websocket frames, which may come in at unpredictable times, pass the -data to the responsible processes which are always ready waiting for -new messages, and perform the operations required by only activating -the required parts of the system.

-

The more recent Web technologies, like Websocket of course, but also -HTTP/2.0, are all fully asynchronous protocols. The concept -of requests and responses is retained of course, but anything could -be sent in between, by both the client or the browser, and the -responses could also be received in a completely different order.

-

Erlang is by nature asynchronous and really good at it thanks to the -great engineering that has been done in the VM over the years. It’s -only natural that it’s so good at dealing with the asynchronous Web.

-
-
-
+

Long ago, the Web was synchronous because HTTP was synchronous. You fired a request, and then waited for a response. Not anymore. It all began when XmlHttpRequest started being used. It allowed the client to perform asynchronous calls to the server.

+

Then Websocket appeared and allowed both the server and the client to send data to the other endpoint completely asynchronously. The data is contained within frames and no response is necessary.

+

Erlang processes work the same. They send each other data contained within messages and then continue running without needing a response. They tend to spend most of their time inactive, waiting for a new message, and the Erlang VM happily activate them when one is received.

+

It is therefore quite easy to imagine Erlang being good at receiving Websocket frames, which may come in at unpredictable times, pass the data to the responsible processes which are always ready waiting for new messages, and perform the operations required by only activating the required parts of the system.

+

The more recent Web technologies, like Websocket of course, but also HTTP/2.0, are all fully asynchronous protocols. The concept of requests and responses is retained of course, but anything could be sent in between, by both the client or the browser, and the responses could also be received in a completely different order.

+

Erlang is by nature asynchronous and really good at it thanks to the great engineering that has been done in the VM over the years. It's only natural that it's so good at dealing with the asynchronous Web.

The Web is omnipresent

-
-

The Web has taken a very important part of our lives. We’re -connected at all times, when we’re on our phone, using our computer, -passing time using a tablet while in the bathroom… And this -isn’t going to slow down, every single device at home or on us -will be connected.

-

All these devices are always connected. And with the number of -alternatives to give you access to the content you seek, users -tend to not stick around when problems arise. Users today want -their applications to be always available and if it’s having -too many issues they just move on.

-

Despite this, when developers choose a product to use for building -web applications, their only concern seems to be "Is it fast?", -and they look around for synthetic benchmarks showing which one -is the fastest at sending "Hello world" with only a handful -concurrent connections. Web benchmarks haven’t been representative -of reality in a long time, and are drifting further away as -time goes on.

-

What developers should really ask themselves is "Can I service -all my users with no interruption?" and they’d find that they have -two choices. They can either hope for the best, or they can use -Erlang.

-

Erlang is built for fault tolerance. When writing code in any other -language, you have to check all the return values and act accordingly -to avoid any unforeseen issues. If you’re lucky, you won’t miss -anything important. When writing Erlang code, you can just check -the success condition and ignore all errors. If an error happens, -the Erlang process crashes and is then restarted by a special -process called a supervisor.

-

Erlang developers thus have no need to fear unhandled -errors, and can focus on handling only the errors that should -give some feedback to the user and let the system take care of -the rest. This also has the advantage of allowing them to write -a lot less code, and let them sleep at night.

-

Erlang’s fault tolerance oriented design is the first piece of -what makes it the best choice for the omnipresent, always available -Web.

-

The second piece is Erlang’s built-in distribution. Distribution -is a key part of building a fault tolerant system, because it -allows you to handle bigger failures, like a whole server going -down, or even a data center entirely.

-

Fault tolerance and distribution are important today, and will be -vital in the future of the Web. Erlang is ready.

-
-
-
+

The Web has taken a very important part of our lives. We're connected at all times, when we're on our phone, using our computer, passing time using a tablet while in the bathroom... And this isn't going to slow down, every single device at home or on us will be connected.

+

All these devices are always connected. And with the number of alternatives to give you access to the content you seek, users tend to not stick around when problems arise. Users today want their applications to be always available and if it's having too many issues they just move on.

+

Despite this, when developers choose a product to use for building web applications, their only concern seems to be "Is it fast?", and they look around for synthetic benchmarks showing which one is the fastest at sending "Hello world" with only a handful concurrent connections. Web benchmarks haven't been representative of reality in a long time, and are drifting further away as time goes on.

+

What developers should really ask themselves is "Can I service all my users with no interruption?" and they'd find that they have two choices. They can either hope for the best, or they can use Erlang.

+

Erlang is built for fault tolerance. When writing code in any other language, you have to check all the return values and act accordingly to avoid any unforeseen issues. If you're lucky, you won't miss anything important. When writing Erlang code, you can just check the success condition and ignore all errors. If an error happens, the Erlang process crashes and is then restarted by a special process called a supervisor.

+

Erlang developers thus have no need to fear unhandled errors, and can focus on handling only the errors that should give some feedback to the user and let the system take care of the rest. This also has the advantage of allowing them to write a lot less code, and let them sleep at night.

+

Erlang's fault tolerance oriented design is the first piece of what makes it the best choice for the omnipresent, always available Web.

+

The second piece is Erlang's built-in distribution. Distribution is a key part of building a fault tolerant system, because it allows you to handle bigger failures, like a whole server going down, or even a data center entirely.

+

Fault tolerance and distribution are important today, and will be vital in the future of the Web. Erlang is ready.

Learn Erlang

-
-

If you are new to Erlang, you may want to grab a book or -two to get started. Those are my recommendations as the -author of Cowboy.

-
+

If you are new to Erlang, you may want to grab a book or two to get started. Those are my recommendations as the author of Cowboy.

The Erlanger Playbook

-

The Erlanger Playbook is an ebook I am currently writing, -which covers a number of different topics from code to -documentation to testing Erlang applications. It also has -an Erlang section where it covers directly the building -blocks and patterns, rather than details like the syntax.

-

You can most likely read it as a complete beginner, but -you will need a companion book to make the most of it. -Buy it from the Nine Nines website.

-
-
+

The Erlanger Playbook is an ebook I am currently writing, which covers a number of different topics from code to documentation to testing Erlang applications. It also has an Erlang section where it covers directly the building blocks and patterns, rather than details like the syntax.

+

You can most likely read it as a complete beginner, but you will need a companion book to make the most of it. Buy it from the Nine Nines website.

Programming Erlang

-

This book is from one of the creator of Erlang, Joe -Armstrong. It provides a very good explanation of what -Erlang is and why it is so. It serves as a very good -introduction to the language and platform.

-

The book is Programming Erlang, -and it also features a chapter on Cowboy.

-
-
+

This book is from one of the creator of Erlang, Joe Armstrong. It provides a very good explanation of what Erlang is and why it is so. It serves as a very good introduction to the language and platform.

+

The book is Programming Erlang, and it also features a chapter on Cowboy.

Learn You Some Erlang for Great Good!

-

LYSE is a much more complete -book covering many aspects of Erlang, while also providing -stories and humor. Be warned: it’s pretty verbose. It comes -with a free online version and a more refined paper and -ebook version.

-
-
-
+

LYSE is a much more complete book covering many aspects of Erlang, while also providing stories and humor. Be warned: it's pretty verbose. It comes with a free online version and a more refined paper and ebook version.

+ diff --git a/docs/en/cowboy/2.2/guide/flow_diagram/index.html b/docs/en/cowboy/2.2/guide/flow_diagram/index.html index ed22d419..303c739a 100644 --- a/docs/en/cowboy/2.2/guide/flow_diagram/index.html +++ b/docs/en/cowboy/2.2/guide/flow_diagram/index.html @@ -62,113 +62,30 @@

Flow diagram

-

Cowboy is a lightweight HTTP server with support for HTTP/1.1, -HTTP/2 and Websocket.

-

It is built on top of Ranch. Please see the Ranch guide for more -information about how the network connections are handled.

-
+

Cowboy is a lightweight HTTP server with support for HTTP/1.1, HTTP/2 and Websocket.

+

It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled.

Overview

-
-
-
-HTTP request/response flowchart -
-
-

As you can see on the diagram, the client -begins by connecting to the server. This step is handled -by a Ranch acceptor, which is a process dedicated to -accepting new connections.

-

After Ranch accepts a new connection, whether it is an -HTTP/1.1 or HTTP/2 connection, Cowboy starts receiving -requests and handling them.

-

In HTTP/1.1 all requests come sequentially. In HTTP/2 -the requests may arrive and be processed concurrently.

-

When a request comes in, Cowboy creates a stream, which -is a set of request/response and all the events associated -with them. The protocol code in Cowboy defers the handling -of these streams to stream handler modules. When you -configure Cowboy you may define one or more module that -will receive all events associated with a stream, including -the request, response, bodies, Erlang messages and more.

-

By default Cowboy comes configured with a stream handler -called cowboy_stream_h. This stream handler will create -a new process for every request coming in, and then -communicate with this process to read the body or send -a response back. The request process executes middlewares -which, by default, including the router and then the -execution of handlers. Like stream handlers, middlewares -may also be customized.

-

A response may be sent at almost any point in this -diagram. If the response must be sent before the stream -is initialized (because an error occurred early, for -example) then stream handlers receive a special event -indicating this error.

-
-
-
+HTTP request/response flowchart

As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections.

+

After Ranch accepts a new connection, whether it is an HTTP/1.1 or HTTP/2 connection, Cowboy starts receiving requests and handling them.

+

In HTTP/1.1 all requests come sequentially. In HTTP/2 the requests may arrive and be processed concurrently.

+

When a request comes in, Cowboy creates a stream, which is a set of request/response and all the events associated with them. The protocol code in Cowboy defers the handling of these streams to stream handler modules. When you configure Cowboy you may define one or more module that will receive all events associated with a stream, including the request, response, bodies, Erlang messages and more.

+

By default Cowboy comes configured with a stream handler called cowboy_stream_h. This stream handler will create a new process for every request coming in, and then communicate with this process to read the body or send a response back. The request process executes middlewares which, by default, including the router and then the execution of handlers. Like stream handlers, middlewares may also be customized.

+

A response may be sent at almost any point in this diagram. If the response must be sent before the stream is initialized (because an error occurred early, for example) then stream handlers receive a special event indicating this error.

Protocol-specific headers

-
-

Cowboy takes care of protocol-specific headers and prevents -you from sending them manually. For HTTP/1.1 this includes -the transfer-encoding and connection headers. For HTTP/2 -this includes the colon headers like :status.

-

Cowboy will also remove protocol-specific headers from -requests before passing them to stream handlers. Cowboy -tries to hide the implementation details of all protocols -as well as possible.

-
-
-
+

Cowboy takes care of protocol-specific headers and prevents you from sending them manually. For HTTP/1.1 this includes the transfer-encoding and connection headers. For HTTP/2 this includes the colon headers like :status.

+

Cowboy will also remove protocol-specific headers from requests before passing them to stream handlers. Cowboy tries to hide the implementation details of all protocols as well as possible.

Number of processes per connection

-
-

By default, Cowboy will use one process per connection, -plus one process per set of request/response (called a -stream, internally).

-

The reason it creates a new process for every request is due -to the requirements of HTTP/2 where requests are executed -concurrently and independently from the connection. The -frames from the different requests end up interleaved on -the single TCP connection.

-

The request processes are never reused. There is therefore -no need to perform any cleanup after the response has been -sent. The process will terminate and Erlang/OTP will reclaim -all memory at once.

-

Cowboy ultimately does not require more than one process -per connection. It is possible to interact with the connection -directly from a stream handler, a low level interface to Cowboy. -They are executed from within the connection process, and can -handle the incoming requests and send responses. This is however -not recommended in normal circumstances, as a stream handler -taking too long to execute could have a negative impact on -concurrent requests or the state of the connection itself.

-
-
-
+

By default, Cowboy will use one process per connection, plus one process per set of request/response (called a stream, internally).

+

The reason it creates a new process for every request is due to the requirements of HTTP/2 where requests are executed concurrently and independently from the connection. The frames from the different requests end up interleaved on the single TCP connection.

+

The request processes are never reused. There is therefore no need to perform any cleanup after the response has been sent. The process will terminate and Erlang/OTP will reclaim all memory at once.

+

Cowboy ultimately does not require more than one process per connection. It is possible to interact with the connection directly from a stream handler, a low level interface to Cowboy. They are executed from within the connection process, and can handle the incoming requests and send responses. This is however not recommended in normal circumstances, as a stream handler taking too long to execute could have a negative impact on concurrent requests or the state of the connection itself.

Date header

-
-

Because querying for the current date and time can be expensive, -Cowboy generates one Date header value every second, shares it -to all other processes, which then simply copy it in the response. -This allows compliance with HTTP/1.1 with no actual performance loss.

-
-
-
+

Because querying for the current date and time can be expensive, Cowboy generates one Date header value every second, shares it to all other processes, which then simply copy it in the response. This allows compliance with HTTP/1.1 with no actual performance loss.

Binaries

-
-

Cowboy makes extensive use of binaries.

-

Binaries are more efficient than lists for representing -strings because they take less memory space. Processing -performance can vary depending on the operation. Binaries -are known for generally getting a great boost if the code -is compiled natively. Please see the HiPE documentation -for more details.

-

Binaries may end up being shared between processes. This -can lead to some large memory usage when one process keeps -the binary data around forever without freeing it. If you -see some weird memory usage in your application, this might -be the cause.

-
-
+

Cowboy makes extensive use of binaries.

+

Binaries are more efficient than lists for representing strings because they take less memory space. Processing performance can vary depending on the operation. Binaries are known for generally getting a great boost if the code is compiled natively. Please see the HiPE documentation for more details.

+

Binaries may end up being shared between processes. This can lead to some large memory usage when one process keeps the binary data around forever without freeing it. If you see some weird memory usage in your application, this might be the cause.

+ diff --git a/docs/en/cowboy/2.2/guide/getting_started/index.html b/docs/en/cowboy/2.2/guide/getting_started/index.html index dfbd7282..56a1205f 100644 --- a/docs/en/cowboy/2.2/guide/getting_started/index.html +++ b/docs/en/cowboy/2.2/guide/getting_started/index.html @@ -62,161 +62,104 @@

Getting started

-

Erlang is more than a language, it is also an operating system -for your applications. Erlang developers rarely write standalone -modules, they write libraries or applications, and then bundle -those into what is called a release. A release contains the -Erlang VM plus all applications required to run the node, so -it can be pushed to production directly.

-

This chapter walks you through all the steps of setting up -Cowboy, writing your first application and generating your first -release. At the end of this chapter you should know everything -you need to push your first Cowboy application to production.

-
+

Erlang is more than a language, it is also an operating system for your applications. Erlang developers rarely write standalone modules, they write libraries or applications, and then bundle those into what is called a release. A release contains the Erlang VM plus all applications required to run the node, so it can be pushed to production directly.

+

This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. At the end of this chapter you should know everything you need to push your first Cowboy application to production.

Prerequisites

-
-

We are going to use the Erlang.mk -build system. If you are using Windows, please check the -Installation instructions -to get your environment setup before you continue.

-
-
-
+

We are going to use the Erlang.mk build system. If you are using Windows, please check the Installation instructions to get your environment setup before you continue.

Bootstrap

-
-

First, let’s create the directory for our application.

-
-
$ mkdir hello_erlang
-$ cd hello_erlang
-

Then we need to download Erlang.mk. Either use the following -command or download it manually.

-
-
-
$ wget https://erlang.mk/erlang.mk
-

We can now bootstrap our application. Since we are going to generate -a release, we will also bootstrap it at the same time.

-
-
-
$ make -f erlang.mk bootstrap bootstrap-rel
-

This creates a Makefile, a base application, and the release files -necessary for creating the release. We can already build and start -this release.

-
-
$ make run
-...
-(hello_erlang@127.0.0.1)1>
-

Entering the command i(). will show the running processes, including -one called hello_erlang_sup. This is the supervisor for our -application.

-

The release currently does nothing. In the rest of this chapter we -will add Cowboy as a dependency and write a simple "Hello world!" -handler.

-
-
-
+... +(hello_erlang@127.0.0.1)1> +
+

Entering the command i(). will show the running processes, including one called hello_erlang_sup. This is the supervisor for our application.

+

The release currently does nothing. In the rest of this chapter we will add Cowboy as a dependency and write a simple "Hello world!" handler.

Cowboy setup

-
-

We will modify the Makefile to tell the build system it needs to -fetch and compile Cowboy:

-
-
-
PROJECT = hello_erlang
+
PROJECT = hello_erlang
 
-DEPS = cowboy
-dep_cowboy_commit = 2.2.2
+DEPS = cowboy
+dep_cowboy_commit = 2.2.2
 
-DEP_PLUGINS = cowboy
+DEP_PLUGINS = cowboy
 
-include erlang.mk
-

We also tell the build system to load the plugins Cowboy provides. -These include predefined templates that we will use soon.

-

If you do make run now, Cowboy will be included in the release -and started automatically. This is not enough however, as Cowboy -doesn’t do anything by default. We still need to tell Cowboy to -listen for connections.

-
- -
+include erlang.mk +
+

We also tell the build system to load the plugins Cowboy provides. These include predefined templates that we will use soon.

+

If you do make run now, Cowboy will be included in the release and started automatically. This is not enough however, as Cowboy doesn't do anything by default. We still need to tell Cowboy to listen for connections.

Listening for connections

-
-

First we define the routes that Cowboy will use to map requests -to handler modules, and then we start the listener. This is best -done at application startup.

-

Open the src/hello_erlang_app.erl file and add the necessary -code to the start/2 function to make it look like this:

-
-
-
start(_Type, _Args) ->
-    Dispatch = cowboy_router:compile([
-        {'_', [{"/", hello_handler, []}]}
+
start(_Type, _Args) ->
+    Dispatch = cowboy_router:compile([
+        {'_', [{"/", hello_handler, []}]}
     ]),
-    {ok, _} = cowboy:start_clear(my_http_listener,
-        [{port, 8080}],
-        #{env => #{dispatch => Dispatch}}
+    {ok, _} = cowboy:start_clear(my_http_listener,
+        [{port, 8080}],
+        #{env => #{dispatch => Dispatch}}
     ),
-    hello_erlang_sup:start_link().
-

Routes are explained in details in the Routing -chapter. For this tutorial we map the path / to the handler -module hello_handler. This module doesn’t exist yet.

-

Build and start the release, then open http://localhost:8080 -in your browser. You will get a 500 error because the module is missing. -Any other URL, like http://localhost:8080/test, will result in a -404 error.

-
- -
+ hello_erlang_sup:start_link(). +
+

Routes are explained in details in the Routing chapter. For this tutorial we map the path / to the handler module hello_handler. This module doesn't exist yet.

+

Build and start the release, then open http://localhost:8080 in your browser. You will get a 500 error because the module is missing. Any other URL, like http://localhost:8080/test, will result in a 404 error.

Handling requests

-
-

Cowboy features different kinds of handlers, including REST -and Websocket handlers. For this tutorial we will use a plain -HTTP handler.

-

Generate a handler from a template:

-
-
-
$ make new t=cowboy.http n=hello_handler
-

Then, open the src/hello_handler.erl file and modify -the init/2 function like this to send a reply.

-
-
-
init(Req0, State) ->
-    Req = cowboy_req:reply(200,
-        #{<<"content-type">> => <<"text/plain">>},
-        <<"Hello Erlang!">>,
-        Req0),
-    {ok, Req, State}.
-

What the above code does is send a 200 OK reply, with the -Content-type header set to text/plain and the response -body set to Hello Erlang!.

-

If you run the release and open http://localhost:8080 -in your browser, you should get a nice Hello Erlang! displayed!

-
- +
init(Req0, State) ->
+    Req = cowboy_req:reply(200,
+        #{<<"content-type">> => <<"text/plain">>},
+        <<"Hello Erlang!">>,
+        Req0),
+    {ok, Req, State}.
+ +

What the above code does is send a 200 OK reply, with the Content-type header set to text/plain and the response body set to Hello Erlang!.

+

If you run the release and open http://localhost:8080 in your browser, you should get a nice Hello Erlang! displayed!

+ diff --git a/docs/en/cowboy/2.2/guide/handlers/index.html b/docs/en/cowboy/2.2/guide/handlers/index.html index 843d05f8..5b957f51 100644 --- a/docs/en/cowboy/2.2/guide/handlers/index.html +++ b/docs/en/cowboy/2.2/guide/handlers/index.html @@ -62,91 +62,57 @@

Handlers

-

Handlers are Erlang modules that handle HTTP requests.

-
+

Handlers are Erlang modules that handle HTTP requests.

Plain HTTP handlers

-
-

The most basic handler in Cowboy implements the mandatory -init/2 callback, manipulates the request, optionally -sends a response and then returns.

-

This callback receives the Req object and the initial -state defined in the router configuration.

-

A handler that does nothing would look like this:

-
-
-
init(Req, State) ->
-    {ok, Req, State}.
-

Despite sending no reply, a 204 No Content response will be -sent to the client, as Cowboy makes sure that a response is -sent for every request.

-

We need to use the Req object to reply.

-
-
-
init(Req0, State) ->
-    Req = cowboy_req:reply(200, #{
-        <<"content-type">> => <<"text/plain">>
-    }, <<"Hello World!">>, Req0),
-    {ok, Req, State}.
-

Cowboy will immediately send a response when cowboy:reply/4 -is called.

-

We then return a 3-tuple. ok means that the handler ran -successfully. We also give the modified Req back to Cowboy.

-

The last value of the tuple is a state that will be used -in every subsequent callbacks to this handler. Plain HTTP -handlers only have one additional callback, the optional -and rarely used terminate/3.

-
-
-
+
init(Req0, State) ->
+    Req = cowboy_req:reply(200, #{
+        <<"content-type">> => <<"text/plain">>
+    }, <<"Hello World!">>, Req0),
+    {ok, Req, State}.
+
+

Cowboy will immediately send a response when cowboy:reply/4 is called.

+

We then return a 3-tuple. ok means that the handler ran successfully. We also give the modified Req back to Cowboy.

+

The last value of the tuple is a state that will be used in every subsequent callbacks to this handler. Plain HTTP handlers only have one additional callback, the optional and rarely used terminate/3.

Other handlers

-
-

The init/2 callback can also be used to inform Cowboy -that this is a different kind of handler and that Cowboy -should switch to it. To do this you simply need to return -the module name of the handler type you want to switch to.

-

Cowboy comes with three handler types you can switch to: -cowboy_rest, cowboy_websocket -and cowboy_loop. In addition to those you -can define your own handler types.

-

Switching is simple. Instead of returning ok, you simply -return the name of the handler type you want to use. The -following snippet switches to a Websocket handler:

-
-
-
init(Req, State) ->
-    {cowboy_websocket, Req, State}.
-
- -
+
init(Req, State) ->
+    {cowboy_websocket, Req, State}.
+

Cleaning up

-
-

All handler types provide the optional terminate/3 callback.

-
-
-
terminate(_Reason, _Req, _State) ->
-    ok.
-

This callback is strictly reserved for any required cleanup. -You cannot send a response from this function. There is no -other return value.

-

This callback is optional because it is rarely necessary. -Cleanup should be done in separate processes directly (by -monitoring the handler process to detect when it exits).

-

Cowboy does not reuse processes for different requests. The -process will terminate soon after this call returns.

-
- +
terminate(_Reason, _Req, _State) ->
+    ok.
+ +

This callback is strictly reserved for any required cleanup. You cannot send a response from this function. There is no other return value.

+

This callback is optional because it is rarely necessary. Cleanup should be done in separate processes directly (by monitoring the handler process to detect when it exits).

+

Cowboy does not reuse processes for different requests. The process will terminate soon after this call returns.

+ diff --git a/docs/en/cowboy/2.2/guide/index.html b/docs/en/cowboy/2.2/guide/index.html index 1e7db9f3..9547fadd 100644 --- a/docs/en/cowboy/2.2/guide/index.html +++ b/docs/en/cowboy/2.2/guide/index.html @@ -62,214 +62,85 @@

Cowboy User Guide

-
+ +

Rationale

- -
-
+

Introduction

- -
-
+

Configuration

-
- -
-
-
+

Handlers

- -
- - - -
+

Advanced

-
- -
-
- + + diff --git a/docs/en/cowboy/2.2/guide/introduction/index.html b/docs/en/cowboy/2.2/guide/introduction/index.html index 62e0310c..08a9d172 100644 --- a/docs/en/cowboy/2.2/guide/introduction/index.html +++ b/docs/en/cowboy/2.2/guide/introduction/index.html @@ -62,79 +62,40 @@

Introduction

-

Cowboy is a small, fast and modern HTTP server for Erlang/OTP.

-

Cowboy aims to provide a complete modern Web stack. -This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and -Webmachine-based REST.

-

Cowboy comes with functions for introspection and tracing, enabling -developers to know precisely what is happening at any time. Its modular -design also easily enable developers to add instrumentation.

-

Cowboy is a high quality project. It has a small code base, is very -efficient (both in latency and memory use) and can easily be embedded -in another application.

-

Cowboy is clean Erlang code. It includes hundreds of tests and its code -is fully compliant with the Dialyzer. It is also well documented and -features a Function Reference, a User Guide and numerous Tutorials.

-
+

Cowboy is a small, fast and modern HTTP server for Erlang/OTP.

+

Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST.

+

Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation.

+

Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application.

+

Cowboy is clean Erlang code. It includes hundreds of tests and its code is fully compliant with the Dialyzer. It is also well documented and features a Function Reference, a User Guide and numerous Tutorials.

Prerequisites

-
-

Beginner Erlang knowledge is recommended for reading this guide.

-

Knowledge of the HTTP protocol is recommended but not required, as it -will be detailed throughout the guide.

-
-
-
+

Beginner Erlang knowledge is recommended for reading this guide.

+

Knowledge of the HTTP protocol is recommended but not required, as it will be detailed throughout the guide.

Supported platforms

-
-

Cowboy is tested and supported on Linux, FreeBSD, Windows and OSX.

-

Cowboy has been reported to work on other platforms, but we make no -guarantee that the experience will be safe and smooth. You are advised -to perform the necessary testing and security audits prior to deploying -on other platforms.

-

Cowboy is developed for Erlang/OTP 19.0 and newer.

-
-
-
+

Cowboy is tested and supported on Linux, FreeBSD, Windows and OSX.

+

Cowboy has been reported to work on other platforms, but we make no guarantee that the experience will be safe and smooth. You are advised to perform the necessary testing and security audits prior to deploying on other platforms.

+

Cowboy is developed for Erlang/OTP 19.0 and newer.

License

-
-

Cowboy uses the ISC License.

-
-
-
Copyright (c) 2011-2017, Loïc Hoguin <essen@ninenines.eu>
+

Cowboy uses the ISC License.

+
Copyright (c) 2011-2017, Loïc Hoguin <essen@ninenines.eu>
 
 Permission to use, copy, modify, and/or distribute this software for any
 purpose with or without fee is hereby granted, provided that the above
 copyright notice and this permission notice appear in all copies.
 
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-
-
-
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Versioning

-
- -
-
-
+

Cowboy uses Semantic Versioning 2.0.0.

Conventions

-
-

In the HTTP protocol, the method name is case sensitive. All standard -method names are uppercase.

-

Header names are case insensitive. When using HTTP/1.1, Cowboy converts -all the request header names to lowercase. HTTP/2 requires clients to -send them as lowercase. Any other header name is expected to be provided -lowercased, including when querying information about the request or -when sending responses.

-

The same applies to any other case insensitive value.

-
-
+

In the HTTP protocol, the method name is case sensitive. All standard method names are uppercase.

+

Header names are case insensitive. When using HTTP/1.1, Cowboy converts all the request header names to lowercase. HTTP/2 requires clients to send them as lowercase. Any other header name is expected to be provided lowercased, including when querying information about the request or when sending responses.

+

The same applies to any other case insensitive value.

+ diff --git a/docs/en/cowboy/2.2/guide/listeners/index.html b/docs/en/cowboy/2.2/guide/listeners/index.html index 7768b145..4c107966 100644 --- a/docs/en/cowboy/2.2/guide/listeners/index.html +++ b/docs/en/cowboy/2.2/guide/listeners/index.html @@ -62,109 +62,61 @@

Listeners

-

A listener is a set of processes that listens on a port for -new connections. Incoming connections get handled by Cowboy. -Depending on the connection handshake, one or another protocol -may be used.

-

This chapter is specific to Cowboy. Please refer to the -Ranch User Guide -for more information about listeners.

-

Cowboy provides two types of listeners: one listening for -clear TCP connections, and one listening for secure TLS -connections. Both of them support the HTTP/1.1 and HTTP/2 -protocols.

-
+

A listener is a set of processes that listens on a port for new connections. Incoming connections get handled by Cowboy. Depending on the connection handshake, one or another protocol may be used.

+

This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners.

+

Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. Both of them support the HTTP/1.1 and HTTP/2 protocols.

Clear TCP listener

-
-

The clear TCP listener will accept connections on the -given port. A typical HTTP server would listen on port 80. -Port 80 requires special permissions on most platforms -however so a common alternative is port 8080.

-

The following snippet starts listening for connections -on port 8080:

-
-
-
start(_Type, _Args) ->
-    Dispatch = cowboy_router:compile([
-        {'_', [{"/", hello_handler, []}]}
+
start(_Type, _Args) ->
+    Dispatch = cowboy_router:compile([
+        {'_', [{"/", hello_handler, []}]}
     ]),
-    {ok, _} = cowboy:start_clear(my_http_listener,
-        [{port, 8080}],
-        #{env => #{dispatch => Dispatch}}
+    {ok, _} = cowboy:start_clear(my_http_listener,
+        [{port, 8080}],
+        #{env => #{dispatch => Dispatch}}
     ),
-    hello_erlang_sup:start_link().
-

The Getting Started chapter uses a -clear TCP listener.

-

Clients connecting to Cowboy on the clear listener port are -expected to use either HTTP/1.1 or HTTP/2.

-

Cowboy supports both methods of initiating a clear -HTTP/2 connection: through the Upgrade mechanism -(RFC 7540 3.2) -or by sending the preface directly -(RFC 7540 3.4).

-

Compatibility with HTTP/1.0 is provided by Cowboy’s HTTP/1.1 -implementation.

-
-
-
+ hello_erlang_sup:start_link(). +
+

The Getting Started chapter uses a clear TCP listener.

+

Clients connecting to Cowboy on the clear listener port are expected to use either HTTP/1.1 or HTTP/2.

+

Cowboy supports both methods of initiating a clear HTTP/2 connection: through the Upgrade mechanism (RFC 7540 3.2) or by sending the preface directly (RFC 7540 3.4).

+

Compatibility with HTTP/1.0 is provided by Cowboy's HTTP/1.1 implementation.

Secure TLS listener

-
-

The secure TLS listener will accept connections on the -given port. A typical HTTPS server would listen on port 443. -Port 443 requires special permissions on most platforms -however so a common alternative is port 8443.

-

The function provided by Cowboy will ensure that the TLS -options given are following the HTTP/2 RFC with regards -to security. For example some TLS extensions or ciphers -may be disabled. This also applies to HTTP/1.1 connections -on this listener. If this is not desirable, Ranch can be -used directly to setup a custom listener.

-
-
+

The function provided by Cowboy will ensure that the TLS options given are following the HTTP/2 RFC with regards to security. For example some TLS extensions or ciphers may be disabled. This also applies to HTTP/1.1 connections on this listener. If this is not desirable, Ranch can be used directly to setup a custom listener.

+
-
start(_Type, _Args) ->
-    Dispatch = cowboy_router:compile([
-        {'_', [{"/", hello_handler, []}]}
+
start(_Type, _Args) ->
+    Dispatch = cowboy_router:compile([
+        {'_', [{"/", hello_handler, []}]}
     ]),
-    {ok, _} = cowboy:start_tls(my_http_listener,
+    {ok, _} = cowboy:start_tls(my_http_listener,
         [
-            {port, 8443},
-            {certfile, "/path/to/certfile"},
-            {keyfile, "/path/to/keyfile"}
+            {port, 8443},
+            {certfile, "/path/to/certfile"},
+            {keyfile, "/path/to/keyfile"}
         ],
-        #{env => #{dispatch => Dispatch}}
+        #{env => #{dispatch => Dispatch}}
     ),
-    hello_erlang_sup:start_link().
-

Clients connecting to Cowboy on the secure listener are -expected to use the ALPN TLS extension to indicate what -protocols they understand. Cowboy always prefers HTTP/2 -over HTTP/1.1 when both are supported. When neither are -supported by the client, or when the ALPN extension was -missing, Cowboy expects HTTP/1.1 to be used.

-

Cowboy also advertises HTTP/2 support through the older -NPN TLS extension for compatibility. Note however that -this support will likely not be enabled by default when -Cowboy 2.0 gets released.

-

Compatibility with HTTP/1.0 is provided by Cowboy’s HTTP/1.1 -implementation.

-
-
-
+ hello_erlang_sup:start_link(). +
+

Clients connecting to Cowboy on the secure listener are expected to use the ALPN TLS extension to indicate what protocols they understand. Cowboy always prefers HTTP/2 over HTTP/1.1 when both are supported. When neither are supported by the client, or when the ALPN extension was missing, Cowboy expects HTTP/1.1 to be used.

+

Cowboy also advertises HTTP/2 support through the older NPN TLS extension for compatibility. Note however that this support will likely not be enabled by default when Cowboy 2.0 gets released.

+

Compatibility with HTTP/1.0 is provided by Cowboy's HTTP/1.1 implementation.

Protocol configuration

-
-

The HTTP/1.1 and HTTP/2 protocols share the same semantics; -only their framing differs. The first is a text protocol and -the second a binary protocol.

-

Cowboy doesn’t separate the configuration for HTTP/1.1 and -HTTP/2. Everything goes into the same map. Many options are -shared.

-
- +

The HTTP/1.1 and HTTP/2 protocols share the same semantics; only their framing differs. The first is a text protocol and the second a binary protocol.

+

Cowboy doesn't separate the configuration for HTTP/1.1 and HTTP/2. Everything goes into the same map. Many options are shared.

+ + + diff --git a/docs/en/cowboy/2.2/guide/loop_handlers/index.html b/docs/en/cowboy/2.2/guide/loop_handlers/index.html index 8c3b3f8d..f6eff9d7 100644 --- a/docs/en/cowboy/2.2/guide/loop_handlers/index.html +++ b/docs/en/cowboy/2.2/guide/loop_handlers/index.html @@ -62,131 +62,72 @@

Loop handlers

-

Loop handlers are a special kind of HTTP handlers used when the -response can not be sent right away. The handler enters instead -a receive loop waiting for the right message before it can send -a response.

-

Loop handlers are used for requests where a response might not -be immediately available, but where you would like to keep the -connection open for a while in case the response arrives. The -most known example of such practice is known as long polling.

-

Loop handlers can also be used for requests where a response is -partially available and you need to stream the response body -while the connection is open. The most known example of such -practice is server-sent events.

-

While the same can be accomplished using plain HTTP handlers, -it is recommended to use loop handlers because they are well-tested -and allow using built-in features like hibernation and timeouts.

-

Loop handlers essentially wait for one or more Erlang messages -and feed these messages to the info/3 callback. It also features -the init/2 and terminate/3 callbacks which work the same as -for plain HTTP handlers.

-
+

Loop handlers are a special kind of HTTP handlers used when the response can not be sent right away. The handler enters instead a receive loop waiting for the right message before it can send a response.

+

Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling.

+

Loop handlers can also be used for requests where a response is partially available and you need to stream the response body while the connection is open. The most known example of such practice is server-sent events.

+

While the same can be accomplished using plain HTTP handlers, it is recommended to use loop handlers because they are well-tested and allow using built-in features like hibernation and timeouts.

+

Loop handlers essentially wait for one or more Erlang messages and feed these messages to the info/3 callback. It also features the init/2 and terminate/3 callbacks which work the same as for plain HTTP handlers.

Initialization

-
-

The init/2 function must return a cowboy_loop tuple to enable -loop handler behavior. This tuple may optionally contain -a timeout value and/or the atom hibernate to make the -process enter hibernation until a message is received.

-

This snippet enables the loop handler:

-
-
-
init(Req, State) ->
-    {cowboy_loop, Req, State}.
-

This also makes the process hibernate:

-
-
-
init(Req, State) ->
-    {cowboy_loop, Req, State, hibernate}.
-
-
-
+
init(Req, State) ->
+    {cowboy_loop, Req, State, hibernate}.
+

Receive loop

-
-

Once initialized, Cowboy will wait for messages to arrive -in the process' mailbox. When a message arrives, Cowboy -calls the info/3 function with the message, the Req object -and the handler’s state.

-

The following snippet sends a reply when it receives a -reply message from another process, or waits for another -message otherwise.

-
-
-
info({reply, Body}, Req, State) ->
-    cowboy_req:reply(200, #{}, Body, Req),
-    {stop, Req, State};
-info(_Msg, Req, State) ->
-    {ok, Req, State, hibernate}.
-

Do note that the reply tuple here may be any message -and is simply an example.

-

This callback may perform any necessary operation including -sending all or parts of a reply, and will subsequently -return a tuple indicating if more messages are to be expected.

-

The callback may also choose to do nothing at all and just -skip the message received.

-

If a reply is sent, then the stop tuple should be returned. -This will instruct Cowboy to end the request.

-

Otherwise an ok tuple should be returned.

-
- -
+
info({reply, Body}, Req, State) ->
+    cowboy_req:reply(200, #{}, Body, Req),
+    {stop, Req, State};
+info(_Msg, Req, State) ->
+    {ok, Req, State, hibernate}.
+
+

Do note that the reply tuple here may be any message and is simply an example.

+

This callback may perform any necessary operation including sending all or parts of a reply, and will subsequently return a tuple indicating if more messages are to be expected.

+

The callback may also choose to do nothing at all and just skip the message received.

+

If a reply is sent, then the stop tuple should be returned. This will instruct Cowboy to end the request.

+

Otherwise an ok tuple should be returned.

Streaming loop

-
-

Another common case well suited for loop handlers is -streaming data received in the form of Erlang messages. -This can be done by initiating a chunked reply in the -init/2 callback and then using cowboy_req:chunk/2 -every time a message is received.

-

The following snippet does exactly that. As you can see -a chunk is sent every time an event message is received, -and the loop is stopped by sending an eof message.

-
-
-
init(Req, State) ->
-    Req2 = cowboy_req:stream_reply(200, Req),
-    {cowboy_loop, Req2, State}.
-
-info(eof, Req, State) ->
-    {stop, Req, State};
-info({event, Data}, Req, State) ->
-    cowboy_req:stream_body(Data, nofin, Req),
-    {ok, Req, State};
-info(_Msg, Req, State) ->
-    {ok, Req, State}.
-
- -
+
init(Req, State) ->
+    Req2 = cowboy_req:stream_reply(200, Req),
+    {cowboy_loop, Req2, State}.
+
+info(eof, Req, State) ->
+    {stop, Req, State};
+info({event, Data}, Req, State) ->
+    cowboy_req:stream_body(Data, nofin, Req),
+    {ok, Req, State};
+info(_Msg, Req, State) ->
+    {ok, Req, State}.
+

Cleaning up

-
-

It is recommended that you set the connection header to -close when replying, as this process may be reused for -a subsequent request.

-

Please refer to the Handlers chapter -for general instructions about cleaning up.

-
- -
+

It is recommended that you set the connection header to close when replying, as this process may be reused for a subsequent request.

+

Please refer to the Handlers chapter for general instructions about cleaning up.

Hibernate

-
-

To save memory, you may hibernate the process in between -messages received. This is done by returning the atom -hibernate as part of the loop tuple callbacks normally -return. Just add the atom at the end and Cowboy will hibernate -accordingly.

-
-
+

To save memory, you may hibernate the process in between messages received. This is done by returning the atom hibernate as part of the loop tuple callbacks normally return. Just add the atom at the end and Cowboy will hibernate accordingly.

+ diff --git a/docs/en/cowboy/2.2/guide/middlewares/index.html b/docs/en/cowboy/2.2/guide/middlewares/index.html index 2d473e24..28d76671 100644 --- a/docs/en/cowboy/2.2/guide/middlewares/index.html +++ b/docs/en/cowboy/2.2/guide/middlewares/index.html @@ -62,92 +62,38 @@

Middlewares

-

Cowboy delegates the request processing to middleware components. -By default, two middlewares are defined, for the routing and handling -of the request, as is detailed in most of this guide.

-

Middlewares give you complete control over how requests are to be -processed. You can add your own middlewares to the mix or completely -change the chain of middlewares as needed.

-

Cowboy will execute all middlewares in the given order, unless one -of them decides to stop processing.

-
+

Cowboy delegates the request processing to middleware components. By default, two middlewares are defined, for the routing and handling of the request, as is detailed in most of this guide.

+

Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed.

+

Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing.

Usage

-
-

Middlewares only need to implement a single callback: execute/2. -It is defined in the cowboy_middleware behavior.

-

This callback has two arguments. The first is the Req object. -The second is the environment.

-

Middlewares can return one of three different values:

-
    -
  • -

    -{ok, Req, Env} to continue the request processing -

    +

    Middlewares only need to implement a single callback: execute/2. It is defined in the cowboy_middleware behavior.

    +

    This callback has two arguments. The first is the Req object. The second is the environment.

    +

    Middlewares can return one of three different values:

    +
    • {ok, Req, Env} to continue the request processing
    • -
    • -

      -{suspend, Module, Function, Args} to hibernate -

      +
    • {suspend, Module, Function, Args} to hibernate
    • -
    • -

      -{stop, Req} to stop processing and move on to the next request -

      +
    • {stop, Req} to stop processing and move on to the next request
    • -
-

Of note is that when hibernating, processing will resume on the given -MFA, discarding all previous stacktrace. Make sure you keep the Req -and Env in the arguments of this MFA for later use.

-

If an error happens during middleware processing, Cowboy will not try -to send an error back to the socket, the process will just crash. It -is up to the middleware to make sure that a reply is sent if something -goes wrong.

-
-
-
+ +

Of note is that when hibernating, processing will resume on the given MFA, discarding all previous stacktrace. Make sure you keep the Req and Env in the arguments of this MFA for later use.

+

If an error happens during middleware processing, Cowboy will not try to send an error back to the socket, the process will just crash. It is up to the middleware to make sure that a reply is sent if something goes wrong.

Configuration

-
-

The middleware environment is defined as the env protocol option. -In the previous chapters we saw it briefly when we needed to pass -the routing information. It is a list of tuples with the first -element being an atom and the second any Erlang term.

-

Two values in the environment are reserved:

-
    -
  • -

    -listener contains the name of the listener -

    +

    The middleware environment is defined as the env protocol option. In the previous chapters we saw it briefly when we needed to pass the routing information. It is a list of tuples with the first element being an atom and the second any Erlang term.

    +

    Two values in the environment are reserved:

    +
    • listener contains the name of the listener
    • -
    • -

      -result contains the result of the processing -

      +
    • result contains the result of the processing
    • -
-

The listener value is always defined. The result value can be -set by any middleware. If set to anything other than ok, Cowboy -will not process any subsequent requests on this connection.

-

The middlewares that come with Cowboy may define or require other -environment values to perform.

-

You can update the environment by calling the cowboy:set_env/3 -convenience function, adding or replacing a value in the environment.

-
-
-
+ +

The listener value is always defined. The result value can be set by any middleware. If set to anything other than ok, Cowboy will not process any subsequent requests on this connection.

+

The middlewares that come with Cowboy may define or require other environment values to perform.

+

You can update the environment by calling the cowboy:set_env/3 convenience function, adding or replacing a value in the environment.

Routing middleware

-
-

The routing middleware requires the dispatch value. If routing -succeeds, it will put the handler name and options in the handler -and handler_opts values of the environment, respectively.

-
-
-
+

The routing middleware requires the dispatch value. If routing succeeds, it will put the handler name and options in the handler and handler_opts values of the environment, respectively.

Handler middleware

-
-

The handler middleware requires the handler and handler_opts -values. It puts the result of the request handling into result.

-
-
+

The handler middleware requires the handler and handler_opts values. It puts the result of the request handling into result.

+ diff --git a/docs/en/cowboy/2.2/guide/migrating_from_1.0/index.html b/docs/en/cowboy/2.2/guide/migrating_from_1.0/index.html index 9b15e77f..a0100863 100644 --- a/docs/en/cowboy/2.2/guide/migrating_from_1.0/index.html +++ b/docs/en/cowboy/2.2/guide/migrating_from_1.0/index.html @@ -62,388 +62,120 @@

Migrating from Cowboy 1.0 to 2.0

-

A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req -interface in particular has seen a massive revamp. Hooks are -gone, their functionality can now be achieved via stream -handlers.

-

The documentation has seen great work, in particular the -manual. Each module and each function now has its own dedicated -manual page with full details and examples.

-
+

A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req interface in particular has seen a massive revamp. Hooks are gone, their functionality can now be achieved via stream handlers.

+

The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples.

Compatibility

-
-

Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. -Erlang/OTP 19.0 or above is required. It is non-trivial to -make Cowboy 2.0 work with older Erlang/OTP versions.

-

Cowboy 2.0 is not compatible with Cowlib versions older than -2.0. It should be compatible with Ranch 1.0 or above, however -it has not been tested with Ranch versions older than 1.4.

-

Cowboy 2.0 is tested on Arch Linux, Ubuntu, FreeBSD, Windows -and OSX. It is tested with every point release (latest patch -release) and also with HiPE on the most recent release.

-

Cowboy 2.0 now comes with Erlang.mk templates.

-
-
-
+

Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. Erlang/OTP 19.0 or above is required. It is non-trivial to make Cowboy 2.0 work with older Erlang/OTP versions.

+

Cowboy 2.0 is not compatible with Cowlib versions older than 2.0. It should be compatible with Ranch 1.0 or above, however it has not been tested with Ranch versions older than 1.4.

+

Cowboy 2.0 is tested on Arch Linux, Ubuntu, FreeBSD, Windows and OSX. It is tested with every point release (latest patch release) and also with HiPE on the most recent release.

+

Cowboy 2.0 now comes with Erlang.mk templates.

Features added

-
-
    -
  • -

    -The HTTP/2 protocol is now supported. -

    -
  • -
  • -

    -Cowboy no longer uses only one process per connection. - It now uses one process per connection plus one process - per request by default. This is necessary for HTTP/2. - There might be a slight drop in performance for HTTP/1.1 - connections due to this change. -

    -
  • -
  • -

    -Cowboy internals have largely been reworked in order to - support HTTP/2. This opened the way to stream handlers, - which are a chain of modules that are called whenever - something happens relating to a request/response. -

    -
  • -
  • -

    -The cowboy_stream_h stream handler has been added. - It provides most of Cowboy’s default behavior. -

    -
  • -
  • -

    -The cowboy_compress_h stream handler has been added. - It compresses responses when possible. It’s worth noting - that it compresses in more cases than Cowboy 1.0 ever did. -

    -
  • -
  • -

    -Because of the many changes in the internals of Cowboy, - many options have been added or modified. Of note is that - the Websocket options are now given per handler rather - than for the entire listener. -

    -
  • -
  • -

    -Websocket permessage-deflate compression is now supported - via the compress option. -

    -
  • -
  • -

    -Static file handlers will now correctly find files found - in .ez archives. -

    -
  • -
  • -

    -Constraints have been generalized and are now used not only - in the router but also in some cowboy_req functions. Their - interface has also been modified to allow for reverse - operations and formatting of errors. -

    -
  • -
-
-
-
+
  • The HTTP/2 protocol is now supported. +
  • +
  • Cowboy no longer uses only one process per connection. It now uses one process per connection plus one process per request by default. This is necessary for HTTP/2. There might be a slight drop in performance for HTTP/1.1 connections due to this change. +
  • +
  • Cowboy internals have largely been reworked in order to support HTTP/2. This opened the way to stream handlers, which are a chain of modules that are called whenever something happens relating to a request/response. +
  • +
  • The cowboy_stream_h stream handler has been added. It provides most of Cowboy's default behavior. +
  • +
  • The cowboy_compress_h stream handler has been added. It compresses responses when possible. It's worth noting that it compresses in more cases than Cowboy 1.0 ever did. +
  • +
  • Because of the many changes in the internals of Cowboy, many options have been added or modified. Of note is that the Websocket options are now given per handler rather than for the entire listener. +
  • +
  • Websocket permessage-deflate compression is now supported via the compress option. +
  • +
  • Static file handlers will now correctly find files found in .ez archives. +
  • +
  • Constraints have been generalized and are now used not only in the router but also in some cowboy_req functions. Their interface has also been modified to allow for reverse operations and formatting of errors. +
  • +

Features removed

-
-
    -
  • -

    -SPDY support has been removed. Use HTTP/2 instead. -

    -
  • -
  • -

    -Hooks have been removed. Use stream handlers instead. -

    -
  • -
  • -

    -The undocumented waiting_stream hack has been removed. - It allowed disabling chunked transfer-encoding for HTTP/1.1. - It has no equivalent in Cowboy 2.0. Open a ticket if necessary. -

    -
  • -
  • -

    -Sub protocols still exist, but their interface has largely changed - and they are no longer documented for the time being. -

    -
  • -
-
-
-
+
  • SPDY support has been removed. Use HTTP/2 instead. +
  • +
  • Hooks have been removed. Use stream handlers instead. +
  • +
  • The undocumented waiting_stream hack has been removed. It allowed disabling chunked transfer-encoding for HTTP/1.1. It has no equivalent in Cowboy 2.0. Open a ticket if necessary. +
  • +
  • Sub protocols still exist, but their interface has largely changed and they are no longer documented for the time being. +
  • +

Changed behaviors

-
-
    -
  • -

    -The handler behaviors have been renamed and are now cowboy_handler, - cowboy_loop, cowboy_rest and cowboy_websocket. -

    -
  • -
  • -

    -Plain HTTP, loop, REST and Websocket handlers have had their - init and terminate callbacks unified. They now all use the - init/2 and terminate/3 callbacks. The latter is now optional. - The terminate reason has now been documented for all handlers. -

    -
  • -
  • -

    -The tuple returned to switch to a different handler type has - changed. It now takes the form {Module, Req, State} or - {Module, Req, State, Opts}, where Opts is a map of options - to configure the handler. The timeout and hibernate options - must now be specified using this map, where applicable. -

    -
  • -
  • -

    -All behaviors that used to accept halt or shutdown tuples - as a return value no longer do so. The return value is now - a stop tuple, consistent across Cowboy. -

    -
  • -
  • -

    -Middlewares can no longer return an error tuple. They have - to send the response and return a stop tuple instead. -

    -
  • -
  • -

    -The known_content_type REST handler callback has been removed - as it was found unnecessary. -

    -
  • -
  • -

    -Websocket handlers have both the normal init/2 and - an optional websocket_init/1 function. The reason for - that exception is that the websocket_* callbacks execute - in a separate process from the init/2 callback, and it - was therefore not obvious how timers or monitors should - be setup properly. They are effectively initializing the - handler before and after the HTTP/1.1 upgrade. -

    -
  • -
  • -

    -Websocket handlers can now send frames directly from - websocket_init/1. The frames will be sent immediately - after the handshake. -

    -
  • -
  • -

    -Websocket handler callbacks no longer receive the Req - argument. The init/2 callback still receives it and - can be used to extract relevant information. The terminate/3 - callback, if implemented, may still receive the Req - (see next bullet point). -

    -
  • -
  • -

    -Websocket handlers have a new req_filter option that - can be used to customize how much information should be - discarded from the Req object after the handshake. Note - that the Req object is only available in terminate/3 - past that point. -

    -
  • -
  • -

    -Websocket handlers have their timeout default changed - from infinity to 60 seconds. -

    -
  • -
-
-
-
+
  • The handler behaviors have been renamed and are now cowboy_handler, cowboy_loop, cowboy_rest and cowboy_websocket. +
  • +
  • Plain HTTP, loop, REST and Websocket handlers have had their init and terminate callbacks unified. They now all use the init/2 and terminate/3 callbacks. The latter is now optional. The terminate reason has now been documented for all handlers. +
  • +
  • The tuple returned to switch to a different handler type has changed. It now takes the form {Module, Req, State} or {Module, Req, State, Opts}, where Opts is a map of options to configure the handler. The timeout and hibernate options must now be specified using this map, where applicable. +
  • +
  • All behaviors that used to accept halt or shutdown tuples as a return value no longer do so. The return value is now a stop tuple, consistent across Cowboy. +
  • +
  • Middlewares can no longer return an error tuple. They have to send the response and return a stop tuple instead. +
  • +
  • The known_content_type REST handler callback has been removed as it was found unnecessary. +
  • +
  • Websocket handlers have both the normal init/2 and an optional websocket_init/1 function. The reason for that exception is that the websocket_* callbacks execute in a separate process from the init/2 callback, and it was therefore not obvious how timers or monitors should be setup properly. They are effectively initializing the handler before and after the HTTP/1.1 upgrade. +
  • +
  • Websocket handlers can now send frames directly from websocket_init/1. The frames will be sent immediately after the handshake. +
  • +
  • Websocket handler callbacks no longer receive the Req argument. The init/2 callback still receives it and can be used to extract relevant information. The terminate/3 callback, if implemented, may still receive the Req (see next bullet point). +
  • +
  • Websocket handlers have a new req_filter option that can be used to customize how much information should be discarded from the Req object after the handshake. Note that the Req object is only available in terminate/3 past that point. +
  • +
  • Websocket handlers have their timeout default changed from infinity to 60 seconds. +
  • +

New functions

-
-
    -
  • -

    -The cowboy_req:scheme/1 function has been added. -

    -
  • -
  • -

    -The cowboy_req:uri/1,2 function has been added, replacing the - less powerful functions cowboy_req:url/1 and cowboy_req:host_url/1. -

    -
  • -
  • -

    -The functions cowboy_req:match_qs/2 and cowboy_req:match_cookies/2 - allow matching query string and cookies against constraints. -

    -
  • -
  • -

    -The function cowboy_req:set_resp_cookie/3 has been added to - complement cowboy_req:set_resp_cookie/4. -

    -
  • -
  • -

    -The functions cowboy_req:resp_header/2,3 and cowboy_req:resp_headers/1 - have been added. They can be used to retrieve response headers - that were previously set. -

    -
  • -
  • -

    -The function cowboy_req:set_resp_headers/2 has been added. It - allows setting many response headers at once. -

    -
  • -
  • -

    -The functions cowboy_req:push/3,4 can be used to push resources - for protocols that support it (by default only HTTP/2). -

    -
  • -
-
-
-
+
  • The cowboy_req:scheme/1 function has been added. +
  • +
  • The cowboy_req:uri/1,2 function has been added, replacing the less powerful functions cowboy_req:url/1 and cowboy_req:host_url/1. +
  • +
  • The functions cowboy_req:match_qs/2 and cowboy_req:match_cookies/2 allow matching query string and cookies against constraints. +
  • +
  • The function cowboy_req:set_resp_cookie/3 has been added to complement cowboy_req:set_resp_cookie/4. +
  • +
  • The functions cowboy_req:resp_header/2,3 and cowboy_req:resp_headers/1 have been added. They can be used to retrieve response headers that were previously set. +
  • +
  • The function cowboy_req:set_resp_headers/2 has been added. It allows setting many response headers at once. +
  • +
  • The functions cowboy_req:push/3,4 can be used to push resources for protocols that support it (by default only HTTP/2). +
  • +

Changed functions

-
-
    -
  • -

    -The cowboy:start_http/4 function was renamed to cowboy:start_clear/3. -

    -
  • -
  • -

    -The cowboy:start_https/4 function was renamed to cowboy:start_tls/3. -

    -
  • -
  • -

    -Most, if not all, functions in the cowboy_req module have been modified. - Please consult the changelog of each individual functions. The changes - are mainly about simplifying and clarifying the interface. The Req is no - longer returned when not necessary, maps are used wherever possible, - and some functions have been renamed. -

    -
  • -
  • -

    -The position of the Opts argument for cowboy_req:set_resp_cookie/4 - has changed to improve consistency. It is now the last argument. -

    -
  • -
-
-
-
+
  • The cowboy:start_http/4 function was renamed to cowboy:start_clear/3. +
  • +
  • The cowboy:start_https/4 function was renamed to cowboy:start_tls/3. +
  • +
  • Most, if not all, functions in the cowboy_req module have been modified. Please consult the changelog of each individual functions. The changes are mainly about simplifying and clarifying the interface. The Req is no longer returned when not necessary, maps are used wherever possible, and some functions have been renamed. +
  • +
  • The position of the Opts argument for cowboy_req:set_resp_cookie/4 has changed to improve consistency. It is now the last argument. +
  • +

Removed functions

-
-
    -
  • -

    -The functions cowboy_req:url/1 and cowboy_req:host_url/1 have been - removed in favor of the new function cowboy_req:uri/1,2. -

    -
  • -
  • -

    -The functions cowboy_req:meta/2,3 and cowboy_req:set_meta/3 have - been removed. The Req object is now a public map, therefore they became - unnecessary. -

    -
  • -
  • -

    -The functions cowboy_req:set_resp_body_fun/2,3 have been removed. - For sending files, the function cowboy_req:set_resp_body/2 can now - take a sendfile tuple. -

    -
  • -
  • -

    -Remove many undocumented functions from cowboy_req, including the - functions cowboy_req:get/2 and cowboy_req:set/3. -

    -
  • -
-
-
-
+
  • The functions cowboy_req:url/1 and cowboy_req:host_url/1 have been removed in favor of the new function cowboy_req:uri/1,2. +
  • +
  • The functions cowboy_req:meta/2,3 and cowboy_req:set_meta/3 have been removed. The Req object is now a public map, therefore they became unnecessary. +
  • +
  • The functions cowboy_req:set_resp_body_fun/2,3 have been removed. For sending files, the function cowboy_req:set_resp_body/2 can now take a sendfile tuple. +
  • +
  • Remove many undocumented functions from cowboy_req, including the functions cowboy_req:get/2 and cowboy_req:set/3. +
  • +

Other changes

-
-
    -
  • -

    -The correct percent-decoding algorithm is now used for path elements - during routing. It will no longer decode + characters. -

    -
  • -
  • -

    -The router will now properly handle path segments . and ... -

    -
  • -
  • -

    -Routing behavior has changed for URIs containing latin1 characters. - They are no longer allowed. URIs are expected to be in UTF-8 once - they are percent-decoded. -

    -
  • -
  • -

    -Clients that send multiple headers of the same name - will have the values of those headers concatenated into a - comma-separated list. This is of special importance in the - case of the content-type header, as previously only the - first value was used in the content_types_accepted/2 step - in REST handlers. -

    -
  • -
  • -

    -Etag comparison in REST handlers has been fixed. Some requests may - now fail when they succeeded in the past. -

    -
  • -
  • -

    -The If-*-Since headers are now ignored in REST handlers if - the corresponding If*-Match header exist. The former is - largely a backward compatible header and this shouldn’t create - any issue. The new behavior follows the current RFCs more closely. -

    -
  • -
  • -

    -The static file handler has been improved to handle more special - characters on systems that accept them. -

    -
  • -
-
-
+
  • The correct percent-decoding algorithm is now used for path elements during routing. It will no longer decode + characters. +
  • +
  • The router will now properly handle path segments . and ... +
  • +
  • Routing behavior has changed for URIs containing latin1 characters. They are no longer allowed. URIs are expected to be in UTF-8 once they are percent-decoded. +
  • +
  • Clients that send multiple headers of the same name will have the values of those headers concatenated into a comma-separated list. This is of special importance in the case of the content-type header, as previously only the first value was used in the content_types_accepted/2 step in REST handlers. +
  • +
  • Etag comparison in REST handlers has been fixed. Some requests may now fail when they succeeded in the past. +
  • +
  • The If-*-Since headers are now ignored in REST handlers if the corresponding If*-Match header exist. The former is largely a backward compatible header and this shouldn't create any issue. The new behavior follows the current RFCs more closely. +
  • +
  • The static file handler has been improved to handle more special characters on systems that accept them. +
  • +
+ diff --git a/docs/en/cowboy/2.2/guide/migrating_from_2.0/index.html b/docs/en/cowboy/2.2/guide/migrating_from_2.0/index.html index b8c27361..f32a168c 100644 --- a/docs/en/cowboy/2.2/guide/migrating_from_2.0/index.html +++ b/docs/en/cowboy/2.2/guide/migrating_from_2.0/index.html @@ -62,188 +62,55 @@

Migrating from Cowboy 2.0 to 2.1

-

Cowboy 2.1 focused on adding features that were temporarily -removed in Cowboy 2.0. A number of bugs found in the 2.0 -release were also fixed.

-
+

Cowboy 2.1 focused on adding features that were temporarily removed in Cowboy 2.0. A number of bugs found in the 2.0 release were also fixed.

Features added

-
-
    -
  • -

    -It is now possible to obtain the client TLS certificate - and the local IP/port for the connection from the Req object. -

    +
    • It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object.
    • -
    • -

      -Informational responses (1XX responses) can now be sent. - They must be sent before initiating the final response. -

      +
    • Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response.
    • -
    • -

      -The expect: 100-continue header is now handled - automatically. The 100 response will be sent on the - first cowboy_req:read_body/2,3,4 call. This only applies - when using the default cowboy_stream_h stream handler. -

      +
    • The expect: 100-continue header is now handled automatically. The 100 response will be sent on the first cowboy_req:read_body/2,3,4 call. This only applies when using the default cowboy_stream_h stream handler.
    • -
-
-
-
+

Experimental features added

-
-

Experimental features are previews of features that will be -added in a future release. They are not documented and their -interface may change at any time. You are welcome to try them -and provide feedback.

-
    -
  • -

    -The cowboy_metrics_h stream handler can be used to - extract metrics out of Cowboy. It must be used first in - the list of stream handlers, and will record all events - related to requests, responses and spawned processes. - When the stream terminates it will pass this information - to a user-defined callback. -

    +

    Experimental features are previews of features that will be added in a future release. They are not documented and their interface may change at any time. You are welcome to try them and provide feedback.

    +
    • The cowboy_metrics_h stream handler can be used to extract metrics out of Cowboy. It must be used first in the list of stream handlers, and will record all events related to requests, responses and spawned processes. When the stream terminates it will pass this information to a user-defined callback.
    • -
    • -

      -The cowboy_tracer_h stream handler can be used to setup - automatic tracing of specific requests. You can conditionally - enable tracing based on a function, header, path or any other - element from the request and the trace will apply to the - entire connection and any processes created by it. This is - meant to be used for debugging both in tests and production. -

      +
    • The cowboy_tracer_h stream handler can be used to setup automatic tracing of specific requests. You can conditionally enable tracing based on a function, header, path or any other element from the request and the trace will apply to the entire connection and any processes created by it. This is meant to be used for debugging both in tests and production.
    • -
-
-
-
+

Changed behaviors

-
-
    -
  • -

    -The cowboy_rest handler now implements a mechanism for - switching to a different type of handler from any callback - where stop is also allowed. Switch by returning - {switch_handler, Module} or {switch_handler, Module, Opts}. - This is especially useful for switching to cowboy_loop - for streaming the request or response body. -

    +
    • The cowboy_rest handler now implements a mechanism for switching to a different type of handler from any callback where stop is also allowed. Switch by returning {switch_handler, Module} or {switch_handler, Module, Opts}. This is especially useful for switching to cowboy_loop for streaming the request or response body.
    • -
    • -

      -REST callbacks that do not allow stop as a return value - are now explicitly listed in the documentation. -

      +
    • REST callbacks that do not allow stop as a return value are now explicitly listed in the documentation.
    • -
-
-
-
+

New functions

-
-
    -
  • -

    -The function cowboy_req:sock/1 returns the IP/port - of the local socket. -

    +
    • The function cowboy_req:sock/1 returns the IP/port of the local socket.
    • -
    • -

      -The function cowboy_req:cert/1 returns the client - TLS certificate or undefined if it isn’t available. -

      +
    • The function cowboy_req:cert/1 returns the client TLS certificate or undefined if it isn't available.
    • -
    • -

      -The function cowboy_req:inform/2,3 sends an - informational response. -

      +
    • The function cowboy_req:inform/2,3 sends an informational response.
    • -
-
-
-
+

Bugs fixed

-
-
    -
  • -

    -Ensure HTTP/2 connections are not closed prematurely - when the user code does not read the request body. -

    +
    • Ensure HTTP/2 connections are not closed prematurely when the user code does not read the request body.
    • -
    • -

      -Ensure HTTP/1.1 streams are not terminated too early. - Their behavior is now consistent with the HTTP/2 code - where the stream handler is only terminated when the - stop command is returned. -

      +
    • Ensure HTTP/1.1 streams are not terminated too early. Their behavior is now consistent with the HTTP/2 code where the stream handler is only terminated when the stop command is returned.
    • -
    • -

      -Sending zero-sized data from stream handlers or from - cowboy_req:stream_body/3 could lead to issues with - HTTP/1.1. This has been fixed. -

      +
    • Sending zero-sized data from stream handlers or from cowboy_req:stream_body/3 could lead to issues with HTTP/1.1. This has been fixed.
    • -
    • -

      -The final chunk sent by Cowboy when it terminates a - chunked body after the handler process exits was not - passed through stream handlers, which could lead to - issues when cowboy_compress_h was being used. This - is now corrected. -

      +
    • The final chunk sent by Cowboy when it terminates a chunked body after the handler process exits was not passed through stream handlers, which could lead to issues when cowboy_compress_h was being used. This is now corrected.
    • -
    • -

      -The stream handler state was discarded in some cases - where Cowboy had to send a response or response data - automatically when ending a stream. This has now - been corrected. -

      +
    • The stream handler state was discarded in some cases where Cowboy had to send a response or response data automatically when ending a stream. This has now been corrected.
    • -
    • -

      -The stream handler callback terminate/3 will now be - called when switching to another protocol using the - command switch_protocol. This doesn’t apply when - doing upgrades to HTTP/2 as those occur before the - stream is initialized. -

      +
    • The stream handler callback terminate/3 will now be called when switching to another protocol using the command switch_protocol. This doesn't apply when doing upgrades to HTTP/2 as those occur before the stream is initialized.
    • -
    • -

      -Cowlib has been updated to 2.0.1 to fix an issue with - Websocket compression when using Erlang/OTP 20.1. Note - that at the time of writing all 20.1 versions (from - 20.1 to 20.1.4) have issues when compression is enabled. - It is expected to work properly from 20.1.5 onward. In - the meantime it is recommended to run the plain 20.1 - release and disable Websocket compression, or use a - release before 20.1. -

      +
    • Cowlib has been updated to 2.0.1 to fix an issue with Websocket compression when using Erlang/OTP 20.1. Note that at the time of writing all 20.1 versions (from 20.1 to 20.1.4) have issues when compression is enabled. It is expected to work properly from 20.1.5 onward. In the meantime it is recommended to run the plain 20.1 release and disable Websocket compression, or use a release before 20.1.
    • -
    • -

      -Cowboy will no longer crash when the cowboy_clock - process is not running. This can happen when Cowboy - is being restarted during upgrades, for example. -

      +
    • Cowboy will no longer crash when the cowboy_clock process is not running. This can happen when Cowboy is being restarted during upgrades, for example.
    • -
-
-
+ + diff --git a/docs/en/cowboy/2.2/guide/migrating_from_2.1/index.html b/docs/en/cowboy/2.2/guide/migrating_from_2.1/index.html index 1115964c..3f62d4a9 100644 --- a/docs/en/cowboy/2.2/guide/migrating_from_2.1/index.html +++ b/docs/en/cowboy/2.2/guide/migrating_from_2.1/index.html @@ -62,203 +62,66 @@

Migrating from Cowboy 2.1 to 2.2

-

Cowboy 2.2 focused on adding features required for writing -gRPC servers and on completing test suites for the core -HTTP RFCs, fixing many bugs along the way.

-
+

Cowboy 2.2 focused on adding features required for writing gRPC servers and on completing test suites for the core HTTP RFCs, fixing many bugs along the way.

Features added

-
-
    -
  • -

    -Add support for sending trailers at the end of response bodies. - Trailers are additional header fields that may be sent after the - body to add more information to the response. Their usage is - required in gRPC servers. They are optional and may be discarded - in other scenarios (for example if the request goes through an - HTTP/1.0 proxy, as HTTP/1.0 does not support trailers). -

    +
    • Add support for sending trailers at the end of response bodies. Trailers are additional header fields that may be sent after the body to add more information to the response. Their usage is required in gRPC servers. They are optional and may be discarded in other scenarios (for example if the request goes through an HTTP/1.0 proxy, as HTTP/1.0 does not support trailers).
    • -
    • -

      -The max_skip_body_length option was added to cowboy_http. - It controls how much of a request body Cowboy is willing to skip - when the handler did not touch it. If the remaining body size is - too large Cowboy instead closes the connection. It defaults to 1MB. -

      +
    • The max_skip_body_length option was added to cowboy_http. It controls how much of a request body Cowboy is willing to skip when the handler did not touch it. If the remaining body size is too large Cowboy instead closes the connection. It defaults to 1MB.
    • -
    • -

      -The CONNECT and TRACE methods are now rejected as they are - currently not implemented and must be handled differently than - other methods. They will be implemented in a future release. -

      +
    • The CONNECT and TRACE methods are now rejected as they are currently not implemented and must be handled differently than other methods. They will be implemented in a future release.
    • -
-
-
-
+

New functions

-
-
    -
  • -

    -The function stream_trailers/2 has been added. It terminates - a stream and adds trailer fields at the end of the response. A - corresponding stream handler command {trailers, Trailers} - has also been added. -

    +
    • The function stream_trailers/2 has been added. It terminates a stream and adds trailer fields at the end of the response. A corresponding stream handler command {trailers, Trailers} has also been added.
    • -
-
-
-
+

Bugs fixed

-
-
    -
  • -

    -Test suites for the core HTTP RFCs RFC7230, RFC7231 and RFC7540 - have been completed. Many of the bugs listed here were fixed as - a result of this work. -

    +
    • Test suites for the core HTTP RFCs RFC7230, RFC7231 and RFC7540 have been completed. Many of the bugs listed here were fixed as a result of this work.
    • -
    • -

      -Many HTTP/2 edge cases when clients are misbehaving have been - corrected. This includes many cases where the request is malformed - (for example when a pseudo-header is present twice). -

      +
    • Many HTTP/2 edge cases when clients are misbehaving have been corrected. This includes many cases where the request is malformed (for example when a pseudo-header is present twice).
    • -
    • -

      -When the HTTP/2 SETTINGS_INITIAL_WINDOW_SIZE value changes, - Cowboy now properly updates the flow control windows. -

      +
    • When the HTTP/2 SETTINGS_INITIAL_WINDOW_SIZE value changes, Cowboy now properly updates the flow control windows.
    • -
    • -

      -HTTP/2 could mistakenly log stray messages that actually were - expected. This is no longer the case. -

      +
    • HTTP/2 could mistakenly log stray messages that actually were expected. This is no longer the case.
    • -
    • -

      -We no longer send a GOAWAY frame when the HTTP/2 preface is invalid. -

      +
    • We no longer send a GOAWAY frame when the HTTP/2 preface is invalid.
    • -
    • -

      -Some values in the Req object of pushed requests were in the - wrong type. They are now the expected binary instead of iolist. -

      +
    • Some values in the Req object of pushed requests were in the wrong type. They are now the expected binary instead of iolist.
    • -
    • -

      -A response body was sometimes sent in response to HEAD requests - when using HTTP/2. The body is now ignored. -

      +
    • A response body was sometimes sent in response to HEAD requests when using HTTP/2. The body is now ignored.
    • -
    • -

      -The max_headers option for cowboy_http was not always respected - depending on the contents of the buffer. The limit is now strict. -

      +
    • The max_headers option for cowboy_http was not always respected depending on the contents of the buffer. The limit is now strict.
    • -
    • -

      -When an early error occurred on the HTTP/1.1 request line, the - partial Req given to stream handlers was missing the ref and - peer information. This has been corrected. -

      +
    • When an early error occurred on the HTTP/1.1 request line, the partial Req given to stream handlers was missing the ref and peer information. This has been corrected.
    • -
    • -

      -Absolute URIs with a userinfo component, or without an authority - component, are now properly rejected for HTTP/1.0 and HTTP/1.1. -

      +
    • Absolute URIs with a userinfo component, or without an authority component, are now properly rejected for HTTP/1.0 and HTTP/1.1.
    • -
    • -

      -Whitespace is no longer allowed in header lines before the colon. -

      +
    • Whitespace is no longer allowed in header lines before the colon.
    • -
    • -

      -408 responses to HTTP/1.1 requests now properly include a - connection: close header indicating that we are going to - close the connection. This header will also be sent for - other early errors resulting in the closing of the connection. -

      +
    • 408 responses to HTTP/1.1 requests now properly include a connection: close header indicating that we are going to close the connection. This header will also be sent for other early errors resulting in the closing of the connection.
    • -
    • -

      -When both the transfer-encoding and content-length headers are - sent in an HTTP/1.1 request, the transfer-encoding now takes - precedence over the content-length header and the latter is - removed from the Req object. -

      +
    • When both the transfer-encoding and content-length headers are sent in an HTTP/1.1 request, the transfer-encoding now takes precedence over the content-length header and the latter is removed from the Req object.
    • -
    • -

      -A 400 response is now returned when the transfer-encoding - header is invalid or contains any transfer-coding other - than chunked. -

      +
    • A 400 response is now returned when the transfer-encoding header is invalid or contains any transfer-coding other than chunked.
    • -
    • -

      -Invalid chunk sizes are now rejected immediately. -

      +
    • Invalid chunk sizes are now rejected immediately.
    • -
    • -

      -Chunk extensions are now limited to 129 characters. They are - not used in practice and are still ignored by Cowboy. The limit - is not configurable. -

      +
    • Chunk extensions are now limited to 129 characters. They are not used in practice and are still ignored by Cowboy. The limit is not configurable.
    • -
    • -

      -The final chunk was mistakenly sent in responses to HEAD - requests. This is now corrected. -

      +
    • The final chunk was mistakenly sent in responses to HEAD requests. This is now corrected.
    • -
    • -

      -OPTIONS * requests were broken in Cowboy 2.0. They are now - working again. Both the routing and cowboy_req:uri/1,2 have - been corrected. -

      +
    • OPTIONS * requests were broken in Cowboy 2.0. They are now working again. Both the routing and cowboy_req:uri/1,2 have been corrected.
    • -
    • -

      -204 responses no longer include a content-length header. -

      +
    • 204 responses no longer include a content-length header.
    • -
    • -

      -A packet could be lost when switching to Websocket or any - other protocol via the switch_protocol command. This is - now fixed. -

      +
    • A packet could be lost when switching to Websocket or any other protocol via the switch_protocol command. This is now fixed.
    • -
    • -

      -A 426 response will now be sent when a handler requires - the client to upgrade to Websocket and the request did not - include the required headers. -

      +
    • A 426 response will now be sent when a handler requires the client to upgrade to Websocket and the request did not include the required headers.
    • -
    • -

      -Both experimental stream handlers cowboy_metrics_h and - cowboy_tracer_h received a number of fixes and improvements. -

      +
    • Both experimental stream handlers cowboy_metrics_h and cowboy_tracer_h received a number of fixes and improvements.
    • -
-
-
+ + diff --git a/docs/en/cowboy/2.2/guide/migrating_from_2.2/index.html b/docs/en/cowboy/2.2/guide/migrating_from_2.2/index.html index 20c0b89c..bf42330c 100644 --- a/docs/en/cowboy/2.2/guide/migrating_from_2.2/index.html +++ b/docs/en/cowboy/2.2/guide/migrating_from_2.2/index.html @@ -62,48 +62,20 @@

Changes since Cowboy 2.2

-

The following patch versions were released since Cowboy 2.2:

-
+

The following patch versions were released since Cowboy 2.2:

Cowboy 2.2.2

-
-
    -
  • -

    -While fixing the miscount in the previous patch release an - issue was introduced where HTTP/2 bodies could be sent out - of orders when using iolists. This has been corrected. -

    +
    • While fixing the miscount in the previous patch release an issue was introduced where HTTP/2 bodies could be sent out of orders when using iolists. This has been corrected.
    • -
-
-
-
+

Cowboy 2.2.1

-
-
    -
  • -

    -Colons are now allowed within path segments in routes provided - to cowboy_router:compile/1 as long as they are not the first - character of the path segment. -

    +
    • Colons are now allowed within path segments in routes provided to cowboy_router:compile/1 as long as they are not the first character of the path segment.
    • -
    • -

      -The cowboy_req:delete_resp_header/2 function will no longer - crash when no response header was set before calling it. -

      +
    • The cowboy_req:delete_resp_header/2 function will no longer crash when no response header was set before calling it.
    • -
    • -

      -A miscount of the output HTTP/2 flow control window has been - fixed. It prevented sending the response body fully with some - clients. The issue only affected response bodies sent as iolists. -

      +
    • A miscount of the output HTTP/2 flow control window has been fixed. It prevented sending the response body fully with some clients. The issue only affected response bodies sent as iolists.
    • -
-
-
+ + diff --git a/docs/en/cowboy/2.2/guide/modern_web/index.html b/docs/en/cowboy/2.2/guide/modern_web/index.html index 6a48b79b..4cda7790 100644 --- a/docs/en/cowboy/2.2/guide/modern_web/index.html +++ b/docs/en/cowboy/2.2/guide/modern_web/index.html @@ -62,115 +62,38 @@

The modern Web

-

Cowboy is a server for the modern Web. This chapter explains -what it means and details all the standards involved.

-

Cowboy supports all the standards listed in this document.

-
+

Cowboy is a server for the modern Web. This chapter explains what it means and details all the standards involved.

+

Cowboy supports all the standards listed in this document.

HTTP/2

-
-

HTTP/2 is the most efficient protocol for consuming Web -services. It enables clients to keep a connection open -for long periods of time; to send requests concurrently; -to reduce the size of requests through HTTP headers -compression; and more. The protocol is binary, greatly -reducing the resources needed to parse it.

-

HTTP/2 also enables the server to push messages to the -client. This can be used for various purposes, including -the sending of related resources before the client requests -them, in an effort to reduce latency. This can also be used -to enable bidirectional communication.

-

Cowboy provides transparent support for HTTP/2. Clients -that know it can use it; others fall back to HTTP/1.1 -automatically.

-

HTTP/2 is compatible with the HTTP/1.1 semantics.

-

HTTP/2 is defined by RFC 7540 and RFC 7541.

-
-
-
+

HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. The protocol is binary, greatly reducing the resources needed to parse it.

+

HTTP/2 also enables the server to push messages to the client. This can be used for various purposes, including the sending of related resources before the client requests them, in an effort to reduce latency. This can also be used to enable bidirectional communication.

+

Cowboy provides transparent support for HTTP/2. Clients that know it can use it; others fall back to HTTP/1.1 automatically.

+

HTTP/2 is compatible with the HTTP/1.1 semantics.

+

HTTP/2 is defined by RFC 7540 and RFC 7541.

HTTP/1.1

-
-

HTTP/1.1 is the previous version of the HTTP protocol. -The protocol itself is text-based and suffers from numerous -issues and limitations. In particular it is not possible -to execute requests concurrently (though pipelining is -sometimes possible), and it’s also sometimes difficult -to detect that a client disconnected.

-

HTTP/1.1 does provide very good semantics for interacting -with Web services. It defines the standard methods, headers -and status codes used by HTTP/1.1 and HTTP/2 clients and -servers.

-

HTTP/1.1 also defines compatibility with an older version -of the protocol, HTTP/1.0, which was never really standardized -across implementations.

-

The core of HTTP/1.1 is defined by RFC 7230, RFC 7231, -RFC 7232, RFC 7233, RFC 7234 and RFC 7235. Numerous RFCs -and other specifications exist defining additional HTTP -methods, status codes, headers or semantics.

-
-
-
+

HTTP/1.1 is the previous version of the HTTP protocol. The protocol itself is text-based and suffers from numerous issues and limitations. In particular it is not possible to execute requests concurrently (though pipelining is sometimes possible), and it's also sometimes difficult to detect that a client disconnected.

+

HTTP/1.1 does provide very good semantics for interacting with Web services. It defines the standard methods, headers and status codes used by HTTP/1.1 and HTTP/2 clients and servers.

+

HTTP/1.1 also defines compatibility with an older version of the protocol, HTTP/1.0, which was never really standardized across implementations.

+

The core of HTTP/1.1 is defined by RFC 7230, RFC 7231, RFC 7232, RFC 7233, RFC 7234 and RFC 7235. Numerous RFCs and other specifications exist defining additional HTTP methods, status codes, headers or semantics.

Websocket

-
-

Websocket is a protocol built on top of HTTP/1.1 -that provides a two-ways communication channel between the client and -the server. Communication is asynchronous and can occur concurrently.

-

It consists of a Javascript object allowing setting up a -Websocket connection to the server, and a binary based -protocol for sending data to the server or the client.

-

Websocket connections can transfer either UTF-8 encoded text -data or binary data. The protocol also includes support for -implementing a ping/pong mechanism, allowing the server and -the client to have more confidence that the connection is still -alive.

-

A Websocket connection can be used to transfer any kind of data, -small or big, text or binary. Because of this Websocket is -sometimes used for communication between systems.

-

Websocket messages have no semantics on their own. Websocket -is closer to TCP in that aspect, and requires you to design -and implement your own protocol on top of it; or adapt an -existing protocol to Websocket.

-

Cowboy provides an interface known as Websocket handlers -that gives complete control over a Websocket connection.

-

The Websocket protocol is defined by RFC 6455.

-
-
-
+

Websocket is a protocol built on top of HTTP/1.1 that provides a two-ways communication channel between the client and the server. Communication is asynchronous and can occur concurrently.

+

It consists of a Javascript object allowing setting up a Websocket connection to the server, and a binary based protocol for sending data to the server or the client.

+

Websocket connections can transfer either UTF-8 encoded text data or binary data. The protocol also includes support for implementing a ping/pong mechanism, allowing the server and the client to have more confidence that the connection is still alive.

+

A Websocket connection can be used to transfer any kind of data, small or big, text or binary. Because of this Websocket is sometimes used for communication between systems.

+

Websocket messages have no semantics on their own. Websocket is closer to TCP in that aspect, and requires you to design and implement your own protocol on top of it; or adapt an existing protocol to Websocket.

+

Cowboy provides an interface known as Websocket handlers that gives complete control over a Websocket connection.

+

The Websocket protocol is defined by RFC 6455.

Long-lived requests

-
-

Cowboy provides an interface that can be used to support -long-polling or to stream large amounts of data reliably, -including using Server-Sent Events.

-

Long-polling is a mechanism in which the client performs -a request which may not be immediately answered by the -server. It allows clients to request resources that may -not currently exist, but are expected to be created soon, -and which will be returned as soon as they are.

-

Long-polling is essentially a hack, but it is widely used -to overcome limitations on older clients and servers.

-

Server-Sent Events is a small protocol defined as a media -type, text/event-stream, along with a new HTTP header, -Last-Event-ID. It is defined in the EventSource W3C -specification.

-

Cowboy provides an interface known as loop handlers -that facilitates the implementation of long-polling or stream -mechanisms. It works regardless of the underlying protocol.

-
-
-
+

Cowboy provides an interface that can be used to support long-polling or to stream large amounts of data reliably, including using Server-Sent Events.

+

Long-polling is a mechanism in which the client performs a request which may not be immediately answered by the server. It allows clients to request resources that may not currently exist, but are expected to be created soon, and which will be returned as soon as they are.

+

Long-polling is essentially a hack, but it is widely used to overcome limitations on older clients and servers.

+

Server-Sent Events is a small protocol defined as a media type, text/event-stream, along with a new HTTP header, Last-Event-ID. It is defined in the EventSource W3C specification.

+

Cowboy provides an interface known as loop handlers that facilitates the implementation of long-polling or stream mechanisms. It works regardless of the underlying protocol.

REST

-
-

REST, or REpresentational State Transfer, -is a style of architecture for loosely connected distributed -systems. It can easily be implemented on top of HTTP.

-

REST is essentially a set of constraints to be followed. -Many of these constraints are purely architectural and -solved by simply using HTTP. Some constraints must be -explicitly followed by the developer.

-

Cowboy provides an interface known as REST handlers -that simplifies the implementation of a REST API on top of -the HTTP protocol.

-
-
+

REST, or REpresentational State Transfer, is a style of architecture for loosely connected distributed systems. It can easily be implemented on top of HTTP.

+

REST is essentially a set of constraints to be followed. Many of these constraints are purely architectural and solved by simply using HTTP. Some constraints must be explicitly followed by the developer.

+

Cowboy provides an interface known as REST handlers that simplifies the implementation of a REST API on top of the HTTP protocol.

+ diff --git a/docs/en/cowboy/2.2/guide/multipart/index.html b/docs/en/cowboy/2.2/guide/multipart/index.html index f3097664..9e8494e2 100644 --- a/docs/en/cowboy/2.2/guide/multipart/index.html +++ b/docs/en/cowboy/2.2/guide/multipart/index.html @@ -62,169 +62,107 @@

Multipart requests

-

Multipart originates from MIME, an Internet standard that -extends the format of emails.

-

A multipart message is a list of parts. A part contains -headers and a body. The body of the parts may be -of any media type, and contain text or binary data. -It is possible for parts to contain a multipart media -type.

-

In the context of HTTP, multipart is most often used -with the multipart/form-data media type. It is what -browsers use to upload files through HTML forms.

-

The multipart/byteranges is also common. It is the -media type used to send arbitrary bytes from a resource, -enabling clients to resume downloads.

-
+

Multipart originates from MIME, an Internet standard that extends the format of emails.

+

A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type.

+

In the context of HTTP, multipart is most often used with the multipart/form-data media type. It is what browsers use to upload files through HTML forms.

+

The multipart/byteranges is also common. It is the media type used to send arbitrary bytes from a resource, enabling clients to resume downloads.

Form-data

-
-

In the normal case, when a form is submitted, the -browser will use the application/x-www-form-urlencoded -content-type. This type is just a list of keys and -values and is therefore not fit for uploading files.

-

That’s where the multipart/form-data content-type -comes in. When the form is configured to use this -content-type, the browser will create a multipart -message where each part corresponds to a field on -the form. For files, it also adds some metadata in -the part headers, like the file name.

-

A form with a text input, a file input and a select -choice box will result in a multipart message with -three parts, one for each field.

-

The browser does its best to determine the media type -of the files it sends this way, but you should not -rely on it for determining the contents of the file. -Proper investigation of the contents is recommended.

-
-
-
+

In the normal case, when a form is submitted, the browser will use the application/x-www-form-urlencoded content-type. This type is just a list of keys and values and is therefore not fit for uploading files.

+

That's where the multipart/form-data content-type comes in. When the form is configured to use this content-type, the browser will create a multipart message where each part corresponds to a field on the form. For files, it also adds some metadata in the part headers, like the file name.

+

A form with a text input, a file input and a select choice box will result in a multipart message with three parts, one for each field.

+

The browser does its best to determine the media type of the files it sends this way, but you should not rely on it for determining the contents of the file. Proper investigation of the contents is recommended.

Checking for multipart messages

-
-

The content-type header indicates the presence of -a multipart message:

-
-
-
{<<"multipart">>, <<"form-data">>, _}
-    = cowboy_req:parse_header(<<"content-type">>, Req).
-
-
-
+
{<<"multipart">>, <<"form-data">>, _}
+    = cowboy_req:parse_header(<<"content-type">>, Req).
+

Reading a multipart message

-
-

Cowboy provides two sets of functions for reading -request bodies as multipart messages.

-

The cowboy_req:read_part/1,2 functions return the -next part’s headers, if any.

-

The cowboy_req:read_part_body/1,2 functions return -the current part’s body. For large bodies you may -need to call the function multiple times.

-

To read a multipart message you need to iterate over -all its parts:

-
-
-
multipart(Req0) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, _Headers, Req1} ->
-            {ok, _Body, Req} = cowboy_req:read_part_body(Req1),
-            multipart(Req);
-        {done, Req} ->
-            Req
-    end.
-

When part bodies are too large, Cowboy will return -a more tuple, and allow you to loop until the part -body has been fully read.

-

The function cow_multipart:form_data/1 can be used -to quickly obtain information about a part from a -multipart/form-data message. The function returns -a data or a file tuple depending on whether this -is a normal field or a file being uploaded.

-

The following snippet will use this function and -use different strategies depending on whether the -part is a file:

-
-
-
multipart(Req0) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, Headers, Req1} ->
-            Req = case cow_multipart:form_data(Headers) of
-                {data, _FieldName} ->
-                    {ok, _Body, Req2} = cowboy_req:read_part_body(Req1),
-                    Req2;
-                {file, _FieldName, _Filename, _CType} ->
-                    stream_file(Req1)
-            end,
-            multipart(Req);
-        {done, Req} ->
-            Req
-    end.
-
-stream_file(Req0) ->
-    case cowboy_req:read_part_body(Req0) of
-        {ok, _LastBodyChunk, Req} ->
-            Req;
-        {more, _BodyChunk, Req} ->
-            stream_file(Req)
-    end.
-

Both the part header and body reading functions can take -options that will be given to the request body reading -functions. By default, cowboy_req:read_part/1 reads -up to 64KB for up to 5 seconds. cowboy_req:read_part_body/1 -has the same defaults as cowboy_req:read_body/1.

-

To change the defaults for part headers:

-
-
-
cowboy_req:read_part(Req, #{length => 128000}).
-

And for part bodies:

-
-
-
cowboy_req:read_part_body(Req, #{length => 1000000, period => 7000}).
-
- -
+
cowboy_req:read_part_body(Req, #{length => 1000000, period => 7000}).
+

Skipping unwanted parts

-
-

Part bodies do not have to be read. Cowboy will automatically -skip it when you request the next part’s body.

-

The following snippet reads all part headers and skips -all bodies:

-
-
-
multipart(Req0) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, _Headers, Req} ->
-            multipart(Req);
-        {done, Req} ->
-            Req
-    end.
-

Similarly, if you start reading the body and it ends up -being too big, you can simply continue with the next part. -Cowboy will automatically skip what remains.

-

While Cowboy can skip part bodies automatically, the read -rate is not configurable. Depending on your application -you may want to skip manually, in particular if you observe -poor performance while skipping.

-

You do not have to read all parts either. You can stop -reading as soon as you find the data you need.

-
- +
multipart(Req0) ->
+    case cowboy_req:read_part(Req0) of
+        {ok, _Headers, Req} ->
+            multipart(Req);
+        {done, Req} ->
+            Req
+    end.
+ +

Similarly, if you start reading the body and it ends up being too big, you can simply continue with the next part. Cowboy will automatically skip what remains.

+

While Cowboy can skip part bodies automatically, the read rate is not configurable. Depending on your application you may want to skip manually, in particular if you observe poor performance while skipping.

+

You do not have to read all parts either. You can stop reading as soon as you find the data you need.

+ + diff --git a/docs/en/cowboy/2.2/guide/req/index.html b/docs/en/cowboy/2.2/guide/req/index.html index d8025446..97e2a55d 100644 --- a/docs/en/cowboy/2.2/guide/req/index.html +++ b/docs/en/cowboy/2.2/guide/req/index.html @@ -62,407 +62,283 @@

The Req object

-

The Req object is a variable used for obtaining information -about a request, read its body or send a response.

-

It is not really an object in the object-oriented sense. -It is a simple map that can be directly accessed or -used when calling functions from the cowboy_req module.

-

The Req object is the subject of a few different chapters. -In this chapter we will learn about the Req object and -look at how to retrieve information about the request.

-
+

The Req object is a variable used for obtaining information about a request, read its body or send a response.

+

It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module.

+

The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request.

Direct access

-
-

The Req map contains a number of fields which are documented -and can be accessed directly. They are the fields that have -a direct mapping to HTTP: the request method; the HTTP -version used; the effective URI components scheme, -host, port, path and qs; the request headers; -and the connection peer address and port.

-

Note that the version field can be used to determine -whether a connection is using HTTP/2.

-

To access a field, you can simply match in the function -head. The following example sends a simple "Hello world!" -response when the method is GET, and a 405 error -otherwise.

-
-
-
init(Req0=#{method := <<"GET">>}, State) ->
-    Req = cowboy_req:reply(200, #{
-        <<"content-type">> => <<"text/plain">>
-    }, <<"Hello world!">>, Req0),
-    {ok, Req, State};
-init(Req0, State) ->
-    Req = cowboy_req:reply(405, #{
-        <<"allow">> => <<"GET">>
-    }, Req0),
-    {ok, Req, State}.
-

Any other field is internal and should not be accessed. -They may change in future releases, including maintenance -releases, without notice.

-

Modifying the Req object, while allowed, is not recommended -unless strictly necessary. If adding new fields, make sure -to namespace the field names so that no conflict can occur -with future Cowboy updates or third party projects.

-
-
-
+
init(Req0=#{method := <<"GET">>}, State) ->
+    Req = cowboy_req:reply(200, #{
+        <<"content-type">> => <<"text/plain">>
+    }, <<"Hello world!">>, Req0),
+    {ok, Req, State};
+init(Req0, State) ->
+    Req = cowboy_req:reply(405, #{
+        <<"allow">> => <<"GET">>
+    }, Req0),
+    {ok, Req, State}.
+
+

Any other field is internal and should not be accessed. They may change in future releases, including maintenance releases, without notice.

+

Modifying the Req object, while allowed, is not recommended unless strictly necessary. If adding new fields, make sure to namespace the field names so that no conflict can occur with future Cowboy updates or third party projects.

+

Introduction to the cowboy_req interface

-
-

Functions in the cowboy_req module provide access to -the request information but also various operations that -are common when dealing with HTTP requests.

-

All the functions that begin with a verb indicate an action. -Other functions simply return the corresponding value -(sometimes that value does need to be built, but the -cost of the operation is equivalent to retrieving a value).

-

Some of the cowboy_req functions return an updated Req -object. They are the read, reply, set and delete functions. -While ignoring the returned Req will not cause incorrect -behavior for some of them, it is highly recommended to -always keep and use the last returned Req object. The -manual for cowboy_req details these functions and what -modifications are done to the Req object.

-

Some of the calls to cowboy_req have side effects. This -is the case of the read and reply functions. Cowboy reads -the request body or replies immediately when the function -is called.

-

All functions will crash if something goes wrong. There -is usually no need to catch these errors, Cowboy will -send the appropriate 4xx or 5xx response depending on -where the crash occurred.

-
- -
+ +

Functions in the cowboy_req module provide access to the request information but also various operations that are common when dealing with HTTP requests.

+

All the functions that begin with a verb indicate an action. Other functions simply return the corresponding value (sometimes that value does need to be built, but the cost of the operation is equivalent to retrieving a value).

+

Some of the cowboy_req functions return an updated Req object. They are the read, reply, set and delete functions. While ignoring the returned Req will not cause incorrect behavior for some of them, it is highly recommended to always keep and use the last returned Req object. The manual for cowboy_req details these functions and what modifications are done to the Req object.

+

Some of the calls to cowboy_req have side effects. This is the case of the read and reply functions. Cowboy reads the request body or replies immediately when the function is called.

+

All functions will crash if something goes wrong. There is usually no need to catch these errors, Cowboy will send the appropriate 4xx or 5xx response depending on where the crash occurred.

Request method

-
-

The request method can be retrieved directly:

-
-
-
#{method := Method} = Req.
-

Or using a function:

-
-
-
Method = cowboy_req:method(Req).
-

The method is a case sensitive binary string. Standard -methods include GET, HEAD, OPTIONS, PATCH, POST, PUT -or DELETE.

-
-
-
+
Method = cowboy_req:method(Req).
+
+

The method is a case sensitive binary string. Standard methods include GET, HEAD, OPTIONS, PATCH, POST, PUT or DELETE.

HTTP version

-
-

The HTTP version is informational. It does not indicate that -the client implements the protocol well or fully.

-

There is typically no need to change behavior based on the -HTTP version: Cowboy already does it for you.

-

It can be useful in some cases, though. For example, one may -want to redirect HTTP/1.1 clients to use Websocket, while HTTP/2 -clients keep using HTTP/2.

-

The HTTP version can be retrieved directly:

-
-
-
#{version := Version} = Req.
-

Or using a function:

-
-
-
Version = cowboy_req:version(Req).
-

Cowboy defines the 'HTTP/1.0', 'HTTP/1.1' and 'HTTP/2' -versions. Custom protocols can define their own values as -atoms.

-
- -
+
Version = cowboy_req:version(Req).
+
+

Cowboy defines the 'HTTP/1.0', 'HTTP/1.1' and 'HTTP/2' versions. Custom protocols can define their own values as atoms.

Effective request URI

-
-

The scheme, host, port, path and query string components -of the effective request URI can all be retrieved directly:

-
-
#{
-    scheme := Scheme,
-    host := Host,
-    port := Port,
-    path := Path,
-    qs := Qs
-} = Req.
-

Or using the related functions:

-
-
-
Scheme = cowboy_req:scheme(Req),
-Host = cowboy_req:host(Req),
-Port = cowboy_req:port(Req),
-Path = cowboy_req:path(Req).
-Qs = cowboy_req:qs(Req).
-

The scheme and host are lowercased case insensitive binary -strings. The port is an integer representing the port number. -The path and query string are case sensitive binary strings.

-

Cowboy defines only the <<"http">> and <<"https">> schemes. -They are chosen so that the scheme will only be <<"https">> -for requests on secure HTTP/1.1 or HTTP/2 connections.

-

The effective request URI itself can be reconstructed with -the cowboy_req:uri/1,2 function. By default, an absolute -URI is returned:

-
-
+

The effective request URI itself can be reconstructed with the cowboy_req:uri/1,2 function. By default, an absolute URI is returned:

+
-
%% scheme://host[:port]/path[?qs]
-URI = cowboy_req:uri(Req).
-

Options are available to either disable or replace some -or all of the components. Various URIs or URI formats can -be generated this way, including the origin form:

-
-
-
%% /path[?qs]
-URI = cowboy_req:uri(Req, #{host => undefined}).
-

The protocol relative form:

-
-
-
%% //host[:port]/path[?qs]
-URI = cowboy_req:uri(Req, #{scheme => undefined}).
-

The absolute URI without a query string:

-
-
-
URI = cowboy_req:uri(Req, #{qs => undefined}).
-

A different host:

-
-
-
URI = cowboy_req:uri(Req, #{host => <<"example.org">>}).
-

And any other combination.

-
-
-
+
URI = cowboy_req:uri(Req, #{host => <<"example.org">>}).
+
+

And any other combination.

Bindings

-
-

Bindings are the host and path components that you chose -to extract when defining the routes of your application. -They are only available after the routing.

-

Cowboy provides functions to retrieve one or all bindings.

-

To retrieve a single value:

-
-
-
Value = cowboy_req:binding(userid, Req).
-

When attempting to retrieve a value that was not bound, -undefined will be returned. A different default value -can be provided:

-
-
-
Value = cowboy_req:binding(userid, Req, 42).
-

To retrieve everything that was bound:

-
-
-
Bindings = cowboy_req:bindings(Req).
-

They are returned as a map, with keys being atoms.

-

The Cowboy router also allows you to capture many host -or path segments at once using the ... qualifier.

-

To retrieve the segments captured from the host name:

-
-
-
HostInfo = cowboy_req:host_info(Req).
-

And the path segments:

-
-
-
PathInfo = cowboy_req:path_info(Req).
-

Cowboy will return undefined if ... was not used -in the route.

-
- -
+
PathInfo = cowboy_req:path_info(Req).
+
+

Cowboy will return undefined if ... was not used in the route.

Query parameters

-
-

Cowboy provides two functions to access query parameters. -You can use the first to get the entire list of parameters.

-
-
-
QsVals = cowboy_req:parse_qs(Req),
-{_, Lang} = lists:keyfind(<<"lang">>, 1, QsVals).
-

Cowboy will only parse the query string, and not do any -transformation. This function may therefore return duplicates, -or parameter names without an associated value. The order of -the list returned is undefined.

-

When a query string is key=1&key=2, the list returned will -contain two parameters of name key.

-

The same is true when trying to use the PHP-style suffix []. -When a query string is key[]=1&key[]=2, the list returned will -contain two parameters of name key[].

-

When a query string is simply key, Cowboy will return the -list [{<<"key">>, true}], using true to indicate that the -parameter key was defined, but with no value.

-

The second function Cowboy provides allows you to match out -only the parameters you are interested in, and at the same -time do any post processing you require using constraints. -This function returns a map.

-
-
-
#{id := ID, lang := Lang} = cowboy_req:match_qs([id, lang], Req).
-

Constraints can be applied automatically. The following -snippet will crash when the id parameter is not an integer, -or when the lang parameter is empty. At the same time, the -value for id will be converted to an integer term:

-
-
-
QsMap = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req).
-

A default value may also be provided. The default will be used -if the lang key is not found. It will not be used if -the key is found but has an empty value.

-
-
-
#{lang := Lang} = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
-

If no default is provided and the value is missing, the -query string is deemed invalid and the process will crash.

-

When the query string is key=1&key=2, the value for key -will be the list [1, 2]. Parameter names do not need to -include the PHP-style suffix. Constraints may be used to -ensure that only one value was passed through.

-
- -
+
#{lang := Lang} = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
+
+

If no default is provided and the value is missing, the query string is deemed invalid and the process will crash.

+

When the query string is key=1&key=2, the value for key will be the list [1, 2]. Parameter names do not need to include the PHP-style suffix. Constraints may be used to ensure that only one value was passed through.

Headers

-
-

Header values can be retrieved either as a binary string -or parsed into a more meaningful representation.

-

The get the raw value:

-
-
-
HeaderVal = cowboy_req:header(<<"content-type">>, Req).
-

Cowboy expects all header names to be provided as lowercase -binary strings. This is true for both requests and responses, -regardless of the underlying protocol.

-

When the header is missing from the request, undefined -will be returned. A different default can be provided:

-
-
-
HeaderVal = cowboy_req:header(<<"content-type">>, Req, <<"text/plain">>).
-

All headers can be retrieved at once, either directly:

-
-
-
#{headers := AllHeaders} = Req.
-

Or using a function:

-
-
-
AllHeaders = cowboy_req:headers(Req).
-

Cowboy provides equivalent functions to parse individual -headers. There is no function to parse all headers at once.

-

To parse a specific header:

-
-
-
ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req).
-

An exception will be thrown if it doesn’t know how to parse the -given header, or if the value is invalid. The list of known headers -and default values can be found in the manual.

-

When the header is missing, undefined is returned. You can -change the default value. Note that it should be the parsed value -directly:

-
-
-
ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req,
-    {<<"text">>, <<"plain">>, []}).
-
- -
+
ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req,
+    {<<"text">>, <<"plain">>, []}).
+

Peer

-
-

The peer address and port number for the connection can be -retrieved either directly or using a function.

-

To retrieve the peer directly:

-
-
-
#{peer := {IP, Port}} = Req.
-

And using a function:

-
-
-
{IP, Port} = cowboy_req:peer(Req).
-

Note that the peer corresponds to the remote end of the -connection to the server, which may or may not be the -client itself. It may also be a proxy or a gateway.

-
- +
{IP, Port} = cowboy_req:peer(Req).
+ +

Note that the peer corresponds to the remote end of the connection to the server, which may or may not be the client itself. It may also be a proxy or a gateway.

+ diff --git a/docs/en/cowboy/2.2/guide/req_body/index.html b/docs/en/cowboy/2.2/guide/req_body/index.html index 5289d5ea..f1725a55 100644 --- a/docs/en/cowboy/2.2/guide/req_body/index.html +++ b/docs/en/cowboy/2.2/guide/req_body/index.html @@ -62,144 +62,93 @@

Reading the request body

-

The request body can be read using the Req object.

-

Cowboy will not attempt to read the body until requested. -You need to call the body reading functions in order to -retrieve it.

-

Cowboy will not cache the body, it is therefore only -possible to read it once.

-

You are not required to read it, however. If a body is -present and was not read, Cowboy will either cancel or -skip its download, depending on the protocol.

-

Cowboy provides functions for reading the body raw, -and read and parse form urlencoded or multipart bodies. -The latter is covered in its own chapter.

-
+

The request body can be read using the Req object.

+

Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it.

+

Cowboy will not cache the body, it is therefore only possible to read it once.

+

You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol.

+

Cowboy provides functions for reading the body raw, and read and parse form urlencoded or multipart bodies. The latter is covered in its own chapter.

Request body presence

-
-

Not all requests come with a body. You can check for -the presence of a request body with this function:

-
-
-
cowboy_req:has_body(Req).
-

It returns true if there is a body; false otherwise.

-

In practice, this function is rarely used. When the -method is POST, PUT or PATCH, the request body -is often required by the application, which should -just attempt to read it directly.

-
-
-
+
cowboy_req:has_body(Req).
+
+

It returns true if there is a body; false otherwise.

+

In practice, this function is rarely used. When the method is POST, PUT or PATCH, the request body is often required by the application, which should just attempt to read it directly.

Request body length

-
-

You can obtain the length of the body:

-
-
-
Length = cowboy_req:body_length(Req).
-

Note that the length may not be known in advance. In -that case undefined will be returned. This can happen -with HTTP/1.1’s chunked transfer-encoding, or HTTP/2 -when no content-length was provided.

-

Cowboy will update the body length in the Req object -once the body has been read completely. A length will -always be returned when attempting to call this function -after reading the body completely.

-
- -
+
Length = cowboy_req:body_length(Req).
+
+

Note that the length may not be known in advance. In that case undefined will be returned. This can happen with HTTP/1.1's chunked transfer-encoding, or HTTP/2 when no content-length was provided.

+

Cowboy will update the body length in the Req object once the body has been read completely. A length will always be returned when attempting to call this function after reading the body completely.

Reading the body

-
-

You can read the entire body with one function call:

-
-
-
{ok, Data, Req} = cowboy_req:read_body(Req0).
-

Cowboy returns an ok tuple when the body has been -read fully.

-

By default, Cowboy will attempt to read up to 8MB -of data, for up to 15 seconds. The call will return -once Cowboy has read at least 8MB of data, or at -the end of the 15 seconds period.

-

These values can be customized. For example, to read -only up to 1MB for up to 5 seconds:

-
-
-
{ok, Data, Req} = cowboy_req:read_body(Req0,
-    #{length => 1000000, period => 5000}).
-

You may also disable the length limit:

-
-
-
{ok, Data, Req} = cowboy_req:read_body(Req0, #{length => infinity}).
-

This makes the function wait 15 seconds and return with -whatever arrived during that period. This is not -recommended for public facing applications.

-

These two options can effectively be used to control -the rate of transmission of the request body.

-
- -
+
{ok, Data, Req} = cowboy_req:read_body(Req0, #{length => infinity}).
+
+

This makes the function wait 15 seconds and return with whatever arrived during that period. This is not recommended for public facing applications.

+

These two options can effectively be used to control the rate of transmission of the request body.

Streaming the body

-
-

When the body is too large, the first call will return -a more tuple instead of ok. You can call the -function again to read more of the body, reading -it one chunk at a time.

-
-
-
read_body_to_console(Req0) ->
-    case cowboy_req:read_body(Req0) of
-        {ok, Data, Req} ->
-            io:format("~s", [Data]),
-            Req;
-        {more, Data, Req} ->
-            io:format("~s", [Data]),
-            read_body_to_console(Req)
-    end.
-

The length and period options can also be used. -They need to be passed for every call.

-
- -
+
read_body_to_console(Req0) ->
+    case cowboy_req:read_body(Req0) of
+        {ok, Data, Req} ->
+            io:format("~s", [Data]),
+            Req;
+        {more, Data, Req} ->
+            io:format("~s", [Data]),
+            read_body_to_console(Req)
+    end.
+
+

The length and period options can also be used. They need to be passed for every call.

Reading a form urlencoded body

-
-

Cowboy provides a convenient function for reading and -parsing bodies sent as application/x-www-form-urlencoded.

-
-
-
{ok, KeyValues, Req} = cowboy_req:read_urlencoded_body(Req0).
-

This function returns a list of key/values, exactly like -the function cowboy_req:parse_qs/1.

-

The defaults for this function are different. Cowboy will -read for up to 64KB and up to 5 seconds. They can be modified:

-
-
-
{ok, KeyValues, Req} = cowboy_req:read_urlencoded_body(Req0,
-    #{length => 4096, period => 3000}).
-
- +
{ok, KeyValues, Req} = cowboy_req:read_urlencoded_body(Req0,
+    #{length => 4096, period => 3000}).
+ + diff --git a/docs/en/cowboy/2.2/guide/resource_design/index.html b/docs/en/cowboy/2.2/guide/resource_design/index.html index 9914fd18..a2f559ed 100644 --- a/docs/en/cowboy/2.2/guide/resource_design/index.html +++ b/docs/en/cowboy/2.2/guide/resource_design/index.html @@ -62,213 +62,66 @@

Designing a resource handler

-

This chapter aims to provide you with a list of questions -you must answer in order to write a good resource handler. -It is meant to be usable as a step by step guide.

-
+

This chapter aims to provide you with a list of questions you must answer in order to write a good resource handler. It is meant to be usable as a step by step guide.

The service

-
-

Can the service become unavailable, and when it does, can -we detect it? For example, database connectivity problems -may be detected early. We may also have planned outages -of all or parts of the system. Implement the -service_available callback.

-

What HTTP methods does the service implement? Do we need -more than the standard OPTIONS, HEAD, GET, PUT, POST, -PATCH and DELETE? Are we not using one of those at all? -Implement the known_methods callback.

-
-
-
+

Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. Implement the service_available callback.

+

What HTTP methods does the service implement? Do we need more than the standard OPTIONS, HEAD, GET, PUT, POST, PATCH and DELETE? Are we not using one of those at all? Implement the known_methods callback.

Type of resource handler

-
-

Am I writing a handler for a collection of resources, -or for a single resource?

-

The semantics for each of these are quite different. -You should not mix collection and single resource in -the same handler.

-
-
-
+

Am I writing a handler for a collection of resources, or for a single resource?

+

The semantics for each of these are quite different. You should not mix collection and single resource in the same handler.

Collection handler

-
-

Skip this section if you are not doing a collection.

-

Is the collection hardcoded or dynamic? For example, -if you use the route /users for the collection of -users then the collection is hardcoded; if you use -/forums/:category for the collection of threads -then it isn’t. When the collection is hardcoded you -can safely assume the resource always exists.

-

What methods should I implement?

-

OPTIONS is used to get some information about the -collection. It is recommended to allow it even if you -do not implement it, as Cowboy has a default -implementation built-in.

-

HEAD and GET are used to retrieve the collection. -If you allow GET, also allow HEAD as there’s no extra -work required to make it work.

-

POST is used to create a new resource inside the -collection. Creating a resource by using POST on -the collection is useful when resources may be -created before knowing their URI, usually because -parts of it are generated dynamically. A common -case is some kind of auto incremented integer -identifier.

-

The next methods are more rarely allowed.

-

PUT is used to create a new collection (when -the collection isn’t hardcoded), or replace -the entire collection.

-

DELETE is used to delete the entire collection.

-

PATCH is used to modify the collection using -instructions given in the request body. A PATCH -operation is atomic. The PATCH operation may -be used for such things as reordering; adding, -modifying or deleting parts of the collection.

-
-
-
+

Skip this section if you are not doing a collection.

+

Is the collection hardcoded or dynamic? For example, if you use the route /users for the collection of users then the collection is hardcoded; if you use /forums/:category for the collection of threads then it isn't. When the collection is hardcoded you can safely assume the resource always exists.

+

What methods should I implement?

+

OPTIONS is used to get some information about the collection. It is recommended to allow it even if you do not implement it, as Cowboy has a default implementation built-in.

+

HEAD and GET are used to retrieve the collection. If you allow GET, also allow HEAD as there's no extra work required to make it work.

+

POST is used to create a new resource inside the collection. Creating a resource by using POST on the collection is useful when resources may be created before knowing their URI, usually because parts of it are generated dynamically. A common case is some kind of auto incremented integer identifier.

+

The next methods are more rarely allowed.

+

PUT is used to create a new collection (when the collection isn't hardcoded), or replace the entire collection.

+

DELETE is used to delete the entire collection.

+

PATCH is used to modify the collection using instructions given in the request body. A PATCH operation is atomic. The PATCH operation may be used for such things as reordering; adding, modifying or deleting parts of the collection.

Single resource handler

-
-

Skip this section if you are doing a collection.

-

What methods should I implement?

-

OPTIONS is used to get some information about the -resource. It is recommended to allow it even if you -do not implement it, as Cowboy has a default -implementation built-in.

-

HEAD and GET are used to retrieve the resource. -If you allow GET, also allow HEAD as there’s no extra -work required to make it work.

-

POST is used to update the resource.

-

PUT is used to create a new resource (when it doesn’t -already exist) or replace the resource.

-

DELETE is used to delete the resource.

-

PATCH is used to modify the resource using -instructions given in the request body. A PATCH -operation is atomic. The PATCH operation may -be used for adding, removing or modifying specific -values in the resource.

-
-
-
+

Skip this section if you are doing a collection.

+

What methods should I implement?

+

OPTIONS is used to get some information about the resource. It is recommended to allow it even if you do not implement it, as Cowboy has a default implementation built-in.

+

HEAD and GET are used to retrieve the resource. If you allow GET, also allow HEAD as there's no extra work required to make it work.

+

POST is used to update the resource.

+

PUT is used to create a new resource (when it doesn't already exist) or replace the resource.

+

DELETE is used to delete the resource.

+

PATCH is used to modify the resource using instructions given in the request body. A PATCH operation is atomic. The PATCH operation may be used for adding, removing or modifying specific values in the resource.

The resource

-
-

Following the above discussion, implement the -allowed_methods callback.

-

Does the resource always exist? If it may not, implement -the resource_exists callback.

-

Do I need to authenticate the client before they can -access the resource? What authentication mechanisms -should I provide? This may include form-based, token-based -(in the URL or a cookie), HTTP basic, HTTP digest, -SSL certificate or any other form of authentication. -Implement the is_authorized callback.

-

Do I need fine-grained access control? How do I determine -that they are authorized access? Handle that in your -is_authorized callback.

-

Can access to a resource be forbidden regardless of access -being authorized? A simple example of that is censorship -of a resource. Implement the forbidden callback.

-

Are there any constraints on the length of the resource URI? -For example, the URI may be used as a key in storage and may -have a limit in length. Implement uri_too_long.

-
-
-
+

Following the above discussion, implement the allowed_methods callback.

+

Does the resource always exist? If it may not, implement the resource_exists callback.

+

Do I need to authenticate the client before they can access the resource? What authentication mechanisms should I provide? This may include form-based, token-based (in the URL or a cookie), HTTP basic, HTTP digest, SSL certificate or any other form of authentication. Implement the is_authorized callback.

+

Do I need fine-grained access control? How do I determine that they are authorized access? Handle that in your is_authorized callback.

+

Can access to a resource be forbidden regardless of access being authorized? A simple example of that is censorship of a resource. Implement the forbidden callback.

+

Are there any constraints on the length of the resource URI? For example, the URI may be used as a key in storage and may have a limit in length. Implement uri_too_long.

Representations

-
-

What media types do I provide? If text based, what charsets -are provided? What languages do I provide?

-

Implement the mandatory content_types_provided. Prefix -the callbacks with to_ for clarity. For example, to_html -or to_text.

-

Implement the languages_provided or charsets_provided -callbacks if applicable.

-

Is there any other header that may make the representation -of the resource vary? Implement the variances callback.

-

Depending on your choices for caching content, you may -want to implement one or more of the generate_etag, -last_modified and expires callbacks.

-

Do I want the user or user agent to actively choose a -representation available? Send a list of available -representations in the response body and implement -the multiple_choices callback.

-
-
-
+

What media types do I provide? If text based, what charsets are provided? What languages do I provide?

+

Implement the mandatory content_types_provided. Prefix the callbacks with to_ for clarity. For example, to_html or to_text.

+

Implement the languages_provided or charsets_provided callbacks if applicable.

+

Is there any other header that may make the representation of the resource vary? Implement the variances callback.

+

Depending on your choices for caching content, you may want to implement one or more of the generate_etag, last_modified and expires callbacks.

+

Do I want the user or user agent to actively choose a representation available? Send a list of available representations in the response body and implement the multiple_choices callback.

Redirections

-
-

Do I need to keep track of what resources were deleted? -For example, you may have a mechanism where moving a -resource leaves a redirect link to its new location. -Implement the previously_existed callback.

-

Was the resource moved, and is the move temporary? If -it is explicitly temporary, for example due to maintenance, -implement the moved_temporarily callback. Otherwise, -implement the moved_permanently callback.

-
-
-
+

Do I need to keep track of what resources were deleted? For example, you may have a mechanism where moving a resource leaves a redirect link to its new location. Implement the previously_existed callback.

+

Was the resource moved, and is the move temporary? If it is explicitly temporary, for example due to maintenance, implement the moved_temporarily callback. Otherwise, implement the moved_permanently callback.

The request

-
-

Do you need to read the query string? Individual headers? -Implement malformed_request and do all the parsing and -validation in this function. Note that the body should not -be read at this point.

-

May there be a request body? Will I know its size? -What’s the maximum size of the request body I’m willing -to accept? Implement valid_entity_length.

-

Finally, take a look at the sections corresponding to the -methods you are implementing.

-
-
-
+

Do you need to read the query string? Individual headers? Implement malformed_request and do all the parsing and validation in this function. Note that the body should not be read at this point.

+

May there be a request body? Will I know its size? What's the maximum size of the request body I'm willing to accept? Implement valid_entity_length.

+

Finally, take a look at the sections corresponding to the methods you are implementing.

OPTIONS method

-
-

Cowboy by default will send back a list of allowed methods. -Do I need to add more information to the response? Implement -the options method.

-
-
-
+

Cowboy by default will send back a list of allowed methods. Do I need to add more information to the response? Implement the options method.

GET and HEAD methods

-
-

If you implement the methods GET and/or HEAD, you must -implement one ProvideResource callback for each -content-type returned by the content_types_provided -callback.

-
-
-
-

PUT, POST and PATCH methods

-
-

If you implement the methods PUT, POST and/or PATCH, -you must implement the content_types_accepted callback, -and one AcceptCallback callback for each content-type -it returns. Prefix the AcceptCallback callback names -with from_ for clarity. For example, from_html or -from_json.

-

Do we want to allow the POST method to create individual -resources directly through their URI (like PUT)? Implement -the allow_missing_post callback. It is recommended to -explicitly use PUT in these cases instead.

-

May there be conflicts when using PUT to create or replace -a resource? Do we want to make sure that two updates around -the same time are not cancelling one another? Implement the -is_conflict callback.

-
-
-
+

If you implement the methods GET and/or HEAD, you must implement one ProvideResource callback for each content-type returned by the content_types_provided callback.

+

PUT, POST and PATCH methods

+

If you implement the methods PUT, POST and/or PATCH, you must implement the content_types_accepted callback, and one AcceptCallback callback for each content-type it returns. Prefix the AcceptCallback callback names with from_ for clarity. For example, from_html or from_json.

+

Do we want to allow the POST method to create individual resources directly through their URI (like PUT)? Implement the allow_missing_post callback. It is recommended to explicitly use PUT in these cases instead.

+

May there be conflicts when using PUT to create or replace a resource? Do we want to make sure that two updates around the same time are not cancelling one another? Implement the is_conflict callback.

DELETE methods

-
-

If you implement the method DELETE, you must implement -the delete_resource callback.

-

When delete_resource returns, is the resource completely -removed from the server, including from any caching service? -If not, and/or if the deletion is asynchronous and we have -no way of knowing it has been completed yet, implement the -delete_completed callback.

-
-
+

If you implement the method DELETE, you must implement the delete_resource callback.

+

When delete_resource returns, is the resource completely removed from the server, including from any caching service? If not, and/or if the deletion is asynchronous and we have no way of knowing it has been completed yet, implement the delete_completed callback.

+ diff --git a/docs/en/cowboy/2.2/guide/resp/index.html b/docs/en/cowboy/2.2/guide/resp/index.html index 0f728866..6fbbd78a 100644 --- a/docs/en/cowboy/2.2/guide/resp/index.html +++ b/docs/en/cowboy/2.2/guide/resp/index.html @@ -62,374 +62,250 @@

Sending a response

-

The response must be sent using the Req object.

-

Cowboy provides two different ways of sending responses: -either directly or by streaming the body. Response headers -and body may be set in advance. The response is sent as -soon as one of the reply or stream reply function is -called.

-

Cowboy also provides a simplified interface for sending -files. It can also send only specific parts of a file.

-

While only one response is allowed for every request, -HTTP/2 introduced a mechanism that allows the server -to push additional resources related to the response. -This chapter also describes how this feature works in -Cowboy.

-
+

The response must be sent using the Req object.

+

Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called.

+

Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file.

+

While only one response is allowed for every request, HTTP/2 introduced a mechanism that allows the server to push additional resources related to the response. This chapter also describes how this feature works in Cowboy.

Reply

-
-

Cowboy provides three functions for sending the entire reply, -depending on whether you need to set headers and body. In all -cases, Cowboy will add any headers required by the protocol -(for example the date header will always be sent).

-

When you need to set only the status code, -use cowboy_req:reply/2:

-
-
-
Req = cowboy_req:reply(200, Req0).
-

When you need to set response headers at the same time, -use cowboy_req:reply/3:

-
-
-
Req = cowboy_req:reply(303, #{
-    <<"location">> => <<"https://ninenines.eu">>
-}, Req0).
-

Note that the header name must always be a lowercase -binary.

-

When you also need to set the response body, -use cowboy_req:reply/4:

-
-
-
Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, "Hello world!", Req0).
-

You should always set the content-type header when the -response has a body. There is however no need to set -the content-length header; Cowboy does it automatically.

-

The response body and the header values must be either -a binary or an iolist. An iolist is a list containing -binaries, characters, strings or other iolists. This -allows you to build a response from different parts -without having to do any concatenation:

-
-
-
Title = "Hello world!",
-Body = <<"Hats off!">>,
-Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/html">>
-}, ["<html><head><title>", Title, "</title></head>",
-    "<body><p>", Body, "</p></body></html>"], Req0).
-

This method of building responses is more efficient than -concatenating. Behind the scenes, each element of the list -is simply a pointer, and those pointers are used directly -when writing to the socket.

-
-
-
+
Title = "Hello world!",
+Body = <<"Hats off!">>,
+Req = cowboy_req:reply(200, #{
+    <<"content-type">> => <<"text/html">>
+}, ["<html><head><title>", Title, "</title></head>",
+    "<body><p>", Body, "</p></body></html>"], Req0).
+
+

This method of building responses is more efficient than concatenating. Behind the scenes, each element of the list is simply a pointer, and those pointers are used directly when writing to the socket.

Stream reply

-
-

Cowboy provides two functions for initiating a response, -and an additional function for streaming the response body. -Cowboy will add any required headers to the response.

-

When you need to set only the status code, -use cowboy_req:stream_reply/2:

-
-
+

When you need to set only the status code, use cowboy_req:stream_reply/2:

+
-
Req = cowboy_req:stream_reply(200, Req0),
-
-cowboy_req:stream_body("Hello...", nofin, Req),
-cowboy_req:stream_body("chunked...", nofin, Req),
-cowboy_req:stream_body("world!!", fin, Req).
-

The second argument to cowboy_req:stream_body/3 indicates -whether this data terminates the body. Use fin for the -final flag, and nofin otherwise.

-

This snippet does not set a content-type header. This is -not recommended. All responses with a body should have -a content-type. The header can be set beforehand, or -using the cowboy_req:stream_reply/3:

-
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/html">>
-}, Req0),
-
-cowboy_req:stream_body("<html><head>Hello world!</head>", nofin, Req),
-cowboy_req:stream_body("<body><p>Hats off!</p></body></html>", fin, Req).
-

HTTP provides a few different ways to stream response bodies. -Cowboy will select the most appropriate one based on the HTTP -version and the request and response headers.

-

While not required by any means, it is recommended that you -set the content-length header in the response if you know it -in advance. This will ensure that the best response method -is selected and help clients understand when the response -is fully received.

-

Cowboy also provides a function to send response trailers. -Response trailers are semantically equivalent to the headers -you send in the response, only they are sent at the end. -This is especially useful to attach information to the -response that could not be generated until the response -body was fully generated.

-

Trailer fields must be listed in the trailer header. Any -field not listed might be dropped by the client or an intermediary.

-
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/html">>,
-    <<"trailer">> => <<"expires, content-md5">>
-}, Req0),
-
-cowboy_req:stream_body("<html><head>Hello world!</head>", nofin, Req),
-cowboy_req:stream_body("<body><p>Hats off!</p></body></html>", nofin, Req),
-
-cowboy_req:stream_trailers(#{
-    <<"expires">> => <<"Sun, 10 Dec 2017 19:13:47 GMT">>,
-    <<"content-md5">> => <<"c6081d20ff41a42ce17048ed1c0345e2">>
-}, Req).
-

The stream ends with trailers. It is no longer possible to -send data after sending trailers. You cannot send trailers -after setting the fin flag when streaming the body.

-
-
-
+
Req = cowboy_req:stream_reply(200, #{
+    <<"content-type">> => <<"text/html">>,
+    <<"trailer">> => <<"expires, content-md5">>
+}, Req0),
+
+cowboy_req:stream_body("<html><head>Hello world!</head>", nofin, Req),
+cowboy_req:stream_body("<body><p>Hats off!</p></body></html>", nofin, Req),
+
+cowboy_req:stream_trailers(#{
+    <<"expires">> => <<"Sun, 10 Dec 2017 19:13:47 GMT">>,
+    <<"content-md5">> => <<"c6081d20ff41a42ce17048ed1c0345e2">>
+}, Req).
+
+

The stream ends with trailers. It is no longer possible to send data after sending trailers. You cannot send trailers after setting the fin flag when streaming the body.

Preset response headers

-
-

Cowboy provides functions to set response headers without -immediately sending them. They are stored in the Req object -and sent as part of the response when a reply function is -called.

-

To set response headers:

-
-
-
Req = cowboy_req:set_resp_header(<<"allow">>, "GET", Req0).
-

Header names must be a lowercase binary.

-

Do not use this function for setting cookies. Refer to -the Cookies chapter for more information.

-

To check if a response header has already been set:

-
-
-
cowboy_req:has_resp_header(<<"allow">>, Req).
-

It returns true if the header was set, false otherwise.

-

To delete a response header that was set previously:

-
-
-
Req = cowboy_req:delete_resp_header(<<"allow">>, Req0).
-
- -
+
Req = cowboy_req:delete_resp_header(<<"allow">>, Req0).
+

Overriding headers

-
-

As Cowboy provides different ways of setting response -headers and body, clashes may occur, so it’s important -to understand what happens when a header is set twice.

-

Headers come from five different origins:

-
    -
  • -

    -Protocol-specific headers (for example HTTP/1.1’s connection header) -

    +

    As Cowboy provides different ways of setting response headers and body, clashes may occur, so it's important to understand what happens when a header is set twice.

    +

    Headers come from five different origins:

    +
    • Protocol-specific headers (for example HTTP/1.1's connection header)
    • -
    • -

      -Other required headers (for example the date header) -

      +
    • Other required headers (for example the date header)
    • -
    • -

      -Preset headers -

      +
    • Preset headers
    • -
    • -

      -Headers given to the reply function -

      +
    • Headers given to the reply function
    • -
    • -

      -Set-cookie headers -

      +
    • Set-cookie headers
    • -
-

Cowboy does not allow overriding protocol-specific headers.

-

Set-cookie headers will always be appended at the end of -the list of headers before sending the response.

-

Headers given to the reply function will always override -preset headers and required headers. If a header is found -in two or three of these, then the one in the reply function -is picked and the others are dropped.

-

Similarly, preset headers will always override required -headers.

-

To illustrate, look at the following snippet. Cowboy by -default sends the server header with the value "Cowboy". -We can override it:

-
-
-
Req = cowboy_req:reply(200, #{
-    <<"server">> => <<"yaws">>
-}, Req0).
-
- -
+
Req = cowboy_req:reply(200, #{
+    <<"server">> => <<"yaws">>
+}, Req0).
+

Preset response body

-
-

Cowboy provides functions to set the response body without -immediately sending it. It is stored in the Req object and -sent when the reply function is called.

-

To set the response body:

-
-
-
Req = cowboy_req:set_resp_body("Hello world!", Req0).
-

To check if a response body has already been set:

-
-
+ +

To check if a response body has already been set:

+
-
cowboy_req:has_resp_body(Req).
-

It returns true if the body was set and is non-empty, -false otherwise.

-

The preset response body is only sent if the reply function -used is cowboy_req:reply/2 or cowboy_req:reply/3.

-
-
-
+
cowboy_req:has_resp_body(Req).
+
+

It returns true if the body was set and is non-empty, false otherwise.

+ + + +

The preset response body is only sent if the reply function used is cowboy_req:reply/2 or cowboy_req:reply/3.

Sending files

-
-

Cowboy provides a shortcut for sending files. When -using cowboy_req:reply/4, or when presetting the -response header, you can give a sendfile tuple to -Cowboy:

-
-
-
{sendfile, Offset, Length, Filename}
-

Depending on the values for Offset or Length, the -entire file may be sent, or just a part of it.

-

The length is required even for sending the entire file. -Cowboy sends it in the content-length header.

-

To send a file while replying:

-
-
-
Req = cowboy_req:reply(200, #{
-    <<"content-type">> => "image/png"
-}, {sendfile, 0, 12345, "path/to/logo.png"}, Req0).
-
- -
+
Req = cowboy_req:reply(200, #{
+    <<"content-type">> => "image/png"
+}, {sendfile, 0, 12345, "path/to/logo.png"}, Req0).
+
+ + + + + + + + +

Informational responses

-
-

Cowboy allows you to send informational responses.

-

Informational responses are responses that have a status -code between 100 and 199. Any number can be sent before -the proper response. Sending an informational response -does not change the behavior of the proper response, and -clients are expected to ignore any informational response -they do not understand.

-

The following snippet sends a 103 informational response -with some headers that are expected to be in the final -response.

-
-
-
Req = cowboy_req:inform(103, #{
-    <<"link">> => <<"</style.css>; rel=preload; as=style">>,
-    <<"link">> => <<"</script.js>; rel=preload; as=script">>
-}, Req0).
-
- -
+
Req = cowboy_req:inform(103, #{
+    <<"link">> => <<"</style.css>; rel=preload; as=style">>,
+    <<"link">> => <<"</script.js>; rel=preload; as=script">>
+}, Req0).
+

Push

-
-

The HTTP/2 protocol introduced the ability to push resources -related to the one sent in the response. Cowboy provides two -functions for that purpose: cowboy_req:push/3,4.

-

Push is only available for HTTP/2. Cowboy will automatically -ignore push requests if the protocol doesn’t support it.

-

The push function must be called before any of the reply -functions. Doing otherwise will result in a crash.

-

To push a resource, you need to provide the same information -as a client performing a request would. This includes the -HTTP method, the URI and any necessary request headers.

-

Cowboy by default only requires you to give the path to -the resource and the request headers. The rest of the URI -is taken from the current request (excluding the query -string, set to empty) and the method is GET by default.

-

The following snippet pushes a CSS file that is linked to -in the response:

-
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, Req0),
-Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/html">>
-}, ["<html><head><title>My web page</title>",
-    "<link rel='stylesheet' type='text/css' href='/static/style.css'>",
-    "<body><p>Welcome to Erlang!</p></body></html>"], Req0).
-

To override the method, scheme, host, port or query string, -simply pass in a fourth argument. The following snippet -uses a different host name:

-
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, #{host => <<"cdn.example.org">>}, Req),
-

Pushed resources don’t have to be files. As long as the push -request is cacheable, safe and does not include a body, the -resource can be pushed.

-

Under the hood, Cowboy handles pushed requests the same as -normal requests: a different process is created which will -ultimately send a response to the client.

-
- +
cowboy_req:push("/static/style.css", #{
+    <<"accept">> => <<"text/css">>
+}, #{host => <<"cdn.example.org">>}, Req),
+ +

Pushed resources don't have to be files. As long as the push request is cacheable, safe and does not include a body, the resource can be pushed.

+

Under the hood, Cowboy handles pushed requests the same as normal requests: a different process is created which will ultimately send a response to the client.

+ diff --git a/docs/en/cowboy/2.2/guide/rest_flowcharts/index.html b/docs/en/cowboy/2.2/guide/rest_flowcharts/index.html index 58e0269d..8d526fe4 100644 --- a/docs/en/cowboy/2.2/guide/rest_flowcharts/index.html +++ b/docs/en/cowboy/2.2/guide/rest_flowcharts/index.html @@ -62,244 +62,64 @@

REST flowcharts

-

This chapter will explain the REST handler state machine through -a number of different diagrams.

-

There are four main paths that requests may follow. One for the -method OPTIONS; one for the methods GET and HEAD; one for the -methods PUT, POST and PATCH; and one for the method DELETE.

-

All paths start with the "Start" diagram, and all paths excluding -the OPTIONS path go through the "Content negotiation" diagram -and optionally the "Conditional requests" diagram if the resource -exists.

-

The red squares refer to another diagram. The light green squares -indicate a response. Other squares may be either a callback or a -question answered by Cowboy itself. Green arrows tend to indicate -the default behavior if the callback is undefined.

-
+

This chapter will explain the REST handler state machine through a number of different diagrams.

+

There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE.

+

All paths start with the "Start" diagram, and all paths excluding the OPTIONS path go through the "Content negotiation" diagram and optionally the "Conditional requests" diagram if the resource exists.

+

The red squares refer to another diagram. The light green squares indicate a response. Other squares may be either a callback or a question answered by Cowboy itself. Green arrows tend to indicate the default behavior if the callback is undefined.

Start

-
-

All requests start from here.

-
-
-REST starting flowchart -
-
-

A series of callbacks are called in succession to perform -a general checkup of the service, the request line and -request headers.

-

The request body, if any, is not expected to have been -received for any of these steps. It is only processed -at the end of the "PUT, POST and PATCH methods" diagram, -when all conditions have been met.

-

The known_methods and allowed_methods callbacks -return a list of methods. Cowboy then checks if the request -method is in the list, and stops otherwise.

-

The is_authorized callback may be used to check that -access to the resource is authorized. Authentication -may also be performed as needed. When authorization is -denied, the return value from the callback must include -a challenge applicable to the requested resource, which -will be sent back to the client in the www-authenticate -header.

-

This diagram is immediately followed by either the -"OPTIONS method" diagram when the request method is -OPTIONS, or the "Content negotiation" diagram otherwise.

-
-
-
+

All requests start from here.

+REST starting flowchart

A series of callbacks are called in succession to perform a general checkup of the service, the request line and request headers.

+

The request body, if any, is not expected to have been received for any of these steps. It is only processed at the end of the "PUT, POST and PATCH methods" diagram, when all conditions have been met.

+

The known_methods and allowed_methods callbacks return a list of methods. Cowboy then checks if the request method is in the list, and stops otherwise.

+

The is_authorized callback may be used to check that access to the resource is authorized. Authentication may also be performed as needed. When authorization is denied, the return value from the callback must include a challenge applicable to the requested resource, which will be sent back to the client in the www-authenticate header.

+

This diagram is immediately followed by either the "OPTIONS method" diagram when the request method is OPTIONS, or the "Content negotiation" diagram otherwise.

OPTIONS method

-
-

This diagram only applies to OPTIONS requests.

-
-
-REST OPTIONS method flowchart -
-
-

The options callback may be used to add information -about the resource, such as media types or languages -provided; allowed methods; any extra information. A -response body may also be set, although clients should -not be expected to read it.

-

If the options callback is not defined, Cowboy will -send a response containing the list of allowed methods -by default.

-
-
-
+

This diagram only applies to OPTIONS requests.

+REST OPTIONS method flowchart

The options callback may be used to add information about the resource, such as media types or languages provided; allowed methods; any extra information. A response body may also be set, although clients should not be expected to read it.

+

If the options callback is not defined, Cowboy will send a response containing the list of allowed methods by default.

Content negotiation

-
-

This diagram applies to all request methods other than -OPTIONS. It is executed right after the "Start" diagram -is completed.

-
-
-REST content negotiation flowchart -
-
-

The purpose of these steps is to determine an appropriate -representation to be sent back to the client.

-

The request may contain any of the accept header; the -accept-language header; or the accept-charset header. -When present, Cowboy will parse the headers and then -call the corresponding callback to obtain the list -of provided content-type, language or charset for this -resource. It then automatically select the best match -based on the request.

-

If a callback is not defined, Cowboy will select the -content-type, language or charset that the client -prefers.

-

The content_types_provided also returns the name of -a callback for every content-type it accepts. This -callback will only be called at the end of the -"GET and HEAD methods" diagram, when all conditions -have been met.

-

The selected content-type, language and charset are -saved as meta values in the Req object. You should -use the appropriate representation if you set a -response body manually (alongside an error code, -for example).

-

This diagram is immediately followed by -the "GET and HEAD methods" diagram, -the "PUT, POST and PATCH methods" diagram, -or the "DELETE method" diagram, depending on the -method.

-
-
-
+

This diagram applies to all request methods other than OPTIONS. It is executed right after the "Start" diagram is completed.

+REST content negotiation flowchart

The purpose of these steps is to determine an appropriate representation to be sent back to the client.

+

The request may contain any of the accept header; the accept-language header; or the accept-charset header. When present, Cowboy will parse the headers and then call the corresponding callback to obtain the list of provided content-type, language or charset for this resource. It then automatically select the best match based on the request.

+

If a callback is not defined, Cowboy will select the content-type, language or charset that the client prefers.

+

The content_types_provided also returns the name of a callback for every content-type it accepts. This callback will only be called at the end of the "GET and HEAD methods" diagram, when all conditions have been met.

+

The selected content-type, language and charset are saved as meta values in the Req object. You should use the appropriate representation if you set a response body manually (alongside an error code, for example).

+

This diagram is immediately followed by the "GET and HEAD methods" diagram, the "PUT, POST and PATCH methods" diagram, or the "DELETE method" diagram, depending on the method.

GET and HEAD methods

-
-

This diagram only applies to GET and HEAD requests.

-

For a description of the cond step, please see -the "Conditional requests" diagram.

-
-
-REST GET/HEAD methods flowchart -
-
-

When the resource exists, and the conditional steps -succeed, the resource can be retrieved.

-

Cowboy prepares the response by first retrieving -metadata about the representation, then by calling -the ProvideResource callback. This is the callback -you defined for each content-types you returned from -content_types_provided. This callback returns the body -that will be sent back to the client, or a fun if the -body must be streamed.

-

When the resource does not exist, Cowboy will figure out -whether the resource existed previously, and if so whether -it was moved elsewhere in order to redirect the client to -the new URI.

-

The moved_permanently and moved_temporarily callbacks -must return the new location of the resource if it was in -fact moved.

-
-
-
-

PUT, POST and PATCH methods

-
-

This diagram only applies to PUT, POST and PATCH requests.

-

For a description of the cond step, please see -the "Conditional requests" diagram.

-
-
-REST PUT/POST/PATCH methods flowchart -
-
-

When the resource exists, first the conditional steps -are executed. When that succeeds, and the method is PUT, -Cowboy will call the is_conflict callback. This function -can be used to prevent potential race conditions, by locking -the resource for example.

-

Then all three methods reach the content_types_accepted -step that we will describe in a few paragraphs.

-

When the resource does not exist, and the method is PUT, -Cowboy will check for conflicts and then move on to the -content_types_accepted step. For other methods, Cowboy -will figure out whether the resource existed previously, -and if so whether it was moved elsewhere. If the resource -is truly non-existent, the method is POST and the call -for allow_missing_post returns true, then Cowboy will -move on to the content_types_accepted step. Otherwise -the request processing ends there.

-

The moved_permanently and moved_temporarily callbacks -must return the new location of the resource if it was in -fact moved.

-

The content_types_accepted returns a list of -content-types it accepts, but also the name of a callback -for each of them. Cowboy will select the appropriate -callback for processing the request body and call it.

-

This callback may return one of three different return -values.

-

If an error occurred while processing the request body, -it must return false and Cowboy will send an -appropriate error response.

-

If the method is POST, then you may return true with -an URI of where the resource has been created. This is -especially useful for writing handlers for collections.

-

Otherwise, return true to indicate success. Cowboy -will select the appropriate response to be sent depending -on whether a resource has been created, rather than -modified, and on the availability of a location header -or a body in the response.

-
-
-
+

This diagram only applies to GET and HEAD requests.

+

For a description of the cond step, please see the "Conditional requests" diagram.

+REST GET/HEAD methods flowchart

When the resource exists, and the conditional steps succeed, the resource can be retrieved.

+

Cowboy prepares the response by first retrieving metadata about the representation, then by calling the ProvideResource callback. This is the callback you defined for each content-types you returned from content_types_provided. This callback returns the body that will be sent back to the client, or a fun if the body must be streamed.

+

When the resource does not exist, Cowboy will figure out whether the resource existed previously, and if so whether it was moved elsewhere in order to redirect the client to the new URI.

+

The moved_permanently and moved_temporarily callbacks must return the new location of the resource if it was in fact moved.

+

PUT, POST and PATCH methods

+

This diagram only applies to PUT, POST and PATCH requests.

+

For a description of the cond step, please see the "Conditional requests" diagram.

+REST PUT/POST/PATCH methods flowchart

When the resource exists, first the conditional steps are executed. When that succeeds, and the method is PUT, Cowboy will call the is_conflict callback. This function can be used to prevent potential race conditions, by locking the resource for example.

+

Then all three methods reach the content_types_accepted step that we will describe in a few paragraphs.

+

When the resource does not exist, and the method is PUT, Cowboy will check for conflicts and then move on to the content_types_accepted step. For other methods, Cowboy will figure out whether the resource existed previously, and if so whether it was moved elsewhere. If the resource is truly non-existent, the method is POST and the call for allow_missing_post returns true, then Cowboy will move on to the content_types_accepted step. Otherwise the request processing ends there.

+

The moved_permanently and moved_temporarily callbacks must return the new location of the resource if it was in fact moved.

+

The content_types_accepted returns a list of content-types it accepts, but also the name of a callback for each of them. Cowboy will select the appropriate callback for processing the request body and call it.

+

This callback may return one of three different return values.

+

If an error occurred while processing the request body, it must return false and Cowboy will send an appropriate error response.

+

If the method is POST, then you may return true with an URI of where the resource has been created. This is especially useful for writing handlers for collections.

+

Otherwise, return true to indicate success. Cowboy will select the appropriate response to be sent depending on whether a resource has been created, rather than modified, and on the availability of a location header or a body in the response.

DELETE method

-
-

This diagram only applies to DELETE requests.

-

For a description of the cond step, please see -the "Conditional requests" diagram.

-
-
-REST DELETE method flowchart -
-
-

When the resource exists, and the conditional steps -succeed, the resource can be deleted.

-

Deleting the resource is a two steps process. First -the callback delete_resource is executed. Use this -callback to delete the resource.

-

Because the resource may be cached, you must also -delete all cached representations of this resource -in the system. This operation may take a while though, -so you may return before it finished.

-

Cowboy will then call the delete_completed callback. -If you know that the resource has been completely -deleted from your system, including from caches, then -you can return true. If any doubts persist, return -false. Cowboy will assume true by default.

-

To finish, Cowboy checks if you set a response body, -and depending on that, sends the appropriate response.

-

When the resource does not exist, Cowboy will figure out -whether the resource existed previously, and if so whether -it was moved elsewhere in order to redirect the client to -the new URI.

-

The moved_permanently and moved_temporarily callbacks -must return the new location of the resource if it was in -fact moved.

-
-
-
+

This diagram only applies to DELETE requests.

+

For a description of the cond step, please see the "Conditional requests" diagram.

+REST DELETE method flowchart

When the resource exists, and the conditional steps succeed, the resource can be deleted.

+

Deleting the resource is a two steps process. First the callback delete_resource is executed. Use this callback to delete the resource.

+

Because the resource may be cached, you must also delete all cached representations of this resource in the system. This operation may take a while though, so you may return before it finished.

+

Cowboy will then call the delete_completed callback. If you know that the resource has been completely deleted from your system, including from caches, then you can return true. If any doubts persist, return false. Cowboy will assume true by default.

+

To finish, Cowboy checks if you set a response body, and depending on that, sends the appropriate response.

+

When the resource does not exist, Cowboy will figure out whether the resource existed previously, and if so whether it was moved elsewhere in order to redirect the client to the new URI.

+

The moved_permanently and moved_temporarily callbacks must return the new location of the resource if it was in fact moved.

Conditional requests

-
-

This diagram applies to all request methods other than -OPTIONS. It is executed right after the resource_exists -callback, when the resource exists.

-
-
-REST conditional requests flowchart -
-
-

A request becomes conditional when it includes either of -the if-match header; the if-unmodified-since header; the -if-none-match header; or the if-modified-since header.

-

If the condition fails, the request ends immediately -without any retrieval or modification of the resource.

-

The generate_etag and last_modified are called as -needed. Cowboy will only call them once and then cache -the results for subsequent use.

-
-
+

This diagram applies to all request methods other than OPTIONS. It is executed right after the resource_exists callback, when the resource exists.

+REST conditional requests flowchart

A request becomes conditional when it includes either of the if-match header; the if-unmodified-since header; the if-none-match header; or the if-modified-since header.

+

If the condition fails, the request ends immediately without any retrieval or modification of the resource.

+

The generate_etag and last_modified are called as needed. Cowboy will only call them once and then cache the results for subsequent use.

+ diff --git a/docs/en/cowboy/2.2/guide/rest_handlers/index.html b/docs/en/cowboy/2.2/guide/rest_handlers/index.html index b0f3881f..a629d473 100644 --- a/docs/en/cowboy/2.2/guide/rest_handlers/index.html +++ b/docs/en/cowboy/2.2/guide/rest_handlers/index.html @@ -62,287 +62,162 @@

REST handlers

-

REST is implemented in Cowboy as a sub protocol. The request -is handled as a state machine with many optional callbacks -describing the resource and modifying the machine’s behavior.

-

The REST handler is the recommended way to handle HTTP requests.

-
+

REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine's behavior.

+

The REST handler is the recommended way to handle HTTP requests.

Initialization

-
-

First, the init/2 callback is called. This callback is common -to all handlers. To use REST for the current request, this function -must return a cowboy_rest tuple.

-
-
-
init(Req, State) ->
-    {cowboy_rest, Req, State}.
-

Cowboy will then switch to the REST protocol and start executing -the state machine.

-

After reaching the end of the flowchart, the terminate/3 callback -will be called if it is defined.

-
-
-
+
init(Req, State) ->
+    {cowboy_rest, Req, State}.
+
+

Cowboy will then switch to the REST protocol and start executing the state machine.

+

After reaching the end of the flowchart, the terminate/3 callback will be called if it is defined.

Methods

-
-

The REST component has code for handling the following HTTP methods: -HEAD, GET, POST, PATCH, PUT, DELETE and OPTIONS.

-

Other methods can be accepted, however they have no specific callback -defined for them at this time.

-
- -
+

The REST component has code for handling the following HTTP methods: HEAD, GET, POST, PATCH, PUT, DELETE and OPTIONS.

+

Other methods can be accepted, however they have no specific callback defined for them at this time.

Callbacks

-
-

All callbacks are optional. Some may become mandatory depending -on what other defined callbacks return. The various flowcharts -in the next chapter should be a useful to determine which callbacks -you need.

-

All callbacks take two arguments, the Req object and the State, -and return a three-element tuple of the form {Value, Req, State}.

-

Nearly all callbacks can also return {stop, Req, State} to -stop execution of the request, and -{{switch_handler, Module}, Req, State} or -{{switch_handler, Module, Opts}, Req, State} to switch to -a different handler type. The exceptions are expires -generate_etag, last_modified and variances.

-

The following table summarizes the callbacks and their default values. -If the callback isn’t defined, then the default value will be used. -Please look at the flowcharts to find out the result of each return -value.

-

In the following table, "skip" means the callback is entirely skipped -if it is undefined, moving directly to the next step. Similarly, -"none" means there is no default value for this callback.

-
- --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +

All callbacks are optional. Some may become mandatory depending on what other defined callbacks return. The various flowcharts in the next chapter should be a useful to determine which callbacks you need.

+

All callbacks take two arguments, the Req object and the State, and return a three-element tuple of the form {Value, Req, State}.

+

Nearly all callbacks can also return {stop, Req, State} to stop execution of the request, and {{switch_handler, Module}, Req, State} or {{switch_handler, Module, Opts}, Req, State} to switch to a different handler type. The exceptions are expires generate_etag, last_modified and variances.

+

The following table summarizes the callbacks and their default values. If the callback isn't defined, then the default value will be used. Please look at the flowcharts to find out the result of each return value.

+

In the following table, "skip" means the callback is entirely skipped if it is undefined, moving directly to the next step. Similarly, "none" means there is no default value for this callback.

+
Callback name Default value

allowed_methods

[<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]

allow_missing_post

true

charsets_provided

skip

content_types_accepted

none

content_types_provided

[{{ <<"text">>, <<"html">>, '*'}, to_html}]

delete_completed

true

delete_resource

false

expires

undefined

forbidden

false

generate_etag

undefined

is_authorized

true

is_conflict

false

known_methods

[<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]

languages_provided

skip

last_modified

undefined

malformed_request

false

moved_permanently

false

moved_temporarily

false

multiple_choices

false

options

ok

previously_existed

false

resource_exists

true

service_available

true

uri_too_long

false

+ + + + - - - + + - - - + + - - - + + - -
Callback nameDefault value
allowed_methods[<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]

valid_content_headers

true

allow_missing_posttrue

valid_entity_length

true

charsets_providedskip

variances

[]

content_types_acceptednone
-
-

As you can see, Cowboy tries to move on with the request whenever -possible by using well thought out default values.

-

In addition to these, there can be any number of user-defined -callbacks that are specified through content_types_accepted/2 -and content_types_provided/2. They can take any name, however -it is recommended to use a separate prefix for the callbacks of -each function. For example, from_html and to_html indicate -in the first case that we’re accepting a resource given as HTML, -and in the second case that we send one as HTML.

-
-
-
+content_types_provided +[{{ <<"text">>, <<"html">>, '*'}, to_html}] + +delete_completed +true + +delete_resource +false + +expires +undefined + +forbidden +false + +generate_etag +undefined + +is_authorized +true + +is_conflict +false + +known_methods +[<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>] + +languages_provided +skip + +last_modified +undefined + +malformed_request +false + +moved_permanently +false + +moved_temporarily +false + +multiple_choices +false + +options +ok + +previously_existed +false + +resource_exists +true + +service_available +true + +uri_too_long +false + +valid_content_headers +true + +valid_entity_length +true + +variances +[] + + +

As you can see, Cowboy tries to move on with the request whenever possible by using well thought out default values.

+

In addition to these, there can be any number of user-defined callbacks that are specified through content_types_accepted/2 and content_types_provided/2. They can take any name, however it is recommended to use a separate prefix for the callbacks of each function. For example, from_html and to_html indicate in the first case that we're accepting a resource given as HTML, and in the second case that we send one as HTML.

Meta data

-
-

Cowboy will set informative values to the Req object at various -points of the execution. You can retrieve them by matching the -Req object directly. The values are defined in the following table:

-
- --- - - - - - - - - - - - - - - - - - - - -
Key Details

media_type

The content-type negotiated for the response entity.

language

The language negotiated for the response entity.

charset

The charset negotiated for the response entity.

-
-

They can be used to send a proper body with the response to a -request that used a method other than HEAD or GET.

-
-
-
+

Cowboy will set informative values to the Req object at various points of the execution. You can retrieve them by matching the Req object directly. The values are defined in the following table:

+ + + + + + + + + + + + +
KeyDetails
media_typeThe content-type negotiated for the response entity.
languageThe language negotiated for the response entity.
charsetThe charset negotiated for the response entity.
+

They can be used to send a proper body with the response to a request that used a method other than HEAD or GET.

Response headers

-
-

Cowboy will set response headers automatically over the execution -of the REST code. They are listed in the following table.

-
- --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Header name Details

content-language

Language used in the response body

content-type

Media type and charset of the response body

etag

Etag of the resource

expires

Expiration date of the resource

last-modified

Last modification date for the resource

location

Relative or absolute URI to the requested resource

vary

List of headers that may change the representation of the resource

-
-
-
+

Cowboy will set response headers automatically over the execution of the REST code. They are listed in the following table.

+ + + + + + + + + + + + + + + + + + + + + + + + +
Header nameDetails
content-languageLanguage used in the response body
content-typeMedia type and charset of the response body
etagEtag of the resource
expiresExpiration date of the resource
last-modifiedLast modification date for the resource
locationRelative or absolute URI to the requested resource
varyList of headers that may change the representation of the resource
+ diff --git a/docs/en/cowboy/2.2/guide/rest_principles/index.html b/docs/en/cowboy/2.2/guide/rest_principles/index.html index 8ada8c49..7c16c752 100644 --- a/docs/en/cowboy/2.2/guide/rest_principles/index.html +++ b/docs/en/cowboy/2.2/guide/rest_principles/index.html @@ -62,153 +62,38 @@

REST principles

-

This chapter will attempt to define the concepts behind REST -and explain what makes a service RESTful.

-

REST is often confused with performing a distinct operation -depending on the HTTP method, while using more than the GET -and POST methods. That’s highly misguided at best.

-

We will first attempt to define REST and will look at what -it means in the context of HTTP and the Web. -For a more in-depth explanation of REST, you can read -Roy T. Fielding’s dissertation -as it does a great job explaining where it comes from and -what it achieves.

-
+

This chapter will attempt to define the concepts behind REST and explain what makes a service RESTful.

+

REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That's highly misguided at best.

+

We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. Fielding's dissertation as it does a great job explaining where it comes from and what it achieves.

REST architecture

-
-

REST is a client-server architecture. The client and the server -both have a different set of concerns. The server stores and/or -manipulates information and makes it available to the user in -an efficient manner. The client takes that information and -displays it to the user and/or uses it to perform subsequent -requests for information. This separation of concerns allows both -the client and the server to evolve independently as it only -requires that the interface stays the same.

-

REST is stateless. That means the communication between the -client and the server always contains all the information needed -to perform the request. There is no session state in the server, -it is kept entirely on the client’s side. If access to a resource -requires authentication, then the client needs to authenticate -itself with every request.

-

REST is cacheable. The client, the server and any intermediary -components can all cache resources in order to improve performance.

-

REST provides a uniform interface between components. This -simplifies the architecture, as all components follow the same -rules to speak to one another. It also makes it easier to understand -the interactions between the different components of the system. -A number of constraints are required to achieve this. They are -covered in the rest of the chapter.

-

REST is a layered system. Individual components cannot see -beyond the immediate layer with which they are interacting. This -means that a client connecting to an intermediate component, like -a proxy, has no knowledge of what lies beyond. This allows -components to be independent and thus easily replaceable or -extendable.

-

REST optionally provides code on demand. Code may be downloaded -to extend client functionality. This is optional however because -the client may not be able to download or run this code, and so -a REST component cannot rely on it being executed.

-
-
-
+

REST is a client-server architecture. The client and the server both have a different set of concerns. The server stores and/or manipulates information and makes it available to the user in an efficient manner. The client takes that information and displays it to the user and/or uses it to perform subsequent requests for information. This separation of concerns allows both the client and the server to evolve independently as it only requires that the interface stays the same.

+

REST is stateless. That means the communication between the client and the server always contains all the information needed to perform the request. There is no session state in the server, it is kept entirely on the client's side. If access to a resource requires authentication, then the client needs to authenticate itself with every request.

+

REST is cacheable. The client, the server and any intermediary components can all cache resources in order to improve performance.

+

REST provides a uniform interface between components. This simplifies the architecture, as all components follow the same rules to speak to one another. It also makes it easier to understand the interactions between the different components of the system. A number of constraints are required to achieve this. They are covered in the rest of the chapter.

+

REST is a layered system. Individual components cannot see beyond the immediate layer with which they are interacting. This means that a client connecting to an intermediate component, like a proxy, has no knowledge of what lies beyond. This allows components to be independent and thus easily replaceable or extendable.

+

REST optionally provides code on demand. Code may be downloaded to extend client functionality. This is optional however because the client may not be able to download or run this code, and so a REST component cannot rely on it being executed.

Resources and resource identifiers

-
-

A resource is an abstract concept. In a REST system, any information -that can be named may be a resource. This includes documents, images, -a collection of resources and any other information. Any information -that can be the target of an hypertext link can be a resource.

-

A resource is a conceptual mapping to a set of entities. The set of -entities evolves over time; a resource doesn’t. For example, a resource -can map to "users who have logged in this past month" and another -to "all users". At some point in time they may map to the same set of -entities, because all users logged in this past month. But they are -still different resources. Similarly, if nobody logged in recently, -then the first resource may map to the empty set. This resource exists -regardless of the information it maps to.

-

Resources are identified by uniform resource identifiers, also known -as URIs. Sometimes internationalized resource identifiers, or IRIs, -may also be used, but these can be directly translated into a URI.

-

In practice we will identify two kinds of resources. Individual -resources map to a set of one element, for example "user Joe". -Collection of resources map to a set of 0 to N elements, -for example "all users".

-
-
-
+

A resource is an abstract concept. In a REST system, any information that can be named may be a resource. This includes documents, images, a collection of resources and any other information. Any information that can be the target of an hypertext link can be a resource.

+

A resource is a conceptual mapping to a set of entities. The set of entities evolves over time; a resource doesn't. For example, a resource can map to "users who have logged in this past month" and another to "all users". At some point in time they may map to the same set of entities, because all users logged in this past month. But they are still different resources. Similarly, if nobody logged in recently, then the first resource may map to the empty set. This resource exists regardless of the information it maps to.

+

Resources are identified by uniform resource identifiers, also known as URIs. Sometimes internationalized resource identifiers, or IRIs, may also be used, but these can be directly translated into a URI.

+

In practice we will identify two kinds of resources. Individual resources map to a set of one element, for example "user Joe". Collection of resources map to a set of 0 to N elements, for example "all users".

Resource representations

-
-

The representation of a resource is a sequence of bytes associated -with metadata.

-

The metadata comes as a list of key-value pairs, where the name -corresponds to a standard that defines the value’s structure and -semantics. With HTTP, the metadata comes in the form of request -or response headers. The headers' structure and semantics are well -defined in the HTTP standard. Metadata includes representation -metadata, resource metadata and control data.

-

The representation metadata gives information about the -representation, such as its media type, the date of last -modification, or even a checksum.

-

Resource metadata could be link to related resources or -information about additional representations of the resource.

-

Control data allows parameterizing the request or response. -For example, we may only want the representation returned if -it is more recent than the one we have in cache. Similarly, -we may want to instruct the client about how it should cache -the representation. This isn’t restricted to caching. We may, -for example, want to store a new representation of a resource -only if it wasn’t modified since we first retrieved it.

-

The data format of a representation is also known as the media -type. Some media types are intended for direct rendering to the -user, while others are intended for automated processing. The -media type is a key component of the REST architecture.

-
-
-
+

The representation of a resource is a sequence of bytes associated with metadata.

+

The metadata comes as a list of key-value pairs, where the name corresponds to a standard that defines the value's structure and semantics. With HTTP, the metadata comes in the form of request or response headers. The headers' structure and semantics are well defined in the HTTP standard. Metadata includes representation metadata, resource metadata and control data.

+

The representation metadata gives information about the representation, such as its media type, the date of last modification, or even a checksum.

+

Resource metadata could be link to related resources or information about additional representations of the resource.

+

Control data allows parameterizing the request or response. For example, we may only want the representation returned if it is more recent than the one we have in cache. Similarly, we may want to instruct the client about how it should cache the representation. This isn't restricted to caching. We may, for example, want to store a new representation of a resource only if it wasn't modified since we first retrieved it.

+

The data format of a representation is also known as the media type. Some media types are intended for direct rendering to the user, while others are intended for automated processing. The media type is a key component of the REST architecture.

Self-descriptive messages

-
-

Messages must be self-descriptive. That means that the data -format of a representation must always come with its media -type (and similarly requesting a resource involves choosing -the media type of the representation returned). If you are -sending HTML, then you must say it is HTML by sending the -media type with the representation. In HTTP this is done -using the content-type header.

-

The media type is often an IANA registered media type, like -text/html or image/png, but does not need to be. Exactly -two things are important for respecting this constraint: that -the media type is well specified, and that the sender and -recipient agree about what the media type refers to.

-

This means that you can create your own media types, like -application/x-mine, and that as long as you write the -specifications for it and that both endpoints agree about -it then the constraint is respected.

-
-
-
+

Messages must be self-descriptive. That means that the data format of a representation must always come with its media type (and similarly requesting a resource involves choosing the media type of the representation returned). If you are sending HTML, then you must say it is HTML by sending the media type with the representation. In HTTP this is done using the content-type header.

+

The media type is often an IANA registered media type, like text/html or image/png, but does not need to be. Exactly two things are important for respecting this constraint: that the media type is well specified, and that the sender and recipient agree about what the media type refers to.

+

This means that you can create your own media types, like application/x-mine, and that as long as you write the specifications for it and that both endpoints agree about it then the constraint is respected.

Hypermedia as the engine of application state

-
-

The last constraint is generally where services that claim -to be RESTful fail. Interactions with a server must be -entirely driven by hypermedia. The client does not need -any prior knowledge of the service in order to use it, -other than an entry point and of course basic understanding -of the media type of the representations, at the very least -enough to find and identify hyperlinks and link relations.

-

To give a simple example, if your service only works with -the application/json media type then this constraint -cannot be respected (as there are no concept of links in -JSON) and thus your service isn’t RESTful. This is the case -for the majority of self-proclaimed REST services.

-

On the other hand if you create a JSON based media type -that has a concept of links and link relations, then -your service might be RESTful.

-

Respecting this constraint means that the entirety of the -service becomes self-discoverable, not only the resources -in it, but also the operations you can perform on it. This -makes clients very thin as there is no need to implement -anything specific to the service to operate on it.

-
-
+

The last constraint is generally where services that claim to be RESTful fail. Interactions with a server must be entirely driven by hypermedia. The client does not need any prior knowledge of the service in order to use it, other than an entry point and of course basic understanding of the media type of the representations, at the very least enough to find and identify hyperlinks and link relations.

+

To give a simple example, if your service only works with the application/json media type then this constraint cannot be respected (as there are no concept of links in JSON) and thus your service isn't RESTful. This is the case for the majority of self-proclaimed REST services.

+

On the other hand if you create a JSON based media type that has a concept of links and link relations, then your service might be RESTful.

+

Respecting this constraint means that the entirety of the service becomes self-discoverable, not only the resources in it, but also the operations you can perform on it. This makes clients very thin as there is no need to implement anything specific to the service to operate on it.

+ diff --git a/docs/en/cowboy/2.2/guide/routing/index.html b/docs/en/cowboy/2.2/guide/routing/index.html index 441d911c..d393f6c2 100644 --- a/docs/en/cowboy/2.2/guide/routing/index.html +++ b/docs/en/cowboy/2.2/guide/routing/index.html @@ -62,261 +62,181 @@

Routing

-

Cowboy does nothing by default.

-

To make Cowboy useful, you need to map URIs to Erlang modules that will -handle the requests. This is called routing.

-

When Cowboy receives a request, it tries to match the requested host and -path to the configured routes. When there’s a match, the route’s -associated handler is executed.

-

Routes need to be compiled before they can be used by Cowboy. -The result of the compilation is the dispatch rules.

-
+

Cowboy does nothing by default.

+

To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing.

+

When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there's a match, the route's associated handler is executed.

+

Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules.

Syntax

-
-

The general structure for the routes is defined as follow.

-
-
-
Routes = [Host1, Host2, ... HostN].
-

Each host contains matching rules for the host along with optional -constraints, and a list of routes for the path component.

-
-
-
Host1 = {HostMatch, PathsList}.
-Host2 = {HostMatch, Constraints, PathsList}.
-

The list of routes for the path component is defined similar to the -list of hosts.

-
-
-
PathsList = [Path1, Path2, ... PathN].
-

Finally, each path contains matching rules for the path along with -optional constraints, and gives us the handler module to be used -along with its initial state.

-
-
-
Path1 = {PathMatch, Handler, InitialState}.
-Path2 = {PathMatch, Constraints, Handler, InitialState}.
-

Continue reading to learn more about the match syntax and the optional -constraints.

-
-
-
+
Path1 = {PathMatch, Handler, InitialState}.
+Path2 = {PathMatch, Constraints, Handler, InitialState}.
+
+

Continue reading to learn more about the match syntax and the optional constraints.

Match syntax

-
-

The match syntax is used to associate host names and paths with their -respective handlers.

-

The match syntax is the same for host and path with a few subtleties. -Indeed, the segments separator is different, and the host is matched -starting from the last segment going to the first. All examples will -feature both host and path match rules and explain the differences -when encountered.

-

Excluding special values that we will explain at the end of this section, -the simplest match value is a host or a path. It can be given as either -a string() or a binary().

-
-
-
PathMatch1 = "/".
-PathMatch2 = "/path/to/resource".
-
-HostMatch1 = "cowboy.example.org".
-

As you can see, all paths defined this way must start with a slash -character. Note that these two paths are identical as far as routing -is concerned.

-
-
-
PathMatch2 = "/path/to/resource".
-PathMatch3 = "/path/to/resource/".
-

Hosts with and without a trailing dot are equivalent for routing. -Similarly, hosts with and without a leading dot are also equivalent.

-
-
-
HostMatch1 = "cowboy.example.org".
-HostMatch2 = "cowboy.example.org.".
-HostMatch3 = ".cowboy.example.org".
-

It is possible to extract segments of the host and path and to store -the values in the Req object for later use. We call these kind of -values bindings.

-

The syntax for bindings is very simple. A segment that begins with -the : character means that what follows until the end of the segment -is the name of the binding in which the segment value will be stored.

-
-
-
PathMatch = "/hats/:name/prices".
-HostMatch = ":subdomain.example.org".
-

If these two end up matching when routing, you will end up with two -bindings defined, subdomain and name, each containing the -segment value where they were defined. For example, the URL -http://test.example.org/hats/wild_cowboy_legendary/prices will -result in having the value test bound to the name subdomain -and the value wild_cowboy_legendary bound to the name name. -They can later be retrieved using cowboy_req:binding/{2,3}. The -binding name must be given as an atom.

-

There is a special binding name you can use to mimic the underscore -variable in Erlang. Any match against the _ binding will succeed -but the data will be discarded. This is especially useful for -matching against many domain names in one go.

-
-
-
HostMatch = "ninenines.:_".
-

Similarly, it is possible to have optional segments. Anything -between brackets is optional.

-
-
-
PathMatch = "/hats/[page/:number]".
-HostMatch = "[www.]ninenines.eu".
-

You can also have imbricated optional segments.

-
-
-
PathMatch = "/hats/[page/[:number]]".
-

You can retrieve the rest of the host or path using [...]. -In the case of hosts it will match anything before, in the case -of paths anything after the previously matched segments. It is -a special case of optional segments, in that it can have -zero, one or many segments. You can then find the segments using -cowboy_req:host_info/1 and cowboy_req:path_info/1 respectively. -They will be represented as a list of segments.

-
-
-
PathMatch = "/hats/[...]".
-HostMatch = "[...]ninenines.eu".
-

If a binding appears twice in the routing rules, then the match -will succeed only if they share the same value. This copies the -Erlang pattern matching behavior.

-
-
-
PathMatch = "/hats/:name/:name".
-

This is also true when an optional segment is present. In this -case the two values must be identical only if the segment is -available.

-
-
-
PathMatch = "/hats/:name/[:name]".
-

If a binding is defined in both the host and path, then they must -also share the same value.

-
-
-
PathMatch = "/:user/[...]".
-HostMatch = ":user.github.com".
-

Finally, there are two special match values that can be used. The -first is the atom '_' which will match any host or path.

-
-
-
PathMatch = '_'.
-HostMatch = '_'.
-

The second is the special host match "*" which will match the -wildcard path, generally used alongside the OPTIONS method.

-
-
-
HostMatch = "*".
-
- -
+
HostMatch = "*".
+

Constraints

-
-

After the matching has completed, the resulting bindings can be tested -against a set of constraints. Constraints are only tested when the -binding is defined. They run in the order you defined them. The match -will succeed only if they all succeed. If the match fails, then Cowboy -tries the next route in the list.

-

The format used for constraints is the same as match functions in -cowboy_req: they are provided as a list of fields which may have -one or more constraints. While the router accepts the same format, -it will skip fields with no constraints and will also ignore default -values, if any.

-

Read more about constraints.

-
- -
+

After the matching has completed, the resulting bindings can be tested against a set of constraints. Constraints are only tested when the binding is defined. They run in the order you defined them. The match will succeed only if they all succeed. If the match fails, then Cowboy tries the next route in the list.

+

The format used for constraints is the same as match functions in cowboy_req: they are provided as a list of fields which may have one or more constraints. While the router accepts the same format, it will skip fields with no constraints and will also ignore default values, if any.

+

Read more about constraints.

Compilation

-
-

The routes must be compiled before Cowboy can use them. The compilation -step normalizes the routes to simplify the code and speed up the -execution, but the routes are still looked up one by one in the end. -Faster compilation strategies could be to compile the routes directly -to Erlang code, but would require heavier dependencies.

-

To compile routes, just call the appropriate function:

-
-
-
Dispatch = cowboy_router:compile([
-    %% {HostMatch, list({PathMatch, Handler, InitialState})}
-    {'_', [{'_', my_handler, #{}}]}
+
Dispatch = cowboy_router:compile([
+    %% {HostMatch, list({PathMatch, Handler, InitialState})}
+    {'_', [{'_', my_handler, #{}}]}
 ]),
-%% Name, NbAcceptors, TransOpts, ProtoOpts
-cowboy:start_clear(my_http_listener,
-    [{port, 8080}],
-    #{env => #{dispatch => Dispatch}}
-).
-
-
-
+%% Name, NbAcceptors, TransOpts, ProtoOpts +cowboy:start_clear(my_http_listener, + [{port, 8080}], + #{env => #{dispatch => Dispatch}} +). +

Live update

-
-

You can use the cowboy:set_env/3 function for updating the dispatch -list used by routing. This will apply to all new connections accepted -by the listener:

-
-
-
Dispatch = cowboy_router:compile(Routes),
-cowboy:set_env(my_http_listener, dispatch, Dispatch).
-

Note that you need to compile the routes again before updating.

-
- +
Dispatch = cowboy_router:compile(Routes),
+cowboy:set_env(my_http_listener, dispatch, Dispatch).
+ +

Note that you need to compile the routes again before updating.

+ diff --git a/docs/en/cowboy/2.2/guide/specs/index.html b/docs/en/cowboy/2.2/guide/specs/index.html index 0cfcdcf2..265d1a3a 100644 --- a/docs/en/cowboy/2.2/guide/specs/index.html +++ b/docs/en/cowboy/2.2/guide/specs/index.html @@ -62,844 +62,339 @@

HTTP and other specifications

-

This chapter intends to list all the specification documents -for or related to HTTP.

-
+

This chapter intends to list all the specification documents for or related to HTTP.

HTTP

-
- -
+

Current

-
    -
  • -

    -CORS: Cross-Origin Resource Sharing -

    -
  • -
  • -

    -CSP2: Content Security Policy Level 2 -

    -
  • -
  • -

    -DNT: Tracking Preference Expression (DNT) -

    -
  • -
  • -

    -eventsource: Server-Sent Events -

    -
  • -
  • -

    -Form content types: Form content types -

    -
  • -
  • -

    -Preload: Preload -

    -
  • -
  • -

    -REST: Fielding’s Dissertation -

    -
  • -
  • -

    -RFC 1945: HTTP/1.0 -

    -
  • -
  • -

    -RFC 1951: DEFLATE Compressed Data Format Specification version 1.3 -

    -
  • -
  • -

    -RFC 1952: GZIP file format specification version 4.3 -

    -
  • -
  • -

    -RFC 2046: Multipart media type (in MIME Part Two: Media Types) -

    -
  • -
  • -

    -RFC 2295: Transparent Content Negotiation in HTTP -

    -
  • -
  • -

    -RFC 2296: HTTP Remote Variant Selection Algorithm: RVSA/1.0 -

    -
  • -
  • -

    -RFC 2817: Upgrading to TLS Within HTTP/1.1 -

    -
  • -
  • -

    -RFC 2818: HTTP Over TLS -

    -
  • -
  • -

    -RFC 3230: Instance Digests in HTTP -

    -
  • -
  • -

    -RFC 4559: SPNEGO-based Kerberos and NTLM HTTP Authentication in Microsoft Windows -

    -
  • -
  • -

    -RFC 5789: PATCH Method for HTTP -

    -
  • -
  • -

    -RFC 5843: Additional Hash Algorithms for HTTP Instance Digests -

    -
  • -
  • -

    -RFC 5861: HTTP Cache-Control Extensions for Stale Content -

    -
  • -
  • -

    -RFC 5988: Web Linking -

    -
  • -
  • -

    -RFC 6265: HTTP State Management Mechanism -

    -
  • -
  • -

    -RFC 6266: Use of the Content-Disposition Header Field -

    -
  • -
  • -

    -RFC 6454: The Web Origin Concept -

    -
  • -
  • -

    -RFC 6455: The WebSocket Protocol -

    -
  • -
  • -

    -RFC 6585: Additional HTTP Status Codes -

    -
  • -
  • -

    -RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage -

    -
  • -
  • -

    -RFC 6797: HTTP Strict Transport Security (HSTS) -

    -
  • -
  • -

    -RFC 6903: Additional Link Relation Types -

    -
  • -
  • -

    -RFC 7034: HTTP Header Field X-Frame-Options -

    -
  • -
  • -

    -RFC 7089: Time-Based Access to Resource States: Memento -

    -
  • -
  • -

    -RFC 7230: HTTP/1.1 Message Syntax and Routing -

    -
  • -
  • -

    -RFC 7231: HTTP/1.1 Semantics and Content -

    -
  • -
  • -

    -RFC 7232: HTTP/1.1 Conditional Requests -

    -
  • -
  • -

    -RFC 7233: HTTP/1.1 Range Requests -

    -
  • -
  • -

    -RFC 7234: HTTP/1.1 Caching -

    -
  • -
  • -

    -RFC 7235: HTTP/1.1 Authentication -

    -
  • -
  • -

    -RFC 7239: Forwarded HTTP Extension -

    -
  • -
  • -

    -RFC 7240: Prefer Header for HTTP -

    -
  • -
  • -

    -RFC 7469: Public Key Pinning Extension for HTTP -

    -
  • -
  • -

    -RFC 7486: HTTP Origin-Bound Authentication (HOBA) -

    -
  • -
  • -

    -RFC 7538: HTTP Status Code 308 (Permanent Redirect) -

    -
  • -
  • -

    -RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2) -

    -
  • -
  • -

    -RFC 7541: HPACK: Header Compression for HTTP/2 -

    -
  • -
  • -

    -RFC 7578: Returning Values from Forms: multipart/form-data -

    -
  • -
  • -

    -RFC 7615: HTTP Authentication-Info and Proxy-Authentication-Info Response Header Fields -

    -
  • -
  • -

    -RFC 7616: HTTP Digest Access Authentication -

    -
  • -
  • -

    -RFC 7617: The Basic HTTP Authentication Scheme -

    -
  • -
  • -

    -RFC 7639: The ALPN HTTP Header Field -

    -
  • -
  • -

    -RFC 7692: Compression Extensions for WebSocket -

    -
  • -
  • -

    -RFC 7694: HTTP Client-Initiated Content-Encoding -

    -
  • -
  • -

    -RFC 7725: An HTTP Status Code to Report Legal Obstacles -

    -
  • -
  • -

    -RFC 7804: Salted Challenge Response HTTP Authentication Mechanism -

    -
  • -
  • -

    -RFC 7838: HTTP Alternative Services -

    -
  • -
  • -

    -RFC 7932: Brotli Compressed Data Format -

    -
  • -
  • -

    -RFC 7936: Clarifying Registry Procedures for the WebSocket Subprotocol Name Registry -

    -
  • -
  • -

    -RFC 8053: HTTP Authentication Extensions for Interactive Clients -

    -
  • -
  • -

    -RFC 8164: Opportunistic Security for HTTP/2 -

    -
  • -
  • -

    -RFC 8187: Indicating Character Encoding and Language for HTTP Header Field Parameters -

    -
  • -
  • -

    -RFC 8188: Encrypted Content-Encoding for HTTP -

    -
  • -
  • -

    -RFC 8246: HTTP Immutable Responses -

    -
  • -
  • -

    -RFC 8297: An HTTP Status Code for Indicating Hints -

    -
  • -
  • -

    -Webmention: Webmention -

    -
  • -
-
-
+
  • CORS: Cross-Origin Resource Sharing +
  • +
  • CSP2: Content Security Policy Level 2 +
  • +
  • DNT: Tracking Preference Expression (DNT) +
  • +
  • eventsource: Server-Sent Events +
  • +
  • Form content types: Form content types +
  • +
  • Preload: Preload +
  • +
  • REST: Fielding's Dissertation +
  • +
  • RFC 1945: HTTP/1.0 +
  • +
  • RFC 1951: DEFLATE Compressed Data Format Specification version 1.3 +
  • +
  • RFC 1952: GZIP file format specification version 4.3 +
  • +
  • RFC 2046: Multipart media type (in MIME Part Two: Media Types) +
  • +
  • RFC 2295: Transparent Content Negotiation in HTTP +
  • +
  • RFC 2296: HTTP Remote Variant Selection Algorithm: RVSA/1.0 +
  • +
  • RFC 2817: Upgrading to TLS Within HTTP/1.1 +
  • +
  • RFC 2818: HTTP Over TLS +
  • +
  • RFC 3230: Instance Digests in HTTP +
  • +
  • RFC 4559: SPNEGO-based Kerberos and NTLM HTTP Authentication in Microsoft Windows +
  • +
  • RFC 5789: PATCH Method for HTTP +
  • +
  • RFC 5843: Additional Hash Algorithms for HTTP Instance Digests +
  • +
  • RFC 5861: HTTP Cache-Control Extensions for Stale Content +
  • +
  • RFC 5988: Web Linking +
  • +
  • RFC 6265: HTTP State Management Mechanism +
  • +
  • RFC 6266: Use of the Content-Disposition Header Field +
  • +
  • RFC 6454: The Web Origin Concept +
  • +
  • RFC 6455: The WebSocket Protocol +
  • +
  • RFC 6585: Additional HTTP Status Codes +
  • +
  • RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage +
  • +
  • RFC 6797: HTTP Strict Transport Security (HSTS) +
  • +
  • RFC 6903: Additional Link Relation Types +
  • +
  • RFC 7034: HTTP Header Field X-Frame-Options +
  • +
  • RFC 7089: Time-Based Access to Resource States: Memento +
  • +
  • RFC 7230: HTTP/1.1 Message Syntax and Routing +
  • +
  • RFC 7231: HTTP/1.1 Semantics and Content +
  • +
  • RFC 7232: HTTP/1.1 Conditional Requests +
  • +
  • RFC 7233: HTTP/1.1 Range Requests +
  • +
  • RFC 7234: HTTP/1.1 Caching +
  • +
  • RFC 7235: HTTP/1.1 Authentication +
  • +
  • RFC 7239: Forwarded HTTP Extension +
  • +
  • RFC 7240: Prefer Header for HTTP +
  • +
  • RFC 7469: Public Key Pinning Extension for HTTP +
  • +
  • RFC 7486: HTTP Origin-Bound Authentication (HOBA) +
  • +
  • RFC 7538: HTTP Status Code 308 (Permanent Redirect) +
  • +
  • RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2) +
  • +
  • RFC 7541: HPACK: Header Compression for HTTP/2 +
  • +
  • RFC 7578: Returning Values from Forms: multipart/form-data +
  • +
  • RFC 7615: HTTP Authentication-Info and Proxy-Authentication-Info Response Header Fields +
  • +
  • RFC 7616: HTTP Digest Access Authentication +
  • +
  • RFC 7617: The Basic HTTP Authentication Scheme +
  • +
  • RFC 7639: The ALPN HTTP Header Field +
  • +
  • RFC 7692: Compression Extensions for WebSocket +
  • +
  • RFC 7694: HTTP Client-Initiated Content-Encoding +
  • +
  • RFC 7725: An HTTP Status Code to Report Legal Obstacles +
  • +
  • RFC 7804: Salted Challenge Response HTTP Authentication Mechanism +
  • +
  • RFC 7838: HTTP Alternative Services +
  • +
  • RFC 7932: Brotli Compressed Data Format +
  • +
  • RFC 7936: Clarifying Registry Procedures for the WebSocket Subprotocol Name Registry +
  • +
  • RFC 8053: HTTP Authentication Extensions for Interactive Clients +
  • +
  • RFC 8164: Opportunistic Security for HTTP/2 +
  • +
  • RFC 8187: Indicating Character Encoding and Language for HTTP Header Field Parameters +
  • +
  • RFC 8188: Encrypted Content-Encoding for HTTP +
  • +
  • RFC 8246: HTTP Immutable Responses +
  • +
  • RFC 8297: An HTTP Status Code for Indicating Hints +
  • +
  • Webmention: Webmention +
  • +

Upcoming

- -
-
+

Informative

-
    -
  • -

    -Architecture of the World Wide Web -

    -
  • -
  • -

    -RFC 2936: HTTP MIME Type Handler Detection -

    -
  • -
  • -

    -RFC 2964: Use of HTTP State Management -

    -
  • -
  • -

    -RFC 3143: Known HTTP Proxy/Caching Problems -

    -
  • -
  • -

    -RFC 6202: Known Issues and Best Practices for the Use of Long Polling and Streaming in Bidirectional HTTP -

    -
  • -
  • -

    -RFC 6838: Media Type Specifications and Registration Procedures -

    -
  • -
  • -

    -RFC 7478: Web Real-Time Communication Use Cases and Requirements -

    -
  • -
-
-
+
  • Architecture of the World Wide Web +
  • +
  • RFC 2936: HTTP MIME Type Handler Detection +
  • +
  • RFC 2964: Use of HTTP State Management +
  • +
  • RFC 3143: Known HTTP Proxy/Caching Problems +
  • +
  • RFC 6202: Known Issues and Best Practices for the Use of Long Polling and Streaming in Bidirectional HTTP +
  • +
  • RFC 6838: Media Type Specifications and Registration Procedures +
  • +
  • RFC 7478: Web Real-Time Communication Use Cases and Requirements +
  • +
-
-
-
+

Seemingly obsolete

-
    -
  • -

    -RFC 2227: Simple Hit-Metering and Usage-Limiting for HTTP -

    -
  • -
  • -

    -RFC 2310: The Safe Response Header Field -

    -
  • -
  • -

    -RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) -

    -
  • -
  • -

    -RFC 2660: The Secure HyperText Transfer Protocol -

    -
  • -
  • -

    -RFC 2774: An HTTP Extension Framework -

    -
  • -
  • -

    -RFC 2965: HTTP State Management Mechanism (Cookie2) -

    -
  • -
  • -

    -RFC 3229: Delta encoding in HTTP -

    -
  • -
  • -

    -RFC 7168: The Hyper Text Coffee Pot Control Protocol for Tea Efflux Appliances (HTCPCP-TEA) -

    -
  • -
  • -

    -SPDY: SPDY Protocol -

    -
  • -
  • -

    -x-webkit-deflate-frame: Deprecated Websocket compression -

    -
  • -
-
-
-
-
+
  • RFC 2227: Simple Hit-Metering and Usage-Limiting for HTTP +
  • +
  • RFC 2310: The Safe Response Header Field +
  • +
  • RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) +
  • +
  • RFC 2660: The Secure HyperText Transfer Protocol +
  • +
  • RFC 2774: An HTTP Extension Framework +
  • +
  • RFC 2965: HTTP State Management Mechanism (Cookie2) +
  • +
  • RFC 3229: Delta encoding in HTTP +
  • +
  • RFC 7168: The Hyper Text Coffee Pot Control Protocol for Tea Efflux Appliances (HTCPCP-TEA) +
  • +
  • SPDY: SPDY Protocol +
  • +
  • x-webkit-deflate-frame: Deprecated Websocket compression +
  • +

URL

-
-
-
-
-
+

WebDAV

-
-
    -
  • -

    -RFC 3253: Versioning Extensions to WebDAV -

    -
  • -
  • -

    -RFC 3648: WebDAV Ordered Collections Protocol -

    -
  • -
  • -

    -RFC 3744: WebDAV Access Control Protocol -

    -
  • -
  • -

    -RFC 4316: Datatypes for WebDAV Properties -

    -
  • -
  • -

    -RFC 4331: Quota and Size Properties for DAV Collections -

    -
  • -
  • -

    -RFC 4437: WebDAV Redirect Reference Resources -

    -
  • -
  • -

    -RFC 4709: Mounting WebDAV Servers -

    -
  • -
  • -

    -RFC 4791: Calendaring Extensions to WebDAV (CalDAV) -

    -
  • -
  • -

    -RFC 4918: HTTP Extensions for WebDAV -

    -
  • -
  • -

    -RFC 5323: WebDAV SEARCH -

    -
  • -
  • -

    -RFC 5397: WebDAV Current Principal Extension -

    -
  • -
  • -

    -RFC 5689: Extended MKCOL for WebDAV -

    -
  • -
  • -

    -RFC 5842: Binding Extensions to WebDAV -

    -
  • -
  • -

    -RFC 5995: Using POST to Add Members to WebDAV Collections -

    -
  • -
  • -

    -RFC 6352: CardDAV: vCard Extensions to WebDAV -

    -
  • -
  • -

    -RFC 6578: Collection Synchronization for WebDAV -

    -
  • -
  • -

    -RFC 6638: Scheduling Extensions to CalDAV -

    -
  • -
  • -

    -RFC 6764: Locating Services for Calendaring Extensions to WebDAV (CalDAV) and vCard Extensions to WebDAV (CardDAV) -

    -
  • -
  • -

    -RFC 7809: Calendaring Extensions to WebDAV (CalDAV): Time Zones by Reference -

    -
  • -
  • -

    -RFC 7953: Calendar Availability -

    -
  • -
  • -

    -RFC 8144: Use of the Prefer Header Field in WebDAV -

    -
  • -
-
-
-
+
  • RFC 3253: Versioning Extensions to WebDAV +
  • +
  • RFC 3648: WebDAV Ordered Collections Protocol +
  • +
  • RFC 3744: WebDAV Access Control Protocol +
  • +
  • RFC 4316: Datatypes for WebDAV Properties +
  • +
  • RFC 4331: Quota and Size Properties for DAV Collections +
  • +
  • RFC 4437: WebDAV Redirect Reference Resources +
  • +
  • RFC 4709: Mounting WebDAV Servers +
  • +
  • RFC 4791: Calendaring Extensions to WebDAV (CalDAV) +
  • +
  • RFC 4918: HTTP Extensions for WebDAV +
  • +
  • RFC 5323: WebDAV SEARCH +
  • +
  • RFC 5397: WebDAV Current Principal Extension +
  • +
  • RFC 5689: Extended MKCOL for WebDAV +
  • +
  • RFC 5842: Binding Extensions to WebDAV +
  • +
  • RFC 5995: Using POST to Add Members to WebDAV Collections +
  • +
  • RFC 6352: CardDAV: vCard Extensions to WebDAV +
  • +
  • RFC 6578: Collection Synchronization for WebDAV +
  • +
  • RFC 6638: Scheduling Extensions to CalDAV +
  • +
  • RFC 6764: Locating Services for Calendaring Extensions to WebDAV (CalDAV) and vCard Extensions to WebDAV (CardDAV) +
  • +
  • RFC 7809: Calendaring Extensions to WebDAV (CalDAV): Time Zones by Reference +
  • +
  • RFC 7953: Calendar Availability +
  • +
  • RFC 8144: Use of the Prefer Header Field in WebDAV +
  • +

CoAP

-
-
    -
  • -

    -RFC 7252: The Constrained Application Protocol (CoAP) -

    -
  • -
  • -

    -RFC 7390: Group Communication for CoAP -

    -
  • -
  • -

    -RFC 7641: Observing Resources in CoAP -

    -
  • -
  • -

    -RFC 7650: A CoAP Usage for REsource LOcation And Discovery (RELOAD) -

    -
  • -
  • -

    -RFC 7959: Block-Wise Transfers in CoAP -

    -
  • -
  • -

    -RFC 7967: CoAP Option for No Server Response -

    -
  • -
  • -

    -RFC 8075: Guidelines for Mapping Implementations: HTTP to CoAP -

    -
  • -
  • -

    -RFC 8132: PATCH and FETCH Methods for CoAP -

    -
  • -
-
-
+
  • RFC 7252: The Constrained Application Protocol (CoAP) +
  • +
  • RFC 7390: Group Communication for CoAP +
  • +
  • RFC 7641: Observing Resources in CoAP +
  • +
  • RFC 7650: A CoAP Usage for REsource LOcation And Discovery (RELOAD) +
  • +
  • RFC 7959: Block-Wise Transfers in CoAP +
  • +
  • RFC 7967: CoAP Option for No Server Response +
  • +
  • RFC 8075: Guidelines for Mapping Implementations: HTTP to CoAP +
  • +
  • RFC 8132: PATCH and FETCH Methods for CoAP +
  • +
+ diff --git a/docs/en/cowboy/2.2/guide/static_files/index.html b/docs/en/cowboy/2.2/guide/static_files/index.html index e1de8a17..8de517c1 100644 --- a/docs/en/cowboy/2.2/guide/static_files/index.html +++ b/docs/en/cowboy/2.2/guide/static_files/index.html @@ -62,173 +62,101 @@

Static files

-

Cowboy comes with a ready to use handler for serving static -files. It is provided as a convenience for serving files -during development.

-

For systems in production, consider using one of the many -Content Distribution Network (CDN) available on the market, -as they are the best solution for serving files.

-

The static handler can serve either one file or all files -from a given directory. The etag generation and mime types -can be configured.

-
+

Cowboy comes with a ready to use handler for serving static files. It is provided as a convenience for serving files during development.

+

For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files.

+

The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured.

Serve one file

-
-

You can use the static handler to serve one specific file -from an application’s private directory. This is particularly -useful to serve an index.html file when the client requests -the / path, for example. The path configured is relative -to the given application’s private directory.

-

The following rule will serve the file static/index.html -from the application my_app's priv directory whenever the -path / is accessed:

-
-
-
{"/", cowboy_static, {priv_file, my_app, "static/index.html"}}
-

You can also specify the absolute path to a file, or the -path to the file relative to the current directory:

-
-
-
{"/", cowboy_static, {file, "/var/www/index.html"}}
-
-
-
+
{"/", cowboy_static, {file, "/var/www/index.html"}}
+

Serve all files from a directory

-
-

You can also use the static handler to serve all files that -can be found in the configured directory. The handler will -use the path_info information to resolve the file location, -which means that your route must end with a [...] pattern -for it to work. All files are served, including the ones that -may be found in subfolders.

-

You can specify the directory relative to an application’s -private directory.

-

The following rule will serve any file found in the application -my_app's priv directory inside the static/assets folder -whenever the requested path begins with /assets/:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets"}}
-

You can also specify the absolute path to the directory or -set it relative to the current directory:

-
-
-
{"/assets/[...]", cowboy_static, {dir, "/var/www/assets"}}
-
- -
+
{"/assets/[...]", cowboy_static, {dir, "/var/www/assets"}}
+

Customize the mimetype detection

-
-

By default, Cowboy will attempt to recognize the mimetype -of your static files by looking at the extension.

-

You can override the function that figures out the mimetype -of the static files. It can be useful when Cowboy is missing -a mimetype you need to handle, or when you want to reduce -the list to make lookups faster. You can also give a -hard-coded mimetype that will be used unconditionally.

-

Cowboy comes with two functions built-in. The default -function only handles common file types used when building -Web applications. The other function is an extensive list -of hundreds of mimetypes that should cover almost any need -you may have. You can of course create your own function.

-

To use the default function, you should not have to configure -anything, as it is the default. If you insist, though, the -following will do the job:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{mimetypes, cow_mimetypes, web}]}}
-

As you can see, there is an optional field that may contain -a list of less used options, like mimetypes or etag. All option -types have this optional field.

-

To use the function that will detect almost any mimetype, -the following configuration will do:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{mimetypes, cow_mimetypes, all}]}}
-

You probably noticed the pattern by now. The configuration -expects a module and a function name, so you can use any -of your own functions instead:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{mimetypes, Module, Function}]}}
-

The function that performs the mimetype detection receives -a single argument that is the path to the file on disk. It -is recommended to return the mimetype in tuple form, although -a binary string is also allowed (but will require extra -processing). If the function can’t figure out the mimetype, -then it should return {<<"application">>, <<"octet-stream">>, []}.

-

When the static handler fails to find the extension, -it will send the file as application/octet-stream. -A browser receiving such file will attempt to download it -directly to disk.

-

Finally, the mimetype can be hard-coded for all files. -This is especially useful in combination with the file -and priv_file options as it avoids needless computation:

-
-
-
{"/", cowboy_static, {priv_file, my_app, "static/index.html",
-    [{mimetypes, {<<"text">>, <<"html">>, []}}]}}
-
- -
+
{"/", cowboy_static, {priv_file, my_app, "static/index.html",
+    [{mimetypes, {<<"text">>, <<"html">>, []}}]}}
+

Generate an etag

-
-

By default, the static handler will generate an etag header -value based on the size and modified time. This solution -can not be applied to all systems though. It would perform -rather poorly over a cluster of nodes, for example, as the -file metadata will vary from server to server, giving a -different etag on each server.

-

You can however change the way the etag is calculated:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{etag, Module, Function}]}}
-

This function will receive three arguments: the path to the -file on disk, the size of the file and the last modification -time. In a distributed setup, you would typically use the -file path to retrieve an etag value that is identical across -all your servers.

-

You can also completely disable etag handling:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{etag, false}]}}
-
- +
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
+    [{etag, false}]}}
+ + diff --git a/docs/en/cowboy/2.2/guide/streams/index.html b/docs/en/cowboy/2.2/guide/streams/index.html index a5a1e9a4..c4758381 100644 --- a/docs/en/cowboy/2.2/guide/streams/index.html +++ b/docs/en/cowboy/2.2/guide/streams/index.html @@ -62,61 +62,23 @@

Streams

-

A stream is the set of messages that form an HTTP -request/response pair.

-

The term stream comes from HTTP/2. In Cowboy, it is -also used when talking about HTTP/1.1 or HTTP/1.0. -It should not be confused with streaming the request -or response body.

-

All versions of HTTP allow clients to initiate -streams. HTTP/2 is the only one also allowing servers, -through its server push feature. Both client and -server-initiated streams go through the same process -in Cowboy.

-
+

A stream is the set of messages that form an HTTP request/response pair.

+

The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body.

+

All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy.

Stream handlers

-
-

Stream handlers must implement five different callbacks. -Four of them are directly related; one is special.

-

All callbacks receives the stream ID as first argument.

-

Most of them can return a list of commands to be executed -by Cowboy. When callbacks are chained, it is possible to -intercept and modify these commands. This can be useful -for modifying responses for example.

-

The init/3 callback is invoked when a new request -comes in. It receives the Req object and the protocol options -for this listener.

-

The data/4 callback is invoked when data from the request -body is received. It receives both this data and a flag -indicating whether more is to be expected.

-

The info/3 callback is invoked when an Erlang message is -received for this stream. They will typically be messages -sent by the request process.

-

Finally the terminate/3 callback is invoked with the -terminate reason for the stream. The return value is ignored. -Note that as with all terminate callbacks in Erlang, there -is no strong guarantee that it will be called.

-

The special callback early_error/5 is called when an error -occurs before the request headers were fully received and -Cowboy is sending a response. It receives the partial Req -object, the error reason, the protocol options and the response -Cowboy will send. This response must be returned, possibly -modified.

-
-
-
+

Stream handlers must implement five different callbacks. Four of them are directly related; one is special.

+

All callbacks receives the stream ID as first argument.

+

Most of them can return a list of commands to be executed by Cowboy. When callbacks are chained, it is possible to intercept and modify these commands. This can be useful for modifying responses for example.

+

The init/3 callback is invoked when a new request comes in. It receives the Req object and the protocol options for this listener.

+

The data/4 callback is invoked when data from the request body is received. It receives both this data and a flag indicating whether more is to be expected.

+

The info/3 callback is invoked when an Erlang message is received for this stream. They will typically be messages sent by the request process.

+

Finally the terminate/3 callback is invoked with the terminate reason for the stream. The return value is ignored. Note that as with all terminate callbacks in Erlang, there is no strong guarantee that it will be called.

+

The special callback early_error/5 is called when an error occurs before the request headers were fully received and Cowboy is sending a response. It receives the partial Req object, the error reason, the protocol options and the response Cowboy will send. This response must be returned, possibly modified.

Built-in handlers

-
-

Cowboy comes with two handlers.

-

cowboy_stream_h is the default stream handler. -It is the core of much of the functionality of Cowboy. -All chains of stream handlers should call it last.

-

cowboy_compress_h will automatically compress -responses when possible. It is not enabled by default. -It is a good example for writing your own handlers -that will modify responses.

-
-
+

Cowboy comes with two handlers.

+

cowboy_stream_h is the default stream handler. It is the core of much of the functionality of Cowboy. All chains of stream handlers should call it last.

+

cowboy_compress_h will automatically compress responses when possible. It is not enabled by default. It is a good example for writing your own handlers that will modify responses.

+ diff --git a/docs/en/cowboy/2.2/guide/ws_handlers/index.html b/docs/en/cowboy/2.2/guide/ws_handlers/index.html index 0ffb5420..ab587d37 100644 --- a/docs/en/cowboy/2.2/guide/ws_handlers/index.html +++ b/docs/en/cowboy/2.2/guide/ws_handlers/index.html @@ -62,271 +62,171 @@

Websocket handlers

-

Websocket handlers provide an interface for upgrading HTTP/1.1 -connections to Websocket and sending or receiving frames on -the Websocket connection.

-

As Websocket connections are established through the HTTP/1.1 -upgrade mechanism, Websocket handlers need to be able to first -receive the HTTP request for the upgrade, before switching to -Websocket and taking over the connection. They can then receive -or send Websocket frames, handle incoming Erlang messages or -close the connection.

-
+

Websocket handlers provide an interface for upgrading HTTP/1.1 connections to Websocket and sending or receiving frames on the Websocket connection.

+

As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection.

Upgrade

-
-

The init/2 callback is called when the request is received. -To establish a Websocket connection, you must switch to the -cowboy_websocket module:

-
-
-
init(Req, State) ->
-    {cowboy_websocket, Req, State}.
-

Cowboy will perform the Websocket handshake immediately. Note -that the handshake will fail if the client did not request an -upgrade to Websocket.

-

The Req object becomes unavailable after this function returns. -Any information required for proper execution of the Websocket -handler must be saved in the state.

-
-
-
-

Subprotocol

-
-

The client may provide a list of Websocket subprotocols it -supports in the sec-websocket-protocol header. The server must -select one of them and send it back to the client or the -handshake will fail.

-

For example, a client could understand both STOMP and MQTT over -Websocket, and provide the header:

-
-
-
sec-websocket-protocol: v12.stomp, mqtt
+
init(Req, State) ->
+    {cowboy_websocket, Req, State}.
-

If the server only understands MQTT it can return:

-
-
-
sec-websocket-protocol: mqtt
-
-

This selection must be done in init/2. An example usage could -be:

-
-
-
init(Req0, State) ->
-    case cowboy_req:parse_header(<<"sec-websocket-protocol">>, Req0) of
-        undefined ->
-            {cowboy_websocket, Req0, State};
-        Subprotocols ->
-            case lists:keymember(<<"mqtt">>, 1, Subprotocols) of
-                true ->
-                    Req = cowboy_req:set_resp_header(<<"sec-websocket-protocol">>,
-                        <<"mqtt">>, Req0),
-                    {cowboy_websocket, Req, State};
-                false ->
-                    Req = cowboy_req:reply(400, Req0),
-                    {ok, Req, State}
-            end
-    end.
-
-
-
+
init(Req0, State) ->
+    case cowboy_req:parse_header(<<"sec-websocket-protocol">>, Req0) of
+        undefined ->
+            {cowboy_websocket, Req0, State};
+        Subprotocols ->
+            case lists:keymember(<<"mqtt">>, 1, Subprotocols) of
+                true ->
+                    Req = cowboy_req:set_resp_header(<<"sec-websocket-protocol">>,
+                        <<"mqtt">>, Req0),
+                    {cowboy_websocket, Req, State};
+                false ->
+                    Req = cowboy_req:reply(400, Req0),
+                    {ok, Req, State}
+            end
+    end.
+

Post-upgrade initialization

-
-

Cowboy has separate processes for handling the connection -and requests. Because Websocket takes over the connection, -the Websocket protocol handling occurs in a different -process than the request handling.

-

This is reflected in the different callbacks Websocket -handlers have. The init/2 callback is called from the -temporary request process and the websocket_ callbacks -from the connection process.

-

This means that some initialization cannot be done from -init/2. Anything that would require the current pid, -or be tied to the current pid, will not work as intended. -The optional websocket_init/1 can be used instead:

-
-
-
websocket_init(State) ->
-    erlang:start_timer(1000, self(), <<"Hello!">>),
-    {ok, State}.
-

All Websocket callbacks share the same return values. This -means that we can send frames to the client right after -the upgrade:

-
-
-
websocket_init(State) ->
-    {reply, {text, <<"Hello!">>}, State}.
-
- -
+
websocket_init(State) ->
+    {reply, {text, <<"Hello!">>}, State}.
+

Receiving frames

-
-

Cowboy will call websocket_handle/2 whenever a text, binary, -ping or pong frame arrives from the client.

-

The handler can handle or ignore the frames. It can also -send frames back to the client or stop the connection.

-

The following snippet echoes back any text frame received and -ignores all others:

-
-
-
websocket_handle(Frame = {text, _}, State) ->
-    {reply, Frame, State};
-websocket_handle(_Frame, State) ->
-    {ok, State}.
-

Note that ping and pong frames require no action from the -handler as Cowboy will automatically reply to ping frames. -They are provided for informative purposes only.

-
- -
+
websocket_handle(Frame = {text, _}, State) ->
+    {reply, Frame, State};
+websocket_handle(_Frame, State) ->
+    {ok, State}.
+
+

Note that ping and pong frames require no action from the handler as Cowboy will automatically reply to ping frames. They are provided for informative purposes only.

Receiving Erlang messages

-
-

Cowboy will call websocket_info/2 whenever an Erlang message -arrives.

-

The handler can handle or ignore the messages. It can also -send frames to the client or stop the connection.

-

The following snippet forwards log messages to the client -and ignores all others:

-
-
-
websocket_info({log, Text}, State) ->
-    {reply, {text, Text}, State};
-websocket_info(_Info, State) ->
-    {ok, State}.
-
- -
+
websocket_info({log, Text}, State) ->
+    {reply, {text, Text}, State};
+websocket_info(_Info, State) ->
+    {ok, State}.
+

Sending frames

-
-

All websocket_ callbacks share return values. They may -send zero, one or many frames to the client.

-

To send nothing, just return an ok tuple:

-
-
+ + +

All websocket_ callbacks share return values. They may send zero, one or many frames to the client.

+

To send nothing, just return an ok tuple:

+
-
websocket_info(_Info, State) ->
-    {ok, State}.
-

To send one frame, return a reply tuple with the frame to send:

-
-
-
websocket_info(_Info, State) ->
-    {reply, {text, <<"Hello!">>}, State}.
-

You can send frames of any type: text, binary, ping, pong -or close frames.

-

To send many frames at once, return a reply tuple with the -list of frames to send:

-
-
-
websocket_info(_Info, State) ->
-    {reply, [
-        {text, "Hello"},
-        {text, <<"world!">>},
-        {binary, <<0:8000>>}
-    ], State}.
-

They are sent in the given order.

-
-
-
+
websocket_info(_Info, State) ->
+    {reply, [
+        {text, "Hello"},
+        {text, <<"world!">>},
+        {binary, <<0:8000>>}
+    ], State}.
+
+

They are sent in the given order.

Keeping the connection alive

-
-

Cowboy will automatically respond to ping frames sent by -the client. They are still forwarded to the handler for -informative purposes, but no further action is required.

-

Cowboy does not send ping frames itself. The handler can -do it if required. A better solution in most cases is to -let the client handle pings. Doing it from the handler -would imply having an additional timer per connection and -this can be a considerable cost for servers that need to -handle large numbers of connections.

-

Cowboy can be configured to close idle connections -automatically. It is highly recommended to configure -a timeout here, to avoid having processes linger longer -than needed.

-

The init/2 callback can set the timeout to be used -for the connection. For example, this would make Cowboy -close connections idle for more than 30 seconds:

-
-
-
init(Req, State) ->
-    {cowboy_websocket, Req, State, #{
-        idle_timeout => 30000}}.
-

This value cannot be changed once it is set. It defaults to -60000.

-
- -
+
init(Req, State) ->
+    {cowboy_websocket, Req, State, #{
+        idle_timeout => 30000}}.
+
+

This value cannot be changed once it is set. It defaults to 60000.

Saving memory

-
-

The Websocket connection process can be set to hibernate -after the callback returns.

-

Simply add an hibernate field to the ok or reply tuples:

-
-
-
websocket_init(State) ->
-    {ok, State, hibernate}.
-
-websocket_handle(_Frame, State) ->
-    {ok, State, hibernate}.
-
-websocket_info(_Info, State) ->
-    {reply, {text, <<"Hello!">>}, State, hibernate}.
-

It is highly recommended to write your handlers with -hibernate enabled, as this allows to greatly reduce the -memory usage. Do note however that an increase in the -CPU usage or latency can be observed instead, in particular -for the more busy connections.

-
- -
+
websocket_init(State) ->
+    {ok, State, hibernate}.
+
+websocket_handle(_Frame, State) ->
+    {ok, State, hibernate}.
+
+websocket_info(_Info, State) ->
+    {reply, {text, <<"Hello!">>}, State, hibernate}.
+
+

It is highly recommended to write your handlers with hibernate enabled, as this allows to greatly reduce the memory usage. Do note however that an increase in the CPU usage or latency can be observed instead, in particular for the more busy connections.

Closing the connection

-
-

The connection can be closed at any time, either by telling -Cowboy to stop it or by sending a close frame.

-

To tell Cowboy to close the connection, use a stop tuple:

-
-
-
websocket_info(_Info, State) ->
-    {stop, State}.
-

Sending a close frame will immediately initiate the closing -of the Websocket connection. Note that when sending a list of -frames that include a close frame, any frame found after the -close frame will not be sent.

-
- +
websocket_info(_Info, State) ->
+    {stop, State}.
+ +

Sending a close frame will immediately initiate the closing of the Websocket connection. Note that when sending a list of frames that include a close frame, any frame found after the close frame will not be sent.

+ diff --git a/docs/en/cowboy/2.2/guide/ws_protocol/index.html b/docs/en/cowboy/2.2/guide/ws_protocol/index.html index 2ce9b79f..24ec7873 100644 --- a/docs/en/cowboy/2.2/guide/ws_protocol/index.html +++ b/docs/en/cowboy/2.2/guide/ws_protocol/index.html @@ -62,70 +62,22 @@

The Websocket protocol

-

This chapter explains what Websocket is and why it is -a vital component of soft realtime Web applications.

-
+

This chapter explains what Websocket is and why it is a vital component of soft realtime Web applications.

Description

-
-

Websocket is an extension to HTTP that emulates plain TCP -connections between the client, typically a Web browser, -and the server. It uses the HTTP Upgrade mechanism to -establish the connection.

-

Websocket connections are fully asynchronous, unlike -HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the -server can only initiate streams in response to requests). -With Websocket, the client and the server can both send -frames at any time without any restriction. It is closer -to TCP than any of the HTTP protocols.

-

Websocket is an IETF standard. Cowboy supports the standard -and all drafts that were previously implemented by browsers, -excluding the initial flawed draft sometimes known as -"version 0".

-
-
-
+

Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection.

+

Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). With Websocket, the client and the server can both send frames at any time without any restriction. It is closer to TCP than any of the HTTP protocols.

+

Websocket is an IETF standard. Cowboy supports the standard and all drafts that were previously implemented by browsers, excluding the initial flawed draft sometimes known as "version 0".

Websocket vs HTTP/2

-
-

For a few years Websocket was the only way to have a -bidirectional asynchronous connection with the server. -This changed when HTTP/2 was introduced. While HTTP/2 -requires the client to first perform a request before -the server can push data, this is only a minor restriction -as the client can do so just as it connects.

-

Websocket was designed as a kind-of-TCP channel to a -server. It only defines the framing and connection -management and lets the developer implement a protocol -on top of it. For example you could implement IRC over -Websocket and use a Javascript IRC client to speak to -the server.

-

HTTP/2 on the other hand is just an improvement over -the HTTP/1.1 connection and request/response mechanism. -It has the same semantics as HTTP/1.1.

-

If all you need is to access an HTTP API, then HTTP/2 -should be your first choice. On the other hand, if what -you need is a different protocol, then you can use -Websocket to implement it.

-
-
-
+

For a few years Websocket was the only way to have a bidirectional asynchronous connection with the server. This changed when HTTP/2 was introduced. While HTTP/2 requires the client to first perform a request before the server can push data, this is only a minor restriction as the client can do so just as it connects.

+

Websocket was designed as a kind-of-TCP channel to a server. It only defines the framing and connection management and lets the developer implement a protocol on top of it. For example you could implement IRC over Websocket and use a Javascript IRC client to speak to the server.

+

HTTP/2 on the other hand is just an improvement over the HTTP/1.1 connection and request/response mechanism. It has the same semantics as HTTP/1.1.

+

If all you need is to access an HTTP API, then HTTP/2 should be your first choice. On the other hand, if what you need is a different protocol, then you can use Websocket to implement it.

Implementation

-
-

Cowboy implements Websocket as a protocol upgrade. Once the -upgrade is performed from the init/2 callback, Cowboy -switches to Websocket. Please consult the next chapter for -more information on initiating and handling Websocket -connections.

-

The implementation of Websocket in Cowboy is validated using -the Autobahn test suite, which is an extensive suite of tests -covering all aspects of the protocol. Cowboy passes the -suite with 100% success, including all optional tests.

-

Cowboy’s Websocket implementation also includes the -permessage-deflate and x-webkit-deflate-frame compression -extensions.

-

Cowboy will automatically use compression when the -compress option is returned from the init/2 function.

-
-
+

Cowboy implements Websocket as a protocol upgrade. Once the upgrade is performed from the init/2 callback, Cowboy switches to Websocket. Please consult the next chapter for more information on initiating and handling Websocket connections.

+

The implementation of Websocket in Cowboy is validated using the Autobahn test suite, which is an extensive suite of tests covering all aspects of the protocol. Cowboy passes the suite with 100% success, including all optional tests.

+

Cowboy's Websocket implementation also includes the permessage-deflate and x-webkit-deflate-frame compression extensions.

+

Cowboy will automatically use compression when the compress option is returned from the init/2 function.

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy.set_env/index.html b/docs/en/cowboy/2.2/manual/cowboy.set_env/index.html index 4433f10b..455075c0 100644 --- a/docs/en/cowboy/2.2/manual/cowboy.set_env/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy.set_env/index.html @@ -62,117 +62,59 @@

cowboy:set_env(3)

-

Name

-
-

cowboy:set_env - Update a listener’s environment value

-
-
-
+

cowboy:set_env - Update a listener's environment value

Description

-
-
-
-
set_env(Name  :: ranch:ref(),
-        Key   :: atom(),
-        Value :: any())
-    -> ok
-

Set or update an environment value for a previously started -listener.

-

This is most useful for updating the routes dynamically, -without having to restart the listener.

-

The new value will only be available to new connections. -Pre-existing connections will still use the old value.

-
-
-
+
set_env(Name  :: ranch:ref(),
+        Key   :: atom(),
+        Value :: any())
+    -> ok
+
+

Set or update an environment value for a previously started listener.

+

This is most useful for updating the routes dynamically, without having to restart the listener.

+

The new value will only be available to new connections. Pre-existing connections will still use the old value.

Arguments

-
-
-
-Name -
-
-

-The name of the listener to update. -

-

The name of the listener is the first argument given to the -cowboy:start_clear(3), -cowboy:start_tls(3) or -ranch:start_listener(3) function.

+
Name
+

The name of the listener to update.

+

The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function.

-
-Key -
-
-

-The key in the environment map. Common keys include dispatch -and middlewares. -

+
Key
+

The key in the environment map. Common keys include dispatch and middlewares.

-
-Value -
-
-

-The new value. -

-

The type of the value differs depending on the key.

+
Value
+

The new value.

+

The type of the value differs depending on the key.

-
-
- -
+

Return value

-
-

The atom ok is returned on success.

-

An exit:badarg exception is thrown when the listener does -not exist.

-
-
-
+

The atom ok is returned on success.

+

An exit:badarg exception is thrown when the listener does not exist.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Update a listener’s routes
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []},
-        {"/ws", websocket_h, []}
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []},
+        {"/ws", websocket_h, []}
     ]}
 ]),
 
-cowboy:set_env(example, dispatch, Dispatch).
-
-
-
+cowboy:set_env(example, dispatch, Dispatch). +

See also

- - +

cowboy(3), cowboy:start_clear(3), cowboy:start_tls(3), ranch:set_protocol_options(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy.start_clear/index.html b/docs/en/cowboy/2.2/manual/cowboy.start_clear/index.html index 0893ad36..0aa7db74 100644 --- a/docs/en/cowboy/2.2/manual/cowboy.start_clear/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy.start_clear/index.html @@ -62,148 +62,77 @@

cowboy:start_clear(3)

-

Name

-
-

cowboy:start_clear - Listen for connections using plain TCP

-
-
-
+

cowboy:start_clear - Listen for connections using plain TCP

Description

-
-
-
-
start_clear(Name          :: ranch:ref(),
-            TransportOpts :: ranch_tcp:opts(),
-            ProtocolOpts  :: opts())
-    -> {ok, ListenerPid :: pid()}
-     | {error, any()}
-

Start listening for connections over a clear TCP channel.

-

Both HTTP/1.1 and HTTP/2 are supported on this listener. -HTTP/2 has two methods of establishing a connection over -a clear TCP channel. Both the upgrade and the prior knowledge -methods are supported.

-
-
-
+
start_clear(Name          :: ranch:ref(),
+            TransportOpts :: ranch_tcp:opts(),
+            ProtocolOpts  :: opts())
+    -> {ok, ListenerPid :: pid()}
+     | {error, any()}
+
+

Start listening for connections over a clear TCP channel.

+

Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported.

Arguments

-
-
-
-Name -
-
-

-The listener name is used to refer to this listener in -future calls, for example when stopping it or when -updating the routes defined. -

-

It can be any Erlang term. An atom is generally good enough, -for example api, my_app_clear or my_app_tls.

+
Name
+

The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined.

+

It can be any Erlang term. An atom is generally good enough, for example api, my_app_clear or my_app_tls.

-
-TransportOpts -
-
-

-The transport options are where the TCP options, including -the listener’s port number, are defined. Transport options -are provided as a list of keys and values, for example -[{port, 8080}]. -

-

The available options are documented in the -ranch_tcp(3) manual.

+
TransportOpts
+

The transport options are where the TCP options, including the listener's port number, are defined. Transport options are provided as a list of keys and values, for example [{port, 8080}].

+

The available options are documented in the ranch_tcp(3) manual.

-
-ProtocolOpts -
-
-

-The protocol options are in a map containing all the options for -the different protocols that may be involved when connecting -to the listener, including HTTP/1.1 and HTTP/2. -

-

The HTTP/1.1 options are documented in the -cowboy_http(3) manual; -and the HTTP/2 options in -cowboy_http2(3).

+
ProtocolOpts
+

The protocol options are in a map containing all the options for the different protocols that may be involved when connecting to the listener, including HTTP/1.1 and HTTP/2.

+

The HTTP/1.1 options are documented in the cowboy_http(3) manual; and the HTTP/2 options in cowboy_http2(3).

-
-
- -
+

Return value

-
-

An ok tuple is returned on success. It contains the pid of -the top-level supervisor for the listener.

-

An error tuple is returned on error. The error reason may -be any Erlang term.

-

A common error is eaddrinuse. It indicates that the port -configured for Cowboy is already in use.

-
-
-
+

An ok tuple is returned on success. It contains the pid of the top-level supervisor for the listener.

+

An error tuple is returned on error. The error reason may be any Erlang term.

+

A common error is eaddrinuse. It indicates that the port configured for Cowboy is already in use.

Changelog

-
-
    -
  • -

    -2.0: HTTP/2 support added. -

    +
    • 2.0: HTTP/2 support added.
    • -
    • -

      -2.0: Function introduced. Replaces cowboy:start_http/4. -

      +
    • 2.0: Function introduced. Replaces cowboy:start_http/4.
    • -
-
-
-
+

Examples

-
-
-
Start a listener
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []}
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []}
     ]}
 ]),
 
-{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{
-    env => #{dispatch => Dispatch}
-}).
-
-
Start a listener on a random port
-
-
Name = example,
+
Name = example,
 
-{ok, _} = cowboy:start_clear(Name, [], #{
-    env => #{dispatch => Dispatch}
+{ok, _} = cowboy:start_clear(Name, [], #{
+    env => #{dispatch => Dispatch}
 }),
 
-Port = ranch:get_port(Name).
-
-
-
+Port = ranch:get_port(Name). +

See also

- - +

cowboy(3), cowboy:start_tls(3), cowboy:stop_listener(3), ranch(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy.start_tls/index.html b/docs/en/cowboy/2.2/manual/cowboy.start_tls/index.html index cfac1e63..71a6cffe 100644 --- a/docs/en/cowboy/2.2/manual/cowboy.start_tls/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy.start_tls/index.html @@ -62,153 +62,82 @@

cowboy:start_tls(3)

-

Name

-
-

cowboy:start_tls - Listen for connections using TLS

-
-
-
+

cowboy:start_tls - Listen for connections using TLS

Description

-
-
-
-
start_tls(Name          :: ranch:ref(),
-          TransportOpts :: ranch_ssl:opts(),
-          ProtocolOpts  :: opts())
-    -> {ok, ListenerPid :: pid()}
-     | {error, any()}
-

Start listening for connections over a secure TLS channel.

-

Both HTTP/1.1 and HTTP/2 are supported on this listener. -The ALPN TLS extension must be used to initiate an HTTP/2 -connection.

-
-
-
+
start_tls(Name          :: ranch:ref(),
+          TransportOpts :: ranch_ssl:opts(),
+          ProtocolOpts  :: opts())
+    -> {ok, ListenerPid :: pid()}
+     | {error, any()}
+
+

Start listening for connections over a secure TLS channel.

+

Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection.

Arguments

-
-
-
-Name -
-
-

-The listener name is used to refer to this listener in -future calls, for example when stopping it or when -updating the routes defined. -

-

It can be any Erlang term. An atom is generally good enough, -for example api, my_app_clear or my_app_tls.

+
Name
+

The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined.

+

It can be any Erlang term. An atom is generally good enough, for example api, my_app_clear or my_app_tls.

-
-TransportOpts -
-
-

-The transport options are where the TCP options, including -the listener’s port number, are defined. They also contain -the TLS options, like the server’s certificate. Transport options -are provided as a list of keys and values, for example -[{port, 8443}, {certfile, "path/to/cert.pem"}]. -

-

The available options are documented in the -ranch_ssl(3) manual.

+
TransportOpts
+

The transport options are where the TCP options, including the listener's port number, are defined. They also contain the TLS options, like the server's certificate. Transport options are provided as a list of keys and values, for example [{port, 8443}, {certfile, "path/to/cert.pem"}].

+

The available options are documented in the ranch_ssl(3) manual.

-
-ProtocolOpts -
-
-

-The protocol options are in a map containing all the options for -the different protocols that may be involved when connecting -to the listener, including HTTP/1.1 and HTTP/2. -

-

The HTTP/1.1 options are documented in the -cowboy_http(3) manual; -and the HTTP/2 options in -cowboy_http2(3).

+
ProtocolOpts
+

The protocol options are in a map containing all the options for the different protocols that may be involved when connecting to the listener, including HTTP/1.1 and HTTP/2.

+

The HTTP/1.1 options are documented in the cowboy_http(3) manual; and the HTTP/2 options in cowboy_http2(3).

-
-
- -
+

Return value

-
-

An ok tuple is returned on success. It contains the pid of -the top-level supervisor for the listener.

-

An error tuple is returned on error. The error reason may -be any Erlang term.

-

A common error is eaddrinuse. It indicates that the port -configured for Cowboy is already in use.

-
-
-
+

An ok tuple is returned on success. It contains the pid of the top-level supervisor for the listener.

+

An error tuple is returned on error. The error reason may be any Erlang term.

+

A common error is eaddrinuse. It indicates that the port configured for Cowboy is already in use.

Changelog

-
-
    -
  • -

    -2.0: HTTP/2 support added. -

    +
    • 2.0: HTTP/2 support added.
    • -
    • -

      -2.0: Function introduced. Replaces cowboy:start_https/4. -

      +
    • 2.0: Function introduced. Replaces cowboy:start_https/4.
    • -
-
-
-
+

Examples

-
-
-
Start a listener
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []}
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []}
     ]}
 ]),
 
-{ok, _} = cowboy:start_tls(example, [
-    {port, 8443},
-    {cert, "path/to/cert.pem"}
+{ok, _} = cowboy:start_tls(example, [
+    {port, 8443},
+    {cert, "path/to/cert.pem"}
 ], #{
-    env => #{dispatch => Dispatch}
-}).
-
-
Start a listener on a random port
-
-
Name = example,
+
Name = example,
 
-{ok, _} = cowboy:start_tls(Name, [
-    {cert, "path/to/cert.pem"}
+{ok, _} = cowboy:start_tls(Name, [
+    {cert, "path/to/cert.pem"}
 ], #{
-    env => #{dispatch => Dispatch}
+    env => #{dispatch => Dispatch}
 }),
 
-Port = ranch:get_port(Name).
-
-
-
+Port = ranch:get_port(Name). +

See also

- - +

cowboy(3), cowboy:start_clear(3), cowboy:stop_listener(3), ranch(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy.stop_listener/index.html b/docs/en/cowboy/2.2/manual/cowboy.stop_listener/index.html index 253f9b08..4941b0b3 100644 --- a/docs/en/cowboy/2.2/manual/cowboy.stop_listener/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy.stop_listener/index.html @@ -62,87 +62,42 @@

cowboy:stop_listener(3)

-

Name

-
-

cowboy:stop_listener - Stop the given listener

-
-
-
+

cowboy:stop_listener - Stop the given listener

Description

-
-
-
-
stop_listener(Name :: ranch:ref())
-    -> ok | {error, not_found}.
-

Stop a previously started listener.

- -
-
-
+
stop_listener(Name :: ranch:ref())
+    -> ok | {error, not_found}.
+
+

Stop a previously started listener.

+

Alias of ranch:stop_listener(3).

Arguments

-
-
-
-Name -
-
-

-The name of the listener to be stopped. -

-

The name of the listener is the first argument given to the -cowboy:start_clear(3), -cowboy:start_tls(3) or -ranch:start_listener(3) function.

+
Name
+

The name of the listener to be stopped.

+

The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function.

-
-
- -
+

Return value

-
-

The atom ok is returned on success.

-

The {error, not_found} tuple is returned when the listener -does not exist.

-
-
-
+

The atom ok is returned on success.

+

The {error, not_found} tuple is returned when the listener does not exist.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Stop a listener
-
-
ok = cowboy:stop_listener(example).
-
-
-
+
ok = cowboy:stop_listener(example).
+

See also

- - +

cowboy(3), cowboy:start_clear(3), cowboy:start_tls(3), ranch(3), ranch:start_listener(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy/index.html b/docs/en/cowboy/2.2/manual/cowboy/index.html index f75e2b17..e2805b79 100644 --- a/docs/en/cowboy/2.2/manual/cowboy/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy/index.html @@ -62,129 +62,76 @@

cowboy(3)

-

Name

-
-

cowboy - HTTP server

-
-
-
+

cowboy - HTTP server

Description

-
-

The module cowboy provides convenience functions for -manipulating Ranch listeners.

-
-
-
+

The module cowboy provides convenience functions for manipulating Ranch listeners.

Exports

-
-
-
-
-
+

Types

-
-

fields()

-
-
-
fields() :: [Name
-           | {Name, Constraints}
-           | {Name, Constraints, Default}]
-
-Name        :: atom()
-Constraints :: Constraint | [Constraint]
-Constraint  :: cowboy_constraints:constraint()
-Default     :: any()
-

Fields description for match operations.

-

This type is used in cowboy_router(3) -for matching bindings and in the match functions found in -cowboy_req(3).

-
-
+
fields() :: [Name
+           | {Name, Constraints}
+           | {Name, Constraints, Default}]
+
+Name        :: atom()
+Constraints :: Constraint | [Constraint]
+Constraint  :: cowboy_constraints:constraint()
+Default     :: any()
+
+

Fields description for match operations.

+

This type is used in cowboy_router(3) for matching bindings and in the match functions found in cowboy_req(3).

http_headers()

-
-
-
http_headers() :: #{binary() => iodata()}
-

HTTP headers.

-
-
+
http_headers() :: #{binary() => iodata()}
+
+

HTTP headers.

http_status()

-
-
-
http_status() :: non_neg_integer() | binary()
-

HTTP response status.

-

A binary status can be used to set a reason phrase. Note -however that HTTP/2 only sends the status code and drops -the reason phrase entirely.

- -
+
http_status() :: non_neg_integer() | binary()
+
+

HTTP response status.

+

A binary status can be used to set a reason phrase. Note however that HTTP/2 only sends the status code and drops the reason phrase entirely.

http_version()

-
-
-
http_version() :: 'HTTP/2' | 'HTTP/1.1' | 'HTTP/1.0'
-

HTTP version.

-

Note that semantically, HTTP/1.1 and HTTP/2 are equivalent.

- -
+
http_version() :: 'HTTP/2' | 'HTTP/1.1' | 'HTTP/1.0'
+
+

HTTP version.

+

Note that semantically, HTTP/1.1 and HTTP/2 are equivalent.

opts()

-
-
-
opts() :: map()
-

Options for the HTTP/1.1, HTTP/2 and Websocket protocols.

-

The protocol options are in a map containing all the options for -the different protocols that may be involved when connecting -to the listener, including HTTP/1.1 and HTTP/2.

-

The HTTP/1.1 options are documented in the -cowboy_http(3) manual -and the HTTP/2 options in -cowboy_http2(3).

- - - -
+
opts() :: map()
+
+

Options for the HTTP/1.1, HTTP/2 and Websocket protocols.

+

The protocol options are in a map containing all the options for the different protocols that may be involved when connecting to the listener, including HTTP/1.1 and HTTP/2.

+

The HTTP/1.1 options are documented in the cowboy_http(3) manual and the HTTP/2 options in cowboy_http2(3).

See also

- - +

cowboy(7), ranch(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_app/index.html b/docs/en/cowboy/2.2/manual/cowboy_app/index.html index 3f1d1e1e..b09e4cbd 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_app/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_app/index.html @@ -62,171 +62,77 @@

cowboy(7)

-

Name

-
-

cowboy - Small, fast, modern HTTP server for Erlang/OTP

-
-
-
+

cowboy - Small, fast, modern HTTP server for Erlang/OTP

Description

-
-

Cowboy is an HTTP server for Erlang/OTP with support for the -HTTP/1.1, HTTP/2 and Websocket protocols.

-

Cowboy aims to provide a complete HTTP stack. This includes -the implementation of the HTTP RFCs but also any directly -related standards, like Websocket or Server-Sent Events.

-
-
-
+

Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols.

+

Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events.

Modules

-
-

Functions:

-
-

Protocols:

-
+

Protocols:

+
-

Handlers:

-
+

Handlers:

+
-

Behaviors:

-
+

Behaviors:

+
-

Middlewares:

-
+

Middlewares:

+
-
-
-
+ +

Dependencies

-
-
    -
  • -

    -ranch(7) - Socket acceptor pool for TCP protocols -

    +
    • ranch(7) - Socket acceptor pool for TCP protocols
    • -
    • -

      -cowlib(7) - Support library for manipulating Web protocols -

      +
    • cowlib(7) - Support library for manipulating Web protocols
    • -
    • -

      -ssl - Secure communication over sockets -

      +
    • ssl - Secure communication over sockets
    • -
    • -

      -crypto - Crypto functions -

      +
    • crypto - Crypto functions
    • -
-

All these applications must be started before the cowboy -application. To start Cowboy and all dependencies at once:

-
-
-
{ok, _} = application:ensure_all_started(cowboy).
-
-
-
+
{ok, _} = application:ensure_all_started(cowboy).
+

Environment

-
-

The cowboy application does not define any application -environment configuration parameters.

-
- -
+

The cowboy application does not define any application environment configuration parameters.

See also

- -
+

ranch(7), cowlib(7)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_constraints.int/index.html b/docs/en/cowboy/2.2/manual/cowboy_constraints.int/index.html index 7b943d1b..f2274322 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_constraints.int/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_constraints.int/index.html @@ -62,92 +62,52 @@

cowboy_constraints:int(3)

-

Name

-
-

cowboy_constraints:int - Integer constraint

-
-
-
+

cowboy_constraints:int - Integer constraint

Description

-
-

Constraint functions implement a number of different operations.

-
-
-
int(forward, Bin) -> {ok, Int} | {error, not_an_integer}
+
int(forward, Bin) -> {ok, Int} | {error, not_an_integer}
 
-Bin :: binary()
-Int :: integer()
-

Validate and convert the text representation of an integer.

-
-
-
int(reverse, Int) -> {ok, Bin} | {error, not_an_integer}
-

Convert an integer back to its text representation.

-
-
-
int(format_error, Error) -> HumanReadable
+
int(format_error, Error) -> HumanReadable
 
-Error         :: {not_an_integer, Bin | Int}
-HumanReadable :: iolist()
-

Generate a human-readable error message.

-
-
-
+Error :: {not_an_integer, Bin | Int} +HumanReadable :: iolist() +
+

Generate a human-readable error message.

Arguments

-
-

Arguments vary depending on the operation. Constraint -functions always take the operation type as first argument, -and the value as second argument.

-
- -
+

Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument.

Return value

-
-

The return value varies depending on the operation.

-
-
-
+

The return value varies depending on the operation.

Changelog

-
-
    -
  • -

    -2.0: Interface modified to allow for a variety of operations. -

    +
    • 2.0: Interface modified to allow for a variety of operations.
    • -
    • -

      -1.0: Constraint introduced. -

      +
    • 1.0: Constraint introduced.
    • -
-
-
-
+

Examples

-
-

This function is not meant to be called directly.

-
-
-
+

This function is not meant to be called directly.

See also

- -
+

cowboy_constraints(3), cowboy_constraints:nonempty(3), cowboy_router(3), cowboy_req:match_cookies(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_constraints.nonempty/index.html b/docs/en/cowboy/2.2/manual/cowboy_constraints.nonempty/index.html index facd0167..b287ca1a 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_constraints.nonempty/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_constraints.nonempty/index.html @@ -62,91 +62,51 @@

cowboy_constraints:nonempty(3)

-

Name

-
-

cowboy_constraints:nonempty - Non-empty constraint

-
-
-
+

cowboy_constraints:nonempty - Non-empty constraint

Description

-
-

Constraint functions implement a number of different operations.

-
-
-
nonempty(forward | reverse, <<>>) -> {error, empty}
-

Reject empty values.

-
-
-
nonempty(forward | reverse, Bin) -> {ok, Bin}
+
nonempty(forward | reverse, Bin) -> {ok, Bin}
 
-Bin :: binary()
-

Accept any other binary values.

-
-
-
nonempty(format_error, Error) -> HumanReadable
+
nonempty(format_error, Error) -> HumanReadable
 
-Error         :: {empty, Bin}
-HumanReadable :: iolist()
-

Generate a human-readable error message.

-
-
-
+Error :: {empty, Bin} +HumanReadable :: iolist() +
+

Generate a human-readable error message.

Arguments

-
-

Arguments vary depending on the operation. Constraint -functions always take the operation type as first argument, -and the value as second argument.

-
- -
+

Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument.

Return value

-
-

The return value varies depending on the operation.

-
-
-
+

The return value varies depending on the operation.

Changelog

-
-
    -
  • -

    -2.0: Interface modified to allow for a variety of operations. -

    +
    • 2.0: Interface modified to allow for a variety of operations.
    • -
    • -

      -1.0: Constraint introduced. -

      +
    • 1.0: Constraint introduced.
    • -
-
-
-
+

Examples

-
-

This function is not meant to be called directly.

-
-
-
+

This function is not meant to be called directly.

See also

- -
+

cowboy_constraints(3), cowboy_constraints:int(3), cowboy_router(3), cowboy_req:match_cookies(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_constraints/index.html b/docs/en/cowboy/2.2/manual/cowboy_constraints/index.html index 98a7305d..d5005eff 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_constraints/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_constraints/index.html @@ -62,84 +62,43 @@

cowboy_constraints(3)

-

Name

-
-

cowboy_constraints - Constraints

-
-
-
+

cowboy_constraints - Constraints

Description

-
-

The module cowboy_constraints defines the built-in -constraints in Cowboy and provides an interface for -manipulating these constraints.

-

Constraints are functions that define what type of -input is allowed. They are used throughout Cowboy, -from the router to query strings to cookies.

-
-
-
+

The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints.

+

Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies.

Exports

-
-

Built-in constraints:

-
-
-
-
+

Types

-
-

constraint()

-
-
-
constraint() :: int | nonempty | fun()
-

A constraint function.

-

The atom constraints are built-in, see the corresponding -function in the exports list above.

-
-
+
constraint() :: int | nonempty | fun()
+
+

A constraint function.

+

The atom constraints are built-in, see the corresponding function in the exports list above.

reason()

-
-
-
reason() :: {constraint(), Reason, Value}
-
-Reason :: any()
-Value  :: any()
-

Reason for the constraint failure.

-

It includes the constraint function in question, -a machine-readable error reason and the value that -made the constraint fail.

-
- - -
+
reason() :: {constraint(), Reason, Value}
+
+Reason :: any()
+Value  :: any()
+
+

Reason for the constraint failure.

+

It includes the constraint function in question, a machine-readable error reason and the value that made the constraint fail.

See also

- - +

cowboy(7), cowboy(3), cowboy_router(3), cowboy_req:match_cookies(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_handler.terminate/index.html b/docs/en/cowboy/2.2/manual/cowboy_handler.terminate/index.html index 5337a771..e5898676 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_handler.terminate/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_handler.terminate/index.html @@ -62,109 +62,54 @@

cowboy_handler:terminate(3)

-

Name

-
-

cowboy_handler:terminate - Terminate the handler

-
-
-
+

cowboy_handler:terminate - Terminate the handler

Description

-
-
-
-
terminate(Reason, PartialReq, State, Handler) -> ok
-
-Reason     :: any()
-PartialReq :: map()
-State      :: any()
-Handler    :: module()
-

Call the optional terminate callback if it is defined.

-

Make sure to use this function at the end of the execution -of modules that implement custom handler behaviors.

-
-
-
+
terminate(Reason, PartialReq, State, Handler) -> ok
+
+Reason     :: any()
+PartialReq :: map()
+State      :: any()
+Handler    :: module()
+
+

Call the optional terminate callback if it is defined.

+

Make sure to use this function at the end of the execution of modules that implement custom handler behaviors.

Arguments

-
-
-
-Reason -
-
-

-Reason for termination. -

+
Reason
+

Reason for termination.

-
-PartialReq -
-
-

-The Req object. -

-

It is possible to remove fields from the Req object to save memory -when the handler has no concept of requests/responses. The only -requirement is that a map is provided.

+
PartialReq
+

The Req object.

+

It is possible to remove fields from the Req object to save memory when the handler has no concept of requests/responses. The only requirement is that a map is provided.

-
-State -
-
-

-Handler state. -

+
State
+

Handler state.

-
-Handler -
-
-

-Handler module. -

+
Handler
+

Handler module.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Terminate a handler normally
-
-
cowboy_handler:terminate(normal, Req, State, Handler).
-
-
-
+
cowboy_handler:terminate(normal, Req, State, Handler).
+

See also

- - +

cowboy_handler(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_handler/index.html b/docs/en/cowboy/2.2/manual/cowboy_handler/index.html index 20503948..4556212d 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_handler/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_handler/index.html @@ -62,96 +62,46 @@

cowboy_handler(3)

-

Name

-
-

cowboy_handler - Plain HTTP handlers

-
-
-
+

cowboy_handler - Plain HTTP handlers

Description

-
-

The cowboy_handler middleware executes the handler selected -by the router or any other preceding middleware.

-

This middleware takes the handler module and initial state -from the handler and handler_opts environment values, -respectively. On completion, it adds a result value to -the middleware environment, containing the return value -of the terminate/3 callback (if defined) and ok otherwise.

-

This module also defines a callback interface for handling -HTTP requests.

-
-
-
+

The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware.

+

This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise.

+

This module also defines a callback interface for handling HTTP requests.

Callbacks

-
-

Plain HTTP handlers implement the following interface:

-
-
-
init(Req, State) -> {ok, Req, State}
-
-terminate(Reason, Req, State) -> ok  %% optional
-
-Req    :: cowboy_req:req()
-State  :: any()
-Reason :: normal
-        | {crash, error | exit | throw, any()}
-

These two callbacks are common to all handlers.

-

Plain HTTP handlers do all their work in the init/2 -callback. Returning ok terminates the handler. If no -response is sent, Cowboy will send a 204 No Content.

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the handler. -Cowboy will terminate the process right after this. There -is no need to perform any cleanup in this callback.

-

The following terminate reasons are defined for plain HTTP -handlers:

-
-
-normal -
-
-

- The connection was closed normally. -

+
init(Req, State) -> {ok, Req, State}
+
+terminate(Reason, Req, State) -> ok  %% optional
+
+Req    :: cowboy_req:req()
+State  :: any()
+Reason :: normal
+        | {crash, error | exit | throw, any()}
+
+

These two callbacks are common to all handlers.

+

Plain HTTP handlers do all their work in the init/2 callback. Returning ok terminates the handler. If no response is sent, Cowboy will send a 204 No Content.

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the handler. Cowboy will terminate the process right after this. There is no need to perform any cleanup in this callback.

+

The following terminate reasons are defined for plain HTTP handlers:

+
normal
+

The connection was closed normally.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
- - -
+

Exports

-
-

The following function should be called by modules implementing -custom handlers to execute the optional terminate callback:

-
-
-
-
+

See also

- -
+

cowboy(7)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_http/index.html b/docs/en/cowboy/2.2/manual/cowboy_http/index.html index b5dd9044..5b8550d6 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_http/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_http/index.html @@ -62,255 +62,116 @@

cowboy_http(3)

-

Name

-
-

cowboy_http - HTTP/1.1

-
-
-
+

cowboy_http - HTTP/1.1

Description

-
-

The module cowboy_http implements HTTP/1.1 and HTTP/1.0 -as a Ranch protocol.

-
-
-
+

The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol.

Options

-
-
-
+ +
-
opts() :: #{
-    connection_type         => worker | supervisor,
-    env                     => cowboy_middleware:env(),
-    idle_timeout            => timeout(),
-    inactivity_timeout      => timeout(),
-    max_empty_lines         => non_neg_integer(),
-    max_header_name_length  => non_neg_integer(),
-    max_header_value_length => non_neg_integer(),
-    max_headers             => non_neg_integer(),
-    max_keepalive           => non_neg_integer(),
-    max_method_length       => non_neg_integer(),
-    max_request_line_length => non_neg_integer(),
-    max_skip_body_length    => non_neg_integer(),
-    middlewares             => [module()],
-    request_timeout         => timeout(),
-    shutdown_timeout        => timeout(),
-    stream_handlers         => [module()]
-}
-

Configuration for the HTTP/1.1 protocol.

-

This configuration is passed to Cowboy when starting listeners -using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

-

It can be updated without restarting listeners using the -Ranch functions ranch:get_protocol_options/1 and -ranch:set_protocol_options/2.

-

The default value is given next to the option name:

-
-
-connection_type (supervisor) -
-
-

- Whether the connection process also acts as a supervisor. -

-
-
-env (#{}) -
-
-

- Middleware environment. -

-
-
-idle_timeout (60000) -
-
-

- Time in ms with no data received before Cowboy closes the connection. -

-
-
-inactivity_timeout (300000) -
-
-

- Time in ms with nothing received at all before Cowboy closes the connection. -

-
-
-max_empty_lines (5) -
-
-

- Maximum number of empty lines before a request. -

-
-
-max_header_name_length (64) -
-
-

- Maximum length of header names. -

-
-
-max_header_value_length (4096) -
-
-

- Maximum length of header values. -

-
-
-max_headers (100) -
-
-

- Maximum number of headers allowed per request. -

-
-
-max_keepalive (100) -
-
-

- Maximum number of requests allowed per connection. -

-
-
-max_method_length (32) -
-
-

- Maximum length of the method. -

-
-
-max_request_line_length (8000) -
-
-

- Maximum length of the request line. -

-
-
-max_skip_body_length (1000000) -
-
-

- Maximum length Cowboy is willing to skip when the user code did not read the body fully. - When the remaining length is too large or unknown Cowboy will close the connection. -

-
-
-middlewares ([cowboy_router, cowboy_handler]) -
-
-

- Middlewares to run for every request. -

-
-
-request_timeout (5000) -
-
-

- Time in ms with no requests before Cowboy closes the connection. -

-
-
-shutdown_timeout (5000) -
-
-

- Time in ms Cowboy will wait for child processes to shut down before killing them. -

-
-
-stream_handlers ([cowboy_stream_h]) -
-
-

- Ordered list of stream handlers that will handle all stream events. -

-
-
-
-
-
+
opts() :: #{
+    connection_type         => worker | supervisor,
+    env                     => cowboy_middleware:env(),
+    idle_timeout            => timeout(),
+    inactivity_timeout      => timeout(),
+    max_empty_lines         => non_neg_integer(),
+    max_header_name_length  => non_neg_integer(),
+    max_header_value_length => non_neg_integer(),
+    max_headers             => non_neg_integer(),
+    max_keepalive           => non_neg_integer(),
+    max_method_length       => non_neg_integer(),
+    max_request_line_length => non_neg_integer(),
+    max_skip_body_length    => non_neg_integer(),
+    middlewares             => [module()],
+    request_timeout         => timeout(),
+    shutdown_timeout        => timeout(),
+    stream_handlers         => [module()]
+}
+
+

Configuration for the HTTP/1.1 protocol.

+

This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

+

It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2.

+

The default value is given next to the option name:

+
connection_type (supervisor)
+

Whether the connection process also acts as a supervisor.

+
+
env (#{})
+

Middleware environment.

+
+
idle_timeout (60000)
+

Time in ms with no data received before Cowboy closes the connection.

+
+
inactivity_timeout (300000)
+

Time in ms with nothing received at all before Cowboy closes the connection.

+
+
max_empty_lines (5)
+

Maximum number of empty lines before a request.

+
+
max_header_name_length (64)
+

Maximum length of header names.

+
+
max_header_value_length (4096)
+

Maximum length of header values.

+
+
max_headers (100)
+

Maximum number of headers allowed per request.

+
+
max_keepalive (100)
+

Maximum number of requests allowed per connection.

+
+
max_method_length (32)
+

Maximum length of the method.

+
+
max_request_line_length (8000)
+

Maximum length of the request line.

+
+
max_skip_body_length (1000000)
+

Maximum length Cowboy is willing to skip when the user code did not read the body fully. When the remaining length is too large or unknown Cowboy will close the connection.

+
+
middlewares ([cowboy_router, cowboy_handler])
+

Middlewares to run for every request.

+
+
request_timeout (5000)
+

Time in ms with no requests before Cowboy closes the connection.

+
+
shutdown_timeout (5000)
+

Time in ms Cowboy will wait for child processes to shut down before killing them.

+
+
stream_handlers ([cowboy_stream_h])
+

Ordered list of stream handlers that will handle all stream events.

+
+

Changelog

-
-
    -
  • -

    -2.2: The max_skip_body_length option was added. -

    +
    • 2.2: The max_skip_body_length option was added.
    • -
    • -

      -2.0: The timeout option was renamed request_timeout. -

      +
    • 2.0: The timeout option was renamed request_timeout.
    • -
    • -

      -2.0: The idle_timeout, inactivity_timeout and shutdown_timeout options were added. -

      +
    • 2.0: The idle_timeout, inactivity_timeout and shutdown_timeout options were added.
    • -
    • -

      -2.0: The max_method_length option was added. -

      +
    • 2.0: The max_method_length option was added.
    • -
    • -

      -2.0: The max_request_line_length default was increased from 4096 to 8000. -

      +
    • 2.0: The max_request_line_length default was increased from 4096 to 8000.
    • -
    • -

      -2.0: The connection_type option was added. -

      +
    • 2.0: The connection_type option was added.
    • -
    • -

      -2.0: The env option is now a map instead of a proplist. -

      +
    • 2.0: The env option is now a map instead of a proplist.
    • -
    • -

      -2.0: The stream_handlers option was added. -

      +
    • 2.0: The stream_handlers option was added.
    • -
    • -

      -2.0: The compress option was removed in favor of the cowboy_compress_h stream handler. -

      +
    • 2.0: The compress option was removed in favor of the cowboy_compress_h stream handler.
    • -
    • -

      -2.0: Options are now a map instead of a proplist. -

      +
    • 2.0: Options are now a map instead of a proplist.
    • -
    • -

      -2.0: Protocol introduced. Replaces cowboy_protocol. -

      +
    • 2.0: Protocol introduced. Replaces cowboy_protocol.
    • -
-
-
- +

cowboy(7), cowboy_http2(3), cowboy_websocket(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_http2/index.html b/docs/en/cowboy/2.2/manual/cowboy_http2/index.html index 46bfd807..e93e2e4c 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_http2/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_http2/index.html @@ -62,123 +62,60 @@

cowboy_http2(3)

-

Name

-
-

cowboy_http2 - HTTP/2

-
-
-
+

cowboy_http2 - HTTP/2

Description

-
-

The module cowboy_http2 implements HTTP/2 -as a Ranch protocol.

-
-
-
+

The module cowboy_http2 implements HTTP/2 as a Ranch protocol.

Options

-
-
-
+ +
-
opts() :: #{
-    connection_type    => worker | supervisor,
-    env                => cowboy_middleware:env(),
-    inactivity_timeout => timeout(),
-    middlewares        => [module()],
-    preface_timeout    => timeout(),
-    shutdown_timeout   => timeout(),
-    stream_handlers    => [module()]
-}
-

Configuration for the HTTP/2 protocol.

-

This configuration is passed to Cowboy when starting listeners -using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

-

It can be updated without restarting listeners using the -Ranch functions ranch:get_protocol_options/1 and -ranch:set_protocol_options/2.

-

The default value is given next to the option name:

-
-
-connection_type (supervisor) -
-
-

- Whether the connection process also acts as a supervisor. -

+
opts() :: #{
+    connection_type    => worker | supervisor,
+    env                => cowboy_middleware:env(),
+    inactivity_timeout => timeout(),
+    middlewares        => [module()],
+    preface_timeout    => timeout(),
+    shutdown_timeout   => timeout(),
+    stream_handlers    => [module()]
+}
+
+

Configuration for the HTTP/2 protocol.

+

This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

+

It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2.

+

The default value is given next to the option name:

+
connection_type (supervisor)
+

Whether the connection process also acts as a supervisor.

-
-env (#{}) -
-
-

- Middleware environment. -

+
env (#{})
+

Middleware environment.

-
-inactivity_timeout (300000) -
-
-

- Time in ms with nothing received at all before Cowboy closes the connection. -

+
inactivity_timeout (300000)
+

Time in ms with nothing received at all before Cowboy closes the connection.

-
-middlewares ([cowboy_router, cowboy_handler]) -
-
-

- Middlewares to run for every request. -

+
middlewares ([cowboy_router, cowboy_handler])
+

Middlewares to run for every request.

-
-preface_timeout (5000) -
-
-

- Time in ms Cowboy is willing to wait for the connection preface. -

+
preface_timeout (5000)
+

Time in ms Cowboy is willing to wait for the connection preface.

-
-shutdown_timeout (5000) -
-
-

- Time in ms Cowboy will wait for child processes to shut down before killing them. -

+
shutdown_timeout (5000)
+

Time in ms Cowboy will wait for child processes to shut down before killing them.

-
-stream_handlers ([cowboy_stream_h]) -
-
-

- Ordered list of stream handlers that will handle all stream events. -

+
stream_handlers ([cowboy_stream_h])
+

Ordered list of stream handlers that will handle all stream events.

-
-
-
-
+

Changelog

-
-
    -
  • -

    -2.0: Protocol introduced. -

    +
    • 2.0: Protocol introduced.
    • -
-
-
- +

cowboy(7), cowboy_http(3), cowboy_websocket(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_loop/index.html b/docs/en/cowboy/2.2/manual/cowboy_loop/index.html index ac091fb4..22c782de 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_loop/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_loop/index.html @@ -62,120 +62,60 @@

cowboy_loop(3)

-

Name

-
-

cowboy_loop - Loop handlers

-
-
-
+

cowboy_loop - Loop handlers

Description

-
-

The module cowboy_loop defines a callback interface for -long running HTTP connections.

-

You should switch to this behavior for long polling, -server-sent events and similar long-running requests.

-

There are generally two usage patterns:

-
    -
  • -

    -Loop until receiving a specific message, then send - a response and stop execution (for example long polling); -

    +

    The module cowboy_loop defines a callback interface for long running HTTP connections.

    +

    You should switch to this behavior for long polling, server-sent events and similar long-running requests.

    +

    There are generally two usage patterns:

    +
    • Loop until receiving a specific message, then send a response and stop execution (for example long polling);
    • -
    • -

      -Or initiate a response in init/2 and stream the - body in info/3 as necessary (for example server-sent events). -

      +
    • Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events).
    • -
-
-
-
+

Callbacks

-
-

Loop handlers implement the following interface:

-
-
-
init(Req, State)
-    -> {cowboy_loop, Req, State}
-     | {cowboy_loop, Req, State, hibernate}
-
-info(Info, Req, State)
-    -> {ok, Req, State}
-     | {ok, Req, State, hibernate}
-     | {stop, Req, State}
-
-terminate(Reason, Req, State) -> ok  %% optional
-
-Req    :: cowboy_req:req()
-State  :: any()
-Info   :: any()
-Reason :: stop
-        | {crash, error | exit | throw, any()}
-

The init/2 callback is common to all handlers. To switch -to the loop behavior, it must return cowboy_loop as the -first element of the tuple.

-

The info/3 callback will be called for every Erlang message -received. It may choose to continue the receive loop or stop -it.

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the handler. -Cowboy will terminate the process right after this. There -is no need to perform any cleanup in this callback.

-

The following terminate reasons are defined for loop handlers:

-
-
-stop -
-
-

- The handler requested to close the connection by returning - a stop tuple. -

+
init(Req, State)
+    -> {cowboy_loop, Req, State}
+     | {cowboy_loop, Req, State, hibernate}
+
+info(Info, Req, State)
+    -> {ok, Req, State}
+     | {ok, Req, State, hibernate}
+     | {stop, Req, State}
+
+terminate(Reason, Req, State) -> ok  %% optional
+
+Req    :: cowboy_req:req()
+State  :: any()
+Info   :: any()
+Reason :: stop
+        | {crash, error | exit | throw, any()}
+
+

The init/2 callback is common to all handlers. To switch to the loop behavior, it must return cowboy_loop as the first element of the tuple.

+

The info/3 callback will be called for every Erlang message received. It may choose to continue the receive loop or stop it.

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the handler. Cowboy will terminate the process right after this. There is no need to perform any cleanup in this callback.

+

The following terminate reasons are defined for loop handlers:

+
stop
+

The handler requested to close the connection by returning a stop tuple.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
- - -
+

Changelog

-
-
    -
  • -

    -2.0: Loop handlers no longer need to handle overflow/timeouts. -

    +
    • 2.0: Loop handlers no longer need to handle overflow/timeouts.
    • -
    • -

      -1.0: Behavior introduced. -

      +
    • 1.0: Behavior introduced.
    • -
-
-
-
+

See also

- -
+

cowboy(7), cowboy_handler(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_middleware/index.html b/docs/en/cowboy/2.2/manual/cowboy_middleware/index.html index 063d9d98..fcd1acaa 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_middleware/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_middleware/index.html @@ -62,115 +62,56 @@

cowboy_middleware(3)

-

Name

-
-

cowboy_middleware - Middlewares

-
-
-
+

cowboy_middleware - Middlewares

Description

-
-

The module cowboy_middleware defines a callback interface for -Cowboy middlewares.

-

Middlewares process the request sequentially in the order they -are configured.

-
-
-
+

The module cowboy_middleware defines a callback interface for Cowboy middlewares.

+

Middlewares process the request sequentially in the order they are configured.

Callbacks

-
-

Middlewares implement the following interface:

-
-
-
execute(Req, Env)
-    -> {ok, Req, Env}
-     | {suspend, module(), atom(), [any()]}
-     | {stop, Req}
-
-Req :: cowboy_req:req()
-Env :: cowboy_middleware:env()
-

The execute/2 is the only callback that needs to be -implemented. It must execute the middleware and return -with instructions for Cowboy.

-
-
-ok -
-
-

-Cowboy should continue processing the request using the -returned Req object and environment. -

+
execute(Req, Env)
+    -> {ok, Req, Env}
+     | {suspend, module(), atom(), [any()]}
+     | {stop, Req}
+
+Req :: cowboy_req:req()
+Env :: cowboy_middleware:env()
+
+

The execute/2 is the only callback that needs to be implemented. It must execute the middleware and return with instructions for Cowboy.

+
ok
+

Cowboy should continue processing the request using the returned Req object and environment.

-
-suspend -
-
-

-Cowboy will hibernate the process. When resuming, Cowboy -will apply the returned module, function and arguments. -

+
suspend
+

Cowboy will hibernate the process. When resuming, Cowboy will apply the returned module, function and arguments.

-
-stop -
-
-

-Cowboy will stop middleware execution. No other middleware -will be executed. This effectively ends the processing of -the request. -

+
stop
+

Cowboy will stop middleware execution. No other middleware will be executed. This effectively ends the processing of the request.

-
- - -
+

Types

-
-

env()

-
-
-
env() :: #{atom() => any()}
-

Middleware environment.

-

A new environment is created for every request. The initial -environment contained the user configured environment values -(like dispatch for example) plus the listener value which -contains the name of the listener for this connection.

-

Middlewares may modify the environment as necessary.

-
-
-
-
+
env() :: #{atom() => any()}
+
+

Middleware environment.

+

A new environment is created for every request. The initial environment contained the user configured environment values (like dispatch for example) plus the listener value which contains the name of the listener for this connection.

+

Middlewares may modify the environment as necessary.

Changelog

-
-
    -
  • -

    -2.0: The env type is now a map instead of a proplist. -

    +
    • 2.0: The env type is now a map instead of a proplist.
    • -
    • -

      -1.0: Behavior introduced. -

      +
    • 1.0: Behavior introduced.
    • -
-
- -
+

See also

- -
+

cowboy(7)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.binding/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.binding/index.html index d588558e..ec5d9b34 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.binding/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.binding/index.html @@ -62,116 +62,60 @@

cowboy_req:binding(3)

-

Name

-
-

cowboy_req:binding - Access a value bound from the route

-
-
-
+

cowboy_req:binding - Access a value bound from the route

Description

-
-
-
-
binding(Name, Req)          -> binding(Name, Req, undefined)
-binding(Name, Req, Default) -> any() | Default
-
-Name    :: atom()
-Req     :: cowboy_req:req()
-Default :: any()
-

Return the value for the given binding.

-
-
-
+
binding(Name, Req)          -> binding(Name, Req, undefined)
+binding(Name, Req, Default) -> any() | Default
+
+Name    :: atom()
+Req     :: cowboy_req:req()
+Default :: any()
+
+

Return the value for the given binding.

Arguments

-
-
-
-Name -
-
-

-Desired binding name as an atom. -

+
Name
+

Desired binding name as an atom.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the binding is missing. -

+
Default
+

Default value returned when the binding is missing.

-
-
- -
+

Return value

-
-

By default the value is a case sensitive binary string, however -constraints may change the type of this value (for example -automatically converting numbers to integer).

-
-
-
+

By default the value is a case sensitive binary string, however constraints may change the type of this value (for example automatically converting numbers to integer).

Changelog

-
-
    -
  • -

    -2.0: Only the value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the username from the path
-
-
%% Route is "/users/:user"
-Username = cowboy_req:binding(user, Req).
-
-
Get the branch name, with a default
-
-
%% Route is "/log[/:branch]"
-Branch = cowboy_req:binding(branch, Req, <<"master">>)
-
-
-
+
%% Route is "/log[/:branch]"
+Branch = cowboy_req:binding(branch, Req, <<"master">>)
+

See also

- - +

cowboy_req(3), cowboy_req:bindings(3), cowboy_req:host_info(3), cowboy_req:path_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.bindings/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.bindings/index.html index 5a869543..c767fc26 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.bindings/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.bindings/index.html @@ -62,86 +62,40 @@

cowboy_req:bindings(3)

-

Name

-
-

cowboy_req:bindings - Access all values bound from the route

-
-
-
+

cowboy_req:bindings - Access all values bound from the route

Description

-
-
-
-
bindings(Req :: cowboy_req:req()) -> cowboy_router:bindings()
-

Return a map containing all bindings.

-
-
-
+
bindings(Req :: cowboy_req:req()) -> cowboy_router:bindings()
+
+

Return a map containing all bindings.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

By default values are case sensitive binary strings, however -constraints may change the type of this value (for example -automatically converting numbers to integer).

-
-
-
+

By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer).

Changelog

-
-
    -
  • -

    -2.0: Only the values are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the values are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get all bindings
-
-
Bindings = cowboy_req:bindings(Req).
-
-
-
+
Bindings = cowboy_req:bindings(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:host_info(3), cowboy_req:path_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.body_length/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.body_length/index.html index 824bf4e1..9d9ee111 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.body_length/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.body_length/index.html @@ -62,89 +62,41 @@

cowboy_req:body_length(3)

-

Name

-
-

cowboy_req:body_length - Body length

-
-
-
+

cowboy_req:body_length - Body length

Description

-
-
-
-
body_length(Req :: cowboy_req:req()) -> undefined | non_neg_integer()
-

Return the length of the request body.

-

The length is not always known before reading the body. -In those cases Cowboy will return undefined. The body -length is available after the body has been fully read.

-
-
-
+
body_length(Req :: cowboy_req:req()) -> undefined | non_neg_integer()
+
+

Return the length of the request body.

+

The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The length of the request body, or undefined if it is -not known.

-
-
-
+

The length of the request body, or undefined if it is not known.

Changelog

-
-
    -
  • -

    -2.0: Only the length is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the length is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the body length
-
-
Length = cowboy_req:body_length(Req).
-
-
-
+
Length = cowboy_req:body_length(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.cert/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.cert/index.html index 4aac5b14..b156f21b 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.cert/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.cert/index.html @@ -62,104 +62,60 @@

cowboy_req:cert(3)

-

Name

-
-

cowboy_req:cert - Client TLS certificate

-
-
-
+

cowboy_req:cert - Client TLS certificate

Description

-
-
-
-
cert(Req :: cowboy_req:req()) -> binary() | undefined
-

Return the peer’s TLS certificate.

-

Using the default configuration this function will always return -undefined. You need to explicitly configure Cowboy to request -the client certificate. To do this you need to set the verify -transport option to verify_peer:

-
-
-
{ok, _} = cowboy:start_tls(example, [
-    {port, 8443},
-    {cert, "path/to/cert.pem"},
-    {verify, verify_peer}
+
{ok, _} = cowboy:start_tls(example, [
+    {port, 8443},
+    {cert, "path/to/cert.pem"},
+    {verify, verify_peer}
 ], #{
-    env => #{dispatch => Dispatch}
-}).
-

You may also want to customize the verify_fun function. Please -consult the ssl application’s manual for more details.

-

TCP connections do not allow a certificate and this function -will therefore always return undefined.

-

The certificate can also be obtained using pattern matching:

-
-
-
#{cert := Cert} = Req.
-
-
-
+
#{cert := Cert} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The client TLS certificate.

-
-
-
+

The client TLS certificate.

Changelog

-
-
    -
  • -

    -2.1: Function introduced. -

    +
    • 2.1: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the client TLS certificate.
-
-
Cert = cowboy_req:cert(Req).
-
-
-
+
Cert = cowboy_req:cert(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:peer(3), cowboy_req:sock(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.delete_resp_header/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.delete_resp_header/index.html index e1832768..fa8761cc 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.delete_resp_header/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.delete_resp_header/index.html @@ -62,95 +62,45 @@

cowboy_req:delete_resp_header(3)

-

Name

-
-

cowboy_req:delete_resp_header - Delete a response header

-
-
-
+

cowboy_req:delete_resp_header - Delete a response header

Description

-
-
-
-
delete_resp_header(Name, Req :: cowboy_req:req()) -> Req
+
delete_resp_header(Name, Req :: cowboy_req:req()) -> Req
 
-Name :: binary()  %% lowercase; case insensitive
-

Delete the given response header.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+Name :: binary() %% lowercase; case insensitive +
+

Delete the given response header.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Name -
-
-

-Header name as a lowercase binary string. -

+
Name
+

Header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the header will still be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the header will still be sent in the response.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Remove the content-type header from the response
-
-
Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),
-
-
-
+
Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:has_resp_header(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.has_body/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.has_body/index.html index 4f737a14..85936e6d 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.has_body/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.has_body/index.html @@ -62,80 +62,38 @@

cowboy_req:has_body(3)

-

Name

-
-

cowboy_req:has_body - Is there a request body?

-
-
-
+

cowboy_req:has_body - Is there a request body?

Description

-
-
-
-
has_body(Req :: cowboy_req:req()) -> boolean()
-

Return whether the request has a body.

-
-
-
+
has_body(Req :: cowboy_req:req()) -> boolean()
+
+

Return whether the request has a body.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A boolean indicating whether the request has a body.

-
-
-
+

A boolean indicating whether the request has a body.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Ensure the request has a body
-
-
true = cowboy_req:has_body(Req).
-
-
-
+
true = cowboy_req:has_body(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.has_resp_body/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.has_resp_body/index.html index 9ff21d91..3507755d 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.has_resp_body/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.has_resp_body/index.html @@ -62,82 +62,43 @@

cowboy_req:has_resp_body(3)

-

Name

-
-

cowboy_req:has_resp_body - Is there a response body?

-
-
-
+

cowboy_req:has_resp_body - Is there a response body?

Description

-
-
-
-
has_resp_body(Req :: cowboy_req:req()) -> boolean()
-

Return whether a response body has been set.

-
-
-
+
has_resp_body(Req :: cowboy_req:req()) -> boolean()
+
+

Return whether a response body has been set.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A boolean indicating whether a response body has been set.

-

This function will return false when an empty response -body has been set.

-
-
-
+

A boolean indicating whether a response body has been set.

+

This function will return false when an empty response body has been set.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Check whether a body has been set
-
-
false = cowboy_req:has_resp_body(Req0),
-Req1 = cowboy_req:set_resp_body(<<"Hello!">>, Req0),
-true = cowboy_req:has_resp_body(Req1),
-Req = cowboy_req:set_resp_body(<<>>, Req1),
-false = cowboy_req:has_resp_body(Req).
-
-
-
+
false = cowboy_req:has_resp_body(Req0),
+Req1 = cowboy_req:set_resp_body(<<"Hello!">>, Req0),
+true = cowboy_req:has_resp_body(Req1),
+Req = cowboy_req:set_resp_body(<<>>, Req1),
+false = cowboy_req:has_resp_body(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_body(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.has_resp_header/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.has_resp_header/index.html index 5b00ff74..779880de 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.has_resp_header/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.has_resp_header/index.html @@ -62,95 +62,46 @@

cowboy_req:has_resp_header(3)

-

Name

-
-

cowboy_req:has_resp_header - Is the given response header set?

-
-
-
+

cowboy_req:has_resp_header - Is the given response header set?

Description

-
-
-
-
has_resp_header(Name, Req :: cowboy_req:req()) -> boolean()
+
has_resp_header(Name, Req :: cowboy_req:req()) -> boolean()
 
-Name :: binary()  %% lowercase; case insensitive
-

Return whether the given response header has been set.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+Name :: binary() %% lowercase; case insensitive +
+

Return whether the given response header has been set.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Name -
-
-

-Header name as a lowercase binary string. -

+
Name
+

Header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A boolean indicating whether the given response header has been set.

-
-
-
+

A boolean indicating whether the given response header has been set.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Check whether the content-type header has been set
-
-
false = cowboy_req:has_resp_header(<<"content-type">>, Req0),
-Req = cowboy_req:set_resp_header(<<"content-type">>, <<"text/html">>, Req0),
-true = cowboy_req:has_resp_header(<<"content-type">>, Req).
-
-
-
+
false = cowboy_req:has_resp_header(<<"content-type">>, Req0),
+Req = cowboy_req:set_resp_header(<<"content-type">>, <<"text/html">>, Req0),
+true = cowboy_req:has_resp_header(<<"content-type">>, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3), cowboy_req:delete_resp_header(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.header/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.header/index.html index b2048ccd..cc90c29d 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.header/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.header/index.html @@ -62,122 +62,67 @@

cowboy_req:header(3)

-

Name

-
-

cowboy_req:header - HTTP header

-
-
-
+

cowboy_req:header - HTTP header

Description

-
-
-
-
header(Name, Req)          -> header(Name, Req, undefined)
-header(Name, Req, Default) -> binary() | Default
-
-Name    :: binary()          %% lowercase; case insensitive
-Req     :: cowboy_req:req()
-Default :: any()
-

Return the value for the given HTTP header.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Headers can also be obtained using pattern matching:

-
-
-
#{headers := #{Name := Value}} = Req.
-

Note that this snippet will crash if the header is missing.

-
-
-
+
#{headers := #{Name := Value}} = Req.
+
+

Note that this snippet will crash if the header is missing.

Arguments

-
-
-
-Name -
-
-

-Desired HTTP header name as a lowercase binary string. -

+
Name
+

Desired HTTP header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the header is missing. -

+
Default
+

Default value returned when the header is missing.

-
-
- -
+

Return value

-
-

The header value is returned as a binary string. When the -header is missing, the default argument is returned.

-
-
-
+

The header value is returned as a binary string. When the header is missing, the default argument is returned.

Changelog

-
-
    -
  • -

    -2.0: Only the header value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the header value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the accept header
-
-
Accept = cowboy_req:header(<<"accept">>, Req).
-
-
Get the content-length header with a default value
-
-
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).
-
-
-
+
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).
+

See also

- - +

cowboy_req(3), cowboy_req:headers(3), cowboy_req:parse_header(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.headers/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.headers/index.html index 3a052774..805bcbbb 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.headers/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.headers/index.html @@ -62,90 +62,47 @@

cowboy_req:headers(3)

-

Name

-
-

cowboy_req:headers - HTTP headers

-
-
-
+

cowboy_req:headers - HTTP headers

Description

-
-
-
-
headers(Req :: cowboy_req:req()) -> cowboy:http_headers()
-

Return all request headers.

-

Request headers can also be obtained using pattern matching:

-
-
-
#{headers := Headers} = Req.
-
-
-
+
#{headers := Headers} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Headers are returned as a map with keys being lowercase -binary strings, and values as binary strings.

-
-
-
+

Headers are returned as a map with keys being lowercase binary strings, and values as binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the headers are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the headers are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get all headers
-
-
Headers = cowboy_req:headers(Req).
-
-
-
+
Headers = cowboy_req:headers(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:header(3), cowboy_req:parse_header(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.host/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.host/index.html index 4d2f2c33..525c2138 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.host/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.host/index.html @@ -62,91 +62,47 @@

cowboy_req:host(3)

-

Name

-
-

cowboy_req:host - URI host name

-
-
-
+

cowboy_req:host - URI host name

Description

-
-
-
-
host(Req :: cowboy_req:req()) -> Host :: binary()
-

Return the host name of the effective request URI.

-

The host name can also be obtained using pattern matching:

-
-
-
#{host := Host} = Req.
-
-
-
+
#{host := Host} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The host name is returned as a lowercase binary string. -It is case insensitive.

-
-
-
+

The host name is returned as a lowercase binary string. It is case insensitive.

Changelog

-
-
    -
  • -

    -2.0: Only the host name is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the host name is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s host name
-
-
Host = cowboy_req:host(Req).
-
-
-
+
Host = cowboy_req:host(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:host_info(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.host_info/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.host_info/index.html index 2a7c3f44..d48eed1f 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.host_info/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.host_info/index.html @@ -62,87 +62,41 @@

cowboy_req:host_info(3)

-

Name

-
-

cowboy_req:host_info - Access the route’s heading host segments

-
-
-
+

cowboy_req:host_info - Access the route's heading host segments

Description

-
-
-
-
host_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
-

Return the tokens for the heading host segments.

-

This is the part of the host name that was matched using -the ... notation.

-
-
-
+
host_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
+
+

Return the tokens for the heading host segments.

+

This is the part of the host name that was matched using the ... notation.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The tokens are returned as a list of case insensitive -binary strings.

-
-
-
+

The tokens are returned as a list of case insensitive binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the tokens are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the host_info tokens
-
-
HostInfo = cowboy_req:host_info(Req).
-
-
-
+
HostInfo = cowboy_req:host_info(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:path_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.inform/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.inform/index.html index e4a2af7b..e3a18497 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.inform/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.inform/index.html @@ -62,125 +62,66 @@

cowboy_req:inform(3)

-

Name

-
-

cowboy_req:inform - Send an informational response

-
-
-
+

cowboy_req:inform - Send an informational response

Description

-
-
-
-
inform(Status, Req :: cowboy_req:req())
-    -> inform(StatusCode, #{}, Req)
-
-inform(Status, Headers, Req :: cowboy_req:req())
-    -> ok
-
-Status  :: cowboy:http_status()
-Headers :: cowboy:http_headers()
-

Send an informational response.

-

Informational responses use a status code between 100 and 199. -They cannot include a body. This function will not use any -of the previously set headers. All headers to be sent must -be given directly.

-

Any number of informational responses can be sent as long as -they are sent before the proper response. Attempting to use -this function after sending a normal response will result -in an error.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+
inform(Status, Req :: cowboy_req:req())
+    -> inform(StatusCode, #{}, Req)
+
+inform(Status, Headers, Req :: cowboy_req:req())
+    -> ok
+
+Status  :: cowboy:http_status()
+Headers :: cowboy:http_headers()
+
+

Send an informational response.

+

Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly.

+

Any number of informational responses can be sent as long as they are sent before the proper response. Attempting to use this function after sending a normal response will result in an error.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Status -
-
-

-The status code for the response. -

+
Status
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Req -
-
-

-The Req object. -

+
+

Header names must be given as lowercase binary strings.

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.1: Function introduced. -

    +
    • 2.1: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Send an informational response
-
-
Req = cowboy_req:inform(102, Req0).
-
-
Send an informational response with headers
-
-
Req = cowboy_req:inform(103, #{
-    <<"link">> => <<"</style.css>; rel=preload; as=style">>,
-    <<"link">> => <<"</script.js>; rel=preload; as=script">>
-}, Req0).
-
-
-
+
Req = cowboy_req:inform(103, #{
+    <<"link">> => <<"</style.css>; rel=preload; as=style">>,
+    <<"link">> => <<"</script.js>; rel=preload; as=script">>
+}, Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:reply(3), cowboy_req:stream_reply(3), cowboy_req:push(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.match_cookies/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.match_cookies/index.html index cbf262b2..c1d6a1ca 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.match_cookies/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.match_cookies/index.html @@ -62,123 +62,67 @@

cowboy_req:match_cookies(3)

-

Name

-
-

cowboy_req:match_cookies - Match cookies against constraints

-
-
-
+

cowboy_req:match_cookies - Match cookies against constraints

Description

-
-
-
-
match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req())
-    -> #{atom() => any()}
-

Parse the cookies and match specific values against -constraints.

-

Cowboy will only return the cookie values specified in the -fields list, and ignore all others. Fields can be either -the name of the cookie requested; the name along with a -list of constraints; or the name, a list of constraints -and a default value in case the cookie is missing.

-

This function will crash if the cookie is missing and no -default value is provided. This function will also crash -if a constraint fails.

-

The name of the cookie must be provided as an atom. The -key of the returned map will be that atom. The value may -be converted through the use of constraints, making this -function able to extract, validate and convert values all -in one step.

-
-
-
+
match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req())
+    -> #{atom() => any()}
+
+

Parse the cookies and match specific values against constraints.

+

Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing.

+

This function will crash if the cookie is missing and no default value is provided. This function will also crash if a constraint fails.

+

The name of the cookie must be provided as an atom. The key of the returned map will be that atom. The value may be converted through the use of constraints, making this function able to extract, validate and convert values all in one step.

Arguments

-
-
-
-Fields -
-
-

-Cookies to retrieve. -

-

See cowboy(3) for a complete description.

+
Fields
+

Cookies to retrieve.

+

See cowboy(3) for a complete description.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Desired values are returned as a map. The key is the atom -that was given in the list of fields, and the value is the -optionally converted value after applying constraints.

-

The map contains the same keys that were given in the fields.

-

An exception is triggered when the match fails.

-
-
-
+

Desired values are returned as a map. The key is the atom that was given in the list of fields, and the value is the optionally converted value after applying constraints.

+

The map contains the same keys that were given in the fields.

+

An exception is triggered when the match fails.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Match fields
-
-
%% ID and Lang are binaries.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_cookies([id, lang], Req).
-
-
Match fields and apply constraints
-
-
%% ID is an integer and Lang a non-empty binary.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_cookies([{id, int}, {lang, nonempty}], Req).
-
-
Match fields with default values
-
-
#{lang := Lang}
-    = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
-
-
-
+
#{lang := Lang}
+    = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
+

See also

- - +

cowboy_req(3), cowboy_req:parse_cookies(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.match_qs/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.match_qs/index.html index 3cd4cc12..e9f94995 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.match_qs/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.match_qs/index.html @@ -62,123 +62,67 @@

cowboy_req:match_qs(3)

-

Name

-
-

cowboy_req:match_qs - Match the query string against constraints

-
-
-
+

cowboy_req:match_qs - Match the query string against constraints

Description

-
-
-
-
match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req())
-    -> #{atom() => any()}
-

Parse the query string and match specific values against -constraints.

-

Cowboy will only return the query string values specified -in the fields list, and ignore all others. Fields can be -either the key requested; the key along with a list of -constraints; or the key, a list of constraints and a -default value in case the key is missing.

-

This function will crash if the key is missing and no -default value is provided. This function will also crash -if a constraint fails.

-

The key must be provided as an atom. The key of the -returned map will be that atom. The value may be converted -through the use of constraints, making this function able -to extract, validate and convert values all in one step.

-
-
-
+
match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req())
+    -> #{atom() => any()}
+
+

Parse the query string and match specific values against constraints.

+

Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing.

+

This function will crash if the key is missing and no default value is provided. This function will also crash if a constraint fails.

+

The key must be provided as an atom. The key of the returned map will be that atom. The value may be converted through the use of constraints, making this function able to extract, validate and convert values all in one step.

Arguments

-
-
-
-Fields -
-
-

-Fields to retrieve from the query string. -

-

See cowboy(3) for a complete description.

+
Fields
+

Fields to retrieve from the query string.

+

See cowboy(3) for a complete description.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Desired values are returned as a map. The key is the atom -that was given in the list of fields, and the value is the -optionally converted value after applying constraints.

-

The map contains the same keys that were given in the fields.

-

An exception is triggered when the match fails.

-
-
-
+

Desired values are returned as a map. The key is the atom that was given in the list of fields, and the value is the optionally converted value after applying constraints.

+

The map contains the same keys that were given in the fields.

+

An exception is triggered when the match fails.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Match fields
-
-
%% ID and Lang are binaries.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_qs([id, lang], Req).
-
-
Match fields and apply constraints
-
-
%% ID is an integer and Lang a non-empty binary.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req).
-
-
Match fields with default values
-
-
#{lang := Lang}
-    = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
-
-
-
+
#{lang := Lang}
+    = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
+

See also

- - +

cowboy_req(3), cowboy_req:qs(3), cowboy_req:parse_qs(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.method/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.method/index.html index e15d0453..0fcc31a9 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.method/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.method/index.html @@ -62,100 +62,58 @@

cowboy_req:method(3)

-

Name

-
-

cowboy_req:method - HTTP method

-
-
-
+

cowboy_req:method - HTTP method

Description

-
-
-
-
method(Req :: cowboy_req:req()) -> Method :: binary()
-

Return the request’s HTTP method.

-

The method can also be obtained using pattern matching:

-
-
-
#{method := Method} = Req.
-
-
-
+
#{method := Method} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The request’s HTTP method is returned as a binary string. -While methods are case sensitive, standard methods are -always uppercase.

-
-
-
+

The request's HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase.

Changelog

-
-
    -
  • -

    -2.0: Only the method is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the method is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Ensure the request’s method is GET
-
-
<<"GET">> = cowboy_req:method(Req).
-
-
Allow methods from list
-
-
init(Req, State) ->
-    case lists:member(cowboy_req:method(Req), [<<"GET">>, <<"POST">>]) of
-        true -> handle(Req, State);
-        false -> method_not_allowed(Req, State)
-    end.
-
-
-
+
init(Req, State) ->
+    case lists:member(cowboy_req:method(Req), [<<"GET">>, <<"POST">>]) of
+        true -> handle(Req, State);
+        false -> method_not_allowed(Req, State)
+    end.
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.parse_cookies/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.parse_cookies/index.html index 5eacfb94..8a4b082d 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.parse_cookies/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.parse_cookies/index.html @@ -62,91 +62,47 @@

cowboy_req:parse_cookies(3)

-

Name

-
-

cowboy_req:parse_cookies - Parse cookie headers

-
-
-
+

cowboy_req:parse_cookies - Parse cookie headers

Description

-
-
-
-
parse_cookies(Req) -> [{Name, Value}]
-
-Name  :: binary() %% case sensitive
-Value :: binary() %% case sensitive
-

Parse cookie headers.

- -

When the cookie header is missing, [] is returned.

-

While an empty cookie header is not valid, some clients do -send it. Cowboy will in this case also return [].

-
-
-
+
parse_cookies(Req) -> [{Name, Value}]
+
+Name  :: binary() %% case sensitive
+Value :: binary() %% case sensitive
+
+

Parse cookie headers.

+

Alias for cowboy_req:parse_header(<<"cookie">>, Req).

+

When the cookie header is missing, [] is returned.

+

While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return [].

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The cookies are returned as a list of key/values. Keys and -values are case sensitive binary strings.

-
-
-
+

The cookies are returned as a list of key/values. Keys and values are case sensitive binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces cookie/2,3 and cookies/1. -

      +
    • 2.0: Function introduced. Replaces cookie/2,3 and cookies/1.
    • -
-
-
-
+

Examples

-
-
-
Look for a specific cookie
-
-
Cookies = cowboy_req:parse_cookies(Req),
-{_, Token} = lists:keyfind(token, 1, Cookies).
-
-
-
+
Cookies = cowboy_req:parse_cookies(Req),
+{_, Token} = lists:keyfind(token, 1, Cookies).
+

See also

- - +

cowboy_req(3), cowboy_req:parse_header(3), cowboy_req:match_cookies(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.parse_header/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.parse_header/index.html index 50ff77c6..786a1dde 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.parse_header/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.parse_header/index.html @@ -62,283 +62,218 @@

cowboy_req:parse_header(3)

-

Name

-
-

cowboy_req:parse_header - Parse the given HTTP header

-
-
-
+

cowboy_req:parse_header - Parse the given HTTP header

Description

-
-
-
-
parse_header(Name, Req)          -> ParsedValue | Default
-parse_header(Name, Req, Default) -> ParsedValue | Default
-
-Name        :: binary()
-Req         :: cowboy_req:req()
-ParsedValue :: any()
-Default     :: any()
-

Parse the given HTTP header.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

The type of the parsed value varies depending on -the header. Similarly, the default value when calling -cowboy_req:parse_header/2 differs depending on the -header.

-
-
-
+
parse_header(Name, Req)          -> ParsedValue | Default
+parse_header(Name, Req, Default) -> ParsedValue | Default
+
+Name        :: binary()
+Req         :: cowboy_req:req()
+ParsedValue :: any()
+Default     :: any()
+
+

Parse the given HTTP header.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

The type of the parsed value varies depending on the header. Similarly, the default value when calling cowboy_req:parse_header/2 differs depending on the header.

Arguments

-
-
-
-Name -
-
-

-Desired HTTP header name as a lowercase binary string. -

+
Name
+

Desired HTTP header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the header is missing. -

+
Default
+

Default value returned when the header is missing.

-
-
- -
+

Return value

-
-

The parsed header value varies depending on the header. -When the header is missing, the default argument is returned.

-
-
-
+

The parsed header value varies depending on the header. When the header is missing, the default argument is returned.

Headers

-
-

The following snippets detail the types returned by the -different headers. Unless mentioned otherwise, the -default value when the header is missing will be undefined:

-
-
accept
-
-
parse_header(<<"accept">>, Req)
-    -> [{{Type, SubType, Params}, Quality, AcceptExt}]
-
-Type      :: binary()               %% case insensitive
-SubType   :: binary()               %% case insensitive
-Params    :: [{Key, Value}]
-Quality   :: 0..1000
-AcceptExt :: [Key | {Key, Value}]
-Key       :: binary()               %% case insensitive
-Value     :: binary()               %% case sensitive
-
-
accept-charset, accept-encoding and accept-language
-
-
parse_header(Name, Req) -> [{Value, Quality}]
-
-Name    :: <<"accept-charset">>
-         | <<"accept-encoding">>
-         | <<"accept-language">>
-Value   :: binary()                 %% case insensitive
-Quality :: 0..1000
-
-
authorization
-
-
parse_header(<<"authorization">>, Req)
-    -> {basic, Username :: binary(), Password :: binary()}
-     | {bearer, Token :: binary()}
-     | {digest, [{Key :: binary(), Value :: binary()}]}
-
-
content-length
-
+
content-length
+
-
parse_header(<<"content-length">>, Req) -> non_neg_integer()
-

When the content-length header is missing, 0 is returned.

-
-
content-type
-
-
parse_header(<<"content-type">>, Req)
-    -> {Type, SubType, Params}
-
-Type      :: binary()               %% case insensitive
-SubType   :: binary()               %% case insensitive
-Params    :: [{Key, Value}]
-Key       :: binary()               %% case insensitive
-Value     :: binary()               %% case sensitive;
-

Note that the value for the charset parameter is case insensitive -and returned as a lowercase binary string.

-
-
cookie
-
-
parse_header(<<"cookie">>, Req) -> [{Name, Value}]
-
-Name  :: binary()                   %% case sensitive
-Value :: binary()                   %% case sensitive
-

When the cookie header is missing, [] is returned.

-

While an empty cookie header is not valid, some clients do -send it. Cowboy will in this case also return [].

-
-
expect
-
-
parse_header(<<"expect">>, Req) -> continue
-
-
if-match and if-none-match
-
-
parse_header(Name, Req)
-    -> '*' | [{weak | strong, OpaqueTag}]
-
-Name      :: <<"if-match">>
-           | <<"if-none-match">>
-OpaqueTag :: binary()               %% case sensitive
-
-
if-modified-since and if-unmodified-since
-
-
parse_header(Name, Req) -> calendar:datetime()
-
-
range
-
-
parse_header(<<"range">>, Req) -> {From, To} | Final
-
-From  :: non_neg_integer()
-To    :: non_neg_integer() | infinity
-Final :: neg_integer()
-
-
sec-websocket-extensions
-
-
parse_header(<<"sec-websocket-extensions">>, Req)
-    -> [{Extension, Params}]
-
-Extension :: binary()               %% case sensitive
-Params    :: [Key | {Key, Value}]
-Key       :: binary()               %% case sensitive
-Value     :: binary()               %% case sensitive
-
-
sec-websocket-protocol and upgrade
-
-
parse_header(Name, Req) -> [Token]
-
-Name  :: <<"sec-websocket-protocol">>
-       | <<"upgrade">>
-Token :: binary()                   %% case insensitive
-
-
x-forwarded-for
-
-
parse_header(<<"x-forwarded-for">>, Req) -> [Token]
+
parse_header(<<"x-forwarded-for">>, Req) -> [Token]
 
-Token :: binary()                   %% case sensitive
-
-
Unknown headers
-
-
parse_header(_, Req) -> {undefined, RawValue}
-
-
-
+
parse_header(_, Req) -> {undefined, RawValue}
+

Changelog

-
-
    -
  • -

    -2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Parse the accept header with a custom default value
-
-
%% Accept everything when header is missing.
-Accept = cowboy_req:parse_header(<<"accept">>, Req,
-    [{{ <<"*">>, <<"*">>, []}, 1000, []}]).
-
-
Parse the content-length header
-
-
%% Default content-length is 0.
-Length = cowboy_req:header(<<"content-length">>, Req).
-
-
-
+
%% Default content-length is 0.
+Length = cowboy_req:header(<<"content-length">>, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:header(3), cowboy_req:headers(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.parse_qs/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.parse_qs/index.html index c84422d6..83448f19 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.parse_qs/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.parse_qs/index.html @@ -62,117 +62,55 @@

cowboy_req:parse_qs(3)

-

Name

-
-

cowboy_req:parse_qs - Parse the query string

-
-
-
+

cowboy_req:parse_qs - Parse the query string

Description

-
-
-
-
parse_qs(Req :: cowboy_req:req())
-    -> [{Key :: binary(), Value :: binary() | true}]
-

Parse the query string as a list of key/value pairs.

-
-
-
+
parse_qs(Req :: cowboy_req:req())
+    -> [{Key :: binary(), Value :: binary() | true}]
+
+

Parse the query string as a list of key/value pairs.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The parsed query string is returned as a list of key/value pairs. -The key is a binary string. The value is either a binary string, -or the atom true. Both key and value are case sensitive.

-

The atom true is returned when a key is present in the query -string without a value. For example, in the following URIs -the key <<"edit">> will always have the value true:

-
    -
  • -

    -/posts/42?edit -

    +

    The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. Both key and value are case sensitive.

    +

    The atom true is returned when a key is present in the query string without a value. For example, in the following URIs the key <<"edit">> will always have the value true:

    +
    • /posts/42?edit
    • -
    • -

      -/posts/42?edit&exclusive=1 -

      +
    • /posts/42?edit&exclusive=1
    • -
    • -

      -/posts/42?exclusive=1&edit -

      +
    • /posts/42?exclusive=1&edit
    • -
    • -

      -/posts/42?exclusive=1&edit&from=web -

      +
    • /posts/42?exclusive=1&edit&from=web
    • -
-
-
-
+

Changelog

-
-
    -
  • -

    -2.0: The parsed value is not longer cached in the Req object. -

    +
    • 2.0: The parsed value is not longer cached in the Req object.
    • -
    • -

      -2.0: Only the parsed query string is returned, it is no longer wrapped in a tuple. -

      +
    • 2.0: Only the parsed query string is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces qs_val/1 and qs_vals/1. -

      +
    • 2.0: Function introduced. Replaces qs_val/1 and qs_vals/1.
    • -
-
-
-
+

Examples

-
-
-
Parse the query string and convert the keys to atoms
-
-
ParsedQs = cowboy_req:parse_qs(Req),
-AtomsQs = [{binary_to_existing_atom(K, latin1), V}
-    || {K, V} <- ParsedQs].
-
-
-
+
ParsedQs = cowboy_req:parse_qs(Req),
+AtomsQs = [{binary_to_existing_atom(K, latin1), V}
+    || {K, V} <- ParsedQs].
+

See also

- - +

cowboy_req(3), cowboy_req:qs(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.path/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.path/index.html index 90c16d36..b4219182 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.path/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.path/index.html @@ -62,90 +62,47 @@

cowboy_req:path(3)

-

Name

-
-

cowboy_req:path - URI path

-
-
-
+

cowboy_req:path - URI path

Description

-
-
-
-
path(Req :: cowboy_req:req()) -> Path :: binary()
-

Return the path of the effective request URI.

-

The path can also be obtained using pattern matching:

-
-
-
#{path := Path} = Req.
-
-
-
+
#{path := Path} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The path is returned as a binary string. It is case sensitive.

-
-
-
+

The path is returned as a binary string. It is case sensitive.

Changelog

-
-
    -
  • -

    -2.0: Only the path is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the path is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s path
-
-
Path = cowboy_req:path(Req).
-
-
-
+
Path = cowboy_req:path(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:path_info(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.path_info/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.path_info/index.html index 1b37b068..7aa33df4 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.path_info/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.path_info/index.html @@ -62,87 +62,41 @@

cowboy_req:path_info(3)

-

Name

-
-

cowboy_req:path_info - Access the route’s trailing path segments

-
-
-
+

cowboy_req:path_info - Access the route's trailing path segments

Description

-
-
-
-
path_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
-

Return the tokens for the trailing path segments.

-

This is the part of the host name that was matched using -the ... notation.

-
-
-
+
path_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
+
+

Return the tokens for the trailing path segments.

+

This is the part of the host name that was matched using the ... notation.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The tokens are returned as a list of case sensitive -binary strings.

-
-
-
+

The tokens are returned as a list of case sensitive binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the tokens are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the path_info tokens
-
-
PathInfo = cowboy_req:path_info(Req).
-
-
-
+
PathInfo = cowboy_req:path_info(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:host_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.peer/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.peer/index.html index 398e38d7..c57fdc74 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.peer/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.peer/index.html @@ -62,98 +62,51 @@

cowboy_req:peer(3)

-

Name

-
-

cowboy_req:peer - Peer address and port

-
-
-
+

cowboy_req:peer - Peer address and port

Description

-
-
-
-
peer(Req :: cowboy_req:req()) -> Info
+
peer(Req :: cowboy_req:req()) -> Info
 
-Info :: {inet:ip_address(), inet:port_number()}
-

Return the peer’s IP address and port number.

-

The peer information can also be obtained using pattern matching:

-
-
-
#{peer := {IP, Port}} = Req.
-
-
-
+
#{peer := {IP, Port}} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The peer’s IP address and port number.

-

The peer is not necessarily the client’s IP address and port. -It is the IP address of the endpoint connecting directly to -the server, which may be a gateway or a proxy.

-

The forwarded header can be used to get better information -about the different endpoints from the client to the server. -Note however that it is only informative; there is no reliable -way of determining the source of an HTTP request.

-
-
-
+

The peer's IP address and port number.

+

The peer is not necessarily the client's IP address and port. It is the IP address of the endpoint connecting directly to the server, which may be a gateway or a proxy.

+

The forwarded header can be used to get better information about the different endpoints from the client to the server. Note however that it is only informative; there is no reliable way of determining the source of an HTTP request.

Changelog

-
-
    -
  • -

    -2.0: Only the peer is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the peer is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the peer IP address and port number.
-
-
{IP, Port} = cowboy_req:peer(Req).
-
-
-
+
{IP, Port} = cowboy_req:peer(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:sock(3), cowboy_req:cert(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.port/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.port/index.html index 93e0a841..d673b554 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.port/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.port/index.html @@ -62,90 +62,48 @@

cowboy_req:port(3)

-

Name

-
-

cowboy_req:port - URI port number

-
-
-
+

cowboy_req:port - URI port number

Description

-
-
-
-
port(Req :: cowboy_req:req()) -> Port :: inet:port_number()
-

Return the port number of the effective request URI.

-

Note that the port number returned by this function is obtained -by parsing the host header. It may be different from the port -the peer used to connect to Cowboy.

-

The port number can also be obtained using pattern matching:

-
-
-
#{port := Port} = Req.
-
-
-
+
#{port := Port} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The port number is returned as an integer.

-
-
-
+

The port number is returned as an integer.

Changelog

-
-
    -
  • -

    -2.0: Only the port number is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the port number is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s port number
-
-
Port = cowboy_req:port(Req).
-
-
-
+
Port = cowboy_req:port(Req).
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.push/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.push/index.html index 15621773..b896b53b 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.push/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.push/index.html @@ -62,142 +62,74 @@

cowboy_req:push(3)

-

Name

-
-

cowboy_req:push - Push a resource to the client

-
-
-
+

cowboy_req:push - Push a resource to the client

Description

-
-
-
-
push(Path, Headers, Req :: cowboy_req:req())
-    -> push(Path, Headers, Req, #{})
-
-push(Path, Headers, Req :: cowboy_req:req(), Opts)
-    -> ok
-
-Path    :: iodata()                %% case sensitive
-Headers :: cowboy:http_headers()
-Opts    :: cowboy_req:push_opts()
-

Push a resource to the client.

-

Cowboy handles push requests the same way as if they came -from the client, including the creation of a request handling -process, routing and middlewares and so on.

-

This function does nothing when the HTTP/1.1 protocol is -used. You may call it safely without first checking whether -the connection uses HTTP/2.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Note that the headers must be the headers the client is expected -to send if it were to perform the request. They are therefore -request headers, and not response headers.

-

By default, Cowboy will use the GET method, an empty query string, -and take the scheme, host and port directly from the current -request’s URI. You can override them by passing options.

-

It is not possible to push resources after sending a response. -Any attempt will result in an error.

-
-
-
+
push(Path, Headers, Req :: cowboy_req:req())
+    -> push(Path, Headers, Req, #{})
+
+push(Path, Headers, Req :: cowboy_req:req(), Opts)
+    -> ok
+
+Path    :: iodata()                %% case sensitive
+Headers :: cowboy:http_headers()
+Opts    :: cowboy_req:push_opts()
+
+

Push a resource to the client.

+

Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on.

+

This function does nothing when the HTTP/1.1 protocol is used. You may call it safely without first checking whether the connection uses HTTP/2.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Note that the headers must be the headers the client is expected to send if it were to perform the request. They are therefore request headers, and not response headers.

+

By default, Cowboy will use the GET method, an empty query string, and take the scheme, host and port directly from the current request's URI. You can override them by passing options.

+

It is not possible to push resources after sending a response. Any attempt will result in an error.

Arguments

-
-
-
-Path -
-
-

-The status code for the response. -

+
Path
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Req -
-
-

-The Req object. -

+
+

Header names must be given as lowercase binary strings.

+
Req
+

The Req object.

-
-Opts -
-
-

-Customize the HTTP method or the URI scheme, host, port -or query string. -

+
Opts
+

Customize the HTTP method or the URI scheme, host, port or query string.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Push a resource
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, Req),
-
-
Push a resource with a custom host
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, #{host => <<"cdn.example.org">>}, Req),
-
-
-
+
cowboy_req:push("/static/style.css", #{
+    <<"accept">> => <<"text/css">>
+}, #{host => <<"cdn.example.org">>}, Req),
+

See also

- - +

cowboy_req(3), cowboy_req:inform(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.qs/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.qs/index.html index e4d52bab..13c577db 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.qs/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.qs/index.html @@ -62,89 +62,47 @@

cowboy_req:qs(3)

-

Name

-
-

cowboy_req:qs - URI query string

-
-
-
+

cowboy_req:qs - URI query string

Description

-
-
-
-
qs(Req :: cowboy_req:req()) -> Qs :: binary()
-

Return the query string of the effective request URI.

-

The query string can also be obtained using pattern matching:

-
-
-
#{qs := Qs} = Req.
-
-
-
+
#{qs := Qs} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The query string is returned as a binary string. It is case sensitive.

-
-
-
+

The query string is returned as a binary string. It is case sensitive.

Changelog

-
-
    -
  • -

    -2.0: Only the query string is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the query string is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s query string
-
-
Qs = cowboy_req:qs(Req).
-
-
-
+
Qs = cowboy_req:qs(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:parse_qs(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.read_body/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.read_body/index.html index 830c6c10..4330cee2 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.read_body/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.read_body/index.html @@ -62,143 +62,72 @@

cowboy_req:read_body(3)

-

Name

-
-

cowboy_req:read_body - Read the request body

-
-
-
+

cowboy_req:read_body - Read the request body

Description

-
-
-
-
read_body(Req :: cowboy_req:req())
-    -> read_body(Req, #{})
-
-read_body(Req :: cowboy_req:req(), Opts)
-    -> {ok,   Data :: binary(), Req}
-     | {more, Data :: binary(), Req}
-
-Opts :: cowboy_req:read_body_opts()
-

Read the request body.

-

This function reads a chunk of the request body. A more tuple -is returned when more data remains to be read. Call the function -repeatedly until an ok tuple is returned to read the entire body.

-

An ok tuple with empty data is returned when the request has no body, -or when calling this function again after the body has already -been read. It is therefore safe to call this function directly. -Note that the body can only be read once.

-

This function reads the request body from the connection process. -The connection process is responsible for reading from the socket. -The exact behavior varies depending on the protocol.

-

The options therefore are only related to the communication -between the request process and the connection process.

-

Cowboy will automatically handle protocol details including -the expect header, chunked transfer-encoding and others.

-

Once the body has been read fully, Cowboy sets the content-length -header if it was not previously provided.

-
-
-
+
read_body(Req :: cowboy_req:req())
+    -> read_body(Req, #{})
+
+read_body(Req :: cowboy_req:req(), Opts)
+    -> {ok,   Data :: binary(), Req}
+     | {more, Data :: binary(), Req}
+
+Opts :: cowboy_req:read_body_opts()
+
+

Read the request body.

+

This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body.

+

An ok tuple with empty data is returned when the request has no body, or when calling this function again after the body has already been read. It is therefore safe to call this function directly. Note that the body can only be read once.

+

This function reads the request body from the connection process. The connection process is responsible for reading from the socket. The exact behavior varies depending on the protocol.

+

The options therefore are only related to the communication between the request process and the connection process.

+

Cowboy will automatically handle protocol details including the expect header, chunked transfer-encoding and others.

+

Once the body has been read fully, Cowboy sets the content-length header if it was not previously provided.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. -

-

The length option can be used to request smaller or bigger -chunks of data to be sent. It is a best effort approach, Cowboy -may send more data than configured on occasions. It defaults -to 8MB.

-

The period indicates how long the connection process will wait -before it provides us with the data it received. It defaults -to 15 seconds.

-

The connection process sends data to the request process when -either the length of data or the period of time is reached.

-

The timeout option is a safeguard in case the connection -process becomes unresponsive. The function will crash if no -message was received in that interval. The timeout should be -larger than the period. It defaults to the period + 1 second.

+
Opts
+

A map of body reading options.

+

The length option can be used to request smaller or bigger chunks of data to be sent. It is a best effort approach, Cowboy may send more data than configured on occasions. It defaults to 8MB.

+

The period indicates how long the connection process will wait before it provides us with the data it received. It defaults to 15 seconds.

+

The connection process sends data to the request process when either the length of data or the period of time is reached.

+

The timeout option is a safeguard in case the connection process becomes unresponsive. The function will crash if no message was received in that interval. The timeout should be larger than the period. It defaults to the period
1 second.

-
-
- -
+

Return value

-
-

A more tuple is returned when there are more data to be read.

-

An ok tuple is returned when there are no more data to be read, -either because this is the last chunk of data, the body has already -been read, or there was no body to begin with.

-

The data is always returned as a binary.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

A more tuple is returned when there are more data to be read.

+

An ok tuple is returned when there are no more data to be read, either because this is the last chunk of data, the body has already been read, or there was no body to begin with.

+

The data is always returned as a binary.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces body/1,2. -

    +
    • 2.0: Function introduced. Replaces body/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read the entire body
-
-
read_body(Req0, Acc) ->
-    case cowboy_req:read_body(Req0) of
-        {ok, Data, Req} -> {ok, << Acc/binary, Data/binary >>, Req};
-        {more, Data, Req} -> read_body(Req, << Acc/binary, Data/binary >>)
-    end.
-
-
Read the body in small chunks
-
-
cowboy_req:read_body(Req, #{length => 64000}).
-
-
-
+
cowboy_req:read_body(Req, #{length => 64000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.read_part/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.read_part/index.html index 23a7d1bf..dd1976be 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.read_part/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.read_part/index.html @@ -62,162 +62,94 @@

cowboy_req:read_part(3)

-

Name

-
-

cowboy_req:read_part - Read the next multipart headers

-
-
-
+

cowboy_req:read_part - Read the next multipart headers

Description

-
-
-
-
read_part(Req :: cowboy_req:req())
-    -> read_part(Req, #{})
-
-read_part(Req :: cowboy_req:req(), Opts)
-    -> {ok, Headers, Req} | {done, Req}
-
-Opts    :: cowboy_req:read_body_opts()
-Headers :: #{binary() => binary()}
-

Read the next part of a multipart body.

-

This function reads the request body and parses it as -multipart. Each parts of a multipart representation have -their own headers and body. This function parses and returns -headers. Examples of multipart media types are -multipart/form-data and multipart/byteranges.

-

Cowboy will skip any data remaining until the beginning of -the next part. This includes the preamble to the multipart -message but also the body of a previous part if it hasn’t -been read. Both are skipped automatically when calling this -function.

-

Cowboy will read the body before parsing in chunks of size -up to 64KB, with a period of 5 seconds. This is tailored for -reading part headers and might not be the most efficient for -skipping the previous part’s body.

-

The headers returned are MIME headers, NOT HTTP headers. -They can be parsed using the functions from the cow_multipart -module. In addition, the cow_multipart:form_data/1 function -can be used to quickly extract information from multipart/form-data -representations.

-

Once a part has been read, it can not be read again.

-

Once the body has been read, Cowboy sets the content-length -header if it was not previously provided.

-
-
-
+
read_part(Req :: cowboy_req:req())
+    -> read_part(Req, #{})
+
+read_part(Req :: cowboy_req:req(), Opts)
+    -> {ok, Headers, Req} | {done, Req}
+
+Opts    :: cowboy_req:read_body_opts()
+Headers :: #{binary() => binary()}
+
+

Read the next part of a multipart body.

+

This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. Examples of multipart media types are multipart/form-data and multipart/byteranges.

+

Cowboy will skip any data remaining until the beginning of the next part. This includes the preamble to the multipart message but also the body of a previous part if it hasn't been read. Both are skipped automatically when calling this function.

+

Cowboy will read the body before parsing in chunks of size up to 64KB, with a period of 5 seconds. This is tailored for reading part headers and might not be the most efficient for skipping the previous part's body.

+

The headers returned are MIME headers, NOT HTTP headers. They can be parsed using the functions from the cow_multipart module. In addition, the cow_multipart:form_data/1 function can be used to quickly extract information from multipart/form-data representations.

+ +

Once a part has been read, it can not be read again.

+

Once the body has been read, Cowboy sets the content-length header if it was not previously provided.

+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. Please refer to -cowboy_req:read_body(3) -for details about each option. -

-

This function defaults the length to 64KB and the period -to 5 seconds.

+
Opts
+

A map of body reading options. Please refer to cowboy_req:read_body(3) for details about each option.

+

This function defaults the length to 64KB and the period to 5 seconds.

-
-
- -
+

Return value

-
-

An ok tuple is returned containing the next part’s headers -as a map.

-

A done tuple is returned if there are no more parts to read.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

An ok tuple is returned containing the next part's headers as a map.

+

A done tuple is returned if there are no more parts to read.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces part/1,2. -

    +
    • 2.0: Function introduced. Replaces part/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read all parts
-
-
acc_multipart(Req0, Acc) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, Headers, Req1} ->
-            {ok, Body, Req} = stream_body(Req1, <<>>),
-            acc_multipart(Req, [{Headers, Body}|Acc]);
-        {done, Req} ->
-            {lists:reverse(Acc), Req}
-    end.
-
-stream_body(Req0, Acc) ->
-    case cowboy_req:read_part_body(Req0) of
-        {more, Data, Req} ->
-            stream_body(Req, << Acc/binary, Data/binary >>);
-        {ok, Data, Req} ->
-            {ok, << Acc/binary, Data/binary >>, Req}
-    end.
-
-
Read all part headers, skipping bodies
-
-
skip_body_multipart(Req0, Acc) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, Headers, Req} ->
-            skip_body_multipart(Req, [Headers|Acc]);
-        {done, Req} ->
-            {lists:reverse(Acc), Req}
-    end.
-
-
Read a part header in larger chunks
-
-
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).
-
-
-
+
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.read_part_body/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.read_part_body/index.html index ce491c3e..24520497 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.read_part_body/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.read_part_body/index.html @@ -62,130 +62,70 @@

cowboy_req:read_part_body(3)

-

Name

-
-

cowboy_req:read_part_body - Read the current part’s body

-
-
-
+

cowboy_req:read_part_body - Read the current part's body

Description

-
-
-
-
read_part_body(Req :: cowboy_req:req())
-    -> read_part_body(Req, #{})
-
-read_part_body(Req :: cowboy_req:req(), Opts)
-    -> {ok,   Data :: binary(), Req}
-     | {more, Data :: binary(), Req}
-
-Opts :: cowboy_req:read_body_opts()
-

Read the body of the current part of the multipart message.

-

This function reads the request body and parses it as -multipart. Each parts of a multipart representation have -their own headers and body. This function returns the -body of the current part. Examples of multipart media types -are multipart/form-data and multipart/byteranges.

-

This function reads a chunk of the part’s body. A more tuple -is returned when more data remains to be read. Call the function -repeatedly until an ok tuple is returned to read the entire body.

-

Once a part has been read, it can not be read again.

-

Once the body has been read, Cowboy sets the content-length -header if it was not previously provided.

-
-
-
+
read_part_body(Req :: cowboy_req:req())
+    -> read_part_body(Req, #{})
+
+read_part_body(Req :: cowboy_req:req(), Opts)
+    -> {ok,   Data :: binary(), Req}
+     | {more, Data :: binary(), Req}
+
+Opts :: cowboy_req:read_body_opts()
+
+

Read the body of the current part of the multipart message.

+

This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function returns the body of the current part. Examples of multipart media types are multipart/form-data and multipart/byteranges.

+

This function reads a chunk of the part's body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body.

+

Once a part has been read, it can not be read again.

+

Once the body has been read, Cowboy sets the content-length header if it was not previously provided.

+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. Please refer to -cowboy_req:read_body(3) -for details about each option. -

-

This function uses the same default options as the -cowboy_req:read_body(3) -function.

+
Opts
+

A map of body reading options. Please refer to cowboy_req:read_body(3) for details about each option.

+

This function uses the same default options as the cowboy_req:read_body(3) function.

-
-
- -
+

Return value

-
-

A more tuple is returned when there are more data to be read.

-

An ok tuple is returned when there are no more data to be read.

-

The data is always returned as a binary.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

A more tuple is returned when there are more data to be read.

+

An ok tuple is returned when there are no more data to be read.

+

The data is always returned as a binary.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces part_body/1,2. -

    +
    • 2.0: Function introduced. Replaces part_body/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read a full part’s body
-
-
stream_body(Req0, Acc) ->
-    case cowboy_req:read_part_body(Req0) of
-        {more, Data, Req} ->
-            stream_body(Req, << Acc/binary, Data/binary >>);
-        {ok, Data, Req} ->
-            {ok, << Acc/binary, Data/binary >>, Req}
-    end.
-
-
Ensure a part’s body is smaller than 64KB
-
-
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).
-
-
-
+
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.read_urlencoded_body/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.read_urlencoded_body/index.html index 6ff1ab2c..e573bf20 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.read_urlencoded_body/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.read_urlencoded_body/index.html @@ -62,126 +62,64 @@

cowboy_req:read_urlencoded_body(3)

-

Name

-
-

cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body

-
-
-
+

cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body

Description

-
-
-
-
read_urlencoded_body(Req :: cowboy_req:req())
-    -> read_urlencoded_body(Req, #{})
-
-read_urlencoded_body(Req :: cowboy_req:req(), Opts)
-    -> {ok, Body, Req}
-
-Opts :: cowboy_req:read_body_opts()
-Body :: [{Key :: binary(), Value :: binary() | true}]
-

Read and parse a urlencoded request body.

-

This function reads the request body and parses it as -application/x-www-form-urlencoded. It returns a list -of key/values.

-

The urlencoded media type is used by Web browsers when -submitting HTML forms using the POST method.

-

Cowboy needs to read the full body before parsing. By default -it will read bodies of size up to 64KB. It is possible to -provide options to read larger bodies if required.

-

Cowboy will automatically handle protocol details including -the expect header, chunked transfer-encoding and others.

-

Once the body has been read, Cowboy sets the content-length -header if it was not previously provided.

-

This function can only be called once. Calling it again will -result in undefined behavior.

-
-
-
+
read_urlencoded_body(Req :: cowboy_req:req())
+    -> read_urlencoded_body(Req, #{})
+
+read_urlencoded_body(Req :: cowboy_req:req(), Opts)
+    -> {ok, Body, Req}
+
+Opts :: cowboy_req:read_body_opts()
+Body :: [{Key :: binary(), Value :: binary() | true}]
+
+

Read and parse a urlencoded request body.

+

This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values.

+

The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method.

+

Cowboy needs to read the full body before parsing. By default it will read bodies of size up to 64KB. It is possible to provide options to read larger bodies if required.

+

Cowboy will automatically handle protocol details including the expect header, chunked transfer-encoding and others.

+

Once the body has been read, Cowboy sets the content-length header if it was not previously provided.

+

This function can only be called once. Calling it again will result in undefined behavior.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. Please refer to -cowboy_req:read_body(3) -for details about each option. -

-

This function defaults the length to 64KB and the period -to 5 seconds.

+
Opts
+

A map of body reading options. Please refer to cowboy_req:read_body(3) for details about each option.

+

This function defaults the length to 64KB and the period to 5 seconds.

-
-
- -
+

Return value

-
-

An ok tuple is returned containing a list of key/values found -in the body.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

An ok tuple is returned containing a list of key/values found in the body.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces body_qs/1,2. -

    +
    • 2.0: Function introduced. Replaces body_qs/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read a urlencoded body
-
-
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0),
-{_, Lang} = lists:keyfind(<<"lang">>, 1, Body).
-
-
Allow large urlencoded bodies
-
-
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).
-
-
-
+
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.reply/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.reply/index.html index 522ca902..debb4369 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.reply/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.reply/index.html @@ -62,165 +62,87 @@

cowboy_req:reply(3)

-

Name

-
-

cowboy_req:reply - Send the response

-
-
-
+

cowboy_req:reply - Send the response

Description

-
-
-
-
reply(Status, Req :: cowboy_req:req())
-    -> reply(StatusCode, #{}, Req)
-
-reply(Status, Headers, Req :: cowboy_req:req())
-    -> Req
-
-reply(Status, Headers, Body, Req :: cowboy_req:req())
-    -> Req
-
-Status  :: cowboy:http_status()
-Headers :: cowboy:http_headers()
-Body    :: cowboy_req:resp_body()
-

Send the response.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may overwrite those set by set_resp_header/3 -and set_resp_headers/2.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-

The reply/2,3 functions will send the body set previously, -if any. The reply/4 function always sends the given body, -overriding any previously set.

-

You do not need to set the content-length header when -sending a response body. Cowboy takes care of it automatically. -You should however provide a content-type header.

-

No further data can be transmitted after this function -returns. This includes the push mechanism. Attempting to -send two replies, or to push resources after a reply has -been sent, will result in an error.

-
-
-
+
reply(Status, Req :: cowboy_req:req())
+    -> reply(StatusCode, #{}, Req)
+
+reply(Status, Headers, Req :: cowboy_req:req())
+    -> Req
+
+reply(Status, Headers, Body, Req :: cowboy_req:req())
+    -> Req
+
+Status  :: cowboy:http_status()
+Headers :: cowboy:http_headers()
+Body    :: cowboy_req:resp_body()
+
+

Send the response.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3 and set_resp_headers/2.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

+

The reply/2,3 functions will send the body set previously, if any. The reply/4 function always sends the given body, overriding any previously set.

+

You do not need to set the content-length header when sending a response body. Cowboy takes care of it automatically. You should however provide a content-type header.

+

No further data can be transmitted after this function returns. This includes the push mechanism. Attempting to send two replies, or to push resources after a reply has been sent, will result in an error.

Arguments

-
-
-
-Status -
-
-

-The status code for the response. -

+
Status
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Body -
-
-

-The body can be either a binary value, an iolist or a -sendfile tuple telling Cowboy to send the contents of -a file. -

+
+

Header names must be given as lowercase binary strings.

+
Body
+

The body can be either a binary value, an iolist or a sendfile tuple telling Cowboy to send the contents of a file.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object should be used from that point onward -as it contains updated information about the state of the request.

-
-
-
+

A new Req object is returned.

+

The returned Req object should be used from that point onward as it contains updated information about the state of the request.

Changelog

-
-
    -
  • -

    -2.0: Only the Req is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the Req is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Reply
-
-
Req = cowboy_req:reply(404, Req0).
-
-
Reply with custom headers
-
-
Req = cowboy_req:reply(401, #{
-    <<"www-authenticate">> => <<"Basic realm=\"erlang.org\"">>
-}, Req0).
-
-
Reply with custom headers and a body
-
-
Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, "Hello world!", Req0).
-
-
-
+
Req = cowboy_req:reply(200, #{
+    <<"content-type">> => <<"text/plain">>
+}, "Hello world!", Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:set_resp_body(3), cowboy_req:inform(3), cowboy_req:stream_reply(3), cowboy_req:push(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.resp_header/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.resp_header/index.html index d26e9ca4..2d4e1da7 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.resp_header/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.resp_header/index.html @@ -62,113 +62,58 @@

cowboy_req:resp_header(3)

-

Name

-
-

cowboy_req:resp_header - Response header

-
-
-
+

cowboy_req:resp_header - Response header

Description

-
-
-
-
resp_header(Name, Req)          -> resp_header(Name, Req, undefined)
-resp_header(Name, Req, Default) -> binary() | Default
-
-Name    :: binary()          %% lowercase; case insensitive
-Req     :: cowboy_req:req()
-Default :: any()
-

Return the value for the given response header.

-

The response header must have been set previously using -cowboy_req:set_resp_header(3) or -cowboy_req:set_resp_headers(3).

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+
resp_header(Name, Req)          -> resp_header(Name, Req, undefined)
+resp_header(Name, Req, Default) -> binary() | Default
+
+Name    :: binary()          %% lowercase; case insensitive
+Req     :: cowboy_req:req()
+Default :: any()
+
+

Return the value for the given response header.

+

The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3).

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Name -
-
-

-Desired response header name as a lowercase binary string. -

+
Name
+

Desired response header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the header is missing. -

+
Default
+

Default value returned when the header is missing.

-
-
- -
+

Return value

-
-

The header value is returned as a binary string. When the -header is missing, the default argument is returned.

-
-
-
+

The header value is returned as a binary string. When the header is missing, the default argument is returned.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the content-type response header
-
-
Type = cowboy_req:resp_header(<<"content-type">>, Req).
-
-
Get the content-type response header with a default value
-
-
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).
-
-
-
+
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).
+

See also

- - +

cowboy_req(3), cowboy_req:resp_headers(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.resp_headers/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.resp_headers/index.html index 31930660..9cc75985 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.resp_headers/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.resp_headers/index.html @@ -62,79 +62,38 @@

cowboy_req:resp_headers(3)

-

Name

-
-

cowboy_req:resp_headers - Response headers

-
-
-
+

cowboy_req:resp_headers - Response headers

Description

-
-
-
-
resp_headers(Req :: cowboy_req:req()) -> cowboy:http_headers()
-

Return all response headers.

-
-
-
+
resp_headers(Req :: cowboy_req:req()) -> cowboy:http_headers()
+
+

Return all response headers.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Headers are returned as a map with keys being lowercase -binary strings, and values as binary strings.

-
-
-
+

Headers are returned as a map with keys being lowercase binary strings, and values as binary strings.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get all response headers
-
-
Headers = cowboy_req:resp_headers(Req).
-
-
-
+
Headers = cowboy_req:resp_headers(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:resp_header(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.scheme/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.scheme/index.html index 2c4bccb9..1bbf5ecb 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.scheme/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.scheme/index.html @@ -62,89 +62,52 @@

cowboy_req:scheme(3)

-

Name

-
-

cowboy_req:scheme - URI scheme

-
-
-
+

cowboy_req:scheme - URI scheme

Description

-
-
-
-
scheme(Req :: cowboy_req:req()) -> Scheme :: binary()
-

Return the scheme of the effective request URI.

-

The scheme can also be obtained using pattern matching:

-
-
-
#{scheme := Scheme} = Req.
-
-
-
+
#{scheme := Scheme} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The scheme is returned as a binary. It is case insensitive.

-

Cowboy will only set the scheme to <<"http">> or <<"https">>.

-
-
-
+

The scheme is returned as a binary. It is case insensitive.

+

Cowboy will only set the scheme to <<"http">> or <<"https">>.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Redirect HTTP to HTTPS
-
-
init(Req0=#{scheme := <<"http">>}, State) ->
-    Req = cowboy_req:reply(302, #{
-        <<"location">> => cowboy_req:uri(Req, #{scheme => <<"https">>})
-    }, Req0),
-    {ok, Req, State};
-init(Req, State) ->
-    {cowboy_rest, Req, State}.
-
-
-
+
init(Req0=#{scheme := <<"http">>}, State) ->
+    Req = cowboy_req:reply(302, #{
+        <<"location">> => cowboy_req:uri(Req, #{scheme => <<"https">>})
+    }, Req0),
+    {ok, Req, State};
+init(Req, State) ->
+    {cowboy_rest, Req, State}.
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_body/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_body/index.html index 03f71b8c..1b764118 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_body/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_body/index.html @@ -62,138 +62,79 @@

cowboy_req:set_resp_body(3)

-

Name

-
-

cowboy_req:set_resp_body - Set the response body

-
-
-
+

cowboy_req:set_resp_body - Set the response body

Description

-
-
-
-
set_resp_body(Body, Req :: cowboy_req:req())
-        -> Req
-
-Body :: cowboy_req:resp_body()
-

Set the response body.

-

The response body will be sent when a reply is initiated. -Note that the functions stream_reply/2,3 and reply/4 -will override the body set by this function.

-

This function can also be used to remove a response body -that was set previously. To do so, simply call this function -with an empty body.

-
-
-
+
set_resp_body(Body, Req :: cowboy_req:req())
+	-> Req
+
+Body :: cowboy_req:resp_body()
+
+

Set the response body.

+

The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function.

+

This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body.

Arguments

-
-
-
-Body -
-
-

-The body can be either a binary value, an iolist or a -sendfile tuple telling Cowboy to send the contents of -a file. -

+
Body
+

The body can be either a binary value, an iolist or a sendfile tuple telling Cowboy to send the contents of a file.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the body will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the body will not be sent in the response.

Changelog

-
-
    -
  • -

    -2.0: The function now accepts a sendfile tuple. -

    +
    • 2.0: The function now accepts a sendfile tuple.
    • -
    • -

      -2.0: The set_resp_body_fun/2,3 functions were removed. -

      +
    • 2.0: The set_resp_body_fun/2,3 functions were removed.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set the response body
-
-
Req = cowboy_req:set_resp_body(<<"Hello world!">>, Req0).
-
-
Set the response body as an iolist
-
-
Req = cowboy_req:set_resp_body([
-    "<html><head><title>",
-    page_title(),
-    "</title></head><body>",
-    page_body(),
-    "</body></html>"
-], Req0).
-
-
Tell Cowboy to send data from a file
-
-
{ok, #file_info{size=Size}} = file:read_file_info(Filename),
-Req = cowboy_req:set_resp_body({sendfile, 0, Size, Filename}, Req0).
-
-
Clear any previously set response body
-
-
Req = cowboy_req:set_resp_body(<<>>, Req0).
-
-
-
+
Req = cowboy_req:set_resp_body(<<>>, Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_cookie/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_cookie/index.html index a241db59..76363bc0 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_cookie/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_cookie/index.html @@ -62,167 +62,104 @@

cowboy_req:set_resp_cookie(3)

-

Name

-
-

cowboy_req:set_resp_cookie - Set a cookie

-
-
-
+

cowboy_req:set_resp_cookie - Set a cookie

Description

-
-
-
-
set_resp_cookie(Name, Value, Req :: cowboy_req:req())
-    -> set_resp_cookie(Name, Value, [], Req)
-
-set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts)
-    -> Req
-
-Name  :: binary()                  %% case sensitive
-Value :: iodata()                  %% case sensitive
-Opts  :: cow_cookie:cookie_opts()
-

Set a cookie to be sent with the response.

-

Note that cookie names are case sensitive.

-
-
-
+
set_resp_cookie(Name, Value, Req :: cowboy_req:req())
+    -> set_resp_cookie(Name, Value, [], Req)
+
+set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts)
+    -> Req
+
+Name  :: binary()                  %% case sensitive
+Value :: iodata()                  %% case sensitive
+Opts  :: cow_cookie:cookie_opts()
+
+

Set a cookie to be sent with the response.

+

Note that cookie names are case sensitive.

Arguments

-
-
-
-Name -
-
-

-Cookie name. -

+
Name
+

Cookie name.

-
-Value -
-
-

-Cookie value. -

+
Value
+

Cookie value.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-Cookie options. -

+
Opts
+

Cookie options.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the cookie will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the cookie will not be sent in the response.

Changelog

-
-
    -
  • -

    -2.0: set_resp_cookie/3 introduced as an alias to set_resp_cookie/4 with no options. -

    +
    • 2.0: set_resp_cookie/3 introduced as an alias to set_resp_cookie/4 with no options.
    • -
    • -

      -2.0: The first argument type is now binary() instead of iodata(). -

      +
    • 2.0: The first argument type is now binary() instead of iodata().
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set a session cookie
-
-
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0).
-
-
Set a cookie with an expiration time
-
-
Req = cowboy_req:set_resp_cookie(<<"lang">>, <<"fr-FR">>,
-    Req0, #{max_age => 3600}).
-
-
Delete a cookie
-
-
Req = cowboy_req:set_resp_cookie(<<"sessionid">>, <<>>,
-    Req0, #{max_age => 0}).
-
-
Set a cookie for a specific domain and path
-
-
Req = cowboy_req:set_resp_cookie(<<"inaccount">>, <<"1">>,
-    Req0, #{domain => "my.example.org", path => "/account"}).
-
-
Restrict a cookie to HTTPS
-
-
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID,
-    Req0, #{secure => true}).
-
-
Restrict a cookie to HTTP
-
-
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID,
-    Req0, #{http_only => true}).
-
-
-
+
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
+Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID,
+    Req0, #{http_only => true}).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_header/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_header/index.html index 9e78ece1..029d8cab 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_header/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_header/index.html @@ -62,121 +62,60 @@

cowboy_req:set_resp_header(3)

-

Name

-
-

cowboy_req:set_resp_header - Set a response header

-
-
-
+

cowboy_req:set_resp_header - Set a response header

Description

-
-
-
-
set_resp_header(Name, Value, Req :: cowboy_req:req())
-        -> Req
-
-Name  :: binary()  %% lowercase; case insensitive
-Value :: iodata()  %% case depends on header
-

Set a header to be sent with the response.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may be overwritten by those set from the -reply functions.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-
-
-
+
set_resp_header(Name, Value, Req :: cowboy_req:req())
+	-> Req
+
+Name  :: binary()  %% lowercase; case insensitive
+Value :: iodata()  %% case depends on header
+
+

Set a header to be sent with the response.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

Arguments

-
-
-
-Name -
-
-

-Header name as a lowercase binary string. -

+
Name
+

Header name as a lowercase binary string.

-
-Value -
-
-

-Header value. -

+
Value
+

Header value.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the header will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the header will not be sent in the response.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set a header in the response
-
-
Req = cowboy_req:set_resp_header(<<"allow">>, "GET", Req0).
-
-
Construct a header using iolists
-
-
Req = cowboy_req:set_resp_header(<<"allow">>,
-    [allowed_methods(), ", OPTIONS"], Req0).
-
-
-
+
Req = cowboy_req:set_resp_header(<<"allow">>,
+    [allowed_methods(), ", OPTIONS"], Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_headers(3), cowboy_req:has_resp_header(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3), cowboy_req:delete_resp_header(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_headers/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_headers/index.html index 8eb7ab4f..a31f0c5e 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_headers/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_headers/index.html @@ -62,109 +62,51 @@

cowboy_req:set_resp_headers(3)

-

Name

-
-

cowboy_req:set_resp_headers - Set several response headers

-
-
-
+

cowboy_req:set_resp_headers - Set several response headers

Description

-
-
-
-
set_resp_headers(Headers, Req :: cowboy_req:req())
-    -> Req
-
-Headers :: cowboy:http_headers()
-

Set several headers to be sent with the response.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may be overwritten by those set from the -reply functions. Likewise, headers set by this function may -overwrite headers that were set previously.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-
-
-
+
set_resp_headers(Headers, Req :: cowboy_req:req())
+    -> Req
+
+Headers :: cowboy:http_headers()
+
+

Set several headers to be sent with the response.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. Likewise, headers set by this function may overwrite headers that were set previously.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

Arguments

-
-
-
-Headers -
-
-

-Headers as a map with keys being lowercase binary strings, -and values as binary strings. -

+
Headers
+

Headers as a map with keys being lowercase binary strings, and values as binary strings.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the headers will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the headers will not be sent in the response.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set several response headers
-
-
Req = cowboy_req:set_resp_headers(#{
-    <<"content-type">>     => <<"text/html">>,
-    <<"content-encoding">> => <<"gzip">>
-}, Req0).
-
-
-
+
Req = cowboy_req:set_resp_headers(#{
+    <<"content-type">>     => <<"text/html">>,
+    <<"content-encoding">> => <<"gzip">>
+}, Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_header(3), cowboy_req:has_resp_header(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3), cowboy_req:delete_resp_header(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.sock/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.sock/index.html index c7784c1f..7eb0187d 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.sock/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.sock/index.html @@ -62,86 +62,47 @@

cowboy_req:sock(3)

-

Name

-
-

cowboy_req:sock - Socket address and port

-
-
-
+

cowboy_req:sock - Socket address and port

Description

-
-
-
-
sock(Req :: cowboy_req:req()) -> Info
+
sock(Req :: cowboy_req:req()) -> Info
 
-Info :: {inet:ip_address(), inet:port_number()}
-

Return the socket’s IP address and port number.

-

The socket information can also be obtained using pattern matching:

-
-
-
#{sock := {IP, Port}} = Req.
-
-
-
+
#{sock := {IP, Port}} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The socket’s local IP address and port number.

-
-
-
+

The socket's local IP address and port number.

Changelog

-
-
    -
  • -

    -2.1: Function introduced. -

    +
    • 2.1: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the socket’s IP address and port number.
-
-
{IP, Port} = cowboy_req:sock(Req).
-
-
-
+
{IP, Port} = cowboy_req:sock(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:peer(3), cowboy_req:cert(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.stream_body/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.stream_body/index.html index 7c0d9368..e1e94530 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.stream_body/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.stream_body/index.html @@ -62,119 +62,56 @@

cowboy_req:stream_body(3)

-

Name

-
-

cowboy_req:stream_body - Stream the response body

-
-
-
+

cowboy_req:stream_body - Stream the response body

Description

-
-
-
-
stream_body(Data, IsFin, Req :: cowboy_req:req()) -> ok
-
-Data  :: iodata()
-IsFin :: fin | nofin
-

Stream the response body.

-

This function may be called as many times as needed after -initiating a response using the -cowboy_req:stream_reply(3) -function.

-

The second argument indicates if this call is the final -call. Use the nofin value until you know no more data -will be sent. The final call should use fin (possibly -with an empty data value) or be a call to the -cowboy_req:stream_trailers(3) -function.

-

Note that not using fin for the final call is not an -error; Cowboy will take care of it when the request -handler terminates if needed. Depending on the resource -it may however be more efficient to do it as early as -possible.

-

You do not need to handle HEAD requests specifically as -Cowboy will ensure no data is sent when you call this function.

-
-
-
+
stream_body(Data, IsFin, Req :: cowboy_req:req()) -> ok
+
+Data  :: iodata()
+IsFin :: fin | nofin
+
+

Stream the response body.

+

This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function.

+

The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. The final call should use fin (possibly with an empty data value) or be a call to the cowboy_req:stream_trailers(3) function.

+

Note that not using fin for the final call is not an error; Cowboy will take care of it when the request handler terminates if needed. Depending on the resource it may however be more efficient to do it as early as possible.

+

You do not need to handle HEAD requests specifically as Cowboy will ensure no data is sent when you call this function.

Arguments

-
-
-
-Data -
-
-

-The data to be sent. -

+
Data
+

The data to be sent.

-
-IsFin -
-
-

-A flag indicating whether this is the final piece of data -to be sent. -

+
IsFin
+

A flag indicating whether this is the final piece of data to be sent.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces chunk/2. -

    +
    • 2.0: Function introduced. Replaces chunk/2.
    • -
-
-
-
+

Examples

-
-
-
Stream the response body
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, Req0),
-cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
-timer:sleep(1000),
-cowboy_req:stream_body(<<"World!\n">>, fin, Req).
-
-
-
+
Req = cowboy_req:stream_reply(200, #{
+    <<"content-type">> => <<"text/plain">>
+}, Req0),
+cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
+timer:sleep(1000),
+cowboy_req:stream_body(<<"World!\n">>, fin, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:stream_reply(3), cowboy_req:stream_trailers(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.stream_reply/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.stream_reply/index.html index 14f072a3..71a2179c 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.stream_reply/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.stream_reply/index.html @@ -62,152 +62,76 @@

cowboy_req:stream_reply(3)

-

Name

-
-

cowboy_req:stream_reply - Send the response headers

-
-
-
+

cowboy_req:stream_reply - Send the response headers

Description

-
-
-
-
stream_reply(Status, Req :: cowboy_req:req())
-    -> stream_reply(StatusCode, #{}, Req)
-
-stream_reply(Status, Headers, Req :: cowboy_req:req())
-    -> Req
-
-Status  :: cowboy:http_status()
-Headers :: cowboy:http_headers()
-

Send the response headers.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may overwrite those set by set_resp_header/3.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-

If a response body was set before calling this function, -it will not be sent.

-

Use cowboy_req:stream_body(3) -to stream the response body and optionally -cowboy_req:stream_trailers(3) -to send response trailer field values.

-

You may want to set the content-length header when using -this function, if it is known in advance. This will allow -clients using HTTP/2 and HTTP/1.0 to process the response -more efficiently.

-

The streaming method varies depending on the protocol being -used. HTTP/2 will use the usual DATA frames. HTTP/1.1 will -use chunked transfer-encoding. HTTP/1.0 will send the body -unmodified and close the connection at the end if no -content-length was set.

-

It is not possible to push resources after this function -returns. Any attempt will result in an error.

-
-
-
+
stream_reply(Status, Req :: cowboy_req:req())
+    -> stream_reply(StatusCode, #{}, Req)
+
+stream_reply(Status, Headers, Req :: cowboy_req:req())
+    -> Req
+
+Status  :: cowboy:http_status()
+Headers :: cowboy:http_headers()
+
+

Send the response headers.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

+

If a response body was set before calling this function, it will not be sent.

+

Use cowboy_req:stream_body(3) to stream the response body and optionally cowboy_req:stream_trailers(3) to send response trailer field values.

+

You may want to set the content-length header when using this function, if it is known in advance. This will allow clients using HTTP/2 and HTTP/1.0 to process the response more efficiently.

+

The streaming method varies depending on the protocol being used. HTTP/2 will use the usual DATA frames. HTTP/1.1 will use chunked transfer-encoding. HTTP/1.0 will send the body unmodified and close the connection at the end if no content-length was set.

+

It is not possible to push resources after this function returns. Any attempt will result in an error.

Arguments

-
-
-
-Status -
-
-

-The status code for the response. -

+
Status
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Req -
-
-

-The Req object. -

+
+

Header names must be given as lowercase binary strings.

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward -in order to be able to stream the response body.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward in order to be able to stream the response body.

Changelog

-
-
    -
  • -

    -2.0: Only the Req is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the Req is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces chunked_reply/1,2. -

      +
    • 2.0: Function introduced. Replaces chunked_reply/1,2.
    • -
-
-
-
+

Examples

-
-
-
Initiate the response
-
-
Req = cowboy_req:stream_reply(200, Req0).
-
-
Stream the response with custom headers
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, Req0),
-cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
-timer:sleep(1000),
-cowboy_req:stream_body(<<"World!\n">>, fin, Req).
-
-
-
+
Req = cowboy_req:stream_reply(200, #{
+    <<"content-type">> => <<"text/plain">>
+}, Req0),
+cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
+timer:sleep(1000),
+cowboy_req:stream_body(<<"World!\n">>, fin, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:inform(3), cowboy_req:reply(3), cowboy_req:stream_body(3), cowboy_req:stream_trailers(3), cowboy_req:push(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.stream_trailers/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.stream_trailers/index.html index 42961412..600fc5c4 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.stream_trailers/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.stream_trailers/index.html @@ -62,107 +62,55 @@

cowboy_req:stream_trailers(3)

-

Name

-
-

cowboy_req:stream_trailers - Send the response trailers

-
-
-
+

cowboy_req:stream_trailers - Send the response trailers

Description

-
-
-
-
stream_trailers(Trailers, Req :: cowboy_req:req()) -> ok
-
-Trailers :: cowboy:http_headers()
-

Send the response trailers and terminate the stream.

-

This function can only be called once, after initiating -a response using -cowboy_req:stream_reply(3) -and sending zero or more body chunks using -cowboy_req:stream_body(3) -with the nofin argument set. The function stream_trailers/2 -implies fin and automatically terminate the response.

-

You must list all field names sent in trailers in the -trailer header, otherwise they might be dropped by intermediaries -or clients.

-
-
-
+
stream_trailers(Trailers, Req :: cowboy_req:req()) -> ok
+
+Trailers :: cowboy:http_headers()
+
+

Send the response trailers and terminate the stream.

+

This function can only be called once, after initiating a response using cowboy_req:stream_reply(3) and sending zero or more body chunks using cowboy_req:stream_body(3) with the nofin argument set. The function stream_trailers/2 implies fin and automatically terminate the response.

+

You must list all field names sent in trailers in the trailer header, otherwise they might be dropped by intermediaries or clients.

Arguments

-
-
-
-Trailers -
-
-

-Trailer field values to be sent. -

+
Trailers
+

Trailer field values to be sent.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.2: Function introduced. -

    +
    • 2.2: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Stream a response body with trailers
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/plain">>,
-    <<"trailer">> => <<"expires, content-md5">>
-}, Req0),
-cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
-timer:sleep(1000),
-cowboy_req:stream_body(<<"World!\n">>, nofin, Req).
-cowboy_req:stream_trailers(#{
-    <<"expires">> => <<"Sun, 10 Dec 2017 19:13:47 GMT">>,
-    <<"content-md5">> => <<"fbf68a8e34b2ded53bba54e68794b4fe">>
-}, Req).
-
-
-
+
Req = cowboy_req:stream_reply(200, #{
+    <<"content-type">> => <<"text/plain">>,
+    <<"trailer">> => <<"expires, content-md5">>
+}, Req0),
+cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
+timer:sleep(1000),
+cowboy_req:stream_body(<<"World!\n">>, nofin, Req).
+cowboy_req:stream_trailers(#{
+    <<"expires">> => <<"Sun, 10 Dec 2017 19:13:47 GMT">>,
+    <<"content-md5">> => <<"fbf68a8e34b2ded53bba54e68794b4fe">>
+}, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:stream_reply(3), cowboy_req:stream_body(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.uri/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.uri/index.html index 18bcaad2..6abe3b58 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.uri/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.uri/index.html @@ -62,177 +62,106 @@

cowboy_req:uri(3)

-

Name

-
-

cowboy_req:uri - Reconstructed URI

-
-
-
+

cowboy_req:uri - Reconstructed URI

Description

-
-
-
-
uri(Req :: cowboy_req:req())       -> uri(Req, #{})
-uri(Req :: cowboy_req:req(), Opts) -> URI :: iodata()
-
-Opts :: #{
-    scheme   => iodata()           | undefined,
-    host     => iodata()           | undefined,
-    port     => inet:port_number() | undefined,
-    path     => iodata()           | undefined,
-    qs       => iodata()           | undefined,
-    fragment => iodata()           | undefined
-}
-

Reconstruct the effective request URI, optionally modifying components.

-

By default Cowboy will build a URI using the components found -in the request. Options allow disabling or replacing individual -components.

-
-
-
+
uri(Req :: cowboy_req:req())       -> uri(Req, #{})
+uri(Req :: cowboy_req:req(), Opts) -> URI :: iodata()
+
+Opts :: #{
+    scheme   => iodata()           | undefined,
+    host     => iodata()           | undefined,
+    port     => inet:port_number() | undefined,
+    path     => iodata()           | undefined,
+    qs       => iodata()           | undefined,
+    fragment => iodata()           | undefined
+}
+
+

Reconstruct the effective request URI, optionally modifying components.

+

By default Cowboy will build a URI using the components found in the request. Options allow disabling or replacing individual components.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-Map for overriding individual components. -

-

To replace a component, provide its new value as a binary -string or an iolist. To disable a component, set its value -to undefined.

-

As this function always returns a valid URI, there are some -things to note:

-
    -
  • -

    -Disabling the host also disables the scheme and port. -

    +
    Opts
    +

    Map for overriding individual components.

    +

    To replace a component, provide its new value as a binary string or an iolist. To disable a component, set its value to undefined.

    +

    As this function always returns a valid URI, there are some things to note:

    +
    • Disabling the host also disables the scheme and port.
    • -
    • -

      -There is no fragment component by default as these are - not sent with the request. -

      +
    • There is no fragment component by default as these are not sent with the request.
    • -
    • -

      -The port number may not appear in the resulting URI if - it is the default port for the given scheme (http: 80; https: 443). -

      +
    • The port number may not appear in the resulting URI if it is the default port for the given scheme (http: 80; https: 443).
    • -
+
-
-
- -
+

Return value

-
-

The reconstructed URI is returned as an iolist or a binary string.

-
-
-
+

The reconstructed URI is returned as an iolist or a binary string.

Changelog

-
-
    -
  • -

    -2.0: Individual components can be replaced or disabled. -

    +
    • 2.0: Individual components can be replaced or disabled.
    • -
    • -

      -2.0: Only the URI is returned, it is no longer wrapped in a tuple. -

      +
    • 2.0: Only the URI is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces host_url/1 and url/1. -

      +
    • 2.0: Function introduced. Replaces host_url/1 and url/1.
    • -
-
-
-
+

Examples

-
-

With an effective request URI http://example.org/path/to/res?edit=1 -we can have:

-
-
Protocol relative form
-
-
%% //example.org/path/to/res?edit=1
-cowboy_req:uri(Req, #{scheme => undefined}).
-
-
Serialized origin for use in the origin header
-
-
%% http://example.org
-cowboy_req:uri(Req, #{path => undefined, qs => undefined}).
-
-
HTTP/1.1 origin form (path and query string only)
-
-
%% /path/to/res?edit=1
-cowboy_req:uri(Req, #{host => undefined}).
-
-
Add a fragment to the URI
-
-
%% http://example.org/path/to/res?edit=1#errors
-cowboy_req:uri(Req, #{fragment => <<"errors">>}).
-
-
Ensure the scheme is HTTPS
-
-
%% https://example.org/path/to/res?edit=1
-cowboy_req:uri(Req, #{scheme => <<"https">>}).
-
-
Convert the URI to a binary string
-
-
iolist_to_binary(cowboy_req:uri(Req)).
-
-
-
+
iolist_to_binary(cowboy_req:uri(Req)).
+

See also

- - +

cowboy_req(3), cowboy_req:scheme(3), cowboy_req:host(3), cowboy_req:port(3), cowboy_req:path(3), cowboy_req:qs(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req.version/index.html b/docs/en/cowboy/2.2/manual/cowboy_req.version/index.html index 5e4c84fc..0d978ee3 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req.version/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req.version/index.html @@ -62,88 +62,47 @@

cowboy_req:version(3)

-

Name

-
-

cowboy_req:version - HTTP version

-
-
-
+

cowboy_req:version - HTTP version

Description

-
-
-
-
version(Req :: cowboy_req:req()) -> Version :: cowboy:http_version()
-

Return the HTTP version used for the request.

-

The version can also be obtained using pattern matching:

-
-
-
#{version := Version} = Req.
-
-
-
+
#{version := Version} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The HTTP version used for the request is returned as an -atom. It is provided for informative purposes only.

-
-
-
+

The HTTP version used for the request is returned as an atom. It is provided for informative purposes only.

Changelog

-
-
    -
  • -

    -2.0: Only the version is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the version is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the HTTP version
-
-
Version = cowboy_req:version(Req).
-
-
-
+
Version = cowboy_req:version(Req).
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_req/index.html b/docs/en/cowboy/2.2/manual/cowboy_req/index.html index db88a1b4..640e9c82 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_req/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_req/index.html @@ -62,414 +62,218 @@

cowboy_req(3)

-

Name

-
-

cowboy_req - HTTP request and response

-
-
-
+

cowboy_req - HTTP request and response

Description

-
-

The module cowboy_req provides functions to access, manipulate -and respond to requests.

-

There are four types of functions in this module. They can be -differentiated by their name and their return type:

-
- ---- - - - - - - - - - - - +

The module cowboy_req provides functions to access, manipulate and respond to requests.

+

There are four types of functions in this module. They can be differentiated by their name and their return type:

+
Type Name pattern Return type

access

no verb, parse_*, match_*

Value

+ + + + + + - - - - + + + - - - - + + + - - - - + + + - -
TypeName patternReturn type
accessno verb, parse_*, match_*Value

question

has_*

boolean()

questionhas_*boolean()

modification

set_*

Req

modificationset_*Req

action

any other verb

ok | {Result, Value, Req}

actionany other verbok | {Result, Value, Req}
-
-

Any Req returned must be used in place of the one passed as -argument. Functions that perform an action in particular write -state in the Req object to make sure you are using the function -correctly. For example, it’s only possible to send one response, -and to read the body once.

-
-
-
+ +

Any Req returned must be used in place of the one passed as argument. Functions that perform an action in particular write state in the Req object to make sure you are using the function correctly. For example, it's only possible to send one response, and to read the body once.

Exports

-
-

Connection:

-
-

Raw request:

-
-

Processed request:

-
-

Request body:

-
-

Response:

-
-
-
-
+

Connection:

+ +

Raw request:

+ +

Processed request:

+ +

Request body:

+ +

Response:

+

Types

-
-

push_opts()

-
-
-
push_opts() :: #{
-    method => binary(),            %% case sensitive
-    scheme => binary(),            %% lowercase; case insensitive
-    host   => binary(),            %% lowercase; case insensitive
-    port   => inet:port_number(),
-    qs     => binary()             %% case sensitive
-}
-

Push options.

-

By default, Cowboy will use the GET method, an empty query string, -and take the scheme, host and port directly from the current -request’s URI.

-
-
+
push_opts() :: #{
+    method => binary(),            %% case sensitive
+    scheme => binary(),            %% lowercase; case insensitive
+    host   => binary(),            %% lowercase; case insensitive
+    port   => inet:port_number(),
+    qs     => binary()             %% case sensitive
+}
+
+

Push options.

+

By default, Cowboy will use the GET method, an empty query string, and take the scheme, host and port directly from the current request's URI.

read_body_opts()

-
-
-
read_body_opts() :: #{
-    length  => non_neg_integer(),
-    period  => non_neg_integer(),
-    timeout => timeout()
-}
-

Body reading options.

-

The defaults are function-specific.

-
-
+
read_body_opts() :: #{
+    length  => non_neg_integer(),
+    period  => non_neg_integer(),
+    timeout => timeout()
+}
+
+

Body reading options.

+

The defaults are function-specific.

req()

-
-
-
req() :: #{
-    method  := binary(),               %% case sensitive
-    version := cowboy:http_version() | atom(),
-    scheme  := binary(),               %% lowercase; case insensitive
-    host    := binary(),               %% lowercase; case insensitive
-    port    := inet:port_number(),
-    path    := binary(),               %% case sensitive
-    qs      := binary(),               %% case sensitive
-    headers := cowboy:http_headers(),
-    peer    := {inet:ip_address(), inet:port_number()},
-    sock    := {inet:ip_address(), inet:port_number()},
-    cert    := binary() | undefined
-}
-

The Req object.

-

Contains information about the request and response. While -some fields are publicly documented, others aren’t and shouldn’t -be used.

-

You may add custom fields if required. Make sure to namespace -them by prepending an underscore and the name of your application:

-
-
Setting a custom field
-
-
Req#{_myapp_auth_method => pubkey}.
- -
+
Req#{_myapp_auth_method => pubkey}.
+

resp_body()

-
-
-
resp_body() :: iodata()
-    | {sendfile, Offset, Length, Filename}
+
resp_body() :: iodata()
+    | {sendfile, Offset, Length, Filename}
 
-Offset   :: non_neg_integer()
-Length   :: non_neg_integer()
-Filename :: file:name_all()
-

Response body.

-

It can take two forms: the actual data to be sent or a -tuple indicating which file to send.

-

When sending data directly, the type is either a binary or -an iolist. Iolists are an efficient way to build output. -Instead of concatenating strings or binaries, you can simply -build a list containing the fragments you want to send in the -order they should be sent:

-
-
Example iolists usage
-
-
1> RespBody = ["Hello ", [<<"world">>, $!]].
-["Hello ",[<<"world">>,33]]
-2> io:format("~s~n", [RespBody]).
-Hello world!
-

Note that the length must be greater than zero for any data -to be sent. Cowboy will send an empty body when the length -is zero.

- - - -
+
1> RespBody = ["Hello ", [<<"world">>, $!]].
+["Hello ",[<<"world">>,33]]
+2> io:format("~s~n", [RespBody]).
+Hello world!
+
+

Note that the length must be greater than zero for any data to be sent. Cowboy will send an empty body when the length is zero.

See also

- - +

cowboy(7)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_rest/index.html b/docs/en/cowboy/2.2/manual/cowboy_rest/index.html index 9efdf61f..4c0ac588 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_rest/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_rest/index.html @@ -62,670 +62,475 @@

cowboy_rest(3)

-

Name

-
-

cowboy_rest - REST handlers

-
-
-
+

cowboy_rest - REST handlers

Description

-
-

The module cowboy_rest implements the HTTP state machine.

-

Implementing REST handlers is not enough to provide a REST -interface; this interface must also follow the REST -constraints including HATEOAS (hypermedia as the engine -of application state).

-
-
-
+

The module cowboy_rest implements the HTTP state machine.

+

Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state).

Callbacks

-
-

REST handlers implement the following interface:

-
-
-
init(Req, State)
-    -> {cowboy_rest, Req, State}
-
-Callback(Req, State)
-    -> {Result, Req, State}
-     | {stop, Req, State}
-     | {{switch_handler, Module}, Req, State}
-     | {{switch_handler, Module, Opts}, Req, State}
-
-terminate(Reason, Req, State) -> ok  %% optional
-
-Req    :: cowboy_req:req()
-State  :: any()
-Module :: module()
-Opts   :: any()
-Reason :: normal
-        | {crash, error | exit | throw, any()}
-
-Callback - see below
-Result   - see below
-Default  - see below
-

The init/2 callback is common to all handlers. To switch -to the REST handler behavior, it must return cowboy_rest -as the first element of the tuple.

-

The Callback/2 above represents all the REST-specific -callbacks. They are described in the following section -of this manual. REST-specific callbacks differ by their -name, semantics, result and default values. The default -value is the one used when the callback has not been -implemented. They otherwise all follow the same interface.

-

The stop tuple can be returned to stop REST processing. -If no response was sent before then, Cowboy will send a -204 No Content. The stop tuple can be returned from -any callback, excluding expires, generate_etag, -last_modified and variances.

-

A switch_handler tuple can be returned from these same -callbacks to stop REST processing and switch to a different -handler type. This is very useful to, for example, to stream -the response body.

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the handler. -Cowboy will terminate the process right after this. There -is no need to perform any cleanup in this callback.

-

The following terminate reasons are defined for loop handlers:

-
-
-normal -
-
-

- The handler terminated normally. -

+

REST handlers implement the following interface:

+
+
init(Req, State)
+    -> {cowboy_rest, Req, State}
+
+Callback(Req, State)
+    -> {Result, Req, State}
+     | {stop, Req, State}
+     | {{switch_handler, Module}, Req, State}
+     | {{switch_handler, Module, Opts}, Req, State}
+
+terminate(Reason, Req, State) -> ok  %% optional
+
+Req    :: cowboy_req:req()
+State  :: any()
+Module :: module()
+Opts   :: any()
+Reason :: normal
+        | {crash, error | exit | throw, any()}
+
+Callback - see below
+Result   - see below
+Default  - see below
+
+

The init/2 callback is common to all handlers. To switch to the REST handler behavior, it must return cowboy_rest as the first element of the tuple.

+

The Callback/2 above represents all the REST-specific callbacks. They are described in the following section of this manual. REST-specific callbacks differ by their name, semantics, result and default values. The default value is the one used when the callback has not been implemented. They otherwise all follow the same interface.

+

The stop tuple can be returned to stop REST processing. If no response was sent before then, Cowboy will send a 204 No Content. The stop tuple can be returned from any callback, excluding expires, generate_etag, last_modified and variances.

+

A switch_handler tuple can be returned from these same callbacks to stop REST processing and switch to a different handler type. This is very useful to, for example, to stream the response body.

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the handler. Cowboy will terminate the process right after this. There is no need to perform any cleanup in this callback.

+

The following terminate reasons are defined for loop handlers:

+
normal
+

The handler terminated normally.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
-
-
-
+

REST callbacks

-
-

AcceptCallback

-
-
-
AcceptCallback(Req, State) -> {Result, Req, State}
-
-Result  :: true | {true, URI :: iodata()} | false}
-Default  - crash
-

Process the request body.

-

This function should create or update the resource using the -request body.

-

For PUT requests, the body is a representation of the resource -that is being created or replaced.

-

For POST requests, the body is typically application-specific -instructions on how to process the request, but it may also -be a representation of the resource. When creating a new -resource with POST at a different location, return {true, URI} -with URI the new location.

-

For PATCH requests, the body is a series of instructions on -how to update the resource. Patch files or JSON Patch are -examples of such media types.

-

A response body may be sent. The appropriate media type, charset -and language for the response can be retrieved from the Req -object using the media_type, charset and language keys, -respectively. The body can be set using -cowboy_req:set_resp_body(3).

-
-
+
+
AcceptCallback(Req, State) -> {Result, Req, State}
+
+Result  :: true | {true, URI :: iodata()} | false}
+Default  - crash
+
+

Process the request body.

+

This function should create or update the resource using the request body.

+

For PUT requests, the body is a representation of the resource that is being created or replaced.

+

For POST requests, the body is typically application-specific instructions on how to process the request, but it may also be a representation of the resource. When creating a new resource with POST at a different location, return {true, URI} with URI the new location.

+

For PATCH requests, the body is a series of instructions on how to update the resource. Patch files or JSON Patch are examples of such media types.

+

A response body may be sent. The appropriate media type, charset and language for the response can be retrieved from the Req object using the media_type, charset and language keys, respectively. The body can be set using cowboy_req:set_resp_body(3).

allowed_methods

-
-
-
allowed_methods(Req, State) -> {Result, Req, State}
+
allowed_methods(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% case sensitive
-Default :: [<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]
-

Return the list of allowed methods.

-
-
+Result :: [binary()] %% case sensitive +Default :: [<<"GET">>, <<"HEAD">>, <<"OPTIONS">>] +
+

Return the list of allowed methods.

allow_missing_post

-
-
-
allow_missing_post(Req, State) -> {Result, Req, State}
+
allow_missing_post(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether POST is allowed when the resource doesn’t exist.

-

Returning true here means that a new resource will be -created. The URI for the newly created resource should be -returned from the AcceptCallback function.

-
-
+Result :: boolean() +Default :: true +
+

Return whether POST is allowed when the resource doesn't exist.

+

Returning true here means that a new resource will be created. The URI for the newly created resource should be returned from the AcceptCallback function.

charsets_provided

-
-
-
charsets_provided(Req, State) -> {Result, Req, State}
+
charsets_provided(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% lowercase; case insensitive
-Default  - skip this step
-

Return the list of charsets the resource provides in order -of preference.

-

During content negotiation Cowboy will pick the most -appropriate charset for the client. The client advertises -charsets it prefers with the accept-charset header. When -that header is missing, Cowboy picks the first charset -from the resource.

-

Cowboy will add the negotiated charset to the Req object -after this step completes:

-
-
+

Cowboy will add the negotiated charset to the Req object after this step completes:

+
-
req() :: #{
-    charset => binary()  %% lowercase; case insensitive
-}
-
-
+
req() :: #{
+    charset => binary()  %% lowercase; case insensitive
+}
+

content_types_accepted

-
-
-
content_types_accepted(Req, State) -> {Result, Req, State}
-
-Result     :: [{binary() | ParsedMime, AcceptCallback :: atom()}]
-ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-
-Default     - crash
-

Return the list of media types the resource accepts in -order of preference.

-

A media type is made of different parts. The media type -text/html;charset=utf-8 is of type text, subtype html -and has a single parameter charset with value utf-8.

-

Cowboy will match the content-type request header against -the media types the server accepts and select the appropriate -callback. When that header is missing, or when the server does not -accept this media type, the request fails and an error response -is returned. Cowboy will execute the callback immediately otherwise.

-

An empty parameters list [] means that no parameters will be -accepted. When any parameter is acceptable, the tuple form -should be used with parameters as the atom '*'.

-

Cowboy treats all parameters as case sensitive, except for the -charset parameter, which is known to be case insensitive. You -should therefore always provide the charset as a lowercase -binary string.

- -
+
+
content_types_accepted(Req, State) -> {Result, Req, State}
+
+Result     :: [{binary() | ParsedMime, AcceptCallback :: atom()}]
+ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+Default     - crash
+
+ +

Return the list of media types the resource accepts in order of preference.

+

A media type is made of different parts. The media type text/html;charset=utf-8 is of type text, subtype html and has a single parameter charset with value utf-8.

+ + + +

Cowboy will match the content-type request header against the media types the server accepts and select the appropriate callback. When that header is missing, or when the server does not accept this media type, the request fails and an error response is returned. Cowboy will execute the callback immediately otherwise.

+ +

An empty parameters list [] means that no parameters will be accepted. When any parameter is acceptable, the tuple form should be used with parameters as the atom '*'.

+

Cowboy treats all parameters as case sensitive, except for the charset parameter, which is known to be case insensitive. You should therefore always provide the charset as a lowercase binary string.

+ + + + + +

content_types_provided

-
-
-
content_types_provided(Req, State) -> {Result, Req, State}
-
-Result     :: [{binary() | ParsedMime, ProvideCallback :: atom()}]
-ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-
-Default     - [{{ <<"text">>, <<"html">>, '*'}, to_html}]
-

Return the list of media types the resource provides in -order of preference.

-

A media type is made of different parts. The media type -text/html;charset=utf-8 is of type text, subtype html -and has a single parameter charset with value utf-8.

-

During content negotiation Cowboy will pick the most appropriate -media type for the client. The client advertises media types it -prefers with the accept header. When that header is missing, -the content negotiation fails and an error response is returned.

-

The callback given for the selected media type will be called -at the end of the execution of GET and HEAD requests when a -representation must be sent to the client.

-

An empty parameters list [] means that no parameters will be -accepted. When any parameter is acceptable, the tuple form -should be used with parameters as the atom '*'.

-

Cowboy treats all parameters as case sensitive, except for the -charset parameter, which is known to be case insensitive. You -should therefore always provide the charset as a lowercase -binary string.

-

Cowboy will add the negotiated media_type to the Req object -after this step completes:

-
-
-
req() :: #{
-    media_type => ParsedMime
-}
-
-
+
+
content_types_provided(Req, State) -> {Result, Req, State}
+
+Result     :: [{binary() | ParsedMime, ProvideCallback :: atom()}]
+ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+Default     - [{{ <<"text">>, <<"html">>, '*'}, to_html}]
+
+ + +

Return the list of media types the resource provides in order of preference.

+

A media type is made of different parts. The media type text/html;charset=utf-8 is of type text, subtype html and has a single parameter charset with value utf-8.

+ + + +

During content negotiation Cowboy will pick the most appropriate media type for the client. The client advertises media types it prefers with the accept header. When that header is missing, the content negotiation fails and an error response is returned.

+

The callback given for the selected media type will be called at the end of the execution of GET and HEAD requests when a representation must be sent to the client.

+ +

An empty parameters list [] means that no parameters will be accepted. When any parameter is acceptable, the tuple form should be used with parameters as the atom '*'.

+

Cowboy treats all parameters as case sensitive, except for the charset parameter, which is known to be case insensitive. You should therefore always provide the charset as a lowercase binary string.

+

Cowboy will add the negotiated media_type to the Req object after this step completes:

+
+
req() :: #{
+    media_type => ParsedMime
+}
+
+

delete_completed

-
-
-
delete_completed(Req, State) -> {Result, Req, State}
+
delete_completed(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the resource has been fully deleted from the -system, including from any internal cache.

-

Returning false will result in a 202 Accepted response -being sent instead of a 200 OK or 204 No Content.

-
-
+Result :: boolean() +Default :: true +
+

Return whether the resource has been fully deleted from the system, including from any internal cache.

+

Returning false will result in a 202 Accepted response being sent instead of a 200 OK or 204 No Content.

delete_resource

-
-
-
delete_resource(Req, State) -> {Result, Req, State}
+
delete_resource(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Delete the resource.

-

Cowboy will send an error response when this function -returns false.

- -
+Result :: boolean() +Default :: false +
+

Delete the resource.

+

Cowboy will send an error response when this function returns false.

expires

-
-
-
expires(Req, State) -> {Result, Req, State}
+
expires(Req, State) -> {Result, Req, State}
 
-Result  :: calendar:datetime() | binary() | undefined
-Default :: undefined
-

Return the resource’s expiration date.

- -
+Result :: calendar:datetime() | binary() | undefined +Default :: undefined +
+

Return the resource's expiration date.

forbidden

-
-
-
forbidden(Req, State) -> {Result, Req, State}
+
forbidden(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether access to the resource is forbidden.

-

A 403 Forbidden response will be sent if this -function returns true. This status code means that -access is forbidden regardless of authentication, -and that the request shouldn’t be repeated.

- -
+Result :: boolean() +Default :: false +
+

Return whether access to the resource is forbidden.

+

A 403 Forbidden response will be sent if this function returns true. This status code means that access is forbidden regardless of authentication, and that the request shouldn't be repeated.

generate_etag

-
-
-
generate_etag(Req, State) -> {Result, Req, State}
+
generate_etag(Req, State) -> {Result, Req, State}
 
-Result  :: binary() | {weak | strong, binary()}
-Default  - no etag value
-

Return the entity tag of the resource.

-

When a binary is returned, the value is automatically -parsed to a tuple. The binary must be in the same -format as the etag header, including quotes.

- -
+Result :: binary() | {weak | strong, binary()} +Default - no etag value +
+

Return the entity tag of the resource.

+

When a binary is returned, the value is automatically parsed to a tuple. The binary must be in the same format as the etag header, including quotes.

is_authorized

-
-
-
is_authorized(Req, State) -> {Result, Req, State}
+
is_authorized(Req, State) -> {Result, Req, State}
 
-Result  :: true | {false, AuthHeader :: iodata()}
-Default  - true
-

Return whether the user is authorized to perform the action.

-

This function should be used to perform any necessary -authentication of the user before attempting to perform -any action on the resource.

-

When authentication fails, the AuthHeader value will -be sent in the www-authenticate header for the -401 Unauthorized response.

- -
+Result :: true | {false, AuthHeader :: iodata()} +Default - true +
+

Return whether the user is authorized to perform the action.

+

This function should be used to perform any necessary authentication of the user before attempting to perform any action on the resource.

+

When authentication fails, the AuthHeader value will be sent in the www-authenticate header for the 401 Unauthorized response.

is_conflict

-
-
-
is_conflict(Req, State) -> {Result, Req, State}
+
is_conflict(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the PUT request results in a conflict.

-

A 409 Conflict response is sent when true.

- -
+Result :: boolean() +Default :: false +
+

Return whether the PUT request results in a conflict.

+

A 409 Conflict response is sent when true.

known_methods

-
-
-
known_methods(Req, State) -> {Result, Req, State}
+
known_methods(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% case sensitive
-Default :: [<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>,
-            <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]
-

Return the list of known methods.

-

The full list of methods known by the server should be -returned, regardless of their use in the resource.

-

The default value lists the methods Cowboy knows and -implement in cowboy_rest.

- -
+Result :: [binary()] %% case sensitive +Default :: [<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, + <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>] +
+

Return the list of known methods.

+

The full list of methods known by the server should be returned, regardless of their use in the resource.

+

The default value lists the methods Cowboy knows and implement in cowboy_rest.

languages_provided

-
-
-
languages_provided(Req, State) -> {Result, Req, State}
+
languages_provided(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% lowercase; case insensitive
-Default  - skip this step
-

Return the list of languages the resource provides in order -of preference.

-

During content negotiation Cowboy will pick the most -appropriate language for the client. The client advertises -languages it prefers with the accept-language header. When -that header is missing, Cowboy picks the first language -from the resource.

-

Cowboy will add the negotiated language to the Req object -after this step completes:

-
-
+

Cowboy will add the negotiated language to the Req object after this step completes:

+
-
req() :: #{
-    language => binary()  %% lowercase; case insensitive
-}
-
-
+
req() :: #{
+    language => binary()  %% lowercase; case insensitive
+}
+

last_modified

-
-
-
last_modified(Req, State) -> {Result, Req, State}
+
last_modified(Req, State) -> {Result, Req, State}
 
-Result  :: calendar:datetime()
-Default  - no last modified value
-

Return the resource’s last modification date.

-

This date will be used to test against the if-modified-since -and if-unmodified-since headers, and sent as the last-modified -header in the response to GET and HEAD requests.

- -
+Result :: calendar:datetime() +Default - no last modified value +
+

Return the resource's last modification date.

+

This date will be used to test against the if-modified-since and if-unmodified-since headers, and sent as the last-modified header in the response to GET and HEAD requests.

malformed_request

-
-
-
malformed_request(Req, State) -> {Result, Req, State}
+
malformed_request(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the request is malformed.

-

A request is malformed when a component required by the -resource is invalid. This may include the query string -or individual headers. They should be parsed and validated -in this function. The body should not be read at this point.

- -
+Result :: boolean() +Default :: false +
+

Return whether the request is malformed.

+

A request is malformed when a component required by the resource is invalid. This may include the query string or individual headers. They should be parsed and validated in this function. The body should not be read at this point.

moved_permanently

-
-
-
moved_permanently(Req, State) -> {Result, Req, State}
+
moved_permanently(Req, State) -> {Result, Req, State}
 
-Result  :: {true, URI :: iodata()} | false
-Default :: false
-

Return whether the resource was permanently moved, and -what its new location is.

- -
+Result :: {true, URI :: iodata()} | false +Default :: false +
+

Return whether the resource was permanently moved, and what its new location is.

moved_temporarily

-
-
-
moved_temporarily(Req, State) -> {Result, Req, State}
+
moved_temporarily(Req, State) -> {Result, Req, State}
 
-Result  :: {true, URI :: iodata()} | false
-Default :: false
-

Return whether the resource was temporarily moved, and -what its new location is.

- -
+Result :: {true, URI :: iodata()} | false +Default :: false +
+

Return whether the resource was temporarily moved, and what its new location is.

multiple_choices

-
-
-
multiple_choices(Req, State) -> {Result, Req, State}
-
-Result  :: boolean()
-Default :: false
-

Return whether the client should engage in reactive -negotiation.

-

Return true when the server has multiple representations -of a resource, each with their specific identifier, but is -unable to determine which is best for the client. For -example an image might have different sizes and the server -is unable to determine the capabilities of the client.

-

When returning true the server should send a body with -links to the different representations. If the server has -a preferred representation it can send its link inside a -location header.

- -
+
+
multiple_choices(Req, State) -> {Result, Req, State}
+
+Result  :: boolean()
+Default :: false
+
+

Return whether the client should engage in reactive negotiation.

+

Return true when the server has multiple representations of a resource, each with their specific identifier, but is unable to determine which is best for the client. For example an image might have different sizes and the server is unable to determine the capabilities of the client.

+

When returning true the server should send a body with links to the different representations. If the server has a preferred representation it can send its link inside a location header.

options

-
-
-
options(Req, State) -> {ok, Req, State}
-

Respond to an OPTIONS request.

-

The response should inform the client the communication -options available for this resource. By default Cowboy -will send a 200 OK response with the allow header set.

-
-
+
options(Req, State) -> {ok, Req, State}
+
+

Respond to an OPTIONS request.

+

The response should inform the client the communication options available for this resource. By default Cowboy will send a 200 OK response with the allow header set.

previously_existed

-
-
-
previously_existed(Req, State) -> {Result, Req, State}
+
previously_existed(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the resource existed previously.

- -
+Result :: boolean() +Default :: false +
+

Return whether the resource existed previously.

ProvideCallback

-
-
-
ProvideCallback(Req, State) -> {Result, Req, State}
+
ProvideCallback(Req, State) -> {Result, Req, State}
 
-Result  :: cowboy_req:resp_body()
-Default  - crash
-

Return the response body.

-

The response body can be provided either as the actual data -to be sent or a tuple indicating which file to send.

-

This function is called for both GET and HEAD requests. For -the latter the body is not sent, however.

-

Note that there used to be a way to stream the response body. -It was temporarily removed and will be added back in a later -release.

- -
+Result :: cowboy_req:resp_body() +Default - crash +
+

Return the response body.

+

The response body can be provided either as the actual data to be sent or a tuple indicating which file to send.

+

This function is called for both GET and HEAD requests. For the latter the body is not sent, however.

+ + + +

Note that there used to be a way to stream the response body. It was temporarily removed and will be added back in a later release.

+

resource_exists

-
-
-
resource_exists(Req, State) -> {Result, Req, State}
+
resource_exists(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the resource exists.

- -
+Result :: boolean() +Default :: true +
+

Return whether the resource exists.

service_available

-
-
-
service_available(Req, State) -> {Result, Req, State}
+
service_available(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the service is available.

-

A 503 Service Unavailable response will be sent when this -function returns false.

- -
+Result :: boolean() +Default :: true +
+

Return whether the service is available.

+

A 503 Service Unavailable response will be sent when this function returns false.

uri_too_long

-
-
-
uri_too_long(Req, State) -> {Result, Req, State}
+
uri_too_long(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the requested URI is too long.

-

This function can be used to further restrict the length -of the URI for this specific resource.

- -
+Result :: boolean() +Default :: false +
+

Return whether the requested URI is too long.

+

This function can be used to further restrict the length of the URI for this specific resource.

valid_content_headers

-
-
-
valid_content_headers(Req, State) -> {Result, Req, State}
+
valid_content_headers(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the content headers are valid.

-

This callback can be used to reject requests that have -invalid content header values, for example an unsupported -content-encoding.

- -
+Result :: boolean() +Default :: true +
+

Return whether the content headers are valid.

+

This callback can be used to reject requests that have invalid content header values, for example an unsupported content-encoding.

valid_entity_length

-
-
-
valid_entity_length(Req, State) -> {Result, Req, State}
+
valid_entity_length(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the request body length is within acceptable boundaries.

-

A 413 Request Entity Too Large response will be sent if this -function returns false.

- -
+Result :: boolean() +Default :: true +
+

Return whether the request body length is within acceptable boundaries.

+

A 413 Request Entity Too Large response will be sent if this function returns false.

variances

-
-
-
variances(Req, State) -> {Result, Req, State}
+
variances(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% case insensitive
-Default :: []
-

Return the list of request headers that affect the -representation of the resource.

-

Cowboy automatically adds the accept, accept-charset and -accept-language headers when necessary. It’s also useful -to note that some standard headers also do not need to be -listed here, like the authorization header.

- - - -
+Result :: [binary()] %% case insensitive +Default :: [] +
+

Return the list of request headers that affect the representation of the resource.

+

Cowboy automatically adds the accept, accept-charset and accept-language headers when necessary. It's also useful to note that some standard headers also do not need to be listed here, like the authorization header.

Changelog

-
-
    -
  • -

    -2.1: The switch_handler return value was added. -

    +
    • 2.1: The switch_handler return value was added.
    • -
    • -

      -1.0: Behavior introduced. -

      +
    • 1.0: Behavior introduced.
    • -
-
- -
+

See also

- -
+

cowboy(7), cowboy_handler(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_router.compile/index.html b/docs/en/cowboy/2.2/manual/cowboy_router.compile/index.html index 129cab1f..3f134779 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_router.compile/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_router.compile/index.html @@ -62,87 +62,48 @@

cowboy_router:compile(3)

-

Name

-
-

cowboy_router:compile - Compile routes to the resources

-
-
-
+

cowboy_router:compile - Compile routes to the resources

Description

-
-
-
-
compile(cowboy_router:routes()) -> cowboy_router:dispatch_rules()
-

Compile routes to the resources.

-

Takes a human readable list of routes and transforms it -into a form more efficient to process.

-
-
-
+
compile(cowboy_router:routes()) -> cowboy_router:dispatch_rules()
+
+

Compile routes to the resources.

+

Takes a human readable list of routes and transforms it into a form more efficient to process.

Arguments

-
-
-
-Routes -
-
-

-Human readable list of routes. -

+
Routes
+

Human readable list of routes.

-
-
- -
+

Return value

-
-

An opaque dispatch rules value is returned. This value -must be given to Cowboy as a middleware environment value.

-
-
-
+

An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Compile routes and start a listener
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []},
-        {"/[...], cowboy_static, {priv_dir, my_example_app, ""}}
-    ]}
-]),
-
-{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{
-    env => #{dispatch => Dispatch}
-}).
-
-
-
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []},
+        {"/[...], cowboy_static, {priv_dir, my_example_app, ""}}
+    ]}
+]),
+
+{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{
+    env => #{dispatch => Dispatch}
+}).
+

See also

- - +

cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_router/index.html b/docs/en/cowboy/2.2/manual/cowboy_router/index.html index 94b6438d..10333a5c 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_router/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_router/index.html @@ -62,110 +62,65 @@

cowboy_router(3)

-

Name

-
-

cowboy_router - Router middleware

-
-
-
+

cowboy_router - Router middleware

Description

-
-

The cowboy_router middleware maps the requested host and -path to the handler to be used for processing the request.

-

The router takes the dispatch rules as input from the -middleware environment. Dispatch rules are generated by -calling the -cowboy_router:compile(3) -function.

-

When a route matches, the router sets the handler and -handler_opts middleware environment values containing -the handler module and initial state, respectively.

-

The router will stop execution when no route matches. -It will send a 400 response if no host was found, and -a 404 response otherwise.

-
-
-
+

The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request.

+

The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function.

+

When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively.

+

The router will stop execution when no route matches. It will send a 400 response if no host was found, and a 404 response otherwise.

Exports

-
-
-
-
-
+

Types

-
-

bindings()

-
-
-
bindings() :: #{atom() => any()}
-

Bindings found during routing.

-
-
+
bindings() :: #{atom() => any()}
+
+

Bindings found during routing.

dispatch_rules()

-

Opaque type containing the compiled routes.

-
-
+

Opaque type containing the compiled routes.

routes()

-
-
-
routes() = [
-    {Host, PathList} |
-    {Host, Fields, PathList}
+
routes() = [
+    {Host, PathList} |
+    {Host, Fields, PathList}
 ]
 
-PathList :: [
-    {Path, Handler, InitialState} |
-    {Path, Fields, Handler, InitialState}
+PathList :: [
+    {Path, Handler, InitialState} |
+    {Path, Fields, Handler, InitialState}
 ]
 
-Host         :: '_' | iodata()
-Path         :: '_' | iodata()
-Fields       :: cowboy:fields()
-Handler      :: module()
-InitialState :: any()
-

Human readable list of routes to handlers.

-

Cowboy uses this list to map hosts and paths, optionally -augmented with constraints applied to the bindings, to -handler modules.

-

The syntax for routes is currently defined in the user guide.

-
-
+Host :: '_' | iodata() +Path :: '_' | iodata() +Fields :: cowboy:fields() +Handler :: module() +InitialState :: any() +
+

Human readable list of routes to handlers.

+

Cowboy uses this list to map hosts and paths, optionally augmented with constraints applied to the bindings, to handler modules.

+

The syntax for routes is currently defined in the user guide.

+ +

tokens()

-
-
-
tokens() :: [binary()]
-

List of host_info and path_info tokens that were found -using the ... syntax.

- - - -
+
tokens() :: [binary()]
+
+

List of host_info and path_info tokens that were found using the ... syntax.

See also

- - +

cowboy(7), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:host_info(3), cowboy_req:path_info(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_static/index.html b/docs/en/cowboy/2.2/manual/cowboy_static/index.html index 6c6d8ca6..f0c0e34a 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_static/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_static/index.html @@ -62,175 +62,110 @@

cowboy_static(3)

-

Name

-
-

cowboy_static - Static file handler

-
-
-
+

cowboy_static - Static file handler

Description

-
-

The module cowboy_static implements file serving capabilities -using the REST semantics provided by cowboy_rest.

-

The static file handler is a pre-written handler coming with -Cowboy. To serve files, use it in your routes.

-
-
-
+

The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest.

+

The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes.

Options

-
-
-
-
opts() :: {priv_file, App, Path}
-        | {priv_file, App, Path, Extra}
-        | {file, Path}
-        | {file, Path, Extra}
-        | {priv_dir, App, Path}
-        | {priv_dir, App, Path, Extra}
-        | {dir, Path}
-        | {dir, Path, Extra}
-
-App        :: atom()
-Path       :: binary() | string()
-Extra      :: [Etag | Mimetypes]
-
-Etag       :: {etag, module(), function()}
-            | {etag, false}
-
-Mimetypes  :: {mimetypes, module(), function()}
-            | {mimetypes, binary() | ParsedMime}
-
-ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-

Static handler configuration.

-
-
-priv_file -
-
-

-Send a file. -

-

The path is relative to the given application’s private -directory.

+
opts() :: {priv_file, App, Path}
+        | {priv_file, App, Path, Extra}
+        | {file, Path}
+        | {file, Path, Extra}
+        | {priv_dir, App, Path}
+        | {priv_dir, App, Path, Extra}
+        | {dir, Path}
+        | {dir, Path, Extra}
+
+App        :: atom()
+Path       :: binary() | string()
+Extra      :: [Etag | Mimetypes]
+
+Etag       :: {etag, module(), function()}
+            | {etag, false}
+
+Mimetypes  :: {mimetypes, module(), function()}
+            | {mimetypes, binary() | ParsedMime}
+
+ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+

Static handler configuration.

+
priv_file
+

Send a file.

+

The path is relative to the given application's private directory.

-
-file -
-
-

-Send a file. -

-

The path is either absolute or relative to the Erlang node’s -current directory.

+
file
+

Send a file.

+

The path is either absolute or relative to the Erlang node's current directory.

-
-priv_dir -
-
-

-Recursively serve files from a directory. -

-

The path is relative to the given application’s private -directory.

+
priv_dir
+

Recursively serve files from a directory.

+

The path is relative to the given application's private directory.

-
-dir -
-
-

-Recursively serve files from a directory. -

-

The path is either absolute or relative to the Erlang node’s -current directory.

+
dir
+

Recursively serve files from a directory.

+

The path is either absolute or relative to the Erlang node's current directory.

-
-

The extra options allow you to define how the etag should be -calculated and how the MIME type of files should be detected.

-

By default the static handler will generate an etag based -on the size and modification time of the file. You may disable -the etag entirely with {etag, false} or provide a module -and function that will be called when needed:

-
-
-
generate_etag(Path, Size, Mtime) -> {strong | weak, binary()}
-
-Path  :: binary()
-Size  :: non_neg_integer()
-Mtime :: file:date_time()
-

By default the static handler will detect Web-related MIME types -by looking at the file extension. You can provide a specific -MIME type that will always be used, or a module and function that -will be called when needed:

-
-
-
detect_mimetype(Path) -> ParsedMime
-
-Path       :: binary()
-ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-

Cowboy comes with two such functions; the default function -cow_mimetypes:web/1, and a second function generated from -the Apache mime.types file, cow_mimetypes:all/1.

-

The MIME type function should return -{<<"application">>, <<"octet-stream">>, []} -when it fails to detect a file’s MIME type.

- - -
+
detect_mimetype(Path) -> ParsedMime
+
+Path       :: binary()
+ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+ +

Cowboy comes with two such functions; the default function cow_mimetypes:web/1, and a second function generated from the Apache mime.types file, cow_mimetypes:all/1.

+

The MIME type function should return {<<"application">>, <<"octet-stream">>, []} when it fails to detect a file's MIME type.

Changelog

-
-
    -
  • -

    -1.0: Handler introduced. -

    +
    • 1.0: Handler introduced.
    • -
-
- -
+

Examples

-
-
-
Custom etag function
-
-
generate_etag(Path, Size, Mtime) ->
-    {strong, integer_to_binary(
-        erlang:phash2({Path, Size, Mtime}, 16#ffffffff))}.
-
-
Custom MIME type function
-
-
always_octet_stream(_Path) ->
-    case filename:extension(Path) of
-        <<".erl">> -> {<<"text">>, <<"plain">>, []};
-        _ -> {<<"application">>, <<"octet-stream">>, []}
-    end.
-
-
-
+
always_octet_stream(_Path) ->
+    case filename:extension(Path) of
+        <<".erl">> -> {<<"text">>, <<"plain">>, []};
+        _ -> {<<"application">>, <<"octet-stream">>, []}
+    end.
+

See also

- - +

cowboy(7), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_stream/index.html b/docs/en/cowboy/2.2/manual/cowboy_stream/index.html index 1e2e3b35..8b2675a4 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_stream/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_stream/index.html @@ -62,452 +62,307 @@

cowboy_stream(3)

-

Name

-
-

cowboy_handler - Stream handlers

-
-
-
+

cowboy_handler - Stream handlers

Description

-
-

The module cowboy_stream defines a callback interface -and a protocol for handling HTTP streams.

-

An HTTP request and its associated response is called -a stream. A connection may have many streams. In HTTP/1.1 -they are executed sequentially, while in HTTP/2 they are -executed concurrently.

-

Cowboy calls the stream handler for nearly all events -related to a stream. Exceptions vary depending on the -protocol.

-

Extra care must be taken when implementing stream handlers -to ensure compatibility. While some modification of the -events and commands is allowed, it is generally not a good -idea to completely omit them.

-
-
-
+

The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams.

+

An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently.

+

Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol.

+

Extra care must be taken when implementing stream handlers to ensure compatibility. While some modification of the events and commands is allowed, it is generally not a good idea to completely omit them.

Callbacks

-
-

Stream handlers must implement the following interface:

-
-
-
init(StreamID, Req, Opts) -> {Commands, State}
-data(StreamID, IsFin, Data, State) -> {Commands, State}
-info(StreamID, Info, State) -> {Commands, State}
-terminate(StreamID, Reason, State) -> any()
-early_error(StreamID, Reason, PartialReq, Resp, Opts) -> Resp
-
-StreamID   :: cowboy_stream:streamid()
-Req        :: cowboy_req:req()
-Opts       :: cowboy:opts()
-Commands   :: cowboy_stream:commands()
-State      :: any()
-IsFin      :: cowboy_stream:fin()
-Data       :: binary()
-Info       :: any()
-Reason     :: cowboy_stream:reason()
-PartialReq  - cowboy_req:req(), except all fields are optional
-Resp       :: cowboy_stream:resp_command()
-

HTTP/1.1 will initialize a stream only when the request-line -and all headers have been received. When errors occur before -that point Cowboy will call the callback early_error/5 -with a partial request, the error reason and the response -Cowboy intends to send. All other events go throuh the -stream handler using the normal callbacks.

-

HTTP/2 will initialize the stream when the HEADERS block has -been fully received and decoded. Any protocol error occuring -before that will not result in a response being sent and -will therefore not go through the stream handler. In addition -Cowboy may terminate streams without sending an HTTP response -back.

-

The stream is initialized by calling init/3. All streams -that are initialized will eventually be terminated by calling -terminate/3.

-

When Cowboy receives data for the stream it will call data/4. -The data given is the request body after any transfer decoding -has been applied.

-

When Cowboy receives a message addressed to a stream, or when -Cowboy needs to inform the stream handler that an internal -event has occurred, it will call info/3.

-
-
-
+
init(StreamID, Req, Opts) -> {Commands, State}
+data(StreamID, IsFin, Data, State) -> {Commands, State}
+info(StreamID, Info, State) -> {Commands, State}
+terminate(StreamID, Reason, State) -> any()
+early_error(StreamID, Reason, PartialReq, Resp, Opts) -> Resp
+
+StreamID   :: cowboy_stream:streamid()
+Req        :: cowboy_req:req()
+Opts       :: cowboy:opts()
+Commands   :: cowboy_stream:commands()
+State      :: any()
+IsFin      :: cowboy_stream:fin()
+Data       :: binary()
+Info       :: any()
+Reason     :: cowboy_stream:reason()
+PartialReq  - cowboy_req:req(), except all fields are optional
+Resp       :: cowboy_stream:resp_command()
+
+

HTTP/1.1 will initialize a stream only when the request-line and all headers have been received. When errors occur before that point Cowboy will call the callback early_error/5 with a partial request, the error reason and the response Cowboy intends to send. All other events go throuh the stream handler using the normal callbacks.

+

HTTP/2 will initialize the stream when the HEADERS block has been fully received and decoded. Any protocol error occuring before that will not result in a response being sent and will therefore not go through the stream handler. In addition Cowboy may terminate streams without sending an HTTP response back.

+

The stream is initialized by calling init/3. All streams that are initialized will eventually be terminated by calling terminate/3.

+

When Cowboy receives data for the stream it will call data/4. The data given is the request body after any transfer decoding has been applied.

+

When Cowboy receives a message addressed to a stream, or when Cowboy needs to inform the stream handler that an internal event has occurred, it will call info/3.

Commands

-
-

Stream handlers can return a list of commands to be executed -from the init/3, data/4 and info/3 callbacks. In addition, -the early_error/5 callback must return a response command.

-

The following commands are defined:

-
+

Stream handlers can return a list of commands to be executed from the init/3, data/4 and info/3 callbacks. In addition, the early_error/5 callback must return a response command.

+ + + + + +

The following commands are defined:

inform

-

Send an informational response to the client.

-
-
-
{inform, cowboy:http_status(), cowboy:http_headers()}
-

Any number of informational responses may be sent, -but only until the final response is sent.

-
-
+
{inform, cowboy:http_status(), cowboy:http_headers()}
+
+

Any number of informational responses may be sent, but only until the final response is sent.

response

-

Send a response to the client.

-
-
-
{response, cowboy:http_status(), cowboy:http_headers(),
-    cowboy_req:resp_body()}
-

No more data can be sent after this command.

- -
+
{response, cowboy:http_status(), cowboy:http_headers(),
+    cowboy_req:resp_body()}
+
+

No more data can be sent after this command.

headers

-

Initiate a response to the client.

-
-
-
{headers, cowboy:http_status(), cowboy:http_headers()}
-

This initiates a response to the client. The stream -will end when a data command with the fin flag or -a trailer command is returned.

- -
+
{headers, cowboy:http_status(), cowboy:http_headers()}
+
+

This initiates a response to the client. The stream will end when a data command with the fin flag or a trailer command is returned.

data

-

Send data to the client.

-
-
-
{data, fin(), iodata()}
- -
+
{data, fin(), iodata()}
+

trailers

-

Send response trailers to the client.

-
-
-
{trailers, cowboy:http_headers()}
- -
+
{trailers, cowboy:http_headers()}
+

push

-

Push a resource to the client.

-
-
-
{push, Method, Scheme, Host, inet:port_number(),
-    Path, Qs, cowboy:http_headers()}
+
{push, Method, Scheme, Host, inet:port_number(),
+    Path, Qs, cowboy:http_headers()}
 
-Method = Scheme = Host = Path = Qs = binary()
-

The command will be ignored if the protocol does not provide -any server push mechanism.

- -
+Method = Scheme = Host = Path = Qs = binary() +
+

The command will be ignored if the protocol does not provide any server push mechanism.

flow

-
-
-
{flow, pos_integer()}
-

Request more data to be read from the request body. The -exact behavior depends on the protocol.

- -
+
{flow, pos_integer()}
+
+

Request more data to be read from the request body. The exact behavior depends on the protocol.

spawn

-

Inform Cowboy that a process was spawned and should be -supervised.

-
-
-
{spawn, pid(), timeout()}
- -
+
{spawn, pid(), timeout()}
+

error_response

-

Send an error response if no response was sent previously.

-
-
-
{error_response, cowboy:http_status(), cowboy:http_headers(), iodata()}
- -
+
{error_response, cowboy:http_status(), cowboy:http_headers(), iodata()}
+

switch_protocol

-

Switch to a different protocol.

-
-
-
{switch_protocol, cowboy:http_headers(), module(), state()}
-

Contains the headers that will be sent in the 101 response, -along with the module implementing the protocol we are -switching to and its initial state.

- -
+
{switch_protocol, cowboy:http_headers(), module(), state()}
+
+

Contains the headers that will be sent in the 101 response, along with the module implementing the protocol we are switching to and its initial state.

stop

-

Stop the stream.

-
-
-
stop
-

While no more data can be sent after the fin flag was set, -the stream is still tracked by Cowboy until it is stopped by -the handler.

-

The behavior when stopping a stream for which no response -has been sent will vary depending on the protocol. The stream -will end successfully as far as the client is concerned.

-

To indicate that an error occurred, either use error_response -before stopping, or use internal_error.

- -
+
stop
+
+

While no more data can be sent after the fin flag was set, the stream is still tracked by Cowboy until it is stopped by the handler.

+

The behavior when stopping a stream for which no response has been sent will vary depending on the protocol. The stream will end successfully as far as the client is concerned.

+

To indicate that an error occurred, either use error_response before stopping, or use internal_error.

internal_error

-

Stop the stream with an error.

-
-
-
{internal_error, Reason, HumanReadable}
-
-Reason        = any()
-HumanReadable = atom()
-

This command should be used when the stream cannot continue -because of an internal error. An error_response command -may be sent before that to advertise to the client why the -stream is dropped.

- - - -
+
{internal_error, Reason, HumanReadable}
+
+Reason        = any()
+HumanReadable = atom()
+
+

This command should be used when the stream cannot continue because of an internal error. An error_response command may be sent before that to advertise to the client why the stream is dropped.

Predefined events

-
-

Cowboy will forward all messages sent to the stream to -the info/3 callback. To send a message to a stream, -send a message to the connection process with the form -{{Pid, StreamID}, Msg}. The connection process will -then forward Msg to the stream handlers.

-

Cowboy will also forward the exit signals for the -processes that the stream spawned.

-
+

Cowboy will forward all messages sent to the stream to the info/3 callback. To send a message to a stream, send a message to the connection process with the form {{Pid, StreamID}, Msg}. The connection process will then forward Msg to the stream handlers.

+

Cowboy will also forward the exit signals for the processes that the stream spawned.

EXIT

-

A process spawned by this stream has exited.

-
-
+ + +

A process spawned by this stream has exited.

+
-
{'EXIT', pid(), any()}
-

This is the raw exit message without any modification.

-
-
+
{'EXIT', pid(), any()}
+
+

This is the raw exit message without any modification.

+ + + + + + + + + + + + + + + + +

inform

-

Same as the inform command.

-

Sent when the request process reads the body and an -expect: 100-continue header was present in the request, -or when the request process sends an informational -response on its own.

-
-
+

Same as the inform command.

+

Sent when the request process reads the body and an expect: 100-continue header was present in the request, or when the request process sends an informational response on its own.

response

-

Same as the response command.

-

Usually sent when the request process replies to the client. -May also be sent by Cowboy internally.

-
-
+

Same as the response command.

+

Usually sent when the request process replies to the client. May also be sent by Cowboy internally.

headers

-

Same as the headers command.

-

Sent when the request process starts replying to the client.

-
-
+

Same as the headers command.

+

Sent when the request process starts replying to the client.

data

-

Same as the data command.

-

Sent when the request process streams data to the client.

-
-
+

Same as the data command.

+

Sent when the request process streams data to the client.

trailers

-

Same as the trailers command.

-

Sent when the request process sends the trailer field values -to the client.

-
-
+

Same as the trailers command.

+

Sent when the request process sends the trailer field values to the client.

push

-

Same as the push command.

-

Sent when the request process pushes a resource to the client.

-
-
+

Same as the push command.

+

Sent when the request process pushes a resource to the client.

switch_protocol

- -

Sent when switching to the HTTP/2 or Websocket protocol.

-
-
- -
+

Same as the switch_protocol command.

+ +

Sent when switching to the HTTP/2 or Websocket protocol.

Exports

-
-

The following function should be called by modules implementing -stream handlers to execute the next stream handler in the list:

-
-
-
-
+

Types

-
-

commands()

-
-
-
commands() :: [Command]
-

See the list of commands for details.

-
-
+
commands() :: [Command]
+
+

See the list of commands for details.

fin()

-
-
-
fin() :: fin | nofin
-

Used in commands and events to indicate that this is -the end of the stream.

-
-
+
fin() :: fin | nofin
+
+

Used in commands and events to indicate that this is the end of the stream.

partial_req()

-
-
-
req() :: #{
-    method  => binary(),               %% case sensitive
-    version => cowboy:http_version() | atom(),
-    scheme  => binary(),               %% lowercase; case insensitive
-    host    => binary(),               %% lowercase; case insensitive
-    port    => inet:port_number(),
-    path    => binary(),               %% case sensitive
-    qs      => binary(),               %% case sensitive
-    headers => cowboy:http_headers(),
-    peer    => {inet:ip_address(), inet:port_number()}
-}
-

Partial request information received when an early error is -detected.

- -
+
req() :: #{
+    method  => binary(),               %% case sensitive
+    version => cowboy:http_version() | atom(),
+    scheme  => binary(),               %% lowercase; case insensitive
+    host    => binary(),               %% lowercase; case insensitive
+    port    => inet:port_number(),
+    path    => binary(),               %% case sensitive
+    qs      => binary(),               %% case sensitive
+    headers => cowboy:http_headers(),
+    peer    => {inet:ip_address(), inet:port_number()}
+}
+
+

Partial request information received when an early error is detected.

reason()

-
-
-
reason() :: normal | switch_protocol
-    | {internal_error, timeout | {error | exit | throw, any()}, HumanReadable}
-    | {socket_error, closed | atom(), HumanReadable}
-    | {stream_error, Error, HumanReadable}
-    | {connection_error, Error, HumanReadable}
-    | {stop, cow_http2:frame(), HumanReadable}
-
-Error         = atom()
-HumanReadable = atom()
-

Reason for the stream termination.

- -
+
reason() :: normal | switch_protocol
+    | {internal_error, timeout | {error | exit | throw, any()}, HumanReadable}
+    | {socket_error, closed | atom(), HumanReadable}
+    | {stream_error, Error, HumanReadable}
+    | {connection_error, Error, HumanReadable}
+    | {stop, cow_http2:frame(), HumanReadable}
+
+Error         = atom()
+HumanReadable = atom()
+
+

Reason for the stream termination.

resp_command()

-
-
-
resp_command() :: {response, cowboy:http_status(),
-    cowboy:http_headers(), cowboy_req:resp_body()}
-

See the response command for details.

- -
+
resp_command() :: {response, cowboy:http_status(),
+    cowboy:http_headers(), cowboy_req:resp_body()}
+
+

See the response command for details.

streamid()

-
-
-
streamid() :: any()
-

The identifier for this stream.

-

The identifier is unique over the connection process. -It is possible to form a unique identifier node-wide and -cluster-wide by wrapping it in a {self(), StreamID} -tuple.

- - - -
+
streamid() :: any()
+
+

The identifier for this stream.

+

The identifier is unique over the connection process. It is possible to form a unique identifier node-wide and cluster-wide by wrapping it in a {self(), StreamID} tuple.

Changelog

-
-
    -
  • -

    -2.2: The trailers command was introduced. -

    +
    • 2.2: The trailers command was introduced.
    • -
    • -

      -2.0: Module introduced. -

      +
    • 2.0: Module introduced.
    • -
-
- - +

cowboy(7), cowboy_http(3), cowboy_http2(3)

+ diff --git a/docs/en/cowboy/2.2/manual/cowboy_websocket/index.html b/docs/en/cowboy/2.2/manual/cowboy_websocket/index.html index 90bae6a8..4b805744 100644 --- a/docs/en/cowboy/2.2/manual/cowboy_websocket/index.html +++ b/docs/en/cowboy/2.2/manual/cowboy_websocket/index.html @@ -62,295 +62,144 @@

cowboy_websocket(3)

-

Name

-
-

cowboy_websocket - Websocket

-
-
-
+

cowboy_websocket - Websocket

Description

-
-

The module cowboy_websocket implements Websocket -as a Ranch protocol. It also defines a callback interface -for handling Websocket connections.

-
-
-
+

The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections.

Callbacks

-
-

Websocket handlers must implement the following callback -interface:

-
-
-
init(Req, State)
-    -> {cowboy_websocket, Req, State}
-     | {cowboy_websocket, Req, State, Opts}
-
-websocket_init(State)            -> CallResult  %% optional
-websocket_handle(InFrame, State) -> CallResult
-websocket_info(Info, State)      -> CallResult
-
-terminate(Reason, PartialReq, State) -> ok      %% optional
-
-Req        :: cowboy_req:req()
-PartialReq :: map()
-State      :: any()
-Opts       :: cowboy_websocket:opts()
-InFrame    :: {text | binary | ping | pong, binary()}
-OutFrame   :: cow_ws:frame()                    %% see types below
-Info       :: any()
-
-CallResult :: {ok, State}
-            | {ok, State, hibernate}
-            | {reply, OutFrame | [OutFrame], State}
-            | {reply, OutFrame | [OutFrame], State, hibernate}
-            | {stop, State}
-
-Reason     :: normal | stop | timeout
-            | remote | {remote, cow_ws:close_code(), binary()}
-            | {error, badencoding | badframe | closed | atom()}
-            | {crash, error | exit | throw, any()}
-

The init/2 callback is common to all handlers. To upgrade -the connection to Websocket, it must return cowboy_websocket -as the first element of the tuple.

-

Any operation requiring the HTTP request must be done in the -init/2 function, as the Req object will not be available -after it returns. Websocket sub-protocol selection should -therefore be done in this function.

-

The optional websocket_init/1 callback will be called once -the connection has been upgraded to Websocket. It can be used -to perform any required initialization of the handler.

-

Note that the init/2 function does not run in the same -process as the Websocket callbacks. Any Websocket-specific -initialization must be done in websocket_init/1.

-

The websocket_handle/2 callback will be called for every -frame received. The websocket_info/2 callback will be -called for every Erlang message received.

-

All three Websocket callbacks may send one or more frames -back to the client (by returning a reply tuple) or terminate -the connection (by sending a close frame or returning a stop -tuple).

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the connection. This -callback is common to all handlers. Note that Websocket will -not provide the full Req object by default, to save memory.

-

Cowboy will terminate the process right after closing the -Websocket connection. This means that there is no need to -perform any cleanup in the terminate/3 callback.

-

The following terminate reasons are defined for Websocket -connections:

-
-
-normal -
-
-

- The connection was closed normally before establishing a Websocket - connection. This typically happens if an ok tuple is returned - from the init/2 callback. -

+
init(Req, State)
+    -> {cowboy_websocket, Req, State}
+     | {cowboy_websocket, Req, State, Opts}
+
+websocket_init(State)            -> CallResult  %% optional
+websocket_handle(InFrame, State) -> CallResult
+websocket_info(Info, State)      -> CallResult
+
+terminate(Reason, PartialReq, State) -> ok      %% optional
+
+Req        :: cowboy_req:req()
+PartialReq :: map()
+State      :: any()
+Opts       :: cowboy_websocket:opts()
+InFrame    :: {text | binary | ping | pong, binary()}
+OutFrame   :: cow_ws:frame()                    %% see types below
+Info       :: any()
+
+CallResult :: {ok, State}
+            | {ok, State, hibernate}
+            | {reply, OutFrame | [OutFrame], State}
+            | {reply, OutFrame | [OutFrame], State, hibernate}
+            | {stop, State}
+
+Reason     :: normal | stop | timeout
+            | remote | {remote, cow_ws:close_code(), binary()}
+            | {error, badencoding | badframe | closed | atom()}
+            | {crash, error | exit | throw, any()}
+
+

The init/2 callback is common to all handlers. To upgrade the connection to Websocket, it must return cowboy_websocket as the first element of the tuple.

+

Any operation requiring the HTTP request must be done in the init/2 function, as the Req object will not be available after it returns. Websocket sub-protocol selection should therefore be done in this function.

+

The optional websocket_init/1 callback will be called once the connection has been upgraded to Websocket. It can be used to perform any required initialization of the handler.

+

Note that the init/2 function does not run in the same process as the Websocket callbacks. Any Websocket-specific initialization must be done in websocket_init/1.

+

The websocket_handle/2 callback will be called for every frame received. The websocket_info/2 callback will be called for every Erlang message received.

+

All three Websocket callbacks may send one or more frames back to the client (by returning a reply tuple) or terminate the connection (by sending a close frame or returning a stop tuple).

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the connection. This callback is common to all handlers. Note that Websocket will not provide the full Req object by default, to save memory.

+

Cowboy will terminate the process right after closing the Websocket connection. This means that there is no need to perform any cleanup in the terminate/3 callback.

+

The following terminate reasons are defined for Websocket connections:

+
normal
+

The connection was closed normally before establishing a Websocket connection. This typically happens if an ok tuple is returned from the init/2 callback.

-
-remote -
-
-

- The remote endpoint closed the connection without giving any - further details. -

+
remote
+

The remote endpoint closed the connection without giving any further details.

-
-{remote, Code, Payload} -
-
-

- The remote endpoint closed the connection with the given - Code and Payload as the reason. -

+
{remote, Code, Payload}
+

The remote endpoint closed the connection with the given Code and Payload as the reason.

-
-stop -
-
-

- The handler requested to close the connection, either by returning - a stop tuple or by sending a close frame. -

+
stop
+

The handler requested to close the connection, either by returning a stop tuple or by sending a close frame.

-
-timeout -
-
-

- The connection has been closed due to inactivity. The timeout - value can be configured from init/2. -

+
timeout
+

The connection has been closed due to inactivity. The timeout value can be configured from init/2.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
-{error, badencoding} -
-
-

- A text frame was sent by the client with invalid encoding. All - text frames must be valid UTF-8. -

+
{error, badencoding}
+

A text frame was sent by the client with invalid encoding. All text frames must be valid UTF-8.

-
-{error, badframe} -
-
-

- A protocol error has been detected. -

+
{error, badframe}
+

A protocol error has been detected.

-
-{error, closed} -
-
-

- The socket has been closed brutally without a close frame being - received first. -

+
{error, closed}
+

The socket has been closed brutally without a close frame being received first.

-
-{error, Reason} -
-
-

- A socket error ocurred. -

+
{error, Reason}
+

A socket error ocurred.

-
- - -
+

Types

-
-

cow_ws:frame()

-
-
-
frame() :: {text, iodata()}
-    | {binary, iodata()}
-    | ping | {ping, iodata()}
-    | pong | {pong, iodata()}
-    | close | {close, iodata()} | {close, close_code(), iodata()}
-
-close_code() :: 1000..1003 | 1006..1011 | 3000..4999
-

Websocket frames that can be sent as a response.

-

Note that there is no need to send pong frames back as -Cowboy does it automatically for you.

-
-
+
frame() :: {text, iodata()}
+    | {binary, iodata()}
+    | ping | {ping, iodata()}
+    | pong | {pong, iodata()}
+    | close | {close, iodata()} | {close, close_code(), iodata()}
+
+close_code() :: 1000..1003 | 1006..1011 | 3000..4999
+
+

Websocket frames that can be sent as a response.

+

Note that there is no need to send pong frames back as Cowboy does it automatically for you.

opts()

-
-
-
opts() :: #{
-    compress => boolean(),
-    idle_timeout => timeout(),
-    req_filter => fun((cowboy_req:req()) -> map())
-}
-

Websocket handler options.

-

This configuration is passed to Cowboy from the init/2 -function:

-
-
-
init(Req, State) ->
-    Opts = #{compress => true},
-    {cowboy_websocket, Req, State, Opts}.
-

The default value is given next to the option name:

-
-
-compress (false) -
-
-

- Whether to enable the Websocket frame compression - extension. Frames will only be compressed for the - clients that support this extension. -

+
init(Req, State) ->
+    Opts = #{compress => true},
+    {cowboy_websocket, Req, State, Opts}.
+
+

The default value is given next to the option name:

+
compress (false)
+

Whether to enable the Websocket frame compression extension. Frames will only be compressed for the clients that support this extension.

-
-idle_timeout (60000) -
-
-

- Time in milliseconds that Cowboy will keep the - connection open without receiving anything from - the client. -

+
idle_timeout (60000)
+

Time in milliseconds that Cowboy will keep the connection open without receiving anything from the client.

-
-req_filter -
-
-

- A function applied to the Req to compact it and - only keep required information. The Req is only - given back in the terminate/3 callback. By default - it keeps the method, version, URI components and peer - information. -

+
req_filter
+

A function applied to the Req to compact it and only keep required information. The Req is only given back in the terminate/3 callback. By default it keeps the method, version, URI components and peer information.

-
- - - -
+

Changelog

-
-
    -
  • -

    -2.0: The Req object is no longer passed to Websocket callbacks. -

    +
    • 2.0: The Req object is no longer passed to Websocket callbacks.
    • -
    • -

      -2.0: The callback websocket_terminate/3 was removed in favor of terminate/3. -

      +
    • 2.0: The callback websocket_terminate/3 was removed in favor of terminate/3.
    • -
    • -

      -1.0: Protocol introduced. -

      +
    • 1.0: Protocol introduced.
    • -
-
-
- +

cowboy(7), cowboy_handler(3), cowboy_http(3), cowboy_http2(3)

+ diff --git a/docs/en/cowboy/2.2/manual/http_status_codes/index.html b/docs/en/cowboy/2.2/manual/http_status_codes/index.html index a76f19ca..1af65a41 100644 --- a/docs/en/cowboy/2.2/manual/http_status_codes/index.html +++ b/docs/en/cowboy/2.2/manual/http_status_codes/index.html @@ -62,271 +62,92 @@

HTTP status codes(7)

-

Name

-
-

HTTP status codes - status codes used by Cowboy

-
-
-
+

HTTP status codes - status codes used by Cowboy

Description

-
-

This chapter aims to list all HTTP status codes that Cowboy -may return, with details on the reasons why. The list given -here only includes the replies that Cowboy sends, not user -replies.

-
-
-
+

This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies.

100 Continue

-
-

When the client sends an expect: 100-continue header, -Cowboy automatically sends a this status code before -trying to read the request body. This behavior can be -disabled using the appropriate body option.

-
-
-
+

When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. This behavior can be disabled using the appropriate body option.

101 Switching Protocols

-
-

This is the status code sent when switching to the -Websocket protocol.

-
-
-
+

This is the status code sent when switching to the Websocket protocol.

200 OK

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

201 Created

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

202 Accepted

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

204 No Content

-
-

This status code is sent when the processing of a request -ends without any reply having been sent. It may also be -sent by cowboy_rest under normal conditions.

-
-
-
+

This status code is sent when the processing of a request ends without any reply having been sent. It may also be sent by cowboy_rest under normal conditions.

300 Multiple Choices

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

301 Moved Permanently

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

303 See Other

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

304 Not Modified

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

307 Temporary Redirect

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

400 Bad Request

-
-

Cowboy will send this status code for any of the -following reasons:

-
    -
  • -

    -Too many empty lines were sent before the request. -

    +

    Cowboy will send this status code for any of the following reasons:

    +
    • Too many empty lines were sent before the request.
    • -
    • -

      -The request-line could not be parsed. -

      +
    • The request-line could not be parsed.
    • -
    • -

      -Too many headers were sent. -

      +
    • Too many headers were sent.
    • -
    • -

      -A header name was too long. -

      +
    • A header name was too long.
    • -
    • -

      -A header value was too long. -

      +
    • A header value was too long.
    • -
    • -

      -The host header was missing from an HTTP/1.1 request. -

      +
    • The host header was missing from an HTTP/1.1 request.
    • -
    • -

      -The host header could not be parsed. -

      +
    • The host header could not be parsed.
    • -
    • -

      -The requested host was not found. -

      +
    • The requested host was not found.
    • -
    • -

      -The requested path could not be parsed. -

      +
    • The requested path could not be parsed.
    • -
    • -

      -The accept header could not be parsed when using REST. -

      +
    • The accept header could not be parsed when using REST.
    • -
    • -

      -REST under normal conditions. -

      +
    • REST under normal conditions.
    • -
    • -

      -A Websocket upgrade failed. -

      +
    • A Websocket upgrade failed.
    • -
-
-
-
+

401 Unauthorized

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

403 Forbidden

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

404 Not Found

-
-

This status code is sent when the router successfully -resolved the host but didn’t find a matching path for -the request. It may also be sent by cowboy_rest under -normal conditions.

-
-
-
+

This status code is sent when the router successfully resolved the host but didn't find a matching path for the request. It may also be sent by cowboy_rest under normal conditions.

405 Method Not Allowed

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

406 Not Acceptable

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

408 Request Timeout

-
-

Cowboy will send this status code to the client if the -client started to send a request, indicated by the -request-line being received fully, but failed to send -all headers in a reasonable time.

-
-
-
+

Cowboy will send this status code to the client if the client started to send a request, indicated by the request-line being received fully, but failed to send all headers in a reasonable time.

409 Conflict

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

410 Gone

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

412 Precondition Failed

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

413 Request Entity Too Large

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

414 Request-URI Too Long

-
-

Cowboy will send this status code to the client if the -request-line is too long. It may also be sent by -cowboy_rest under normal conditions.

-
-
-
+

Cowboy will send this status code to the client if the request-line is too long. It may also be sent by cowboy_rest under normal conditions.

415 Unsupported Media Type

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

500 Internal Server Error

-
-

This status code is sent when a crash occurs in HTTP, loop -or REST handlers, or when an invalid return value is -returned. It may also be sent by cowboy_rest under -normal conditions.

-
-
-
+

This status code is sent when a crash occurs in HTTP, loop or REST handlers, or when an invalid return value is returned. It may also be sent by cowboy_rest under normal conditions.

501 Not Implemented

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

503 Service Unavailable

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

505 HTTP Version Not Supported

-
-

Cowboy only supports the versions 1.0 and 1.1 of HTTP. -In all other cases this status code is sent back to the -client and the connection is closed.

-
-
+

Cowboy only supports the versions 1.0 and 1.1 of HTTP. In all other cases this status code is sent back to the client and the connection is closed.

+ diff --git a/docs/en/cowboy/2.2/manual/index.html b/docs/en/cowboy/2.2/manual/index.html index 24224831..805dfe85 100644 --- a/docs/en/cowboy/2.2/manual/index.html +++ b/docs/en/cowboy/2.2/manual/index.html @@ -62,171 +62,77 @@

Cowboy Function Reference

-

Name

-
-

cowboy - Small, fast, modern HTTP server for Erlang/OTP

-
-
-
+

cowboy - Small, fast, modern HTTP server for Erlang/OTP

Description

-
-

Cowboy is an HTTP server for Erlang/OTP with support for the -HTTP/1.1, HTTP/2 and Websocket protocols.

-

Cowboy aims to provide a complete HTTP stack. This includes -the implementation of the HTTP RFCs but also any directly -related standards, like Websocket or Server-Sent Events.

-
-
-
+

Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols.

+

Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events.

Modules

-
-

Functions:

-
-

Protocols:

-
+

Protocols:

+
-

Handlers:

-
+

Handlers:

+
-

Behaviors:

-
+

Behaviors:

+
-

Middlewares:

-
+

Middlewares:

+
-
-
-
+ +

Dependencies

-
-
    -
  • -

    -ranch(7) - Socket acceptor pool for TCP protocols -

    +
    • ranch(7) - Socket acceptor pool for TCP protocols
    • -
    • -

      -cowlib(7) - Support library for manipulating Web protocols -

      +
    • cowlib(7) - Support library for manipulating Web protocols
    • -
    • -

      -ssl - Secure communication over sockets -

      +
    • ssl - Secure communication over sockets
    • -
    • -

      -crypto - Crypto functions -

      +
    • crypto - Crypto functions
    • -
-

All these applications must be started before the cowboy -application. To start Cowboy and all dependencies at once:

-
-
-
{ok, _} = application:ensure_all_started(cowboy).
-
-
-
+
{ok, _} = application:ensure_all_started(cowboy).
+

Environment

-
-

The cowboy application does not define any application -environment configuration parameters.

-
- -
+

The cowboy application does not define any application environment configuration parameters.

See also

- -
+

ranch(7), cowlib(7)

+ diff --git a/docs/en/cowboy/2.3/guide/constraints/index.html b/docs/en/cowboy/2.3/guide/constraints/index.html index 029dcc19..7907e2b5 100644 --- a/docs/en/cowboy/2.3/guide/constraints/index.html +++ b/docs/en/cowboy/2.3/guide/constraints/index.html @@ -62,141 +62,86 @@

Constraints

-

Constraints are validation and conversion functions applied -to user input.

-

They are used in various places in Cowboy, including the -router and the cowboy_req match functions.

-
+

Constraints are validation and conversion functions applied to user input.

+

They are used in various places in Cowboy, including the router and the cowboy_req match functions.

Syntax

-
-

Constraints are provided as a list of fields. For each field -in the list, specific constraints can be applied, as well as -a default value if the field is missing.

-

A field can take the form of an atom field, a tuple with -constraints {field, Constraints} or a tuple with constraints -and a default value {field, Constraints, Default}. -The field form indicates the field is mandatory.

-

Note that when used with the router, only the second form -makes sense, as it does not use the default and the field -is always defined.

-

Constraints for each field are provided as an ordered list -of atoms or funs to apply. Built-in constraints are provided -as atoms, while custom constraints are provided as funs.

-

When multiple constraints are provided, they are applied in -the order given. If the value has been modified by a constraint -then the next one receives the new value.

-

For example, the following constraints will first validate -and convert the field my_value to an integer, and then -check that the integer is positive:

-
-
-
PositiveFun = fun
-    (_, V) when V > 0 ->
-        {ok, V};
-    (_, _) ->
-        {error, not_positive}
-end,
-{my_value, [int, PositiveFun]}.
-

We ignore the first fun argument in this snippet. We shouldn’t. -We will simply learn what it is later in this chapter.

-

When there’s only one constraint, it can be provided directly -without wrapping it into a list:

-
-
-
{my_value, int}
-
-
-
+
{my_value, int}
+

Built-in constraints

-
-

Built-in constraints are specified as an atom:

-
- --- - - - - - - - - - +

Built-in constraints are specified as an atom:

+
Constraint Description

int

Converts binary value to integer.

+ + + + - - - + + - -
ConstraintDescription
intConverts binary value to integer.

nonempty

Ensures the binary value is non-empty.

nonemptyEnsures the binary value is non-empty.
-
-
- -
+

Custom constraints

-
-

Custom constraints are specified as a fun. This fun takes -two arguments. The first argument indicates the operation -to be performed, and the second is the value. What the -value is and what must be returned depends on the operation.

-

Cowboy currently defines three operations. The operation -used for validating and converting user input is the forward -operation.

-
-
-
int(forward, Value) ->
-    try
-        {ok, binary_to_integer(Value)}
-    catch _:_ ->
-        {error, not_an_integer}
-    end;
-

The value must be returned even if it is not converted -by the constraint.

-

The reverse operation does the opposite: it -takes a converted value and changes it back to what the -user input would have been.

-
-
-
int(reverse, Value) ->
-        try
-                {ok, integer_to_binary(Value)}
-        catch _:_ ->
-                {error, not_an_integer}
-        end;
-

Finally, the format_error operation takes an error -returned by any other operation and returns a formatted -human-readable error message.

-
-
-
int(format_error, {not_an_integer, Value}) ->
-        io_lib:format("The value ~p is not an integer.", [Value]).
-

Notice that for this case you get both the error and -the value that was given to the constraint that produced -this error.

-

Cowboy will not catch exceptions coming from constraint -functions. They should be written to not emit any exceptions.

-
-
+
int(format_error, {not_an_integer, Value}) ->
+	io_lib:format("The value ~p is not an integer.", [Value]).
+ +

Notice that for this case you get both the error and the value that was given to the constraint that produced this error.

+

Cowboy will not catch exceptions coming from constraint functions. They should be written to not emit any exceptions.

+ diff --git a/docs/en/cowboy/2.3/guide/cookies/index.html b/docs/en/cowboy/2.3/guide/cookies/index.html index 2f4c28f8..8d1e67bb 100644 --- a/docs/en/cowboy/2.3/guide/cookies/index.html +++ b/docs/en/cowboy/2.3/guide/cookies/index.html @@ -62,144 +62,103 @@

Using cookies

-

Cookies are a mechanism allowing applications to maintain -state on top of the stateless HTTP protocol.

-

Cookies are a name/value store where the names and values are -stored in plain text. They expire either after a delay -or when the browser closes. They can be configured on a -specific domain name or path, and restricted to secure -resources (sent or downloaded over HTTPS), or restricted -to the server (disallowing access from client-side scripts).

-

Cookie names are de facto case sensitive.

-

Cookies are stored client-side and sent with every subsequent -request that matches the domain and path for which they were -stored, until they expire. This can create a non-negligible -cost.

-

Cookies should not be considered secure. They are stored on -the user’s computer in plain text, and can be read by any -program. They can also be read by proxies when using clear -connections. Always validate the value before using it, -and never store any sensitive information inside it.

-

Cookies set by the server are only available in requests -following the client reception of the response containing -them.

-

Cookies may be sent repeatedly. This is often useful to -update the expiration time and avoid losing a cookie.

-
+

Cookies are a mechanism allowing applications to maintain state on top of the stateless HTTP protocol.

+

Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts).

+

Cookie names are de facto case sensitive.

+

Cookies are stored client-side and sent with every subsequent request that matches the domain and path for which they were stored, until they expire. This can create a non-negligible cost.

+

Cookies should not be considered secure. They are stored on the user's computer in plain text, and can be read by any program. They can also be read by proxies when using clear connections. Always validate the value before using it, and never store any sensitive information inside it.

+

Cookies set by the server are only available in requests following the client reception of the response containing them.

+

Cookies may be sent repeatedly. This is often useful to update the expiration time and avoid losing a cookie.

Setting cookies

-
-

By default cookies are defined for the duration of the session:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0).
-

They can also be set for a duration in seconds:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{max_age => 3600}).
-

To delete cookies, set max_age to 0:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{max_age => 0}).
-

To restrict cookies to a specific domain and path, the options -of the same name can be used:

-
-
-
Req = cowboy_req:set_resp_cookie(<<"inaccount">>, <<"1">>, Req0,
-    #{domain => "my.example.org", path => "/account"}).
-

Cookies will be sent with requests to this domain and all -its subdomains, and to resources on this path or deeper -in the path hierarchy.

-

To restrict cookies to secure channels (typically resources -available over HTTPS):

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{secure => true}).
-

To prevent client-side scripts from accessing a cookie:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{http_only => true}).
-

Cookies may also be set client-side, for example using -Javascript.

-
-
-
+
SessionID = generate_session_id(),
+Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
+    #{http_only => true}).
+
+

Cookies may also be set client-side, for example using Javascript.

Reading cookies

-
-

The client only ever sends back the cookie name and value. -All other options that can be set are never sent back.

-

Cowboy provides two functions for reading cookies. Both -involve parsing the cookie header(s) and so should not -be called repeatedly.

-

You can get all cookies as a key/value list:

-
-
-
Cookies = cowboy_req:parse_cookies(Req),
-{_, Lang} = lists:keyfind(<<"lang">>, 1, Cookies).
-

Or you can perform a match against cookies and retrieve -only the ones you need, while at the same time doing -any required post processing using constraints. -This function returns a map:

-
-
-
#{id := ID, lang := Lang} = cowboy_req:match_cookies([id, lang], Req).
-

You can use constraints to validate the values while matching -them. The following snippet will crash if the id cookie is -not an integer number or if the lang cookie is empty. Additionally -the id cookie value will be converted to an integer term:

-
-
-
CookiesMap = cowboy_req:match_cookies([{id, int}, {lang, nonempty}], Req).
-

Note that if two cookies share the same name, then the map value -will be a list of the two cookie values.

-

A default value can be provided. The default will be used -if the lang cookie is not found. It will not be used if -the cookie is found but has an empty value:

-
-
-
#{lang := Lang} = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
-

If no default is provided and the value is missing, an -exception is thrown.

-
- +
#{lang := Lang} = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
+ +

If no default is provided and the value is missing, an exception is thrown.

+ diff --git a/docs/en/cowboy/2.3/guide/erlang_web/index.html b/docs/en/cowboy/2.3/guide/erlang_web/index.html index 97bc07d2..76a54644 100644 --- a/docs/en/cowboy/2.3/guide/erlang_web/index.html +++ b/docs/en/cowboy/2.3/guide/erlang_web/index.html @@ -62,194 +62,52 @@

Erlang and the Web

-

Erlang is the ideal platform for writing Web applications. -Its features are a perfect match for the requirements of -modern Web applications.

-
+

Erlang is the ideal platform for writing Web applications. Its features are a perfect match for the requirements of modern Web applications.

The Web is concurrent

-
-

When you access a website there is little concurrency -involved. A few connections are opened and requests -are sent through these connections. Then the web page -is displayed on your screen. Your browser will only -open up to 4 or 8 connections to the server, depending -on your settings. This isn’t much.

-

But think about it. You are not the only one accessing -the server at the same time. There can be hundreds, if -not thousands, if not millions of connections to the -same server at the same time.

-

Even today a lot of systems used in production haven’t -solved the C10K problem (ten thousand concurrent connections). -And the ones who did are trying hard to get to the next -step, C100K, and are pretty far from it.

-

Erlang meanwhile has no problem handling millions of -connections. At the time of writing there are application -servers written in Erlang that can handle more than two -million connections on a single server in a real production -application, with spare memory and CPU!

-

The Web is concurrent, and Erlang is a language designed -for concurrency, so it is a perfect match.

-

Of course, various platforms need to scale beyond a few -million connections. This is where Erlang’s built-in -distribution mechanisms come in. If one server isn’t -enough, add more! Erlang allows you to use the same code -for talking to local processes or to processes in other -parts of your cluster, which means you can scale very -quickly if the need arises.

-

The Web has large userbases, and the Erlang platform was -designed to work in a distributed setting, so it is a -perfect match.

-

Or is it? Surely you can find solutions to handle that many -concurrent connections with your favorite language… But all -these solutions will break down in the next few years. Why? -Firstly because servers don’t get any more powerful, they -instead get a lot more cores and memory. This is only useful -if your application can use them properly, and Erlang is -light-years away from anything else in that area. Secondly, -today your computer and your phone are online, tomorrow your -watch, goggles, bike, car, fridge and tons of other devices -will also connect to various applications on the Internet.

-

Only Erlang is prepared to deal with what’s coming.

-
-
-
+

When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. This isn't much.

+

But think about it. You are not the only one accessing the server at the same time. There can be hundreds, if not thousands, if not millions of connections to the same server at the same time.

+

Even today a lot of systems used in production haven't solved the C10K problem (ten thousand concurrent connections). And the ones who did are trying hard to get to the next step, C100K, and are pretty far from it.

+

Erlang meanwhile has no problem handling millions of connections. At the time of writing there are application servers written in Erlang that can handle more than two million connections on a single server in a real production application, with spare memory and CPU!

+

The Web is concurrent, and Erlang is a language designed for concurrency, so it is a perfect match.

+

Of course, various platforms need to scale beyond a few million connections. This is where Erlang's built-in distribution mechanisms come in. If one server isn't enough, add more! Erlang allows you to use the same code for talking to local processes or to processes in other parts of your cluster, which means you can scale very quickly if the need arises.

+

The Web has large userbases, and the Erlang platform was designed to work in a distributed setting, so it is a perfect match.

+

Or is it? Surely you can find solutions to handle that many concurrent connections with your favorite language... But all these solutions will break down in the next few years. Why? Firstly because servers don't get any more powerful, they instead get a lot more cores and memory. This is only useful if your application can use them properly, and Erlang is light-years away from anything else in that area. Secondly, today your computer and your phone are online, tomorrow your watch, goggles, bike, car, fridge and tons of other devices will also connect to various applications on the Internet.

+

Only Erlang is prepared to deal with what's coming.

The Web is soft real time

-
-

What does soft real time mean, you ask? It means we want the -operations done as quickly as possible, and in the case of -web applications, it means we want the data propagated fast.

-

In comparison, hard real time has a similar meaning, but also -has a hard time constraint, for example an operation needs to -be done in under N milliseconds otherwise the system fails -entirely.

-

Users aren’t that needy yet, they just want to get access -to their content in a reasonable delay, and they want the -actions they make to register at most a few seconds after -they submitted them, otherwise they’ll start worrying about -whether it successfully went through.

-

The Web is soft real time because taking longer to perform an -operation would be seen as bad quality of service.

-

Erlang is a soft real time system. It will always run -processes fairly, a little at a time, switching to another -process after a while and preventing a single process to -steal resources from all others. This means that Erlang -can guarantee stable low latency of operations.

-

Erlang provides the guarantees that the soft real time Web -requires.

-
-
-
+

What does soft real time mean, you ask? It means we want the operations done as quickly as possible, and in the case of web applications, it means we want the data propagated fast.

+

In comparison, hard real time has a similar meaning, but also has a hard time constraint, for example an operation needs to be done in under N milliseconds otherwise the system fails entirely.

+

Users aren't that needy yet, they just want to get access to their content in a reasonable delay, and they want the actions they make to register at most a few seconds after they submitted them, otherwise they'll start worrying about whether it successfully went through.

+

The Web is soft real time because taking longer to perform an operation would be seen as bad quality of service.

+

Erlang is a soft real time system. It will always run processes fairly, a little at a time, switching to another process after a while and preventing a single process to steal resources from all others. This means that Erlang can guarantee stable low latency of operations.

+

Erlang provides the guarantees that the soft real time Web requires.

The Web is asynchronous

-
-

Long ago, the Web was synchronous because HTTP was synchronous. -You fired a request, and then waited for a response. Not anymore. -It all began when XmlHttpRequest started being used. It allowed -the client to perform asynchronous calls to the server.

-

Then Websocket appeared and allowed both the server and the client -to send data to the other endpoint completely asynchronously. The -data is contained within frames and no response is necessary.

-

Erlang processes work the same. They send each other data contained -within messages and then continue running without needing a response. -They tend to spend most of their time inactive, waiting for a new -message, and the Erlang VM happily activate them when one is received.

-

It is therefore quite easy to imagine Erlang being good at receiving -Websocket frames, which may come in at unpredictable times, pass the -data to the responsible processes which are always ready waiting for -new messages, and perform the operations required by only activating -the required parts of the system.

-

The more recent Web technologies, like Websocket of course, but also -HTTP/2.0, are all fully asynchronous protocols. The concept -of requests and responses is retained of course, but anything could -be sent in between, by both the client or the browser, and the -responses could also be received in a completely different order.

-

Erlang is by nature asynchronous and really good at it thanks to the -great engineering that has been done in the VM over the years. It’s -only natural that it’s so good at dealing with the asynchronous Web.

-
-
-
+

Long ago, the Web was synchronous because HTTP was synchronous. You fired a request, and then waited for a response. Not anymore. It all began when XmlHttpRequest started being used. It allowed the client to perform asynchronous calls to the server.

+

Then Websocket appeared and allowed both the server and the client to send data to the other endpoint completely asynchronously. The data is contained within frames and no response is necessary.

+

Erlang processes work the same. They send each other data contained within messages and then continue running without needing a response. They tend to spend most of their time inactive, waiting for a new message, and the Erlang VM happily activate them when one is received.

+

It is therefore quite easy to imagine Erlang being good at receiving Websocket frames, which may come in at unpredictable times, pass the data to the responsible processes which are always ready waiting for new messages, and perform the operations required by only activating the required parts of the system.

+

The more recent Web technologies, like Websocket of course, but also HTTP/2.0, are all fully asynchronous protocols. The concept of requests and responses is retained of course, but anything could be sent in between, by both the client or the browser, and the responses could also be received in a completely different order.

+

Erlang is by nature asynchronous and really good at it thanks to the great engineering that has been done in the VM over the years. It's only natural that it's so good at dealing with the asynchronous Web.

The Web is omnipresent

-
-

The Web has taken a very important part of our lives. We’re -connected at all times, when we’re on our phone, using our computer, -passing time using a tablet while in the bathroom… And this -isn’t going to slow down, every single device at home or on us -will be connected.

-

All these devices are always connected. And with the number of -alternatives to give you access to the content you seek, users -tend to not stick around when problems arise. Users today want -their applications to be always available and if it’s having -too many issues they just move on.

-

Despite this, when developers choose a product to use for building -web applications, their only concern seems to be "Is it fast?", -and they look around for synthetic benchmarks showing which one -is the fastest at sending "Hello world" with only a handful -concurrent connections. Web benchmarks haven’t been representative -of reality in a long time, and are drifting further away as -time goes on.

-

What developers should really ask themselves is "Can I service -all my users with no interruption?" and they’d find that they have -two choices. They can either hope for the best, or they can use -Erlang.

-

Erlang is built for fault tolerance. When writing code in any other -language, you have to check all the return values and act accordingly -to avoid any unforeseen issues. If you’re lucky, you won’t miss -anything important. When writing Erlang code, you can just check -the success condition and ignore all errors. If an error happens, -the Erlang process crashes and is then restarted by a special -process called a supervisor.

-

Erlang developers thus have no need to fear unhandled -errors, and can focus on handling only the errors that should -give some feedback to the user and let the system take care of -the rest. This also has the advantage of allowing them to write -a lot less code, and let them sleep at night.

-

Erlang’s fault tolerance oriented design is the first piece of -what makes it the best choice for the omnipresent, always available -Web.

-

The second piece is Erlang’s built-in distribution. Distribution -is a key part of building a fault tolerant system, because it -allows you to handle bigger failures, like a whole server going -down, or even a data center entirely.

-

Fault tolerance and distribution are important today, and will be -vital in the future of the Web. Erlang is ready.

-
-
-
+

The Web has taken a very important part of our lives. We're connected at all times, when we're on our phone, using our computer, passing time using a tablet while in the bathroom... And this isn't going to slow down, every single device at home or on us will be connected.

+

All these devices are always connected. And with the number of alternatives to give you access to the content you seek, users tend to not stick around when problems arise. Users today want their applications to be always available and if it's having too many issues they just move on.

+

Despite this, when developers choose a product to use for building web applications, their only concern seems to be "Is it fast?", and they look around for synthetic benchmarks showing which one is the fastest at sending "Hello world" with only a handful concurrent connections. Web benchmarks haven't been representative of reality in a long time, and are drifting further away as time goes on.

+

What developers should really ask themselves is "Can I service all my users with no interruption?" and they'd find that they have two choices. They can either hope for the best, or they can use Erlang.

+

Erlang is built for fault tolerance. When writing code in any other language, you have to check all the return values and act accordingly to avoid any unforeseen issues. If you're lucky, you won't miss anything important. When writing Erlang code, you can just check the success condition and ignore all errors. If an error happens, the Erlang process crashes and is then restarted by a special process called a supervisor.

+

Erlang developers thus have no need to fear unhandled errors, and can focus on handling only the errors that should give some feedback to the user and let the system take care of the rest. This also has the advantage of allowing them to write a lot less code, and let them sleep at night.

+

Erlang's fault tolerance oriented design is the first piece of what makes it the best choice for the omnipresent, always available Web.

+

The second piece is Erlang's built-in distribution. Distribution is a key part of building a fault tolerant system, because it allows you to handle bigger failures, like a whole server going down, or even a data center entirely.

+

Fault tolerance and distribution are important today, and will be vital in the future of the Web. Erlang is ready.

Learn Erlang

-
-

If you are new to Erlang, you may want to grab a book or -two to get started. Those are my recommendations as the -author of Cowboy.

-
+

If you are new to Erlang, you may want to grab a book or two to get started. Those are my recommendations as the author of Cowboy.

The Erlanger Playbook

-

The Erlanger Playbook is an ebook I am currently writing, -which covers a number of different topics from code to -documentation to testing Erlang applications. It also has -an Erlang section where it covers directly the building -blocks and patterns, rather than details like the syntax.

-

You can most likely read it as a complete beginner, but -you will need a companion book to make the most of it. -Buy it from the Nine Nines website.

-
-
+

The Erlanger Playbook is an ebook I am currently writing, which covers a number of different topics from code to documentation to testing Erlang applications. It also has an Erlang section where it covers directly the building blocks and patterns, rather than details like the syntax.

+

You can most likely read it as a complete beginner, but you will need a companion book to make the most of it. Buy it from the Nine Nines website.

Programming Erlang

-

This book is from one of the creator of Erlang, Joe -Armstrong. It provides a very good explanation of what -Erlang is and why it is so. It serves as a very good -introduction to the language and platform.

-

The book is Programming Erlang, -and it also features a chapter on Cowboy.

-
-
+

This book is from one of the creator of Erlang, Joe Armstrong. It provides a very good explanation of what Erlang is and why it is so. It serves as a very good introduction to the language and platform.

+

The book is Programming Erlang, and it also features a chapter on Cowboy.

Learn You Some Erlang for Great Good!

-

LYSE is a much more complete -book covering many aspects of Erlang, while also providing -stories and humor. Be warned: it’s pretty verbose. It comes -with a free online version and a more refined paper and -ebook version.

-
-
-
+

LYSE is a much more complete book covering many aspects of Erlang, while also providing stories and humor. Be warned: it's pretty verbose. It comes with a free online version and a more refined paper and ebook version.

+ diff --git a/docs/en/cowboy/2.3/guide/flow_diagram/index.html b/docs/en/cowboy/2.3/guide/flow_diagram/index.html index 05bc677a..d675a2f5 100644 --- a/docs/en/cowboy/2.3/guide/flow_diagram/index.html +++ b/docs/en/cowboy/2.3/guide/flow_diagram/index.html @@ -62,113 +62,30 @@

Flow diagram

-

Cowboy is a lightweight HTTP server with support for HTTP/1.1, -HTTP/2 and Websocket.

-

It is built on top of Ranch. Please see the Ranch guide for more -information about how the network connections are handled.

-
+

Cowboy is a lightweight HTTP server with support for HTTP/1.1, HTTP/2 and Websocket.

+

It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled.

Overview

-
-
-
-HTTP request/response flowchart -
-
-

As you can see on the diagram, the client -begins by connecting to the server. This step is handled -by a Ranch acceptor, which is a process dedicated to -accepting new connections.

-

After Ranch accepts a new connection, whether it is an -HTTP/1.1 or HTTP/2 connection, Cowboy starts receiving -requests and handling them.

-

In HTTP/1.1 all requests come sequentially. In HTTP/2 -the requests may arrive and be processed concurrently.

-

When a request comes in, Cowboy creates a stream, which -is a set of request/response and all the events associated -with them. The protocol code in Cowboy defers the handling -of these streams to stream handler modules. When you -configure Cowboy you may define one or more module that -will receive all events associated with a stream, including -the request, response, bodies, Erlang messages and more.

-

By default Cowboy comes configured with a stream handler -called cowboy_stream_h. This stream handler will create -a new process for every request coming in, and then -communicate with this process to read the body or send -a response back. The request process executes middlewares -which, by default, including the router and then the -execution of handlers. Like stream handlers, middlewares -may also be customized.

-

A response may be sent at almost any point in this -diagram. If the response must be sent before the stream -is initialized (because an error occurred early, for -example) then stream handlers receive a special event -indicating this error.

-
-
-
+HTTP request/response flowchart

As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections.

+

After Ranch accepts a new connection, whether it is an HTTP/1.1 or HTTP/2 connection, Cowboy starts receiving requests and handling them.

+

In HTTP/1.1 all requests come sequentially. In HTTP/2 the requests may arrive and be processed concurrently.

+

When a request comes in, Cowboy creates a stream, which is a set of request/response and all the events associated with them. The protocol code in Cowboy defers the handling of these streams to stream handler modules. When you configure Cowboy you may define one or more module that will receive all events associated with a stream, including the request, response, bodies, Erlang messages and more.

+

By default Cowboy comes configured with a stream handler called cowboy_stream_h. This stream handler will create a new process for every request coming in, and then communicate with this process to read the body or send a response back. The request process executes middlewares which, by default, including the router and then the execution of handlers. Like stream handlers, middlewares may also be customized.

+

A response may be sent at almost any point in this diagram. If the response must be sent before the stream is initialized (because an error occurred early, for example) then stream handlers receive a special event indicating this error.

Protocol-specific headers

-
-

Cowboy takes care of protocol-specific headers and prevents -you from sending them manually. For HTTP/1.1 this includes -the transfer-encoding and connection headers. For HTTP/2 -this includes the colon headers like :status.

-

Cowboy will also remove protocol-specific headers from -requests before passing them to stream handlers. Cowboy -tries to hide the implementation details of all protocols -as well as possible.

-
-
-
+

Cowboy takes care of protocol-specific headers and prevents you from sending them manually. For HTTP/1.1 this includes the transfer-encoding and connection headers. For HTTP/2 this includes the colon headers like :status.

+

Cowboy will also remove protocol-specific headers from requests before passing them to stream handlers. Cowboy tries to hide the implementation details of all protocols as well as possible.

Number of processes per connection

-
-

By default, Cowboy will use one process per connection, -plus one process per set of request/response (called a -stream, internally).

-

The reason it creates a new process for every request is due -to the requirements of HTTP/2 where requests are executed -concurrently and independently from the connection. The -frames from the different requests end up interleaved on -the single TCP connection.

-

The request processes are never reused. There is therefore -no need to perform any cleanup after the response has been -sent. The process will terminate and Erlang/OTP will reclaim -all memory at once.

-

Cowboy ultimately does not require more than one process -per connection. It is possible to interact with the connection -directly from a stream handler, a low level interface to Cowboy. -They are executed from within the connection process, and can -handle the incoming requests and send responses. This is however -not recommended in normal circumstances, as a stream handler -taking too long to execute could have a negative impact on -concurrent requests or the state of the connection itself.

-
-
-
+

By default, Cowboy will use one process per connection, plus one process per set of request/response (called a stream, internally).

+

The reason it creates a new process for every request is due to the requirements of HTTP/2 where requests are executed concurrently and independently from the connection. The frames from the different requests end up interleaved on the single TCP connection.

+

The request processes are never reused. There is therefore no need to perform any cleanup after the response has been sent. The process will terminate and Erlang/OTP will reclaim all memory at once.

+

Cowboy ultimately does not require more than one process per connection. It is possible to interact with the connection directly from a stream handler, a low level interface to Cowboy. They are executed from within the connection process, and can handle the incoming requests and send responses. This is however not recommended in normal circumstances, as a stream handler taking too long to execute could have a negative impact on concurrent requests or the state of the connection itself.

Date header

-
-

Because querying for the current date and time can be expensive, -Cowboy generates one Date header value every second, shares it -to all other processes, which then simply copy it in the response. -This allows compliance with HTTP/1.1 with no actual performance loss.

-
-
-
+

Because querying for the current date and time can be expensive, Cowboy generates one Date header value every second, shares it to all other processes, which then simply copy it in the response. This allows compliance with HTTP/1.1 with no actual performance loss.

Binaries

-
-

Cowboy makes extensive use of binaries.

-

Binaries are more efficient than lists for representing -strings because they take less memory space. Processing -performance can vary depending on the operation. Binaries -are known for generally getting a great boost if the code -is compiled natively. Please see the HiPE documentation -for more details.

-

Binaries may end up being shared between processes. This -can lead to some large memory usage when one process keeps -the binary data around forever without freeing it. If you -see some weird memory usage in your application, this might -be the cause.

-
-
+

Cowboy makes extensive use of binaries.

+

Binaries are more efficient than lists for representing strings because they take less memory space. Processing performance can vary depending on the operation. Binaries are known for generally getting a great boost if the code is compiled natively. Please see the HiPE documentation for more details.

+

Binaries may end up being shared between processes. This can lead to some large memory usage when one process keeps the binary data around forever without freeing it. If you see some weird memory usage in your application, this might be the cause.

+ diff --git a/docs/en/cowboy/2.3/guide/getting_started/index.html b/docs/en/cowboy/2.3/guide/getting_started/index.html index b06cbf46..d214b33a 100644 --- a/docs/en/cowboy/2.3/guide/getting_started/index.html +++ b/docs/en/cowboy/2.3/guide/getting_started/index.html @@ -62,161 +62,104 @@

Getting started

-

Erlang is more than a language, it is also an operating system -for your applications. Erlang developers rarely write standalone -modules, they write libraries or applications, and then bundle -those into what is called a release. A release contains the -Erlang VM plus all applications required to run the node, so -it can be pushed to production directly.

-

This chapter walks you through all the steps of setting up -Cowboy, writing your first application and generating your first -release. At the end of this chapter you should know everything -you need to push your first Cowboy application to production.

-
+

Erlang is more than a language, it is also an operating system for your applications. Erlang developers rarely write standalone modules, they write libraries or applications, and then bundle those into what is called a release. A release contains the Erlang VM plus all applications required to run the node, so it can be pushed to production directly.

+

This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. At the end of this chapter you should know everything you need to push your first Cowboy application to production.

Prerequisites

-
-

We are going to use the Erlang.mk -build system. If you are using Windows, please check the -Installation instructions -to get your environment setup before you continue.

-
-
-
+

We are going to use the Erlang.mk build system. If you are using Windows, please check the Installation instructions to get your environment setup before you continue.

Bootstrap

-
-

First, let’s create the directory for our application.

-
-
$ mkdir hello_erlang
-$ cd hello_erlang
-

Then we need to download Erlang.mk. Either use the following -command or download it manually.

-
-
-
$ wget https://erlang.mk/erlang.mk
-

We can now bootstrap our application. Since we are going to generate -a release, we will also bootstrap it at the same time.

-
-
-
$ make -f erlang.mk bootstrap bootstrap-rel
-

This creates a Makefile, a base application, and the release files -necessary for creating the release. We can already build and start -this release.

-
-
$ make run
-...
-(hello_erlang@127.0.0.1)1>
-

Entering the command i(). will show the running processes, including -one called hello_erlang_sup. This is the supervisor for our -application.

-

The release currently does nothing. In the rest of this chapter we -will add Cowboy as a dependency and write a simple "Hello world!" -handler.

-
-
-
+... +(hello_erlang@127.0.0.1)1> +
+

Entering the command i(). will show the running processes, including one called hello_erlang_sup. This is the supervisor for our application.

+

The release currently does nothing. In the rest of this chapter we will add Cowboy as a dependency and write a simple "Hello world!" handler.

Cowboy setup

-
-

We will modify the Makefile to tell the build system it needs to -fetch and compile Cowboy:

-
-
-
PROJECT = hello_erlang
+
PROJECT = hello_erlang
 
-DEPS = cowboy
-dep_cowboy_commit = 2.3.0
+DEPS = cowboy
+dep_cowboy_commit = 2.3.0
 
-DEP_PLUGINS = cowboy
+DEP_PLUGINS = cowboy
 
-include erlang.mk
-

We also tell the build system to load the plugins Cowboy provides. -These include predefined templates that we will use soon.

-

If you do make run now, Cowboy will be included in the release -and started automatically. This is not enough however, as Cowboy -doesn’t do anything by default. We still need to tell Cowboy to -listen for connections.

-
- -
+include erlang.mk +
+

We also tell the build system to load the plugins Cowboy provides. These include predefined templates that we will use soon.

+

If you do make run now, Cowboy will be included in the release and started automatically. This is not enough however, as Cowboy doesn't do anything by default. We still need to tell Cowboy to listen for connections.

Listening for connections

-
-

First we define the routes that Cowboy will use to map requests -to handler modules, and then we start the listener. This is best -done at application startup.

-

Open the src/hello_erlang_app.erl file and add the necessary -code to the start/2 function to make it look like this:

-
-
-
start(_Type, _Args) ->
-    Dispatch = cowboy_router:compile([
-        {'_', [{"/", hello_handler, []}]}
+
start(_Type, _Args) ->
+    Dispatch = cowboy_router:compile([
+        {'_', [{"/", hello_handler, []}]}
     ]),
-    {ok, _} = cowboy:start_clear(my_http_listener,
-        [{port, 8080}],
-        #{env => #{dispatch => Dispatch}}
+    {ok, _} = cowboy:start_clear(my_http_listener,
+        [{port, 8080}],
+        #{env => #{dispatch => Dispatch}}
     ),
-    hello_erlang_sup:start_link().
-

Routes are explained in details in the Routing -chapter. For this tutorial we map the path / to the handler -module hello_handler. This module doesn’t exist yet.

-

Build and start the release, then open http://localhost:8080 -in your browser. You will get a 500 error because the module is missing. -Any other URL, like http://localhost:8080/test, will result in a -404 error.

-
- -
+ hello_erlang_sup:start_link(). +
+

Routes are explained in details in the Routing chapter. For this tutorial we map the path / to the handler module hello_handler. This module doesn't exist yet.

+

Build and start the release, then open http://localhost:8080 in your browser. You will get a 500 error because the module is missing. Any other URL, like http://localhost:8080/test, will result in a 404 error.

Handling requests

-
-

Cowboy features different kinds of handlers, including REST -and Websocket handlers. For this tutorial we will use a plain -HTTP handler.

-

Generate a handler from a template:

-
-
-
$ make new t=cowboy.http n=hello_handler
-

Then, open the src/hello_handler.erl file and modify -the init/2 function like this to send a reply.

-
-
-
init(Req0, State) ->
-    Req = cowboy_req:reply(200,
-        #{<<"content-type">> => <<"text/plain">>},
-        <<"Hello Erlang!">>,
-        Req0),
-    {ok, Req, State}.
-

What the above code does is send a 200 OK reply, with the -Content-type header set to text/plain and the response -body set to Hello Erlang!.

-

If you run the release and open http://localhost:8080 -in your browser, you should get a nice Hello Erlang! displayed!

-
- +
init(Req0, State) ->
+    Req = cowboy_req:reply(200,
+        #{<<"content-type">> => <<"text/plain">>},
+        <<"Hello Erlang!">>,
+        Req0),
+    {ok, Req, State}.
+ +

What the above code does is send a 200 OK reply, with the Content-type header set to text/plain and the response body set to Hello Erlang!.

+

If you run the release and open http://localhost:8080 in your browser, you should get a nice Hello Erlang! displayed!

+ diff --git a/docs/en/cowboy/2.3/guide/handlers/index.html b/docs/en/cowboy/2.3/guide/handlers/index.html index e8567d8e..61d83e67 100644 --- a/docs/en/cowboy/2.3/guide/handlers/index.html +++ b/docs/en/cowboy/2.3/guide/handlers/index.html @@ -62,91 +62,57 @@

Handlers

-

Handlers are Erlang modules that handle HTTP requests.

-
+

Handlers are Erlang modules that handle HTTP requests.

Plain HTTP handlers

-
-

The most basic handler in Cowboy implements the mandatory -init/2 callback, manipulates the request, optionally -sends a response and then returns.

-

This callback receives the Req object and the initial -state defined in the router configuration.

-

A handler that does nothing would look like this:

-
-
-
init(Req, State) ->
-    {ok, Req, State}.
-

Despite sending no reply, a 204 No Content response will be -sent to the client, as Cowboy makes sure that a response is -sent for every request.

-

We need to use the Req object to reply.

-
-
-
init(Req0, State) ->
-    Req = cowboy_req:reply(200, #{
-        <<"content-type">> => <<"text/plain">>
-    }, <<"Hello World!">>, Req0),
-    {ok, Req, State}.
-

Cowboy will immediately send a response when cowboy:reply/4 -is called.

-

We then return a 3-tuple. ok means that the handler ran -successfully. We also give the modified Req back to Cowboy.

-

The last value of the tuple is a state that will be used -in every subsequent callbacks to this handler. Plain HTTP -handlers only have one additional callback, the optional -and rarely used terminate/3.

-
-
-
+
init(Req0, State) ->
+    Req = cowboy_req:reply(200, #{
+        <<"content-type">> => <<"text/plain">>
+    }, <<"Hello World!">>, Req0),
+    {ok, Req, State}.
+
+

Cowboy will immediately send a response when cowboy:reply/4 is called.

+

We then return a 3-tuple. ok means that the handler ran successfully. We also give the modified Req back to Cowboy.

+

The last value of the tuple is a state that will be used in every subsequent callbacks to this handler. Plain HTTP handlers only have one additional callback, the optional and rarely used terminate/3.

Other handlers

-
-

The init/2 callback can also be used to inform Cowboy -that this is a different kind of handler and that Cowboy -should switch to it. To do this you simply need to return -the module name of the handler type you want to switch to.

-

Cowboy comes with three handler types you can switch to: -cowboy_rest, cowboy_websocket -and cowboy_loop. In addition to those you -can define your own handler types.

-

Switching is simple. Instead of returning ok, you simply -return the name of the handler type you want to use. The -following snippet switches to a Websocket handler:

-
-
-
init(Req, State) ->
-    {cowboy_websocket, Req, State}.
-
- -
+
init(Req, State) ->
+    {cowboy_websocket, Req, State}.
+

Cleaning up

-
-

All handler types provide the optional terminate/3 callback.

-
-
-
terminate(_Reason, _Req, _State) ->
-    ok.
-

This callback is strictly reserved for any required cleanup. -You cannot send a response from this function. There is no -other return value.

-

This callback is optional because it is rarely necessary. -Cleanup should be done in separate processes directly (by -monitoring the handler process to detect when it exits).

-

Cowboy does not reuse processes for different requests. The -process will terminate soon after this call returns.

-
- +
terminate(_Reason, _Req, _State) ->
+    ok.
+ +

This callback is strictly reserved for any required cleanup. You cannot send a response from this function. There is no other return value.

+

This callback is optional because it is rarely necessary. Cleanup should be done in separate processes directly (by monitoring the handler process to detect when it exits).

+

Cowboy does not reuse processes for different requests. The process will terminate soon after this call returns.

+ diff --git a/docs/en/cowboy/2.3/guide/index.html b/docs/en/cowboy/2.3/guide/index.html index 88267686..2aede748 100644 --- a/docs/en/cowboy/2.3/guide/index.html +++ b/docs/en/cowboy/2.3/guide/index.html @@ -62,214 +62,85 @@

Cowboy User Guide

-
+ +

Rationale

- -
-
+

Introduction

- -
-
+

Configuration

-
- -
-
-
+

Handlers

- -
- - - -
+

Advanced

-
- -
-
- + + diff --git a/docs/en/cowboy/2.3/guide/introduction/index.html b/docs/en/cowboy/2.3/guide/introduction/index.html index eaeaf485..3a0db4b4 100644 --- a/docs/en/cowboy/2.3/guide/introduction/index.html +++ b/docs/en/cowboy/2.3/guide/introduction/index.html @@ -62,79 +62,40 @@

Introduction

-

Cowboy is a small, fast and modern HTTP server for Erlang/OTP.

-

Cowboy aims to provide a complete modern Web stack. -This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and -Webmachine-based REST.

-

Cowboy comes with functions for introspection and tracing, enabling -developers to know precisely what is happening at any time. Its modular -design also easily enable developers to add instrumentation.

-

Cowboy is a high quality project. It has a small code base, is very -efficient (both in latency and memory use) and can easily be embedded -in another application.

-

Cowboy is clean Erlang code. It includes hundreds of tests and its code -is fully compliant with the Dialyzer. It is also well documented and -features a Function Reference, a User Guide and numerous Tutorials.

-
+

Cowboy is a small, fast and modern HTTP server for Erlang/OTP.

+

Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST.

+

Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation.

+

Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application.

+

Cowboy is clean Erlang code. It includes hundreds of tests and its code is fully compliant with the Dialyzer. It is also well documented and features a Function Reference, a User Guide and numerous Tutorials.

Prerequisites

-
-

Beginner Erlang knowledge is recommended for reading this guide.

-

Knowledge of the HTTP protocol is recommended but not required, as it -will be detailed throughout the guide.

-
-
-
+

Beginner Erlang knowledge is recommended for reading this guide.

+

Knowledge of the HTTP protocol is recommended but not required, as it will be detailed throughout the guide.

Supported platforms

-
-

Cowboy is tested and supported on Linux, FreeBSD, Windows and OSX.

-

Cowboy has been reported to work on other platforms, but we make no -guarantee that the experience will be safe and smooth. You are advised -to perform the necessary testing and security audits prior to deploying -on other platforms.

-

Cowboy is developed for Erlang/OTP 19.0 and newer.

-
-
-
+

Cowboy is tested and supported on Linux, FreeBSD, Windows and OSX.

+

Cowboy has been reported to work on other platforms, but we make no guarantee that the experience will be safe and smooth. You are advised to perform the necessary testing and security audits prior to deploying on other platforms.

+

Cowboy is developed for Erlang/OTP 19.0 and newer.

License

-
-

Cowboy uses the ISC License.

-
-
-
Copyright (c) 2011-2017, Loïc Hoguin <essen@ninenines.eu>
+

Cowboy uses the ISC License.

+
Copyright (c) 2011-2017, Loïc Hoguin <essen@ninenines.eu>
 
 Permission to use, copy, modify, and/or distribute this software for any
 purpose with or without fee is hereby granted, provided that the above
 copyright notice and this permission notice appear in all copies.
 
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-
-
-
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Versioning

-
- -
-
-
+

Cowboy uses Semantic Versioning 2.0.0.

Conventions

-
-

In the HTTP protocol, the method name is case sensitive. All standard -method names are uppercase.

-

Header names are case insensitive. When using HTTP/1.1, Cowboy converts -all the request header names to lowercase. HTTP/2 requires clients to -send them as lowercase. Any other header name is expected to be provided -lowercased, including when querying information about the request or -when sending responses.

-

The same applies to any other case insensitive value.

-
-
+

In the HTTP protocol, the method name is case sensitive. All standard method names are uppercase.

+

Header names are case insensitive. When using HTTP/1.1, Cowboy converts all the request header names to lowercase. HTTP/2 requires clients to send them as lowercase. Any other header name is expected to be provided lowercased, including when querying information about the request or when sending responses.

+

The same applies to any other case insensitive value.

+ diff --git a/docs/en/cowboy/2.3/guide/listeners/index.html b/docs/en/cowboy/2.3/guide/listeners/index.html index 0990f98c..743c25fb 100644 --- a/docs/en/cowboy/2.3/guide/listeners/index.html +++ b/docs/en/cowboy/2.3/guide/listeners/index.html @@ -62,109 +62,61 @@

Listeners

-

A listener is a set of processes that listens on a port for -new connections. Incoming connections get handled by Cowboy. -Depending on the connection handshake, one or another protocol -may be used.

-

This chapter is specific to Cowboy. Please refer to the -Ranch User Guide -for more information about listeners.

-

Cowboy provides two types of listeners: one listening for -clear TCP connections, and one listening for secure TLS -connections. Both of them support the HTTP/1.1 and HTTP/2 -protocols.

-
+

A listener is a set of processes that listens on a port for new connections. Incoming connections get handled by Cowboy. Depending on the connection handshake, one or another protocol may be used.

+

This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners.

+

Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. Both of them support the HTTP/1.1 and HTTP/2 protocols.

Clear TCP listener

-
-

The clear TCP listener will accept connections on the -given port. A typical HTTP server would listen on port 80. -Port 80 requires special permissions on most platforms -however so a common alternative is port 8080.

-

The following snippet starts listening for connections -on port 8080:

-
-
-
start(_Type, _Args) ->
-    Dispatch = cowboy_router:compile([
-        {'_', [{"/", hello_handler, []}]}
+
start(_Type, _Args) ->
+    Dispatch = cowboy_router:compile([
+        {'_', [{"/", hello_handler, []}]}
     ]),
-    {ok, _} = cowboy:start_clear(my_http_listener,
-        [{port, 8080}],
-        #{env => #{dispatch => Dispatch}}
+    {ok, _} = cowboy:start_clear(my_http_listener,
+        [{port, 8080}],
+        #{env => #{dispatch => Dispatch}}
     ),
-    hello_erlang_sup:start_link().
-

The Getting Started chapter uses a -clear TCP listener.

-

Clients connecting to Cowboy on the clear listener port are -expected to use either HTTP/1.1 or HTTP/2.

-

Cowboy supports both methods of initiating a clear -HTTP/2 connection: through the Upgrade mechanism -(RFC 7540 3.2) -or by sending the preface directly -(RFC 7540 3.4).

-

Compatibility with HTTP/1.0 is provided by Cowboy’s HTTP/1.1 -implementation.

-
-
-
+ hello_erlang_sup:start_link(). +
+

The Getting Started chapter uses a clear TCP listener.

+

Clients connecting to Cowboy on the clear listener port are expected to use either HTTP/1.1 or HTTP/2.

+

Cowboy supports both methods of initiating a clear HTTP/2 connection: through the Upgrade mechanism (RFC 7540 3.2) or by sending the preface directly (RFC 7540 3.4).

+

Compatibility with HTTP/1.0 is provided by Cowboy's HTTP/1.1 implementation.

Secure TLS listener

-
-

The secure TLS listener will accept connections on the -given port. A typical HTTPS server would listen on port 443. -Port 443 requires special permissions on most platforms -however so a common alternative is port 8443.

-

The function provided by Cowboy will ensure that the TLS -options given are following the HTTP/2 RFC with regards -to security. For example some TLS extensions or ciphers -may be disabled. This also applies to HTTP/1.1 connections -on this listener. If this is not desirable, Ranch can be -used directly to setup a custom listener.

-
-
+

The function provided by Cowboy will ensure that the TLS options given are following the HTTP/2 RFC with regards to security. For example some TLS extensions or ciphers may be disabled. This also applies to HTTP/1.1 connections on this listener. If this is not desirable, Ranch can be used directly to setup a custom listener.

+
-
start(_Type, _Args) ->
-    Dispatch = cowboy_router:compile([
-        {'_', [{"/", hello_handler, []}]}
+
start(_Type, _Args) ->
+    Dispatch = cowboy_router:compile([
+        {'_', [{"/", hello_handler, []}]}
     ]),
-    {ok, _} = cowboy:start_tls(my_http_listener,
+    {ok, _} = cowboy:start_tls(my_http_listener,
         [
-            {port, 8443},
-            {certfile, "/path/to/certfile"},
-            {keyfile, "/path/to/keyfile"}
+            {port, 8443},
+            {certfile, "/path/to/certfile"},
+            {keyfile, "/path/to/keyfile"}
         ],
-        #{env => #{dispatch => Dispatch}}
+        #{env => #{dispatch => Dispatch}}
     ),
-    hello_erlang_sup:start_link().
-

Clients connecting to Cowboy on the secure listener are -expected to use the ALPN TLS extension to indicate what -protocols they understand. Cowboy always prefers HTTP/2 -over HTTP/1.1 when both are supported. When neither are -supported by the client, or when the ALPN extension was -missing, Cowboy expects HTTP/1.1 to be used.

-

Cowboy also advertises HTTP/2 support through the older -NPN TLS extension for compatibility. Note however that -this support will likely not be enabled by default when -Cowboy 2.0 gets released.

-

Compatibility with HTTP/1.0 is provided by Cowboy’s HTTP/1.1 -implementation.

-
-
-
+ hello_erlang_sup:start_link(). +
+

Clients connecting to Cowboy on the secure listener are expected to use the ALPN TLS extension to indicate what protocols they understand. Cowboy always prefers HTTP/2 over HTTP/1.1 when both are supported. When neither are supported by the client, or when the ALPN extension was missing, Cowboy expects HTTP/1.1 to be used.

+

Cowboy also advertises HTTP/2 support through the older NPN TLS extension for compatibility. Note however that this support will likely not be enabled by default when Cowboy 2.0 gets released.

+

Compatibility with HTTP/1.0 is provided by Cowboy's HTTP/1.1 implementation.

Protocol configuration

-
-

The HTTP/1.1 and HTTP/2 protocols share the same semantics; -only their framing differs. The first is a text protocol and -the second a binary protocol.

-

Cowboy doesn’t separate the configuration for HTTP/1.1 and -HTTP/2. Everything goes into the same map. Many options are -shared.

-
- +

The HTTP/1.1 and HTTP/2 protocols share the same semantics; only their framing differs. The first is a text protocol and the second a binary protocol.

+

Cowboy doesn't separate the configuration for HTTP/1.1 and HTTP/2. Everything goes into the same map. Many options are shared.

+ + + diff --git a/docs/en/cowboy/2.3/guide/loop_handlers/index.html b/docs/en/cowboy/2.3/guide/loop_handlers/index.html index 57c5be92..637a54e1 100644 --- a/docs/en/cowboy/2.3/guide/loop_handlers/index.html +++ b/docs/en/cowboy/2.3/guide/loop_handlers/index.html @@ -62,131 +62,72 @@

Loop handlers

-

Loop handlers are a special kind of HTTP handlers used when the -response can not be sent right away. The handler enters instead -a receive loop waiting for the right message before it can send -a response.

-

Loop handlers are used for requests where a response might not -be immediately available, but where you would like to keep the -connection open for a while in case the response arrives. The -most known example of such practice is known as long polling.

-

Loop handlers can also be used for requests where a response is -partially available and you need to stream the response body -while the connection is open. The most known example of such -practice is server-sent events.

-

While the same can be accomplished using plain HTTP handlers, -it is recommended to use loop handlers because they are well-tested -and allow using built-in features like hibernation and timeouts.

-

Loop handlers essentially wait for one or more Erlang messages -and feed these messages to the info/3 callback. It also features -the init/2 and terminate/3 callbacks which work the same as -for plain HTTP handlers.

-
+

Loop handlers are a special kind of HTTP handlers used when the response can not be sent right away. The handler enters instead a receive loop waiting for the right message before it can send a response.

+

Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling.

+

Loop handlers can also be used for requests where a response is partially available and you need to stream the response body while the connection is open. The most known example of such practice is server-sent events.

+

While the same can be accomplished using plain HTTP handlers, it is recommended to use loop handlers because they are well-tested and allow using built-in features like hibernation and timeouts.

+

Loop handlers essentially wait for one or more Erlang messages and feed these messages to the info/3 callback. It also features the init/2 and terminate/3 callbacks which work the same as for plain HTTP handlers.

Initialization

-
-

The init/2 function must return a cowboy_loop tuple to enable -loop handler behavior. This tuple may optionally contain -a timeout value and/or the atom hibernate to make the -process enter hibernation until a message is received.

-

This snippet enables the loop handler:

-
-
-
init(Req, State) ->
-    {cowboy_loop, Req, State}.
-

This also makes the process hibernate:

-
-
-
init(Req, State) ->
-    {cowboy_loop, Req, State, hibernate}.
-
-
-
+
init(Req, State) ->
+    {cowboy_loop, Req, State, hibernate}.
+

Receive loop

-
-

Once initialized, Cowboy will wait for messages to arrive -in the process' mailbox. When a message arrives, Cowboy -calls the info/3 function with the message, the Req object -and the handler’s state.

-

The following snippet sends a reply when it receives a -reply message from another process, or waits for another -message otherwise.

-
-
-
info({reply, Body}, Req, State) ->
-    cowboy_req:reply(200, #{}, Body, Req),
-    {stop, Req, State};
-info(_Msg, Req, State) ->
-    {ok, Req, State, hibernate}.
-

Do note that the reply tuple here may be any message -and is simply an example.

-

This callback may perform any necessary operation including -sending all or parts of a reply, and will subsequently -return a tuple indicating if more messages are to be expected.

-

The callback may also choose to do nothing at all and just -skip the message received.

-

If a reply is sent, then the stop tuple should be returned. -This will instruct Cowboy to end the request.

-

Otherwise an ok tuple should be returned.

-
- -
+
info({reply, Body}, Req, State) ->
+    cowboy_req:reply(200, #{}, Body, Req),
+    {stop, Req, State};
+info(_Msg, Req, State) ->
+    {ok, Req, State, hibernate}.
+
+

Do note that the reply tuple here may be any message and is simply an example.

+

This callback may perform any necessary operation including sending all or parts of a reply, and will subsequently return a tuple indicating if more messages are to be expected.

+

The callback may also choose to do nothing at all and just skip the message received.

+

If a reply is sent, then the stop tuple should be returned. This will instruct Cowboy to end the request.

+

Otherwise an ok tuple should be returned.

Streaming loop

-
-

Another common case well suited for loop handlers is -streaming data received in the form of Erlang messages. -This can be done by initiating a chunked reply in the -init/2 callback and then using cowboy_req:chunk/2 -every time a message is received.

-

The following snippet does exactly that. As you can see -a chunk is sent every time an event message is received, -and the loop is stopped by sending an eof message.

-
-
-
init(Req, State) ->
-    Req2 = cowboy_req:stream_reply(200, Req),
-    {cowboy_loop, Req2, State}.
-
-info(eof, Req, State) ->
-    {stop, Req, State};
-info({event, Data}, Req, State) ->
-    cowboy_req:stream_body(Data, nofin, Req),
-    {ok, Req, State};
-info(_Msg, Req, State) ->
-    {ok, Req, State}.
-
- -
+
init(Req, State) ->
+    Req2 = cowboy_req:stream_reply(200, Req),
+    {cowboy_loop, Req2, State}.
+
+info(eof, Req, State) ->
+    {stop, Req, State};
+info({event, Data}, Req, State) ->
+    cowboy_req:stream_body(Data, nofin, Req),
+    {ok, Req, State};
+info(_Msg, Req, State) ->
+    {ok, Req, State}.
+

Cleaning up

-
-

It is recommended that you set the connection header to -close when replying, as this process may be reused for -a subsequent request.

-

Please refer to the Handlers chapter -for general instructions about cleaning up.

-
- -
+

It is recommended that you set the connection header to close when replying, as this process may be reused for a subsequent request.

+

Please refer to the Handlers chapter for general instructions about cleaning up.

Hibernate

-
-

To save memory, you may hibernate the process in between -messages received. This is done by returning the atom -hibernate as part of the loop tuple callbacks normally -return. Just add the atom at the end and Cowboy will hibernate -accordingly.

-
-
+

To save memory, you may hibernate the process in between messages received. This is done by returning the atom hibernate as part of the loop tuple callbacks normally return. Just add the atom at the end and Cowboy will hibernate accordingly.

+ diff --git a/docs/en/cowboy/2.3/guide/middlewares/index.html b/docs/en/cowboy/2.3/guide/middlewares/index.html index a02ce678..6dbf8869 100644 --- a/docs/en/cowboy/2.3/guide/middlewares/index.html +++ b/docs/en/cowboy/2.3/guide/middlewares/index.html @@ -62,92 +62,38 @@

Middlewares

-

Cowboy delegates the request processing to middleware components. -By default, two middlewares are defined, for the routing and handling -of the request, as is detailed in most of this guide.

-

Middlewares give you complete control over how requests are to be -processed. You can add your own middlewares to the mix or completely -change the chain of middlewares as needed.

-

Cowboy will execute all middlewares in the given order, unless one -of them decides to stop processing.

-
+

Cowboy delegates the request processing to middleware components. By default, two middlewares are defined, for the routing and handling of the request, as is detailed in most of this guide.

+

Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed.

+

Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing.

Usage

-
-

Middlewares only need to implement a single callback: execute/2. -It is defined in the cowboy_middleware behavior.

-

This callback has two arguments. The first is the Req object. -The second is the environment.

-

Middlewares can return one of three different values:

-
    -
  • -

    -{ok, Req, Env} to continue the request processing -

    +

    Middlewares only need to implement a single callback: execute/2. It is defined in the cowboy_middleware behavior.

    +

    This callback has two arguments. The first is the Req object. The second is the environment.

    +

    Middlewares can return one of three different values:

    +
    • {ok, Req, Env} to continue the request processing
    • -
    • -

      -{suspend, Module, Function, Args} to hibernate -

      +
    • {suspend, Module, Function, Args} to hibernate
    • -
    • -

      -{stop, Req} to stop processing and move on to the next request -

      +
    • {stop, Req} to stop processing and move on to the next request
    • -
-

Of note is that when hibernating, processing will resume on the given -MFA, discarding all previous stacktrace. Make sure you keep the Req -and Env in the arguments of this MFA for later use.

-

If an error happens during middleware processing, Cowboy will not try -to send an error back to the socket, the process will just crash. It -is up to the middleware to make sure that a reply is sent if something -goes wrong.

-
-
-
+ +

Of note is that when hibernating, processing will resume on the given MFA, discarding all previous stacktrace. Make sure you keep the Req and Env in the arguments of this MFA for later use.

+

If an error happens during middleware processing, Cowboy will not try to send an error back to the socket, the process will just crash. It is up to the middleware to make sure that a reply is sent if something goes wrong.

Configuration

-
-

The middleware environment is defined as the env protocol option. -In the previous chapters we saw it briefly when we needed to pass -the routing information. It is a list of tuples with the first -element being an atom and the second any Erlang term.

-

Two values in the environment are reserved:

-
    -
  • -

    -listener contains the name of the listener -

    +

    The middleware environment is defined as the env protocol option. In the previous chapters we saw it briefly when we needed to pass the routing information. It is a list of tuples with the first element being an atom and the second any Erlang term.

    +

    Two values in the environment are reserved:

    +
    • listener contains the name of the listener
    • -
    • -

      -result contains the result of the processing -

      +
    • result contains the result of the processing
    • -
-

The listener value is always defined. The result value can be -set by any middleware. If set to anything other than ok, Cowboy -will not process any subsequent requests on this connection.

-

The middlewares that come with Cowboy may define or require other -environment values to perform.

-

You can update the environment by calling the cowboy:set_env/3 -convenience function, adding or replacing a value in the environment.

-
-
-
+ +

The listener value is always defined. The result value can be set by any middleware. If set to anything other than ok, Cowboy will not process any subsequent requests on this connection.

+

The middlewares that come with Cowboy may define or require other environment values to perform.

+

You can update the environment by calling the cowboy:set_env/3 convenience function, adding or replacing a value in the environment.

Routing middleware

-
-

The routing middleware requires the dispatch value. If routing -succeeds, it will put the handler name and options in the handler -and handler_opts values of the environment, respectively.

-
-
-
+

The routing middleware requires the dispatch value. If routing succeeds, it will put the handler name and options in the handler and handler_opts values of the environment, respectively.

Handler middleware

-
-

The handler middleware requires the handler and handler_opts -values. It puts the result of the request handling into result.

-
-
+

The handler middleware requires the handler and handler_opts values. It puts the result of the request handling into result.

+ diff --git a/docs/en/cowboy/2.3/guide/migrating_from_1.0/index.html b/docs/en/cowboy/2.3/guide/migrating_from_1.0/index.html index c284d717..b8a30584 100644 --- a/docs/en/cowboy/2.3/guide/migrating_from_1.0/index.html +++ b/docs/en/cowboy/2.3/guide/migrating_from_1.0/index.html @@ -62,388 +62,120 @@

Migrating from Cowboy 1.0 to 2.0

-

A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req -interface in particular has seen a massive revamp. Hooks are -gone, their functionality can now be achieved via stream -handlers.

-

The documentation has seen great work, in particular the -manual. Each module and each function now has its own dedicated -manual page with full details and examples.

-
+

A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req interface in particular has seen a massive revamp. Hooks are gone, their functionality can now be achieved via stream handlers.

+

The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples.

Compatibility

-
-

Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. -Erlang/OTP 19.0 or above is required. It is non-trivial to -make Cowboy 2.0 work with older Erlang/OTP versions.

-

Cowboy 2.0 is not compatible with Cowlib versions older than -2.0. It should be compatible with Ranch 1.0 or above, however -it has not been tested with Ranch versions older than 1.4.

-

Cowboy 2.0 is tested on Arch Linux, Ubuntu, FreeBSD, Windows -and OSX. It is tested with every point release (latest patch -release) and also with HiPE on the most recent release.

-

Cowboy 2.0 now comes with Erlang.mk templates.

-
-
-
+

Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. Erlang/OTP 19.0 or above is required. It is non-trivial to make Cowboy 2.0 work with older Erlang/OTP versions.

+

Cowboy 2.0 is not compatible with Cowlib versions older than 2.0. It should be compatible with Ranch 1.0 or above, however it has not been tested with Ranch versions older than 1.4.

+

Cowboy 2.0 is tested on Arch Linux, Ubuntu, FreeBSD, Windows and OSX. It is tested with every point release (latest patch release) and also with HiPE on the most recent release.

+

Cowboy 2.0 now comes with Erlang.mk templates.

Features added

-
-
    -
  • -

    -The HTTP/2 protocol is now supported. -

    -
  • -
  • -

    -Cowboy no longer uses only one process per connection. - It now uses one process per connection plus one process - per request by default. This is necessary for HTTP/2. - There might be a slight drop in performance for HTTP/1.1 - connections due to this change. -

    -
  • -
  • -

    -Cowboy internals have largely been reworked in order to - support HTTP/2. This opened the way to stream handlers, - which are a chain of modules that are called whenever - something happens relating to a request/response. -

    -
  • -
  • -

    -The cowboy_stream_h stream handler has been added. - It provides most of Cowboy’s default behavior. -

    -
  • -
  • -

    -The cowboy_compress_h stream handler has been added. - It compresses responses when possible. It’s worth noting - that it compresses in more cases than Cowboy 1.0 ever did. -

    -
  • -
  • -

    -Because of the many changes in the internals of Cowboy, - many options have been added or modified. Of note is that - the Websocket options are now given per handler rather - than for the entire listener. -

    -
  • -
  • -

    -Websocket permessage-deflate compression is now supported - via the compress option. -

    -
  • -
  • -

    -Static file handlers will now correctly find files found - in .ez archives. -

    -
  • -
  • -

    -Constraints have been generalized and are now used not only - in the router but also in some cowboy_req functions. Their - interface has also been modified to allow for reverse - operations and formatting of errors. -

    -
  • -
-
-
-
+
  • The HTTP/2 protocol is now supported. +
  • +
  • Cowboy no longer uses only one process per connection. It now uses one process per connection plus one process per request by default. This is necessary for HTTP/2. There might be a slight drop in performance for HTTP/1.1 connections due to this change. +
  • +
  • Cowboy internals have largely been reworked in order to support HTTP/2. This opened the way to stream handlers, which are a chain of modules that are called whenever something happens relating to a request/response. +
  • +
  • The cowboy_stream_h stream handler has been added. It provides most of Cowboy's default behavior. +
  • +
  • The cowboy_compress_h stream handler has been added. It compresses responses when possible. It's worth noting that it compresses in more cases than Cowboy 1.0 ever did. +
  • +
  • Because of the many changes in the internals of Cowboy, many options have been added or modified. Of note is that the Websocket options are now given per handler rather than for the entire listener. +
  • +
  • Websocket permessage-deflate compression is now supported via the compress option. +
  • +
  • Static file handlers will now correctly find files found in .ez archives. +
  • +
  • Constraints have been generalized and are now used not only in the router but also in some cowboy_req functions. Their interface has also been modified to allow for reverse operations and formatting of errors. +
  • +

Features removed

-
-
    -
  • -

    -SPDY support has been removed. Use HTTP/2 instead. -

    -
  • -
  • -

    -Hooks have been removed. Use stream handlers instead. -

    -
  • -
  • -

    -The undocumented waiting_stream hack has been removed. - It allowed disabling chunked transfer-encoding for HTTP/1.1. - It has no equivalent in Cowboy 2.0. Open a ticket if necessary. -

    -
  • -
  • -

    -Sub protocols still exist, but their interface has largely changed - and they are no longer documented for the time being. -

    -
  • -
-
-
-
+
  • SPDY support has been removed. Use HTTP/2 instead. +
  • +
  • Hooks have been removed. Use stream handlers instead. +
  • +
  • The undocumented waiting_stream hack has been removed. It allowed disabling chunked transfer-encoding for HTTP/1.1. It has no equivalent in Cowboy 2.0. Open a ticket if necessary. +
  • +
  • Sub protocols still exist, but their interface has largely changed and they are no longer documented for the time being. +
  • +

Changed behaviors

-
-
    -
  • -

    -The handler behaviors have been renamed and are now cowboy_handler, - cowboy_loop, cowboy_rest and cowboy_websocket. -

    -
  • -
  • -

    -Plain HTTP, loop, REST and Websocket handlers have had their - init and terminate callbacks unified. They now all use the - init/2 and terminate/3 callbacks. The latter is now optional. - The terminate reason has now been documented for all handlers. -

    -
  • -
  • -

    -The tuple returned to switch to a different handler type has - changed. It now takes the form {Module, Req, State} or - {Module, Req, State, Opts}, where Opts is a map of options - to configure the handler. The timeout and hibernate options - must now be specified using this map, where applicable. -

    -
  • -
  • -

    -All behaviors that used to accept halt or shutdown tuples - as a return value no longer do so. The return value is now - a stop tuple, consistent across Cowboy. -

    -
  • -
  • -

    -Middlewares can no longer return an error tuple. They have - to send the response and return a stop tuple instead. -

    -
  • -
  • -

    -The known_content_type REST handler callback has been removed - as it was found unnecessary. -

    -
  • -
  • -

    -Websocket handlers have both the normal init/2 and - an optional websocket_init/1 function. The reason for - that exception is that the websocket_* callbacks execute - in a separate process from the init/2 callback, and it - was therefore not obvious how timers or monitors should - be setup properly. They are effectively initializing the - handler before and after the HTTP/1.1 upgrade. -

    -
  • -
  • -

    -Websocket handlers can now send frames directly from - websocket_init/1. The frames will be sent immediately - after the handshake. -

    -
  • -
  • -

    -Websocket handler callbacks no longer receive the Req - argument. The init/2 callback still receives it and - can be used to extract relevant information. The terminate/3 - callback, if implemented, may still receive the Req - (see next bullet point). -

    -
  • -
  • -

    -Websocket handlers have a new req_filter option that - can be used to customize how much information should be - discarded from the Req object after the handshake. Note - that the Req object is only available in terminate/3 - past that point. -

    -
  • -
  • -

    -Websocket handlers have their timeout default changed - from infinity to 60 seconds. -

    -
  • -
-
-
-
+
  • The handler behaviors have been renamed and are now cowboy_handler, cowboy_loop, cowboy_rest and cowboy_websocket. +
  • +
  • Plain HTTP, loop, REST and Websocket handlers have had their init and terminate callbacks unified. They now all use the init/2 and terminate/3 callbacks. The latter is now optional. The terminate reason has now been documented for all handlers. +
  • +
  • The tuple returned to switch to a different handler type has changed. It now takes the form {Module, Req, State} or {Module, Req, State, Opts}, where Opts is a map of options to configure the handler. The timeout and hibernate options must now be specified using this map, where applicable. +
  • +
  • All behaviors that used to accept halt or shutdown tuples as a return value no longer do so. The return value is now a stop tuple, consistent across Cowboy. +
  • +
  • Middlewares can no longer return an error tuple. They have to send the response and return a stop tuple instead. +
  • +
  • The known_content_type REST handler callback has been removed as it was found unnecessary. +
  • +
  • Websocket handlers have both the normal init/2 and an optional websocket_init/1 function. The reason for that exception is that the websocket_* callbacks execute in a separate process from the init/2 callback, and it was therefore not obvious how timers or monitors should be setup properly. They are effectively initializing the handler before and after the HTTP/1.1 upgrade. +
  • +
  • Websocket handlers can now send frames directly from websocket_init/1. The frames will be sent immediately after the handshake. +
  • +
  • Websocket handler callbacks no longer receive the Req argument. The init/2 callback still receives it and can be used to extract relevant information. The terminate/3 callback, if implemented, may still receive the Req (see next bullet point). +
  • +
  • Websocket handlers have a new req_filter option that can be used to customize how much information should be discarded from the Req object after the handshake. Note that the Req object is only available in terminate/3 past that point. +
  • +
  • Websocket handlers have their timeout default changed from infinity to 60 seconds. +
  • +

New functions

-
-
    -
  • -

    -The cowboy_req:scheme/1 function has been added. -

    -
  • -
  • -

    -The cowboy_req:uri/1,2 function has been added, replacing the - less powerful functions cowboy_req:url/1 and cowboy_req:host_url/1. -

    -
  • -
  • -

    -The functions cowboy_req:match_qs/2 and cowboy_req:match_cookies/2 - allow matching query string and cookies against constraints. -

    -
  • -
  • -

    -The function cowboy_req:set_resp_cookie/3 has been added to - complement cowboy_req:set_resp_cookie/4. -

    -
  • -
  • -

    -The functions cowboy_req:resp_header/2,3 and cowboy_req:resp_headers/1 - have been added. They can be used to retrieve response headers - that were previously set. -

    -
  • -
  • -

    -The function cowboy_req:set_resp_headers/2 has been added. It - allows setting many response headers at once. -

    -
  • -
  • -

    -The functions cowboy_req:push/3,4 can be used to push resources - for protocols that support it (by default only HTTP/2). -

    -
  • -
-
-
-
+
  • The cowboy_req:scheme/1 function has been added. +
  • +
  • The cowboy_req:uri/1,2 function has been added, replacing the less powerful functions cowboy_req:url/1 and cowboy_req:host_url/1. +
  • +
  • The functions cowboy_req:match_qs/2 and cowboy_req:match_cookies/2 allow matching query string and cookies against constraints. +
  • +
  • The function cowboy_req:set_resp_cookie/3 has been added to complement cowboy_req:set_resp_cookie/4. +
  • +
  • The functions cowboy_req:resp_header/2,3 and cowboy_req:resp_headers/1 have been added. They can be used to retrieve response headers that were previously set. +
  • +
  • The function cowboy_req:set_resp_headers/2 has been added. It allows setting many response headers at once. +
  • +
  • The functions cowboy_req:push/3,4 can be used to push resources for protocols that support it (by default only HTTP/2). +
  • +

Changed functions

-
-
    -
  • -

    -The cowboy:start_http/4 function was renamed to cowboy:start_clear/3. -

    -
  • -
  • -

    -The cowboy:start_https/4 function was renamed to cowboy:start_tls/3. -

    -
  • -
  • -

    -Most, if not all, functions in the cowboy_req module have been modified. - Please consult the changelog of each individual functions. The changes - are mainly about simplifying and clarifying the interface. The Req is no - longer returned when not necessary, maps are used wherever possible, - and some functions have been renamed. -

    -
  • -
  • -

    -The position of the Opts argument for cowboy_req:set_resp_cookie/4 - has changed to improve consistency. It is now the last argument. -

    -
  • -
-
-
-
+
  • The cowboy:start_http/4 function was renamed to cowboy:start_clear/3. +
  • +
  • The cowboy:start_https/4 function was renamed to cowboy:start_tls/3. +
  • +
  • Most, if not all, functions in the cowboy_req module have been modified. Please consult the changelog of each individual functions. The changes are mainly about simplifying and clarifying the interface. The Req is no longer returned when not necessary, maps are used wherever possible, and some functions have been renamed. +
  • +
  • The position of the Opts argument for cowboy_req:set_resp_cookie/4 has changed to improve consistency. It is now the last argument. +
  • +

Removed functions

-
-
    -
  • -

    -The functions cowboy_req:url/1 and cowboy_req:host_url/1 have been - removed in favor of the new function cowboy_req:uri/1,2. -

    -
  • -
  • -

    -The functions cowboy_req:meta/2,3 and cowboy_req:set_meta/3 have - been removed. The Req object is now a public map, therefore they became - unnecessary. -

    -
  • -
  • -

    -The functions cowboy_req:set_resp_body_fun/2,3 have been removed. - For sending files, the function cowboy_req:set_resp_body/2 can now - take a sendfile tuple. -

    -
  • -
  • -

    -Remove many undocumented functions from cowboy_req, including the - functions cowboy_req:get/2 and cowboy_req:set/3. -

    -
  • -
-
-
-
+
  • The functions cowboy_req:url/1 and cowboy_req:host_url/1 have been removed in favor of the new function cowboy_req:uri/1,2. +
  • +
  • The functions cowboy_req:meta/2,3 and cowboy_req:set_meta/3 have been removed. The Req object is now a public map, therefore they became unnecessary. +
  • +
  • The functions cowboy_req:set_resp_body_fun/2,3 have been removed. For sending files, the function cowboy_req:set_resp_body/2 can now take a sendfile tuple. +
  • +
  • Remove many undocumented functions from cowboy_req, including the functions cowboy_req:get/2 and cowboy_req:set/3. +
  • +

Other changes

-
-
    -
  • -

    -The correct percent-decoding algorithm is now used for path elements - during routing. It will no longer decode + characters. -

    -
  • -
  • -

    -The router will now properly handle path segments . and ... -

    -
  • -
  • -

    -Routing behavior has changed for URIs containing latin1 characters. - They are no longer allowed. URIs are expected to be in UTF-8 once - they are percent-decoded. -

    -
  • -
  • -

    -Clients that send multiple headers of the same name - will have the values of those headers concatenated into a - comma-separated list. This is of special importance in the - case of the content-type header, as previously only the - first value was used in the content_types_accepted/2 step - in REST handlers. -

    -
  • -
  • -

    -Etag comparison in REST handlers has been fixed. Some requests may - now fail when they succeeded in the past. -

    -
  • -
  • -

    -The If-*-Since headers are now ignored in REST handlers if - the corresponding If*-Match header exist. The former is - largely a backward compatible header and this shouldn’t create - any issue. The new behavior follows the current RFCs more closely. -

    -
  • -
  • -

    -The static file handler has been improved to handle more special - characters on systems that accept them. -

    -
  • -
-
-
+
  • The correct percent-decoding algorithm is now used for path elements during routing. It will no longer decode + characters. +
  • +
  • The router will now properly handle path segments . and ... +
  • +
  • Routing behavior has changed for URIs containing latin1 characters. They are no longer allowed. URIs are expected to be in UTF-8 once they are percent-decoded. +
  • +
  • Clients that send multiple headers of the same name will have the values of those headers concatenated into a comma-separated list. This is of special importance in the case of the content-type header, as previously only the first value was used in the content_types_accepted/2 step in REST handlers. +
  • +
  • Etag comparison in REST handlers has been fixed. Some requests may now fail when they succeeded in the past. +
  • +
  • The If-*-Since headers are now ignored in REST handlers if the corresponding If*-Match header exist. The former is largely a backward compatible header and this shouldn't create any issue. The new behavior follows the current RFCs more closely. +
  • +
  • The static file handler has been improved to handle more special characters on systems that accept them. +
  • +
+ diff --git a/docs/en/cowboy/2.3/guide/migrating_from_2.0/index.html b/docs/en/cowboy/2.3/guide/migrating_from_2.0/index.html index d547b8c6..fa7978d1 100644 --- a/docs/en/cowboy/2.3/guide/migrating_from_2.0/index.html +++ b/docs/en/cowboy/2.3/guide/migrating_from_2.0/index.html @@ -62,188 +62,55 @@

Migrating from Cowboy 2.0 to 2.1

-

Cowboy 2.1 focused on adding features that were temporarily -removed in Cowboy 2.0. A number of bugs found in the 2.0 -release were also fixed.

-
+

Cowboy 2.1 focused on adding features that were temporarily removed in Cowboy 2.0. A number of bugs found in the 2.0 release were also fixed.

Features added

-
-
    -
  • -

    -It is now possible to obtain the client TLS certificate - and the local IP/port for the connection from the Req object. -

    +
    • It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object.
    • -
    • -

      -Informational responses (1XX responses) can now be sent. - They must be sent before initiating the final response. -

      +
    • Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response.
    • -
    • -

      -The expect: 100-continue header is now handled - automatically. The 100 response will be sent on the - first cowboy_req:read_body/2,3,4 call. This only applies - when using the default cowboy_stream_h stream handler. -

      +
    • The expect: 100-continue header is now handled automatically. The 100 response will be sent on the first cowboy_req:read_body/2,3,4 call. This only applies when using the default cowboy_stream_h stream handler.
    • -
-
-
-
+

Experimental features added

-
-

Experimental features are previews of features that will be -added in a future release. They are not documented and their -interface may change at any time. You are welcome to try them -and provide feedback.

-
    -
  • -

    -The cowboy_metrics_h stream handler can be used to - extract metrics out of Cowboy. It must be used first in - the list of stream handlers, and will record all events - related to requests, responses and spawned processes. - When the stream terminates it will pass this information - to a user-defined callback. -

    +

    Experimental features are previews of features that will be added in a future release. They are not documented and their interface may change at any time. You are welcome to try them and provide feedback.

    +
    • The cowboy_metrics_h stream handler can be used to extract metrics out of Cowboy. It must be used first in the list of stream handlers, and will record all events related to requests, responses and spawned processes. When the stream terminates it will pass this information to a user-defined callback.
    • -
    • -

      -The cowboy_tracer_h stream handler can be used to setup - automatic tracing of specific requests. You can conditionally - enable tracing based on a function, header, path or any other - element from the request and the trace will apply to the - entire connection and any processes created by it. This is - meant to be used for debugging both in tests and production. -

      +
    • The cowboy_tracer_h stream handler can be used to setup automatic tracing of specific requests. You can conditionally enable tracing based on a function, header, path or any other element from the request and the trace will apply to the entire connection and any processes created by it. This is meant to be used for debugging both in tests and production.
    • -
-
-
-
+

Changed behaviors

-
-
    -
  • -

    -The cowboy_rest handler now implements a mechanism for - switching to a different type of handler from any callback - where stop is also allowed. Switch by returning - {switch_handler, Module} or {switch_handler, Module, Opts}. - This is especially useful for switching to cowboy_loop - for streaming the request or response body. -

    +
    • The cowboy_rest handler now implements a mechanism for switching to a different type of handler from any callback where stop is also allowed. Switch by returning {switch_handler, Module} or {switch_handler, Module, Opts}. This is especially useful for switching to cowboy_loop for streaming the request or response body.
    • -
    • -

      -REST callbacks that do not allow stop as a return value - are now explicitly listed in the documentation. -

      +
    • REST callbacks that do not allow stop as a return value are now explicitly listed in the documentation.
    • -
-
-
-
+

New functions

-
-
    -
  • -

    -The function cowboy_req:sock/1 returns the IP/port - of the local socket. -

    +
    • The function cowboy_req:sock/1 returns the IP/port of the local socket.
    • -
    • -

      -The function cowboy_req:cert/1 returns the client - TLS certificate or undefined if it isn’t available. -

      +
    • The function cowboy_req:cert/1 returns the client TLS certificate or undefined if it isn't available.
    • -
    • -

      -The function cowboy_req:inform/2,3 sends an - informational response. -

      +
    • The function cowboy_req:inform/2,3 sends an informational response.
    • -
-
-
-
+

Bugs fixed

-
-
    -
  • -

    -Ensure HTTP/2 connections are not closed prematurely - when the user code does not read the request body. -

    +
    • Ensure HTTP/2 connections are not closed prematurely when the user code does not read the request body.
    • -
    • -

      -Ensure HTTP/1.1 streams are not terminated too early. - Their behavior is now consistent with the HTTP/2 code - where the stream handler is only terminated when the - stop command is returned. -

      +
    • Ensure HTTP/1.1 streams are not terminated too early. Their behavior is now consistent with the HTTP/2 code where the stream handler is only terminated when the stop command is returned.
    • -
    • -

      -Sending zero-sized data from stream handlers or from - cowboy_req:stream_body/3 could lead to issues with - HTTP/1.1. This has been fixed. -

      +
    • Sending zero-sized data from stream handlers or from cowboy_req:stream_body/3 could lead to issues with HTTP/1.1. This has been fixed.
    • -
    • -

      -The final chunk sent by Cowboy when it terminates a - chunked body after the handler process exits was not - passed through stream handlers, which could lead to - issues when cowboy_compress_h was being used. This - is now corrected. -

      +
    • The final chunk sent by Cowboy when it terminates a chunked body after the handler process exits was not passed through stream handlers, which could lead to issues when cowboy_compress_h was being used. This is now corrected.
    • -
    • -

      -The stream handler state was discarded in some cases - where Cowboy had to send a response or response data - automatically when ending a stream. This has now - been corrected. -

      +
    • The stream handler state was discarded in some cases where Cowboy had to send a response or response data automatically when ending a stream. This has now been corrected.
    • -
    • -

      -The stream handler callback terminate/3 will now be - called when switching to another protocol using the - command switch_protocol. This doesn’t apply when - doing upgrades to HTTP/2 as those occur before the - stream is initialized. -

      +
    • The stream handler callback terminate/3 will now be called when switching to another protocol using the command switch_protocol. This doesn't apply when doing upgrades to HTTP/2 as those occur before the stream is initialized.
    • -
    • -

      -Cowlib has been updated to 2.0.1 to fix an issue with - Websocket compression when using Erlang/OTP 20.1. Note - that at the time of writing all 20.1 versions (from - 20.1 to 20.1.4) have issues when compression is enabled. - It is expected to work properly from 20.1.5 onward. In - the meantime it is recommended to run the plain 20.1 - release and disable Websocket compression, or use a - release before 20.1. -

      +
    • Cowlib has been updated to 2.0.1 to fix an issue with Websocket compression when using Erlang/OTP 20.1. Note that at the time of writing all 20.1 versions (from 20.1 to 20.1.4) have issues when compression is enabled. It is expected to work properly from 20.1.5 onward. In the meantime it is recommended to run the plain 20.1 release and disable Websocket compression, or use a release before 20.1.
    • -
    • -

      -Cowboy will no longer crash when the cowboy_clock - process is not running. This can happen when Cowboy - is being restarted during upgrades, for example. -

      +
    • Cowboy will no longer crash when the cowboy_clock process is not running. This can happen when Cowboy is being restarted during upgrades, for example.
    • -
-
-
+ + diff --git a/docs/en/cowboy/2.3/guide/migrating_from_2.1/index.html b/docs/en/cowboy/2.3/guide/migrating_from_2.1/index.html index 6d6fed21..364c295f 100644 --- a/docs/en/cowboy/2.3/guide/migrating_from_2.1/index.html +++ b/docs/en/cowboy/2.3/guide/migrating_from_2.1/index.html @@ -62,203 +62,66 @@

Migrating from Cowboy 2.1 to 2.2

-

Cowboy 2.2 focused on adding features required for writing -gRPC servers and on completing test suites for the core -HTTP RFCs, fixing many bugs along the way.

-
+

Cowboy 2.2 focused on adding features required for writing gRPC servers and on completing test suites for the core HTTP RFCs, fixing many bugs along the way.

Features added

-
-
    -
  • -

    -Add support for sending trailers at the end of response bodies. - Trailers are additional header fields that may be sent after the - body to add more information to the response. Their usage is - required in gRPC servers. They are optional and may be discarded - in other scenarios (for example if the request goes through an - HTTP/1.0 proxy, as HTTP/1.0 does not support trailers). -

    +
    • Add support for sending trailers at the end of response bodies. Trailers are additional header fields that may be sent after the body to add more information to the response. Their usage is required in gRPC servers. They are optional and may be discarded in other scenarios (for example if the request goes through an HTTP/1.0 proxy, as HTTP/1.0 does not support trailers).
    • -
    • -

      -The max_skip_body_length option was added to cowboy_http. - It controls how much of a request body Cowboy is willing to skip - when the handler did not touch it. If the remaining body size is - too large Cowboy instead closes the connection. It defaults to 1MB. -

      +
    • The max_skip_body_length option was added to cowboy_http. It controls how much of a request body Cowboy is willing to skip when the handler did not touch it. If the remaining body size is too large Cowboy instead closes the connection. It defaults to 1MB.
    • -
    • -

      -The CONNECT and TRACE methods are now rejected as they are - currently not implemented and must be handled differently than - other methods. They will be implemented in a future release. -

      +
    • The CONNECT and TRACE methods are now rejected as they are currently not implemented and must be handled differently than other methods. They will be implemented in a future release.
    • -
-
-
-
+

New functions

-
-
    -
  • -

    -The function stream_trailers/2 has been added. It terminates - a stream and adds trailer fields at the end of the response. A - corresponding stream handler command {trailers, Trailers} - has also been added. -

    +
    • The function stream_trailers/2 has been added. It terminates a stream and adds trailer fields at the end of the response. A corresponding stream handler command {trailers, Trailers} has also been added.
    • -
-
-
-
+

Bugs fixed

-
-
    -
  • -

    -Test suites for the core HTTP RFCs RFC7230, RFC7231 and RFC7540 - have been completed. Many of the bugs listed here were fixed as - a result of this work. -

    +
    • Test suites for the core HTTP RFCs RFC7230, RFC7231 and RFC7540 have been completed. Many of the bugs listed here were fixed as a result of this work.
    • -
    • -

      -Many HTTP/2 edge cases when clients are misbehaving have been - corrected. This includes many cases where the request is malformed - (for example when a pseudo-header is present twice). -

      +
    • Many HTTP/2 edge cases when clients are misbehaving have been corrected. This includes many cases where the request is malformed (for example when a pseudo-header is present twice).
    • -
    • -

      -When the HTTP/2 SETTINGS_INITIAL_WINDOW_SIZE value changes, - Cowboy now properly updates the flow control windows. -

      +
    • When the HTTP/2 SETTINGS_INITIAL_WINDOW_SIZE value changes, Cowboy now properly updates the flow control windows.
    • -
    • -

      -HTTP/2 could mistakenly log stray messages that actually were - expected. This is no longer the case. -

      +
    • HTTP/2 could mistakenly log stray messages that actually were expected. This is no longer the case.
    • -
    • -

      -We no longer send a GOAWAY frame when the HTTP/2 preface is invalid. -

      +
    • We no longer send a GOAWAY frame when the HTTP/2 preface is invalid.
    • -
    • -

      -Some values in the Req object of pushed requests were in the - wrong type. They are now the expected binary instead of iolist. -

      +
    • Some values in the Req object of pushed requests were in the wrong type. They are now the expected binary instead of iolist.
    • -
    • -

      -A response body was sometimes sent in response to HEAD requests - when using HTTP/2. The body is now ignored. -

      +
    • A response body was sometimes sent in response to HEAD requests when using HTTP/2. The body is now ignored.
    • -
    • -

      -The max_headers option for cowboy_http was not always respected - depending on the contents of the buffer. The limit is now strict. -

      +
    • The max_headers option for cowboy_http was not always respected depending on the contents of the buffer. The limit is now strict.
    • -
    • -

      -When an early error occurred on the HTTP/1.1 request line, the - partial Req given to stream handlers was missing the ref and - peer information. This has been corrected. -

      +
    • When an early error occurred on the HTTP/1.1 request line, the partial Req given to stream handlers was missing the ref and peer information. This has been corrected.
    • -
    • -

      -Absolute URIs with a userinfo component, or without an authority - component, are now properly rejected for HTTP/1.0 and HTTP/1.1. -

      +
    • Absolute URIs with a userinfo component, or without an authority component, are now properly rejected for HTTP/1.0 and HTTP/1.1.
    • -
    • -

      -Whitespace is no longer allowed in header lines before the colon. -

      +
    • Whitespace is no longer allowed in header lines before the colon.
    • -
    • -

      -408 responses to HTTP/1.1 requests now properly include a - connection: close header indicating that we are going to - close the connection. This header will also be sent for - other early errors resulting in the closing of the connection. -

      +
    • 408 responses to HTTP/1.1 requests now properly include a connection: close header indicating that we are going to close the connection. This header will also be sent for other early errors resulting in the closing of the connection.
    • -
    • -

      -When both the transfer-encoding and content-length headers are - sent in an HTTP/1.1 request, the transfer-encoding now takes - precedence over the content-length header and the latter is - removed from the Req object. -

      +
    • When both the transfer-encoding and content-length headers are sent in an HTTP/1.1 request, the transfer-encoding now takes precedence over the content-length header and the latter is removed from the Req object.
    • -
    • -

      -A 400 response is now returned when the transfer-encoding - header is invalid or contains any transfer-coding other - than chunked. -

      +
    • A 400 response is now returned when the transfer-encoding header is invalid or contains any transfer-coding other than chunked.
    • -
    • -

      -Invalid chunk sizes are now rejected immediately. -

      +
    • Invalid chunk sizes are now rejected immediately.
    • -
    • -

      -Chunk extensions are now limited to 129 characters. They are - not used in practice and are still ignored by Cowboy. The limit - is not configurable. -

      +
    • Chunk extensions are now limited to 129 characters. They are not used in practice and are still ignored by Cowboy. The limit is not configurable.
    • -
    • -

      -The final chunk was mistakenly sent in responses to HEAD - requests. This is now corrected. -

      +
    • The final chunk was mistakenly sent in responses to HEAD requests. This is now corrected.
    • -
    • -

      -OPTIONS * requests were broken in Cowboy 2.0. They are now - working again. Both the routing and cowboy_req:uri/1,2 have - been corrected. -

      +
    • OPTIONS * requests were broken in Cowboy 2.0. They are now working again. Both the routing and cowboy_req:uri/1,2 have been corrected.
    • -
    • -

      -204 responses no longer include a content-length header. -

      +
    • 204 responses no longer include a content-length header.
    • -
    • -

      -A packet could be lost when switching to Websocket or any - other protocol via the switch_protocol command. This is - now fixed. -

      +
    • A packet could be lost when switching to Websocket or any other protocol via the switch_protocol command. This is now fixed.
    • -
    • -

      -A 426 response will now be sent when a handler requires - the client to upgrade to Websocket and the request did not - include the required headers. -

      +
    • A 426 response will now be sent when a handler requires the client to upgrade to Websocket and the request did not include the required headers.
    • -
    • -

      -Both experimental stream handlers cowboy_metrics_h and - cowboy_tracer_h received a number of fixes and improvements. -

      +
    • Both experimental stream handlers cowboy_metrics_h and cowboy_tracer_h received a number of fixes and improvements.
    • -
-
-
+ + diff --git a/docs/en/cowboy/2.3/guide/migrating_from_2.2/index.html b/docs/en/cowboy/2.3/guide/migrating_from_2.2/index.html index ced40d21..95aea629 100644 --- a/docs/en/cowboy/2.3/guide/migrating_from_2.2/index.html +++ b/docs/en/cowboy/2.3/guide/migrating_from_2.2/index.html @@ -62,108 +62,38 @@

Migrating from Cowboy 2.2 to 2.3

-

Cowboy 2.3 focused on making the Cowboy processes behave -properly according to OTP principles. This version is a -very good milestone toward that goal and most of everything -should now work. Release upgrades and a few details will -be improved in future versions.

-
+

Cowboy 2.3 focused on making the Cowboy processes behave properly according to OTP principles. This version is a very good milestone toward that goal and most of everything should now work. Release upgrades and a few details will be improved in future versions.

Features added

-
-
    -
  • -

    -Add support for all functions from the module sys. Note - that Cowboy currently does not implement the sys debugging - mechanisms as tracing is recommended instead. -

    +
    • Add support for all functions from the module sys. Note that Cowboy currently does not implement the sys debugging mechanisms as tracing is recommended instead.
    • -
    • -

      -Add a max_frame_size option for Websocket handlers - to close the connection when the client attempts to - send a frame that’s too large. It currently defaults - to infinity to avoid breaking existing code but will - be changed in a future version. -

      +
    • Add a max_frame_size option for Websocket handlers to close the connection when the client attempts to send a frame that's too large. It currently defaults to infinity to avoid breaking existing code but will be changed in a future version.
    • -
    • -

      -Update Cowlib to 2.2.1. -

      +
    • Update Cowlib to 2.2.1.
    • -
    • -

      -Add support for the 308 status code and a test suite - for RFC7538 where it is defined. -

      +
    • Add support for the 308 status code and a test suite for RFC7538 where it is defined.
    • -
-
-
-
+

Bugs fixed

-
-
    -
  • -

    -Ensure timeout options accept the value infinity as - documented. -

    +
    • Ensure timeout options accept the value infinity as documented.
    • -
    • -

      -Properly reject HTTP/2 requests with an invalid content-length - header instead of simply crashing. -

      +
    • Properly reject HTTP/2 requests with an invalid content-length header instead of simply crashing.
    • -
    • -

      -When switching from HTTP/1.1 to Websocket or user protocols - all the messages in the mailbox were flushed. Only messages - specific to cowboy_http should now be flushed. -

      +
    • When switching from HTTP/1.1 to Websocket or user protocols all the messages in the mailbox were flushed. Only messages specific to cowboy_http should now be flushed.
    • -
    • -

      -Parsing of the x-forwarded-for header has been corrected. - It now supports IPv6 addresses both with and without port. -

      +
    • Parsing of the x-forwarded-for header has been corrected. It now supports IPv6 addresses both with and without port.
    • -
    • -

      -Websocket subprotocol tokens are now parsed in a case - insensitive manner, according to the spec. -

      +
    • Websocket subprotocol tokens are now parsed in a case insensitive manner, according to the spec.
    • -
    • -

      -Cookies without values are now allowed. For example Cookie: foo. -

      +
    • Cookies without values are now allowed. For example Cookie: foo.
    • -
    • -

      -Colons are now allowed within path segments in routes provided - to cowboy_router:compile/1 as long as they are not the first - character of the path segment. -

      +
    • Colons are now allowed within path segments in routes provided to cowboy_router:compile/1 as long as they are not the first character of the path segment.
    • -
    • -

      -The cowboy_req:delete_resp_header/2 function will no longer - crash when no response header was set before calling it. -

      +
    • The cowboy_req:delete_resp_header/2 function will no longer crash when no response header was set before calling it.
    • -
    • -

      -A miscount of the output HTTP/2 flow control window has been - fixed. It prevented sending the response body fully to some - clients. The issue only affected response bodies sent as iolists. -

      +
    • A miscount of the output HTTP/2 flow control window has been fixed. It prevented sending the response body fully to some clients. The issue only affected response bodies sent as iolists.
    • -
-
-
+ + diff --git a/docs/en/cowboy/2.3/guide/modern_web/index.html b/docs/en/cowboy/2.3/guide/modern_web/index.html index 4b1a8406..2f9cc837 100644 --- a/docs/en/cowboy/2.3/guide/modern_web/index.html +++ b/docs/en/cowboy/2.3/guide/modern_web/index.html @@ -62,115 +62,38 @@

The modern Web

-

Cowboy is a server for the modern Web. This chapter explains -what it means and details all the standards involved.

-

Cowboy supports all the standards listed in this document.

-
+

Cowboy is a server for the modern Web. This chapter explains what it means and details all the standards involved.

+

Cowboy supports all the standards listed in this document.

HTTP/2

-
-

HTTP/2 is the most efficient protocol for consuming Web -services. It enables clients to keep a connection open -for long periods of time; to send requests concurrently; -to reduce the size of requests through HTTP headers -compression; and more. The protocol is binary, greatly -reducing the resources needed to parse it.

-

HTTP/2 also enables the server to push messages to the -client. This can be used for various purposes, including -the sending of related resources before the client requests -them, in an effort to reduce latency. This can also be used -to enable bidirectional communication.

-

Cowboy provides transparent support for HTTP/2. Clients -that know it can use it; others fall back to HTTP/1.1 -automatically.

-

HTTP/2 is compatible with the HTTP/1.1 semantics.

-

HTTP/2 is defined by RFC 7540 and RFC 7541.

-
-
-
+

HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. The protocol is binary, greatly reducing the resources needed to parse it.

+

HTTP/2 also enables the server to push messages to the client. This can be used for various purposes, including the sending of related resources before the client requests them, in an effort to reduce latency. This can also be used to enable bidirectional communication.

+

Cowboy provides transparent support for HTTP/2. Clients that know it can use it; others fall back to HTTP/1.1 automatically.

+

HTTP/2 is compatible with the HTTP/1.1 semantics.

+

HTTP/2 is defined by RFC 7540 and RFC 7541.

HTTP/1.1

-
-

HTTP/1.1 is the previous version of the HTTP protocol. -The protocol itself is text-based and suffers from numerous -issues and limitations. In particular it is not possible -to execute requests concurrently (though pipelining is -sometimes possible), and it’s also sometimes difficult -to detect that a client disconnected.

-

HTTP/1.1 does provide very good semantics for interacting -with Web services. It defines the standard methods, headers -and status codes used by HTTP/1.1 and HTTP/2 clients and -servers.

-

HTTP/1.1 also defines compatibility with an older version -of the protocol, HTTP/1.0, which was never really standardized -across implementations.

-

The core of HTTP/1.1 is defined by RFC 7230, RFC 7231, -RFC 7232, RFC 7233, RFC 7234 and RFC 7235. Numerous RFCs -and other specifications exist defining additional HTTP -methods, status codes, headers or semantics.

-
-
-
+

HTTP/1.1 is the previous version of the HTTP protocol. The protocol itself is text-based and suffers from numerous issues and limitations. In particular it is not possible to execute requests concurrently (though pipelining is sometimes possible), and it's also sometimes difficult to detect that a client disconnected.

+

HTTP/1.1 does provide very good semantics for interacting with Web services. It defines the standard methods, headers and status codes used by HTTP/1.1 and HTTP/2 clients and servers.

+

HTTP/1.1 also defines compatibility with an older version of the protocol, HTTP/1.0, which was never really standardized across implementations.

+

The core of HTTP/1.1 is defined by RFC 7230, RFC 7231, RFC 7232, RFC 7233, RFC 7234 and RFC 7235. Numerous RFCs and other specifications exist defining additional HTTP methods, status codes, headers or semantics.

Websocket

-
-

Websocket is a protocol built on top of HTTP/1.1 -that provides a two-ways communication channel between the client and -the server. Communication is asynchronous and can occur concurrently.

-

It consists of a Javascript object allowing setting up a -Websocket connection to the server, and a binary based -protocol for sending data to the server or the client.

-

Websocket connections can transfer either UTF-8 encoded text -data or binary data. The protocol also includes support for -implementing a ping/pong mechanism, allowing the server and -the client to have more confidence that the connection is still -alive.

-

A Websocket connection can be used to transfer any kind of data, -small or big, text or binary. Because of this Websocket is -sometimes used for communication between systems.

-

Websocket messages have no semantics on their own. Websocket -is closer to TCP in that aspect, and requires you to design -and implement your own protocol on top of it; or adapt an -existing protocol to Websocket.

-

Cowboy provides an interface known as Websocket handlers -that gives complete control over a Websocket connection.

-

The Websocket protocol is defined by RFC 6455.

-
-
-
+

Websocket is a protocol built on top of HTTP/1.1 that provides a two-ways communication channel between the client and the server. Communication is asynchronous and can occur concurrently.

+

It consists of a Javascript object allowing setting up a Websocket connection to the server, and a binary based protocol for sending data to the server or the client.

+

Websocket connections can transfer either UTF-8 encoded text data or binary data. The protocol also includes support for implementing a ping/pong mechanism, allowing the server and the client to have more confidence that the connection is still alive.

+

A Websocket connection can be used to transfer any kind of data, small or big, text or binary. Because of this Websocket is sometimes used for communication between systems.

+

Websocket messages have no semantics on their own. Websocket is closer to TCP in that aspect, and requires you to design and implement your own protocol on top of it; or adapt an existing protocol to Websocket.

+

Cowboy provides an interface known as Websocket handlers that gives complete control over a Websocket connection.

+

The Websocket protocol is defined by RFC 6455.

Long-lived requests

-
-

Cowboy provides an interface that can be used to support -long-polling or to stream large amounts of data reliably, -including using Server-Sent Events.

-

Long-polling is a mechanism in which the client performs -a request which may not be immediately answered by the -server. It allows clients to request resources that may -not currently exist, but are expected to be created soon, -and which will be returned as soon as they are.

-

Long-polling is essentially a hack, but it is widely used -to overcome limitations on older clients and servers.

-

Server-Sent Events is a small protocol defined as a media -type, text/event-stream, along with a new HTTP header, -Last-Event-ID. It is defined in the EventSource W3C -specification.

-

Cowboy provides an interface known as loop handlers -that facilitates the implementation of long-polling or stream -mechanisms. It works regardless of the underlying protocol.

-
-
-
+

Cowboy provides an interface that can be used to support long-polling or to stream large amounts of data reliably, including using Server-Sent Events.

+

Long-polling is a mechanism in which the client performs a request which may not be immediately answered by the server. It allows clients to request resources that may not currently exist, but are expected to be created soon, and which will be returned as soon as they are.

+

Long-polling is essentially a hack, but it is widely used to overcome limitations on older clients and servers.

+

Server-Sent Events is a small protocol defined as a media type, text/event-stream, along with a new HTTP header, Last-Event-ID. It is defined in the EventSource W3C specification.

+

Cowboy provides an interface known as loop handlers that facilitates the implementation of long-polling or stream mechanisms. It works regardless of the underlying protocol.

REST

-
-

REST, or REpresentational State Transfer, -is a style of architecture for loosely connected distributed -systems. It can easily be implemented on top of HTTP.

-

REST is essentially a set of constraints to be followed. -Many of these constraints are purely architectural and -solved by simply using HTTP. Some constraints must be -explicitly followed by the developer.

-

Cowboy provides an interface known as REST handlers -that simplifies the implementation of a REST API on top of -the HTTP protocol.

-
-
+

REST, or REpresentational State Transfer, is a style of architecture for loosely connected distributed systems. It can easily be implemented on top of HTTP.

+

REST is essentially a set of constraints to be followed. Many of these constraints are purely architectural and solved by simply using HTTP. Some constraints must be explicitly followed by the developer.

+

Cowboy provides an interface known as REST handlers that simplifies the implementation of a REST API on top of the HTTP protocol.

+ diff --git a/docs/en/cowboy/2.3/guide/multipart/index.html b/docs/en/cowboy/2.3/guide/multipart/index.html index 17224160..2f5559f5 100644 --- a/docs/en/cowboy/2.3/guide/multipart/index.html +++ b/docs/en/cowboy/2.3/guide/multipart/index.html @@ -62,169 +62,107 @@

Multipart requests

-

Multipart originates from MIME, an Internet standard that -extends the format of emails.

-

A multipart message is a list of parts. A part contains -headers and a body. The body of the parts may be -of any media type, and contain text or binary data. -It is possible for parts to contain a multipart media -type.

-

In the context of HTTP, multipart is most often used -with the multipart/form-data media type. It is what -browsers use to upload files through HTML forms.

-

The multipart/byteranges is also common. It is the -media type used to send arbitrary bytes from a resource, -enabling clients to resume downloads.

-
+

Multipart originates from MIME, an Internet standard that extends the format of emails.

+

A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type.

+

In the context of HTTP, multipart is most often used with the multipart/form-data media type. It is what browsers use to upload files through HTML forms.

+

The multipart/byteranges is also common. It is the media type used to send arbitrary bytes from a resource, enabling clients to resume downloads.

Form-data

-
-

In the normal case, when a form is submitted, the -browser will use the application/x-www-form-urlencoded -content-type. This type is just a list of keys and -values and is therefore not fit for uploading files.

-

That’s where the multipart/form-data content-type -comes in. When the form is configured to use this -content-type, the browser will create a multipart -message where each part corresponds to a field on -the form. For files, it also adds some metadata in -the part headers, like the file name.

-

A form with a text input, a file input and a select -choice box will result in a multipart message with -three parts, one for each field.

-

The browser does its best to determine the media type -of the files it sends this way, but you should not -rely on it for determining the contents of the file. -Proper investigation of the contents is recommended.

-
-
-
+

In the normal case, when a form is submitted, the browser will use the application/x-www-form-urlencoded content-type. This type is just a list of keys and values and is therefore not fit for uploading files.

+

That's where the multipart/form-data content-type comes in. When the form is configured to use this content-type, the browser will create a multipart message where each part corresponds to a field on the form. For files, it also adds some metadata in the part headers, like the file name.

+

A form with a text input, a file input and a select choice box will result in a multipart message with three parts, one for each field.

+

The browser does its best to determine the media type of the files it sends this way, but you should not rely on it for determining the contents of the file. Proper investigation of the contents is recommended.

Checking for multipart messages

-
-

The content-type header indicates the presence of -a multipart message:

-
-
-
{<<"multipart">>, <<"form-data">>, _}
-    = cowboy_req:parse_header(<<"content-type">>, Req).
-
-
-
+
{<<"multipart">>, <<"form-data">>, _}
+    = cowboy_req:parse_header(<<"content-type">>, Req).
+

Reading a multipart message

-
-

Cowboy provides two sets of functions for reading -request bodies as multipart messages.

-

The cowboy_req:read_part/1,2 functions return the -next part’s headers, if any.

-

The cowboy_req:read_part_body/1,2 functions return -the current part’s body. For large bodies you may -need to call the function multiple times.

-

To read a multipart message you need to iterate over -all its parts:

-
-
-
multipart(Req0) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, _Headers, Req1} ->
-            {ok, _Body, Req} = cowboy_req:read_part_body(Req1),
-            multipart(Req);
-        {done, Req} ->
-            Req
-    end.
-

When part bodies are too large, Cowboy will return -a more tuple, and allow you to loop until the part -body has been fully read.

-

The function cow_multipart:form_data/1 can be used -to quickly obtain information about a part from a -multipart/form-data message. The function returns -a data or a file tuple depending on whether this -is a normal field or a file being uploaded.

-

The following snippet will use this function and -use different strategies depending on whether the -part is a file:

-
-
-
multipart(Req0) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, Headers, Req1} ->
-            Req = case cow_multipart:form_data(Headers) of
-                {data, _FieldName} ->
-                    {ok, _Body, Req2} = cowboy_req:read_part_body(Req1),
-                    Req2;
-                {file, _FieldName, _Filename, _CType} ->
-                    stream_file(Req1)
-            end,
-            multipart(Req);
-        {done, Req} ->
-            Req
-    end.
-
-stream_file(Req0) ->
-    case cowboy_req:read_part_body(Req0) of
-        {ok, _LastBodyChunk, Req} ->
-            Req;
-        {more, _BodyChunk, Req} ->
-            stream_file(Req)
-    end.
-

Both the part header and body reading functions can take -options that will be given to the request body reading -functions. By default, cowboy_req:read_part/1 reads -up to 64KB for up to 5 seconds. cowboy_req:read_part_body/1 -has the same defaults as cowboy_req:read_body/1.

-

To change the defaults for part headers:

-
-
-
cowboy_req:read_part(Req, #{length => 128000}).
-

And for part bodies:

-
-
-
cowboy_req:read_part_body(Req, #{length => 1000000, period => 7000}).
-
- -
+
cowboy_req:read_part_body(Req, #{length => 1000000, period => 7000}).
+

Skipping unwanted parts

-
-

Part bodies do not have to be read. Cowboy will automatically -skip it when you request the next part’s body.

-

The following snippet reads all part headers and skips -all bodies:

-
-
-
multipart(Req0) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, _Headers, Req} ->
-            multipart(Req);
-        {done, Req} ->
-            Req
-    end.
-

Similarly, if you start reading the body and it ends up -being too big, you can simply continue with the next part. -Cowboy will automatically skip what remains.

-

While Cowboy can skip part bodies automatically, the read -rate is not configurable. Depending on your application -you may want to skip manually, in particular if you observe -poor performance while skipping.

-

You do not have to read all parts either. You can stop -reading as soon as you find the data you need.

-
- +
multipart(Req0) ->
+    case cowboy_req:read_part(Req0) of
+        {ok, _Headers, Req} ->
+            multipart(Req);
+        {done, Req} ->
+            Req
+    end.
+ +

Similarly, if you start reading the body and it ends up being too big, you can simply continue with the next part. Cowboy will automatically skip what remains.

+

While Cowboy can skip part bodies automatically, the read rate is not configurable. Depending on your application you may want to skip manually, in particular if you observe poor performance while skipping.

+

You do not have to read all parts either. You can stop reading as soon as you find the data you need.

+ + diff --git a/docs/en/cowboy/2.3/guide/req/index.html b/docs/en/cowboy/2.3/guide/req/index.html index 9d44a310..b709f063 100644 --- a/docs/en/cowboy/2.3/guide/req/index.html +++ b/docs/en/cowboy/2.3/guide/req/index.html @@ -62,407 +62,283 @@

The Req object

-

The Req object is a variable used for obtaining information -about a request, read its body or send a response.

-

It is not really an object in the object-oriented sense. -It is a simple map that can be directly accessed or -used when calling functions from the cowboy_req module.

-

The Req object is the subject of a few different chapters. -In this chapter we will learn about the Req object and -look at how to retrieve information about the request.

-
+

The Req object is a variable used for obtaining information about a request, read its body or send a response.

+

It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module.

+

The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request.

Direct access

-
-

The Req map contains a number of fields which are documented -and can be accessed directly. They are the fields that have -a direct mapping to HTTP: the request method; the HTTP -version used; the effective URI components scheme, -host, port, path and qs; the request headers; -and the connection peer address and port.

-

Note that the version field can be used to determine -whether a connection is using HTTP/2.

-

To access a field, you can simply match in the function -head. The following example sends a simple "Hello world!" -response when the method is GET, and a 405 error -otherwise.

-
-
-
init(Req0=#{method := <<"GET">>}, State) ->
-    Req = cowboy_req:reply(200, #{
-        <<"content-type">> => <<"text/plain">>
-    }, <<"Hello world!">>, Req0),
-    {ok, Req, State};
-init(Req0, State) ->
-    Req = cowboy_req:reply(405, #{
-        <<"allow">> => <<"GET">>
-    }, Req0),
-    {ok, Req, State}.
-

Any other field is internal and should not be accessed. -They may change in future releases, including maintenance -releases, without notice.

-

Modifying the Req object, while allowed, is not recommended -unless strictly necessary. If adding new fields, make sure -to namespace the field names so that no conflict can occur -with future Cowboy updates or third party projects.

-
-
-
+
init(Req0=#{method := <<"GET">>}, State) ->
+    Req = cowboy_req:reply(200, #{
+        <<"content-type">> => <<"text/plain">>
+    }, <<"Hello world!">>, Req0),
+    {ok, Req, State};
+init(Req0, State) ->
+    Req = cowboy_req:reply(405, #{
+        <<"allow">> => <<"GET">>
+    }, Req0),
+    {ok, Req, State}.
+
+

Any other field is internal and should not be accessed. They may change in future releases, including maintenance releases, without notice.

+

Modifying the Req object, while allowed, is not recommended unless strictly necessary. If adding new fields, make sure to namespace the field names so that no conflict can occur with future Cowboy updates or third party projects.

+

Introduction to the cowboy_req interface

-
-

Functions in the cowboy_req module provide access to -the request information but also various operations that -are common when dealing with HTTP requests.

-

All the functions that begin with a verb indicate an action. -Other functions simply return the corresponding value -(sometimes that value does need to be built, but the -cost of the operation is equivalent to retrieving a value).

-

Some of the cowboy_req functions return an updated Req -object. They are the read, reply, set and delete functions. -While ignoring the returned Req will not cause incorrect -behavior for some of them, it is highly recommended to -always keep and use the last returned Req object. The -manual for cowboy_req details these functions and what -modifications are done to the Req object.

-

Some of the calls to cowboy_req have side effects. This -is the case of the read and reply functions. Cowboy reads -the request body or replies immediately when the function -is called.

-

All functions will crash if something goes wrong. There -is usually no need to catch these errors, Cowboy will -send the appropriate 4xx or 5xx response depending on -where the crash occurred.

-
- -
+ +

Functions in the cowboy_req module provide access to the request information but also various operations that are common when dealing with HTTP requests.

+

All the functions that begin with a verb indicate an action. Other functions simply return the corresponding value (sometimes that value does need to be built, but the cost of the operation is equivalent to retrieving a value).

+

Some of the cowboy_req functions return an updated Req object. They are the read, reply, set and delete functions. While ignoring the returned Req will not cause incorrect behavior for some of them, it is highly recommended to always keep and use the last returned Req object. The manual for cowboy_req details these functions and what modifications are done to the Req object.

+

Some of the calls to cowboy_req have side effects. This is the case of the read and reply functions. Cowboy reads the request body or replies immediately when the function is called.

+

All functions will crash if something goes wrong. There is usually no need to catch these errors, Cowboy will send the appropriate 4xx or 5xx response depending on where the crash occurred.

Request method

-
-

The request method can be retrieved directly:

-
-
-
#{method := Method} = Req.
-

Or using a function:

-
-
-
Method = cowboy_req:method(Req).
-

The method is a case sensitive binary string. Standard -methods include GET, HEAD, OPTIONS, PATCH, POST, PUT -or DELETE.

-
-
-
+
Method = cowboy_req:method(Req).
+
+

The method is a case sensitive binary string. Standard methods include GET, HEAD, OPTIONS, PATCH, POST, PUT or DELETE.

HTTP version

-
-

The HTTP version is informational. It does not indicate that -the client implements the protocol well or fully.

-

There is typically no need to change behavior based on the -HTTP version: Cowboy already does it for you.

-

It can be useful in some cases, though. For example, one may -want to redirect HTTP/1.1 clients to use Websocket, while HTTP/2 -clients keep using HTTP/2.

-

The HTTP version can be retrieved directly:

-
-
-
#{version := Version} = Req.
-

Or using a function:

-
-
-
Version = cowboy_req:version(Req).
-

Cowboy defines the 'HTTP/1.0', 'HTTP/1.1' and 'HTTP/2' -versions. Custom protocols can define their own values as -atoms.

-
- -
+
Version = cowboy_req:version(Req).
+
+

Cowboy defines the 'HTTP/1.0', 'HTTP/1.1' and 'HTTP/2' versions. Custom protocols can define their own values as atoms.

Effective request URI

-
-

The scheme, host, port, path and query string components -of the effective request URI can all be retrieved directly:

-
-
#{
-    scheme := Scheme,
-    host := Host,
-    port := Port,
-    path := Path,
-    qs := Qs
-} = Req.
-

Or using the related functions:

-
-
-
Scheme = cowboy_req:scheme(Req),
-Host = cowboy_req:host(Req),
-Port = cowboy_req:port(Req),
-Path = cowboy_req:path(Req).
-Qs = cowboy_req:qs(Req).
-

The scheme and host are lowercased case insensitive binary -strings. The port is an integer representing the port number. -The path and query string are case sensitive binary strings.

-

Cowboy defines only the <<"http">> and <<"https">> schemes. -They are chosen so that the scheme will only be <<"https">> -for requests on secure HTTP/1.1 or HTTP/2 connections.

-

The effective request URI itself can be reconstructed with -the cowboy_req:uri/1,2 function. By default, an absolute -URI is returned:

-
-
+

The effective request URI itself can be reconstructed with the cowboy_req:uri/1,2 function. By default, an absolute URI is returned:

+
-
%% scheme://host[:port]/path[?qs]
-URI = cowboy_req:uri(Req).
-

Options are available to either disable or replace some -or all of the components. Various URIs or URI formats can -be generated this way, including the origin form:

-
-
-
%% /path[?qs]
-URI = cowboy_req:uri(Req, #{host => undefined}).
-

The protocol relative form:

-
-
-
%% //host[:port]/path[?qs]
-URI = cowboy_req:uri(Req, #{scheme => undefined}).
-

The absolute URI without a query string:

-
-
-
URI = cowboy_req:uri(Req, #{qs => undefined}).
-

A different host:

-
-
-
URI = cowboy_req:uri(Req, #{host => <<"example.org">>}).
-

And any other combination.

-
-
-
+
URI = cowboy_req:uri(Req, #{host => <<"example.org">>}).
+
+

And any other combination.

Bindings

-
-

Bindings are the host and path components that you chose -to extract when defining the routes of your application. -They are only available after the routing.

-

Cowboy provides functions to retrieve one or all bindings.

-

To retrieve a single value:

-
-
-
Value = cowboy_req:binding(userid, Req).
-

When attempting to retrieve a value that was not bound, -undefined will be returned. A different default value -can be provided:

-
-
-
Value = cowboy_req:binding(userid, Req, 42).
-

To retrieve everything that was bound:

-
-
-
Bindings = cowboy_req:bindings(Req).
-

They are returned as a map, with keys being atoms.

-

The Cowboy router also allows you to capture many host -or path segments at once using the ... qualifier.

-

To retrieve the segments captured from the host name:

-
-
-
HostInfo = cowboy_req:host_info(Req).
-

And the path segments:

-
-
-
PathInfo = cowboy_req:path_info(Req).
-

Cowboy will return undefined if ... was not used -in the route.

-
- -
+
PathInfo = cowboy_req:path_info(Req).
+
+

Cowboy will return undefined if ... was not used in the route.

Query parameters

-
-

Cowboy provides two functions to access query parameters. -You can use the first to get the entire list of parameters.

-
-
-
QsVals = cowboy_req:parse_qs(Req),
-{_, Lang} = lists:keyfind(<<"lang">>, 1, QsVals).
-

Cowboy will only parse the query string, and not do any -transformation. This function may therefore return duplicates, -or parameter names without an associated value. The order of -the list returned is undefined.

-

When a query string is key=1&key=2, the list returned will -contain two parameters of name key.

-

The same is true when trying to use the PHP-style suffix []. -When a query string is key[]=1&key[]=2, the list returned will -contain two parameters of name key[].

-

When a query string is simply key, Cowboy will return the -list [{<<"key">>, true}], using true to indicate that the -parameter key was defined, but with no value.

-

The second function Cowboy provides allows you to match out -only the parameters you are interested in, and at the same -time do any post processing you require using constraints. -This function returns a map.

-
-
-
#{id := ID, lang := Lang} = cowboy_req:match_qs([id, lang], Req).
-

Constraints can be applied automatically. The following -snippet will crash when the id parameter is not an integer, -or when the lang parameter is empty. At the same time, the -value for id will be converted to an integer term:

-
-
-
QsMap = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req).
-

A default value may also be provided. The default will be used -if the lang key is not found. It will not be used if -the key is found but has an empty value.

-
-
-
#{lang := Lang} = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
-

If no default is provided and the value is missing, the -query string is deemed invalid and the process will crash.

-

When the query string is key=1&key=2, the value for key -will be the list [1, 2]. Parameter names do not need to -include the PHP-style suffix. Constraints may be used to -ensure that only one value was passed through.

-
- -
+
#{lang := Lang} = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
+
+

If no default is provided and the value is missing, the query string is deemed invalid and the process will crash.

+

When the query string is key=1&key=2, the value for key will be the list [1, 2]. Parameter names do not need to include the PHP-style suffix. Constraints may be used to ensure that only one value was passed through.

Headers

-
-

Header values can be retrieved either as a binary string -or parsed into a more meaningful representation.

-

The get the raw value:

-
-
-
HeaderVal = cowboy_req:header(<<"content-type">>, Req).
-

Cowboy expects all header names to be provided as lowercase -binary strings. This is true for both requests and responses, -regardless of the underlying protocol.

-

When the header is missing from the request, undefined -will be returned. A different default can be provided:

-
-
-
HeaderVal = cowboy_req:header(<<"content-type">>, Req, <<"text/plain">>).
-

All headers can be retrieved at once, either directly:

-
-
-
#{headers := AllHeaders} = Req.
-

Or using a function:

-
-
-
AllHeaders = cowboy_req:headers(Req).
-

Cowboy provides equivalent functions to parse individual -headers. There is no function to parse all headers at once.

-

To parse a specific header:

-
-
-
ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req).
-

An exception will be thrown if it doesn’t know how to parse the -given header, or if the value is invalid. The list of known headers -and default values can be found in the manual.

-

When the header is missing, undefined is returned. You can -change the default value. Note that it should be the parsed value -directly:

-
-
-
ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req,
-    {<<"text">>, <<"plain">>, []}).
-
- -
+
ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req,
+    {<<"text">>, <<"plain">>, []}).
+

Peer

-
-

The peer address and port number for the connection can be -retrieved either directly or using a function.

-

To retrieve the peer directly:

-
-
-
#{peer := {IP, Port}} = Req.
-

And using a function:

-
-
-
{IP, Port} = cowboy_req:peer(Req).
-

Note that the peer corresponds to the remote end of the -connection to the server, which may or may not be the -client itself. It may also be a proxy or a gateway.

-
- +
{IP, Port} = cowboy_req:peer(Req).
+ +

Note that the peer corresponds to the remote end of the connection to the server, which may or may not be the client itself. It may also be a proxy or a gateway.

+ diff --git a/docs/en/cowboy/2.3/guide/req_body/index.html b/docs/en/cowboy/2.3/guide/req_body/index.html index 7db337da..a127f6f2 100644 --- a/docs/en/cowboy/2.3/guide/req_body/index.html +++ b/docs/en/cowboy/2.3/guide/req_body/index.html @@ -62,144 +62,93 @@

Reading the request body

-

The request body can be read using the Req object.

-

Cowboy will not attempt to read the body until requested. -You need to call the body reading functions in order to -retrieve it.

-

Cowboy will not cache the body, it is therefore only -possible to read it once.

-

You are not required to read it, however. If a body is -present and was not read, Cowboy will either cancel or -skip its download, depending on the protocol.

-

Cowboy provides functions for reading the body raw, -and read and parse form urlencoded or multipart bodies. -The latter is covered in its own chapter.

-
+

The request body can be read using the Req object.

+

Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it.

+

Cowboy will not cache the body, it is therefore only possible to read it once.

+

You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol.

+

Cowboy provides functions for reading the body raw, and read and parse form urlencoded or multipart bodies. The latter is covered in its own chapter.

Request body presence

-
-

Not all requests come with a body. You can check for -the presence of a request body with this function:

-
-
-
cowboy_req:has_body(Req).
-

It returns true if there is a body; false otherwise.

-

In practice, this function is rarely used. When the -method is POST, PUT or PATCH, the request body -is often required by the application, which should -just attempt to read it directly.

-
-
-
+
cowboy_req:has_body(Req).
+
+

It returns true if there is a body; false otherwise.

+

In practice, this function is rarely used. When the method is POST, PUT or PATCH, the request body is often required by the application, which should just attempt to read it directly.

Request body length

-
-

You can obtain the length of the body:

-
-
-
Length = cowboy_req:body_length(Req).
-

Note that the length may not be known in advance. In -that case undefined will be returned. This can happen -with HTTP/1.1’s chunked transfer-encoding, or HTTP/2 -when no content-length was provided.

-

Cowboy will update the body length in the Req object -once the body has been read completely. A length will -always be returned when attempting to call this function -after reading the body completely.

-
- -
+
Length = cowboy_req:body_length(Req).
+
+

Note that the length may not be known in advance. In that case undefined will be returned. This can happen with HTTP/1.1's chunked transfer-encoding, or HTTP/2 when no content-length was provided.

+

Cowboy will update the body length in the Req object once the body has been read completely. A length will always be returned when attempting to call this function after reading the body completely.

Reading the body

-
-

You can read the entire body with one function call:

-
-
-
{ok, Data, Req} = cowboy_req:read_body(Req0).
-

Cowboy returns an ok tuple when the body has been -read fully.

-

By default, Cowboy will attempt to read up to 8MB -of data, for up to 15 seconds. The call will return -once Cowboy has read at least 8MB of data, or at -the end of the 15 seconds period.

-

These values can be customized. For example, to read -only up to 1MB for up to 5 seconds:

-
-
-
{ok, Data, Req} = cowboy_req:read_body(Req0,
-    #{length => 1000000, period => 5000}).
-

You may also disable the length limit:

-
-
-
{ok, Data, Req} = cowboy_req:read_body(Req0, #{length => infinity}).
-

This makes the function wait 15 seconds and return with -whatever arrived during that period. This is not -recommended for public facing applications.

-

These two options can effectively be used to control -the rate of transmission of the request body.

-
- -
+
{ok, Data, Req} = cowboy_req:read_body(Req0, #{length => infinity}).
+
+

This makes the function wait 15 seconds and return with whatever arrived during that period. This is not recommended for public facing applications.

+

These two options can effectively be used to control the rate of transmission of the request body.

Streaming the body

-
-

When the body is too large, the first call will return -a more tuple instead of ok. You can call the -function again to read more of the body, reading -it one chunk at a time.

-
-
-
read_body_to_console(Req0) ->
-    case cowboy_req:read_body(Req0) of
-        {ok, Data, Req} ->
-            io:format("~s", [Data]),
-            Req;
-        {more, Data, Req} ->
-            io:format("~s", [Data]),
-            read_body_to_console(Req)
-    end.
-

The length and period options can also be used. -They need to be passed for every call.

-
- -
+
read_body_to_console(Req0) ->
+    case cowboy_req:read_body(Req0) of
+        {ok, Data, Req} ->
+            io:format("~s", [Data]),
+            Req;
+        {more, Data, Req} ->
+            io:format("~s", [Data]),
+            read_body_to_console(Req)
+    end.
+
+

The length and period options can also be used. They need to be passed for every call.

Reading a form urlencoded body

-
-

Cowboy provides a convenient function for reading and -parsing bodies sent as application/x-www-form-urlencoded.

-
-
-
{ok, KeyValues, Req} = cowboy_req:read_urlencoded_body(Req0).
-

This function returns a list of key/values, exactly like -the function cowboy_req:parse_qs/1.

-

The defaults for this function are different. Cowboy will -read for up to 64KB and up to 5 seconds. They can be modified:

-
-
-
{ok, KeyValues, Req} = cowboy_req:read_urlencoded_body(Req0,
-    #{length => 4096, period => 3000}).
-
- +
{ok, KeyValues, Req} = cowboy_req:read_urlencoded_body(Req0,
+    #{length => 4096, period => 3000}).
+ + diff --git a/docs/en/cowboy/2.3/guide/resource_design/index.html b/docs/en/cowboy/2.3/guide/resource_design/index.html index be567d98..699ebc56 100644 --- a/docs/en/cowboy/2.3/guide/resource_design/index.html +++ b/docs/en/cowboy/2.3/guide/resource_design/index.html @@ -62,213 +62,66 @@

Designing a resource handler

-

This chapter aims to provide you with a list of questions -you must answer in order to write a good resource handler. -It is meant to be usable as a step by step guide.

-
+

This chapter aims to provide you with a list of questions you must answer in order to write a good resource handler. It is meant to be usable as a step by step guide.

The service

-
-

Can the service become unavailable, and when it does, can -we detect it? For example, database connectivity problems -may be detected early. We may also have planned outages -of all or parts of the system. Implement the -service_available callback.

-

What HTTP methods does the service implement? Do we need -more than the standard OPTIONS, HEAD, GET, PUT, POST, -PATCH and DELETE? Are we not using one of those at all? -Implement the known_methods callback.

-
-
-
+

Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. Implement the service_available callback.

+

What HTTP methods does the service implement? Do we need more than the standard OPTIONS, HEAD, GET, PUT, POST, PATCH and DELETE? Are we not using one of those at all? Implement the known_methods callback.

Type of resource handler

-
-

Am I writing a handler for a collection of resources, -or for a single resource?

-

The semantics for each of these are quite different. -You should not mix collection and single resource in -the same handler.

-
-
-
+

Am I writing a handler for a collection of resources, or for a single resource?

+

The semantics for each of these are quite different. You should not mix collection and single resource in the same handler.

Collection handler

-
-

Skip this section if you are not doing a collection.

-

Is the collection hardcoded or dynamic? For example, -if you use the route /users for the collection of -users then the collection is hardcoded; if you use -/forums/:category for the collection of threads -then it isn’t. When the collection is hardcoded you -can safely assume the resource always exists.

-

What methods should I implement?

-

OPTIONS is used to get some information about the -collection. It is recommended to allow it even if you -do not implement it, as Cowboy has a default -implementation built-in.

-

HEAD and GET are used to retrieve the collection. -If you allow GET, also allow HEAD as there’s no extra -work required to make it work.

-

POST is used to create a new resource inside the -collection. Creating a resource by using POST on -the collection is useful when resources may be -created before knowing their URI, usually because -parts of it are generated dynamically. A common -case is some kind of auto incremented integer -identifier.

-

The next methods are more rarely allowed.

-

PUT is used to create a new collection (when -the collection isn’t hardcoded), or replace -the entire collection.

-

DELETE is used to delete the entire collection.

-

PATCH is used to modify the collection using -instructions given in the request body. A PATCH -operation is atomic. The PATCH operation may -be used for such things as reordering; adding, -modifying or deleting parts of the collection.

-
-
-
+

Skip this section if you are not doing a collection.

+

Is the collection hardcoded or dynamic? For example, if you use the route /users for the collection of users then the collection is hardcoded; if you use /forums/:category for the collection of threads then it isn't. When the collection is hardcoded you can safely assume the resource always exists.

+

What methods should I implement?

+

OPTIONS is used to get some information about the collection. It is recommended to allow it even if you do not implement it, as Cowboy has a default implementation built-in.

+

HEAD and GET are used to retrieve the collection. If you allow GET, also allow HEAD as there's no extra work required to make it work.

+

POST is used to create a new resource inside the collection. Creating a resource by using POST on the collection is useful when resources may be created before knowing their URI, usually because parts of it are generated dynamically. A common case is some kind of auto incremented integer identifier.

+

The next methods are more rarely allowed.

+

PUT is used to create a new collection (when the collection isn't hardcoded), or replace the entire collection.

+

DELETE is used to delete the entire collection.

+

PATCH is used to modify the collection using instructions given in the request body. A PATCH operation is atomic. The PATCH operation may be used for such things as reordering; adding, modifying or deleting parts of the collection.

Single resource handler

-
-

Skip this section if you are doing a collection.

-

What methods should I implement?

-

OPTIONS is used to get some information about the -resource. It is recommended to allow it even if you -do not implement it, as Cowboy has a default -implementation built-in.

-

HEAD and GET are used to retrieve the resource. -If you allow GET, also allow HEAD as there’s no extra -work required to make it work.

-

POST is used to update the resource.

-

PUT is used to create a new resource (when it doesn’t -already exist) or replace the resource.

-

DELETE is used to delete the resource.

-

PATCH is used to modify the resource using -instructions given in the request body. A PATCH -operation is atomic. The PATCH operation may -be used for adding, removing or modifying specific -values in the resource.

-
-
-
+

Skip this section if you are doing a collection.

+

What methods should I implement?

+

OPTIONS is used to get some information about the resource. It is recommended to allow it even if you do not implement it, as Cowboy has a default implementation built-in.

+

HEAD and GET are used to retrieve the resource. If you allow GET, also allow HEAD as there's no extra work required to make it work.

+

POST is used to update the resource.

+

PUT is used to create a new resource (when it doesn't already exist) or replace the resource.

+

DELETE is used to delete the resource.

+

PATCH is used to modify the resource using instructions given in the request body. A PATCH operation is atomic. The PATCH operation may be used for adding, removing or modifying specific values in the resource.

The resource

-
-

Following the above discussion, implement the -allowed_methods callback.

-

Does the resource always exist? If it may not, implement -the resource_exists callback.

-

Do I need to authenticate the client before they can -access the resource? What authentication mechanisms -should I provide? This may include form-based, token-based -(in the URL or a cookie), HTTP basic, HTTP digest, -SSL certificate or any other form of authentication. -Implement the is_authorized callback.

-

Do I need fine-grained access control? How do I determine -that they are authorized access? Handle that in your -is_authorized callback.

-

Can access to a resource be forbidden regardless of access -being authorized? A simple example of that is censorship -of a resource. Implement the forbidden callback.

-

Are there any constraints on the length of the resource URI? -For example, the URI may be used as a key in storage and may -have a limit in length. Implement uri_too_long.

-
-
-
+

Following the above discussion, implement the allowed_methods callback.

+

Does the resource always exist? If it may not, implement the resource_exists callback.

+

Do I need to authenticate the client before they can access the resource? What authentication mechanisms should I provide? This may include form-based, token-based (in the URL or a cookie), HTTP basic, HTTP digest, SSL certificate or any other form of authentication. Implement the is_authorized callback.

+

Do I need fine-grained access control? How do I determine that they are authorized access? Handle that in your is_authorized callback.

+

Can access to a resource be forbidden regardless of access being authorized? A simple example of that is censorship of a resource. Implement the forbidden callback.

+

Are there any constraints on the length of the resource URI? For example, the URI may be used as a key in storage and may have a limit in length. Implement uri_too_long.

Representations

-
-

What media types do I provide? If text based, what charsets -are provided? What languages do I provide?

-

Implement the mandatory content_types_provided. Prefix -the callbacks with to_ for clarity. For example, to_html -or to_text.

-

Implement the languages_provided or charsets_provided -callbacks if applicable.

-

Is there any other header that may make the representation -of the resource vary? Implement the variances callback.

-

Depending on your choices for caching content, you may -want to implement one or more of the generate_etag, -last_modified and expires callbacks.

-

Do I want the user or user agent to actively choose a -representation available? Send a list of available -representations in the response body and implement -the multiple_choices callback.

-
-
-
+

What media types do I provide? If text based, what charsets are provided? What languages do I provide?

+

Implement the mandatory content_types_provided. Prefix the callbacks with to_ for clarity. For example, to_html or to_text.

+

Implement the languages_provided or charsets_provided callbacks if applicable.

+

Is there any other header that may make the representation of the resource vary? Implement the variances callback.

+

Depending on your choices for caching content, you may want to implement one or more of the generate_etag, last_modified and expires callbacks.

+

Do I want the user or user agent to actively choose a representation available? Send a list of available representations in the response body and implement the multiple_choices callback.

Redirections

-
-

Do I need to keep track of what resources were deleted? -For example, you may have a mechanism where moving a -resource leaves a redirect link to its new location. -Implement the previously_existed callback.

-

Was the resource moved, and is the move temporary? If -it is explicitly temporary, for example due to maintenance, -implement the moved_temporarily callback. Otherwise, -implement the moved_permanently callback.

-
-
-
+

Do I need to keep track of what resources were deleted? For example, you may have a mechanism where moving a resource leaves a redirect link to its new location. Implement the previously_existed callback.

+

Was the resource moved, and is the move temporary? If it is explicitly temporary, for example due to maintenance, implement the moved_temporarily callback. Otherwise, implement the moved_permanently callback.

The request

-
-

Do you need to read the query string? Individual headers? -Implement malformed_request and do all the parsing and -validation in this function. Note that the body should not -be read at this point.

-

May there be a request body? Will I know its size? -What’s the maximum size of the request body I’m willing -to accept? Implement valid_entity_length.

-

Finally, take a look at the sections corresponding to the -methods you are implementing.

-
-
-
+

Do you need to read the query string? Individual headers? Implement malformed_request and do all the parsing and validation in this function. Note that the body should not be read at this point.

+

May there be a request body? Will I know its size? What's the maximum size of the request body I'm willing to accept? Implement valid_entity_length.

+

Finally, take a look at the sections corresponding to the methods you are implementing.

OPTIONS method

-
-

Cowboy by default will send back a list of allowed methods. -Do I need to add more information to the response? Implement -the options method.

-
-
-
+

Cowboy by default will send back a list of allowed methods. Do I need to add more information to the response? Implement the options method.

GET and HEAD methods

-
-

If you implement the methods GET and/or HEAD, you must -implement one ProvideResource callback for each -content-type returned by the content_types_provided -callback.

-
-
-
-

PUT, POST and PATCH methods

-
-

If you implement the methods PUT, POST and/or PATCH, -you must implement the content_types_accepted callback, -and one AcceptCallback callback for each content-type -it returns. Prefix the AcceptCallback callback names -with from_ for clarity. For example, from_html or -from_json.

-

Do we want to allow the POST method to create individual -resources directly through their URI (like PUT)? Implement -the allow_missing_post callback. It is recommended to -explicitly use PUT in these cases instead.

-

May there be conflicts when using PUT to create or replace -a resource? Do we want to make sure that two updates around -the same time are not cancelling one another? Implement the -is_conflict callback.

-
-
-
+

If you implement the methods GET and/or HEAD, you must implement one ProvideResource callback for each content-type returned by the content_types_provided callback.

+

PUT, POST and PATCH methods

+

If you implement the methods PUT, POST and/or PATCH, you must implement the content_types_accepted callback, and one AcceptCallback callback for each content-type it returns. Prefix the AcceptCallback callback names with from_ for clarity. For example, from_html or from_json.

+

Do we want to allow the POST method to create individual resources directly through their URI (like PUT)? Implement the allow_missing_post callback. It is recommended to explicitly use PUT in these cases instead.

+

May there be conflicts when using PUT to create or replace a resource? Do we want to make sure that two updates around the same time are not cancelling one another? Implement the is_conflict callback.

DELETE methods

-
-

If you implement the method DELETE, you must implement -the delete_resource callback.

-

When delete_resource returns, is the resource completely -removed from the server, including from any caching service? -If not, and/or if the deletion is asynchronous and we have -no way of knowing it has been completed yet, implement the -delete_completed callback.

-
-
+

If you implement the method DELETE, you must implement the delete_resource callback.

+

When delete_resource returns, is the resource completely removed from the server, including from any caching service? If not, and/or if the deletion is asynchronous and we have no way of knowing it has been completed yet, implement the delete_completed callback.

+ diff --git a/docs/en/cowboy/2.3/guide/resp/index.html b/docs/en/cowboy/2.3/guide/resp/index.html index bc1a04ea..2fb3f064 100644 --- a/docs/en/cowboy/2.3/guide/resp/index.html +++ b/docs/en/cowboy/2.3/guide/resp/index.html @@ -62,373 +62,249 @@

Sending a response

-

The response must be sent using the Req object.

-

Cowboy provides two different ways of sending responses: -either directly or by streaming the body. Response headers -and body may be set in advance. The response is sent as -soon as one of the reply or stream reply function is -called.

-

Cowboy also provides a simplified interface for sending -files. It can also send only specific parts of a file.

-

While only one response is allowed for every request, -HTTP/2 introduced a mechanism that allows the server -to push additional resources related to the response. -This chapter also describes how this feature works in -Cowboy.

-
+

The response must be sent using the Req object.

+

Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called.

+

Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file.

+

While only one response is allowed for every request, HTTP/2 introduced a mechanism that allows the server to push additional resources related to the response. This chapter also describes how this feature works in Cowboy.

Reply

-
-

Cowboy provides three functions for sending the entire reply, -depending on whether you need to set headers and body. In all -cases, Cowboy will add any headers required by the protocol -(for example the date header will always be sent).

-

When you need to set only the status code, -use cowboy_req:reply/2:

-
-
-
Req = cowboy_req:reply(200, Req0).
-

When you need to set response headers at the same time, -use cowboy_req:reply/3:

-
-
-
Req = cowboy_req:reply(303, #{
-    <<"location">> => <<"https://ninenines.eu">>
-}, Req0).
-

Note that the header name must always be a lowercase -binary.

-

When you also need to set the response body, -use cowboy_req:reply/4:

-
-
-
Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, "Hello world!", Req0).
-

You should always set the content-type header when the -response has a body. There is however no need to set -the content-length header; Cowboy does it automatically.

-

The response body and the header values must be either -a binary or an iolist. An iolist is a list containing -binaries, characters, strings or other iolists. This -allows you to build a response from different parts -without having to do any concatenation:

-
-
-
Title = "Hello world!",
-Body = <<"Hats off!">>,
-Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/html">>
-}, ["<html><head><title>", Title, "</title></head>",
-    "<body><p>", Body, "</p></body></html>"], Req0).
-

This method of building responses is more efficient than -concatenating. Behind the scenes, each element of the list -is simply a pointer, and those pointers are used directly -when writing to the socket.

-
-
-
+
Title = "Hello world!",
+Body = <<"Hats off!">>,
+Req = cowboy_req:reply(200, #{
+    <<"content-type">> => <<"text/html">>
+}, ["<html><head><title>", Title, "</title></head>",
+    "<body><p>", Body, "</p></body></html>"], Req0).
+
+

This method of building responses is more efficient than concatenating. Behind the scenes, each element of the list is simply a pointer, and those pointers are used directly when writing to the socket.

Stream reply

-
-

Cowboy provides two functions for initiating a response, -and an additional function for streaming the response body. -Cowboy will add any required headers to the response.

-

When you need to set only the status code, -use cowboy_req:stream_reply/2:

-
-
+

When you need to set only the status code, use cowboy_req:stream_reply/2:

+
-
Req = cowboy_req:stream_reply(200, Req0),
-
-cowboy_req:stream_body("Hello...", nofin, Req),
-cowboy_req:stream_body("chunked...", nofin, Req),
-cowboy_req:stream_body("world!!", fin, Req).
-

The second argument to cowboy_req:stream_body/3 indicates -whether this data terminates the body. Use fin for the -final flag, and nofin otherwise.

-

This snippet does not set a content-type header. This is -not recommended. All responses with a body should have -a content-type. The header can be set beforehand, or -using the cowboy_req:stream_reply/3:

-
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/html">>
-}, Req0),
-
-cowboy_req:stream_body("<html><head>Hello world!</head>", nofin, Req),
-cowboy_req:stream_body("<body><p>Hats off!</p></body></html>", fin, Req).
-

HTTP provides a few different ways to stream response bodies. -Cowboy will select the most appropriate one based on the HTTP -version and the request and response headers.

-

While not required by any means, it is recommended that you -set the content-length header in the response if you know it -in advance. This will ensure that the best response method -is selected and help clients understand when the response -is fully received.

-

Cowboy also provides a function to send response trailers. -Response trailers are semantically equivalent to the headers -you send in the response, only they are sent at the end. -This is especially useful to attach information to the -response that could not be generated until the response -body was fully generated.

-

Trailer fields must be listed in the trailer header. Any -field not listed might be dropped by the client or an intermediary.

-
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/html">>,
-    <<"trailer">> => <<"expires, content-md5">>
-}, Req0),
-
-cowboy_req:stream_body("<html><head>Hello world!</head>", nofin, Req),
-cowboy_req:stream_body("<body><p>Hats off!</p></body></html>", nofin, Req),
-
-cowboy_req:stream_trailers(#{
-    <<"expires">> => <<"Sun, 10 Dec 2017 19:13:47 GMT">>,
-    <<"content-md5">> => <<"c6081d20ff41a42ce17048ed1c0345e2">>
-}, Req).
-

The stream ends with trailers. It is no longer possible to -send data after sending trailers. You cannot send trailers -after setting the fin flag when streaming the body.

-
-
-
+
Req = cowboy_req:stream_reply(200, #{
+    <<"content-type">> => <<"text/html">>,
+    <<"trailer">> => <<"expires, content-md5">>
+}, Req0),
+
+cowboy_req:stream_body("<html><head>Hello world!</head>", nofin, Req),
+cowboy_req:stream_body("<body><p>Hats off!</p></body></html>", nofin, Req),
+
+cowboy_req:stream_trailers(#{
+    <<"expires">> => <<"Sun, 10 Dec 2017 19:13:47 GMT">>,
+    <<"content-md5">> => <<"c6081d20ff41a42ce17048ed1c0345e2">>
+}, Req).
+
+

The stream ends with trailers. It is no longer possible to send data after sending trailers. You cannot send trailers after setting the fin flag when streaming the body.

Preset response headers

-
-

Cowboy provides functions to set response headers without -immediately sending them. They are stored in the Req object -and sent as part of the response when a reply function is -called.

-

To set response headers:

-
-
-
Req = cowboy_req:set_resp_header(<<"allow">>, "GET", Req0).
-

Header names must be a lowercase binary.

-

Do not use this function for setting cookies. Refer to -the Cookies chapter for more information.

-

To check if a response header has already been set:

-
-
-
cowboy_req:has_resp_header(<<"allow">>, Req).
-

It returns true if the header was set, false otherwise.

-

To delete a response header that was set previously:

-
-
-
Req = cowboy_req:delete_resp_header(<<"allow">>, Req0).
-
- -
+
Req = cowboy_req:delete_resp_header(<<"allow">>, Req0).
+

Overriding headers

-
-

As Cowboy provides different ways of setting response -headers and body, clashes may occur, so it’s important -to understand what happens when a header is set twice.

-

Headers come from five different origins:

-
    -
  • -

    -Protocol-specific headers (for example HTTP/1.1’s connection header) -

    +

    As Cowboy provides different ways of setting response headers and body, clashes may occur, so it's important to understand what happens when a header is set twice.

    +

    Headers come from five different origins:

    +
    • Protocol-specific headers (for example HTTP/1.1's connection header)
    • -
    • -

      -Other required headers (for example the date header) -

      +
    • Other required headers (for example the date header)
    • -
    • -

      -Preset headers -

      +
    • Preset headers
    • -
    • -

      -Headers given to the reply function -

      +
    • Headers given to the reply function
    • -
    • -

      -Set-cookie headers -

      +
    • Set-cookie headers
    • -
-

Cowboy does not allow overriding protocol-specific headers.

-

Set-cookie headers will always be appended at the end of -the list of headers before sending the response.

-

Headers given to the reply function will always override -preset headers and required headers. If a header is found -in two or three of these, then the one in the reply function -is picked and the others are dropped.

-

Similarly, preset headers will always override required -headers.

-

To illustrate, look at the following snippet. Cowboy by -default sends the server header with the value "Cowboy". -We can override it:

-
-
-
Req = cowboy_req:reply(200, #{
-    <<"server">> => <<"yaws">>
-}, Req0).
-
- -
+
Req = cowboy_req:reply(200, #{
+    <<"server">> => <<"yaws">>
+}, Req0).
+

Preset response body

-
-

Cowboy provides functions to set the response body without -immediately sending it. It is stored in the Req object and -sent when the reply function is called.

-

To set the response body:

-
-
-
Req = cowboy_req:set_resp_body("Hello world!", Req0).
-

To check if a response body has already been set:

-
-
+ +

To check if a response body has already been set:

+
-
cowboy_req:has_resp_body(Req).
-

It returns true if the body was set and is non-empty, -false otherwise.

-

The preset response body is only sent if the reply function -used is cowboy_req:reply/2 or cowboy_req:reply/3.

-
-
-
+
cowboy_req:has_resp_body(Req).
+
+

It returns true if the body was set and is non-empty, false otherwise.

+ + + +

The preset response body is only sent if the reply function used is cowboy_req:reply/2 or cowboy_req:reply/3.

Sending files

-
-

Cowboy provides a shortcut for sending files. When -using cowboy_req:reply/4, or when presetting the -response header, you can give a sendfile tuple to -Cowboy:

-
-
-
{sendfile, Offset, Length, Filename}
-

Depending on the values for Offset or Length, the -entire file may be sent, or just a part of it.

-

The length is required even for sending the entire file. -Cowboy sends it in the content-length header.

-

To send a file while replying:

-
-
-
Req = cowboy_req:reply(200, #{
-    <<"content-type">> => "image/png"
-}, {sendfile, 0, 12345, "path/to/logo.png"}, Req0).
-
- -
+
Req = cowboy_req:reply(200, #{
+    <<"content-type">> => "image/png"
+}, {sendfile, 0, 12345, "path/to/logo.png"}, Req0).
+
+ + + + + + + + +

Informational responses

-
-

Cowboy allows you to send informational responses.

-

Informational responses are responses that have a status -code between 100 and 199. Any number can be sent before -the proper response. Sending an informational response -does not change the behavior of the proper response, and -clients are expected to ignore any informational response -they do not understand.

-

The following snippet sends a 103 informational response -with some headers that are expected to be in the final -response.

-
-
-
Req = cowboy_req:inform(103, #{
-    <<"link">> => <<"</style.css>; rel=preload; as=style, </script.js>; rel=preload; as=script">>
-}, Req0).
-
- -
+
Req = cowboy_req:inform(103, #{
+    <<"link">> => <<"</style.css>; rel=preload; as=style, </script.js>; rel=preload; as=script">>
+}, Req0).
+

Push

-
-

The HTTP/2 protocol introduced the ability to push resources -related to the one sent in the response. Cowboy provides two -functions for that purpose: cowboy_req:push/3,4.

-

Push is only available for HTTP/2. Cowboy will automatically -ignore push requests if the protocol doesn’t support it.

-

The push function must be called before any of the reply -functions. Doing otherwise will result in a crash.

-

To push a resource, you need to provide the same information -as a client performing a request would. This includes the -HTTP method, the URI and any necessary request headers.

-

Cowboy by default only requires you to give the path to -the resource and the request headers. The rest of the URI -is taken from the current request (excluding the query -string, set to empty) and the method is GET by default.

-

The following snippet pushes a CSS file that is linked to -in the response:

-
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, Req0),
-Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/html">>
-}, ["<html><head><title>My web page</title>",
-    "<link rel='stylesheet' type='text/css' href='/static/style.css'>",
-    "<body><p>Welcome to Erlang!</p></body></html>"], Req0).
-

To override the method, scheme, host, port or query string, -simply pass in a fourth argument. The following snippet -uses a different host name:

-
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, #{host => <<"cdn.example.org">>}, Req),
-

Pushed resources don’t have to be files. As long as the push -request is cacheable, safe and does not include a body, the -resource can be pushed.

-

Under the hood, Cowboy handles pushed requests the same as -normal requests: a different process is created which will -ultimately send a response to the client.

-
- +
cowboy_req:push("/static/style.css", #{
+    <<"accept">> => <<"text/css">>
+}, #{host => <<"cdn.example.org">>}, Req),
+ +

Pushed resources don't have to be files. As long as the push request is cacheable, safe and does not include a body, the resource can be pushed.

+

Under the hood, Cowboy handles pushed requests the same as normal requests: a different process is created which will ultimately send a response to the client.

+ diff --git a/docs/en/cowboy/2.3/guide/rest_flowcharts/index.html b/docs/en/cowboy/2.3/guide/rest_flowcharts/index.html index 7951c237..698e74db 100644 --- a/docs/en/cowboy/2.3/guide/rest_flowcharts/index.html +++ b/docs/en/cowboy/2.3/guide/rest_flowcharts/index.html @@ -62,244 +62,64 @@

REST flowcharts

-

This chapter will explain the REST handler state machine through -a number of different diagrams.

-

There are four main paths that requests may follow. One for the -method OPTIONS; one for the methods GET and HEAD; one for the -methods PUT, POST and PATCH; and one for the method DELETE.

-

All paths start with the "Start" diagram, and all paths excluding -the OPTIONS path go through the "Content negotiation" diagram -and optionally the "Conditional requests" diagram if the resource -exists.

-

The red squares refer to another diagram. The light green squares -indicate a response. Other squares may be either a callback or a -question answered by Cowboy itself. Green arrows tend to indicate -the default behavior if the callback is undefined.

-
+

This chapter will explain the REST handler state machine through a number of different diagrams.

+

There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE.

+

All paths start with the "Start" diagram, and all paths excluding the OPTIONS path go through the "Content negotiation" diagram and optionally the "Conditional requests" diagram if the resource exists.

+

The red squares refer to another diagram. The light green squares indicate a response. Other squares may be either a callback or a question answered by Cowboy itself. Green arrows tend to indicate the default behavior if the callback is undefined.

Start

-
-

All requests start from here.

-
-
-REST starting flowchart -
-
-

A series of callbacks are called in succession to perform -a general checkup of the service, the request line and -request headers.

-

The request body, if any, is not expected to have been -received for any of these steps. It is only processed -at the end of the "PUT, POST and PATCH methods" diagram, -when all conditions have been met.

-

The known_methods and allowed_methods callbacks -return a list of methods. Cowboy then checks if the request -method is in the list, and stops otherwise.

-

The is_authorized callback may be used to check that -access to the resource is authorized. Authentication -may also be performed as needed. When authorization is -denied, the return value from the callback must include -a challenge applicable to the requested resource, which -will be sent back to the client in the www-authenticate -header.

-

This diagram is immediately followed by either the -"OPTIONS method" diagram when the request method is -OPTIONS, or the "Content negotiation" diagram otherwise.

-
-
-
+

All requests start from here.

+REST starting flowchart

A series of callbacks are called in succession to perform a general checkup of the service, the request line and request headers.

+

The request body, if any, is not expected to have been received for any of these steps. It is only processed at the end of the "PUT, POST and PATCH methods" diagram, when all conditions have been met.

+

The known_methods and allowed_methods callbacks return a list of methods. Cowboy then checks if the request method is in the list, and stops otherwise.

+

The is_authorized callback may be used to check that access to the resource is authorized. Authentication may also be performed as needed. When authorization is denied, the return value from the callback must include a challenge applicable to the requested resource, which will be sent back to the client in the www-authenticate header.

+

This diagram is immediately followed by either the "OPTIONS method" diagram when the request method is OPTIONS, or the "Content negotiation" diagram otherwise.

OPTIONS method

-
-

This diagram only applies to OPTIONS requests.

-
-
-REST OPTIONS method flowchart -
-
-

The options callback may be used to add information -about the resource, such as media types or languages -provided; allowed methods; any extra information. A -response body may also be set, although clients should -not be expected to read it.

-

If the options callback is not defined, Cowboy will -send a response containing the list of allowed methods -by default.

-
-
-
+

This diagram only applies to OPTIONS requests.

+REST OPTIONS method flowchart

The options callback may be used to add information about the resource, such as media types or languages provided; allowed methods; any extra information. A response body may also be set, although clients should not be expected to read it.

+

If the options callback is not defined, Cowboy will send a response containing the list of allowed methods by default.

Content negotiation

-
-

This diagram applies to all request methods other than -OPTIONS. It is executed right after the "Start" diagram -is completed.

-
-
-REST content negotiation flowchart -
-
-

The purpose of these steps is to determine an appropriate -representation to be sent back to the client.

-

The request may contain any of the accept header; the -accept-language header; or the accept-charset header. -When present, Cowboy will parse the headers and then -call the corresponding callback to obtain the list -of provided content-type, language or charset for this -resource. It then automatically select the best match -based on the request.

-

If a callback is not defined, Cowboy will select the -content-type, language or charset that the client -prefers.

-

The content_types_provided also returns the name of -a callback for every content-type it accepts. This -callback will only be called at the end of the -"GET and HEAD methods" diagram, when all conditions -have been met.

-

The selected content-type, language and charset are -saved as meta values in the Req object. You should -use the appropriate representation if you set a -response body manually (alongside an error code, -for example).

-

This diagram is immediately followed by -the "GET and HEAD methods" diagram, -the "PUT, POST and PATCH methods" diagram, -or the "DELETE method" diagram, depending on the -method.

-
-
-
+

This diagram applies to all request methods other than OPTIONS. It is executed right after the "Start" diagram is completed.

+REST content negotiation flowchart

The purpose of these steps is to determine an appropriate representation to be sent back to the client.

+

The request may contain any of the accept header; the accept-language header; or the accept-charset header. When present, Cowboy will parse the headers and then call the corresponding callback to obtain the list of provided content-type, language or charset for this resource. It then automatically select the best match based on the request.

+

If a callback is not defined, Cowboy will select the content-type, language or charset that the client prefers.

+

The content_types_provided also returns the name of a callback for every content-type it accepts. This callback will only be called at the end of the "GET and HEAD methods" diagram, when all conditions have been met.

+

The selected content-type, language and charset are saved as meta values in the Req object. You should use the appropriate representation if you set a response body manually (alongside an error code, for example).

+

This diagram is immediately followed by the "GET and HEAD methods" diagram, the "PUT, POST and PATCH methods" diagram, or the "DELETE method" diagram, depending on the method.

GET and HEAD methods

-
-

This diagram only applies to GET and HEAD requests.

-

For a description of the cond step, please see -the "Conditional requests" diagram.

-
-
-REST GET/HEAD methods flowchart -
-
-

When the resource exists, and the conditional steps -succeed, the resource can be retrieved.

-

Cowboy prepares the response by first retrieving -metadata about the representation, then by calling -the ProvideResource callback. This is the callback -you defined for each content-types you returned from -content_types_provided. This callback returns the body -that will be sent back to the client, or a fun if the -body must be streamed.

-

When the resource does not exist, Cowboy will figure out -whether the resource existed previously, and if so whether -it was moved elsewhere in order to redirect the client to -the new URI.

-

The moved_permanently and moved_temporarily callbacks -must return the new location of the resource if it was in -fact moved.

-
-
-
-

PUT, POST and PATCH methods

-
-

This diagram only applies to PUT, POST and PATCH requests.

-

For a description of the cond step, please see -the "Conditional requests" diagram.

-
-
-REST PUT/POST/PATCH methods flowchart -
-
-

When the resource exists, first the conditional steps -are executed. When that succeeds, and the method is PUT, -Cowboy will call the is_conflict callback. This function -can be used to prevent potential race conditions, by locking -the resource for example.

-

Then all three methods reach the content_types_accepted -step that we will describe in a few paragraphs.

-

When the resource does not exist, and the method is PUT, -Cowboy will check for conflicts and then move on to the -content_types_accepted step. For other methods, Cowboy -will figure out whether the resource existed previously, -and if so whether it was moved elsewhere. If the resource -is truly non-existent, the method is POST and the call -for allow_missing_post returns true, then Cowboy will -move on to the content_types_accepted step. Otherwise -the request processing ends there.

-

The moved_permanently and moved_temporarily callbacks -must return the new location of the resource if it was in -fact moved.

-

The content_types_accepted returns a list of -content-types it accepts, but also the name of a callback -for each of them. Cowboy will select the appropriate -callback for processing the request body and call it.

-

This callback may return one of three different return -values.

-

If an error occurred while processing the request body, -it must return false and Cowboy will send an -appropriate error response.

-

If the method is POST, then you may return true with -an URI of where the resource has been created. This is -especially useful for writing handlers for collections.

-

Otherwise, return true to indicate success. Cowboy -will select the appropriate response to be sent depending -on whether a resource has been created, rather than -modified, and on the availability of a location header -or a body in the response.

-
-
-
+

This diagram only applies to GET and HEAD requests.

+

For a description of the cond step, please see the "Conditional requests" diagram.

+REST GET/HEAD methods flowchart

When the resource exists, and the conditional steps succeed, the resource can be retrieved.

+

Cowboy prepares the response by first retrieving metadata about the representation, then by calling the ProvideResource callback. This is the callback you defined for each content-types you returned from content_types_provided. This callback returns the body that will be sent back to the client, or a fun if the body must be streamed.

+

When the resource does not exist, Cowboy will figure out whether the resource existed previously, and if so whether it was moved elsewhere in order to redirect the client to the new URI.

+

The moved_permanently and moved_temporarily callbacks must return the new location of the resource if it was in fact moved.

+

PUT, POST and PATCH methods

+

This diagram only applies to PUT, POST and PATCH requests.

+

For a description of the cond step, please see the "Conditional requests" diagram.

+REST PUT/POST/PATCH methods flowchart

When the resource exists, first the conditional steps are executed. When that succeeds, and the method is PUT, Cowboy will call the is_conflict callback. This function can be used to prevent potential race conditions, by locking the resource for example.

+

Then all three methods reach the content_types_accepted step that we will describe in a few paragraphs.

+

When the resource does not exist, and the method is PUT, Cowboy will check for conflicts and then move on to the content_types_accepted step. For other methods, Cowboy will figure out whether the resource existed previously, and if so whether it was moved elsewhere. If the resource is truly non-existent, the method is POST and the call for allow_missing_post returns true, then Cowboy will move on to the content_types_accepted step. Otherwise the request processing ends there.

+

The moved_permanently and moved_temporarily callbacks must return the new location of the resource if it was in fact moved.

+

The content_types_accepted returns a list of content-types it accepts, but also the name of a callback for each of them. Cowboy will select the appropriate callback for processing the request body and call it.

+

This callback may return one of three different return values.

+

If an error occurred while processing the request body, it must return false and Cowboy will send an appropriate error response.

+

If the method is POST, then you may return true with an URI of where the resource has been created. This is especially useful for writing handlers for collections.

+

Otherwise, return true to indicate success. Cowboy will select the appropriate response to be sent depending on whether a resource has been created, rather than modified, and on the availability of a location header or a body in the response.

DELETE method

-
-

This diagram only applies to DELETE requests.

-

For a description of the cond step, please see -the "Conditional requests" diagram.

-
-
-REST DELETE method flowchart -
-
-

When the resource exists, and the conditional steps -succeed, the resource can be deleted.

-

Deleting the resource is a two steps process. First -the callback delete_resource is executed. Use this -callback to delete the resource.

-

Because the resource may be cached, you must also -delete all cached representations of this resource -in the system. This operation may take a while though, -so you may return before it finished.

-

Cowboy will then call the delete_completed callback. -If you know that the resource has been completely -deleted from your system, including from caches, then -you can return true. If any doubts persist, return -false. Cowboy will assume true by default.

-

To finish, Cowboy checks if you set a response body, -and depending on that, sends the appropriate response.

-

When the resource does not exist, Cowboy will figure out -whether the resource existed previously, and if so whether -it was moved elsewhere in order to redirect the client to -the new URI.

-

The moved_permanently and moved_temporarily callbacks -must return the new location of the resource if it was in -fact moved.

-
-
-
+

This diagram only applies to DELETE requests.

+

For a description of the cond step, please see the "Conditional requests" diagram.

+REST DELETE method flowchart

When the resource exists, and the conditional steps succeed, the resource can be deleted.

+

Deleting the resource is a two steps process. First the callback delete_resource is executed. Use this callback to delete the resource.

+

Because the resource may be cached, you must also delete all cached representations of this resource in the system. This operation may take a while though, so you may return before it finished.

+

Cowboy will then call the delete_completed callback. If you know that the resource has been completely deleted from your system, including from caches, then you can return true. If any doubts persist, return false. Cowboy will assume true by default.

+

To finish, Cowboy checks if you set a response body, and depending on that, sends the appropriate response.

+

When the resource does not exist, Cowboy will figure out whether the resource existed previously, and if so whether it was moved elsewhere in order to redirect the client to the new URI.

+

The moved_permanently and moved_temporarily callbacks must return the new location of the resource if it was in fact moved.

Conditional requests

-
-

This diagram applies to all request methods other than -OPTIONS. It is executed right after the resource_exists -callback, when the resource exists.

-
-
-REST conditional requests flowchart -
-
-

A request becomes conditional when it includes either of -the if-match header; the if-unmodified-since header; the -if-none-match header; or the if-modified-since header.

-

If the condition fails, the request ends immediately -without any retrieval or modification of the resource.

-

The generate_etag and last_modified are called as -needed. Cowboy will only call them once and then cache -the results for subsequent use.

-
-
+

This diagram applies to all request methods other than OPTIONS. It is executed right after the resource_exists callback, when the resource exists.

+REST conditional requests flowchart

A request becomes conditional when it includes either of the if-match header; the if-unmodified-since header; the if-none-match header; or the if-modified-since header.

+

If the condition fails, the request ends immediately without any retrieval or modification of the resource.

+

The generate_etag and last_modified are called as needed. Cowboy will only call them once and then cache the results for subsequent use.

+ diff --git a/docs/en/cowboy/2.3/guide/rest_handlers/index.html b/docs/en/cowboy/2.3/guide/rest_handlers/index.html index 83d1fb46..1d2fe4e6 100644 --- a/docs/en/cowboy/2.3/guide/rest_handlers/index.html +++ b/docs/en/cowboy/2.3/guide/rest_handlers/index.html @@ -62,287 +62,162 @@

REST handlers

-

REST is implemented in Cowboy as a sub protocol. The request -is handled as a state machine with many optional callbacks -describing the resource and modifying the machine’s behavior.

-

The REST handler is the recommended way to handle HTTP requests.

-
+

REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine's behavior.

+

The REST handler is the recommended way to handle HTTP requests.

Initialization

-
-

First, the init/2 callback is called. This callback is common -to all handlers. To use REST for the current request, this function -must return a cowboy_rest tuple.

-
-
-
init(Req, State) ->
-    {cowboy_rest, Req, State}.
-

Cowboy will then switch to the REST protocol and start executing -the state machine.

-

After reaching the end of the flowchart, the terminate/3 callback -will be called if it is defined.

-
-
-
+
init(Req, State) ->
+    {cowboy_rest, Req, State}.
+
+

Cowboy will then switch to the REST protocol and start executing the state machine.

+

After reaching the end of the flowchart, the terminate/3 callback will be called if it is defined.

Methods

-
-

The REST component has code for handling the following HTTP methods: -HEAD, GET, POST, PATCH, PUT, DELETE and OPTIONS.

-

Other methods can be accepted, however they have no specific callback -defined for them at this time.

-
- -
+

The REST component has code for handling the following HTTP methods: HEAD, GET, POST, PATCH, PUT, DELETE and OPTIONS.

+

Other methods can be accepted, however they have no specific callback defined for them at this time.

Callbacks

-
-

All callbacks are optional. Some may become mandatory depending -on what other defined callbacks return. The various flowcharts -in the next chapter should be a useful to determine which callbacks -you need.

-

All callbacks take two arguments, the Req object and the State, -and return a three-element tuple of the form {Value, Req, State}.

-

Nearly all callbacks can also return {stop, Req, State} to -stop execution of the request, and -{{switch_handler, Module}, Req, State} or -{{switch_handler, Module, Opts}, Req, State} to switch to -a different handler type. The exceptions are expires -generate_etag, last_modified and variances.

-

The following table summarizes the callbacks and their default values. -If the callback isn’t defined, then the default value will be used. -Please look at the flowcharts to find out the result of each return -value.

-

In the following table, "skip" means the callback is entirely skipped -if it is undefined, moving directly to the next step. Similarly, -"none" means there is no default value for this callback.

-
- --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +

All callbacks are optional. Some may become mandatory depending on what other defined callbacks return. The various flowcharts in the next chapter should be a useful to determine which callbacks you need.

+

All callbacks take two arguments, the Req object and the State, and return a three-element tuple of the form {Value, Req, State}.

+

Nearly all callbacks can also return {stop, Req, State} to stop execution of the request, and {{switch_handler, Module}, Req, State} or {{switch_handler, Module, Opts}, Req, State} to switch to a different handler type. The exceptions are expires generate_etag, last_modified and variances.

+

The following table summarizes the callbacks and their default values. If the callback isn't defined, then the default value will be used. Please look at the flowcharts to find out the result of each return value.

+

In the following table, "skip" means the callback is entirely skipped if it is undefined, moving directly to the next step. Similarly, "none" means there is no default value for this callback.

+
Callback name Default value

allowed_methods

[<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]

allow_missing_post

true

charsets_provided

skip

content_types_accepted

none

content_types_provided

[{{ <<"text">>, <<"html">>, '*'}, to_html}]

delete_completed

true

delete_resource

false

expires

undefined

forbidden

false

generate_etag

undefined

is_authorized

true

is_conflict

false

known_methods

[<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]

languages_provided

skip

last_modified

undefined

malformed_request

false

moved_permanently

false

moved_temporarily

false

multiple_choices

false

options

ok

previously_existed

false

resource_exists

true

service_available

true

uri_too_long

false

+ + + + - - - + + - - - + + - - - + + - -
Callback nameDefault value
allowed_methods[<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]

valid_content_headers

true

allow_missing_posttrue

valid_entity_length

true

charsets_providedskip

variances

[]

content_types_acceptednone
-
-

As you can see, Cowboy tries to move on with the request whenever -possible by using well thought out default values.

-

In addition to these, there can be any number of user-defined -callbacks that are specified through content_types_accepted/2 -and content_types_provided/2. They can take any name, however -it is recommended to use a separate prefix for the callbacks of -each function. For example, from_html and to_html indicate -in the first case that we’re accepting a resource given as HTML, -and in the second case that we send one as HTML.

-
-
-
+content_types_provided +[{{ <<"text">>, <<"html">>, '*'}, to_html}] + +delete_completed +true + +delete_resource +false + +expires +undefined + +forbidden +false + +generate_etag +undefined + +is_authorized +true + +is_conflict +false + +known_methods +[<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>] + +languages_provided +skip + +last_modified +undefined + +malformed_request +false + +moved_permanently +false + +moved_temporarily +false + +multiple_choices +false + +options +ok + +previously_existed +false + +resource_exists +true + +service_available +true + +uri_too_long +false + +valid_content_headers +true + +valid_entity_length +true + +variances +[] + + +

As you can see, Cowboy tries to move on with the request whenever possible by using well thought out default values.

+

In addition to these, there can be any number of user-defined callbacks that are specified through content_types_accepted/2 and content_types_provided/2. They can take any name, however it is recommended to use a separate prefix for the callbacks of each function. For example, from_html and to_html indicate in the first case that we're accepting a resource given as HTML, and in the second case that we send one as HTML.

Meta data

-
-

Cowboy will set informative values to the Req object at various -points of the execution. You can retrieve them by matching the -Req object directly. The values are defined in the following table:

-
- --- - - - - - - - - - - - - - - - - - - - -
Key Details

media_type

The content-type negotiated for the response entity.

language

The language negotiated for the response entity.

charset

The charset negotiated for the response entity.

-
-

They can be used to send a proper body with the response to a -request that used a method other than HEAD or GET.

-
-
-
+

Cowboy will set informative values to the Req object at various points of the execution. You can retrieve them by matching the Req object directly. The values are defined in the following table:

+ + + + + + + + + + + + +
KeyDetails
media_typeThe content-type negotiated for the response entity.
languageThe language negotiated for the response entity.
charsetThe charset negotiated for the response entity.
+

They can be used to send a proper body with the response to a request that used a method other than HEAD or GET.

Response headers

-
-

Cowboy will set response headers automatically over the execution -of the REST code. They are listed in the following table.

-
- --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Header name Details

content-language

Language used in the response body

content-type

Media type and charset of the response body

etag

Etag of the resource

expires

Expiration date of the resource

last-modified

Last modification date for the resource

location

Relative or absolute URI to the requested resource

vary

List of headers that may change the representation of the resource

-
-
-
+

Cowboy will set response headers automatically over the execution of the REST code. They are listed in the following table.

+ + + + + + + + + + + + + + + + + + + + + + + + +
Header nameDetails
content-languageLanguage used in the response body
content-typeMedia type and charset of the response body
etagEtag of the resource
expiresExpiration date of the resource
last-modifiedLast modification date for the resource
locationRelative or absolute URI to the requested resource
varyList of headers that may change the representation of the resource
+ diff --git a/docs/en/cowboy/2.3/guide/rest_principles/index.html b/docs/en/cowboy/2.3/guide/rest_principles/index.html index 12de886b..78687d10 100644 --- a/docs/en/cowboy/2.3/guide/rest_principles/index.html +++ b/docs/en/cowboy/2.3/guide/rest_principles/index.html @@ -62,153 +62,38 @@

REST principles

-

This chapter will attempt to define the concepts behind REST -and explain what makes a service RESTful.

-

REST is often confused with performing a distinct operation -depending on the HTTP method, while using more than the GET -and POST methods. That’s highly misguided at best.

-

We will first attempt to define REST and will look at what -it means in the context of HTTP and the Web. -For a more in-depth explanation of REST, you can read -Roy T. Fielding’s dissertation -as it does a great job explaining where it comes from and -what it achieves.

-
+

This chapter will attempt to define the concepts behind REST and explain what makes a service RESTful.

+

REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That's highly misguided at best.

+

We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. Fielding's dissertation as it does a great job explaining where it comes from and what it achieves.

REST architecture

-
-

REST is a client-server architecture. The client and the server -both have a different set of concerns. The server stores and/or -manipulates information and makes it available to the user in -an efficient manner. The client takes that information and -displays it to the user and/or uses it to perform subsequent -requests for information. This separation of concerns allows both -the client and the server to evolve independently as it only -requires that the interface stays the same.

-

REST is stateless. That means the communication between the -client and the server always contains all the information needed -to perform the request. There is no session state in the server, -it is kept entirely on the client’s side. If access to a resource -requires authentication, then the client needs to authenticate -itself with every request.

-

REST is cacheable. The client, the server and any intermediary -components can all cache resources in order to improve performance.

-

REST provides a uniform interface between components. This -simplifies the architecture, as all components follow the same -rules to speak to one another. It also makes it easier to understand -the interactions between the different components of the system. -A number of constraints are required to achieve this. They are -covered in the rest of the chapter.

-

REST is a layered system. Individual components cannot see -beyond the immediate layer with which they are interacting. This -means that a client connecting to an intermediate component, like -a proxy, has no knowledge of what lies beyond. This allows -components to be independent and thus easily replaceable or -extendable.

-

REST optionally provides code on demand. Code may be downloaded -to extend client functionality. This is optional however because -the client may not be able to download or run this code, and so -a REST component cannot rely on it being executed.

-
-
-
+

REST is a client-server architecture. The client and the server both have a different set of concerns. The server stores and/or manipulates information and makes it available to the user in an efficient manner. The client takes that information and displays it to the user and/or uses it to perform subsequent requests for information. This separation of concerns allows both the client and the server to evolve independently as it only requires that the interface stays the same.

+

REST is stateless. That means the communication between the client and the server always contains all the information needed to perform the request. There is no session state in the server, it is kept entirely on the client's side. If access to a resource requires authentication, then the client needs to authenticate itself with every request.

+

REST is cacheable. The client, the server and any intermediary components can all cache resources in order to improve performance.

+

REST provides a uniform interface between components. This simplifies the architecture, as all components follow the same rules to speak to one another. It also makes it easier to understand the interactions between the different components of the system. A number of constraints are required to achieve this. They are covered in the rest of the chapter.

+

REST is a layered system. Individual components cannot see beyond the immediate layer with which they are interacting. This means that a client connecting to an intermediate component, like a proxy, has no knowledge of what lies beyond. This allows components to be independent and thus easily replaceable or extendable.

+

REST optionally provides code on demand. Code may be downloaded to extend client functionality. This is optional however because the client may not be able to download or run this code, and so a REST component cannot rely on it being executed.

Resources and resource identifiers

-
-

A resource is an abstract concept. In a REST system, any information -that can be named may be a resource. This includes documents, images, -a collection of resources and any other information. Any information -that can be the target of an hypertext link can be a resource.

-

A resource is a conceptual mapping to a set of entities. The set of -entities evolves over time; a resource doesn’t. For example, a resource -can map to "users who have logged in this past month" and another -to "all users". At some point in time they may map to the same set of -entities, because all users logged in this past month. But they are -still different resources. Similarly, if nobody logged in recently, -then the first resource may map to the empty set. This resource exists -regardless of the information it maps to.

-

Resources are identified by uniform resource identifiers, also known -as URIs. Sometimes internationalized resource identifiers, or IRIs, -may also be used, but these can be directly translated into a URI.

-

In practice we will identify two kinds of resources. Individual -resources map to a set of one element, for example "user Joe". -Collection of resources map to a set of 0 to N elements, -for example "all users".

-
-
-
+

A resource is an abstract concept. In a REST system, any information that can be named may be a resource. This includes documents, images, a collection of resources and any other information. Any information that can be the target of an hypertext link can be a resource.

+

A resource is a conceptual mapping to a set of entities. The set of entities evolves over time; a resource doesn't. For example, a resource can map to "users who have logged in this past month" and another to "all users". At some point in time they may map to the same set of entities, because all users logged in this past month. But they are still different resources. Similarly, if nobody logged in recently, then the first resource may map to the empty set. This resource exists regardless of the information it maps to.

+

Resources are identified by uniform resource identifiers, also known as URIs. Sometimes internationalized resource identifiers, or IRIs, may also be used, but these can be directly translated into a URI.

+

In practice we will identify two kinds of resources. Individual resources map to a set of one element, for example "user Joe". Collection of resources map to a set of 0 to N elements, for example "all users".

Resource representations

-
-

The representation of a resource is a sequence of bytes associated -with metadata.

-

The metadata comes as a list of key-value pairs, where the name -corresponds to a standard that defines the value’s structure and -semantics. With HTTP, the metadata comes in the form of request -or response headers. The headers' structure and semantics are well -defined in the HTTP standard. Metadata includes representation -metadata, resource metadata and control data.

-

The representation metadata gives information about the -representation, such as its media type, the date of last -modification, or even a checksum.

-

Resource metadata could be link to related resources or -information about additional representations of the resource.

-

Control data allows parameterizing the request or response. -For example, we may only want the representation returned if -it is more recent than the one we have in cache. Similarly, -we may want to instruct the client about how it should cache -the representation. This isn’t restricted to caching. We may, -for example, want to store a new representation of a resource -only if it wasn’t modified since we first retrieved it.

-

The data format of a representation is also known as the media -type. Some media types are intended for direct rendering to the -user, while others are intended for automated processing. The -media type is a key component of the REST architecture.

-
-
-
+

The representation of a resource is a sequence of bytes associated with metadata.

+

The metadata comes as a list of key-value pairs, where the name corresponds to a standard that defines the value's structure and semantics. With HTTP, the metadata comes in the form of request or response headers. The headers' structure and semantics are well defined in the HTTP standard. Metadata includes representation metadata, resource metadata and control data.

+

The representation metadata gives information about the representation, such as its media type, the date of last modification, or even a checksum.

+

Resource metadata could be link to related resources or information about additional representations of the resource.

+

Control data allows parameterizing the request or response. For example, we may only want the representation returned if it is more recent than the one we have in cache. Similarly, we may want to instruct the client about how it should cache the representation. This isn't restricted to caching. We may, for example, want to store a new representation of a resource only if it wasn't modified since we first retrieved it.

+

The data format of a representation is also known as the media type. Some media types are intended for direct rendering to the user, while others are intended for automated processing. The media type is a key component of the REST architecture.

Self-descriptive messages

-
-

Messages must be self-descriptive. That means that the data -format of a representation must always come with its media -type (and similarly requesting a resource involves choosing -the media type of the representation returned). If you are -sending HTML, then you must say it is HTML by sending the -media type with the representation. In HTTP this is done -using the content-type header.

-

The media type is often an IANA registered media type, like -text/html or image/png, but does not need to be. Exactly -two things are important for respecting this constraint: that -the media type is well specified, and that the sender and -recipient agree about what the media type refers to.

-

This means that you can create your own media types, like -application/x-mine, and that as long as you write the -specifications for it and that both endpoints agree about -it then the constraint is respected.

-
-
-
+

Messages must be self-descriptive. That means that the data format of a representation must always come with its media type (and similarly requesting a resource involves choosing the media type of the representation returned). If you are sending HTML, then you must say it is HTML by sending the media type with the representation. In HTTP this is done using the content-type header.

+

The media type is often an IANA registered media type, like text/html or image/png, but does not need to be. Exactly two things are important for respecting this constraint: that the media type is well specified, and that the sender and recipient agree about what the media type refers to.

+

This means that you can create your own media types, like application/x-mine, and that as long as you write the specifications for it and that both endpoints agree about it then the constraint is respected.

Hypermedia as the engine of application state

-
-

The last constraint is generally where services that claim -to be RESTful fail. Interactions with a server must be -entirely driven by hypermedia. The client does not need -any prior knowledge of the service in order to use it, -other than an entry point and of course basic understanding -of the media type of the representations, at the very least -enough to find and identify hyperlinks and link relations.

-

To give a simple example, if your service only works with -the application/json media type then this constraint -cannot be respected (as there are no concept of links in -JSON) and thus your service isn’t RESTful. This is the case -for the majority of self-proclaimed REST services.

-

On the other hand if you create a JSON based media type -that has a concept of links and link relations, then -your service might be RESTful.

-

Respecting this constraint means that the entirety of the -service becomes self-discoverable, not only the resources -in it, but also the operations you can perform on it. This -makes clients very thin as there is no need to implement -anything specific to the service to operate on it.

-
-
+

The last constraint is generally where services that claim to be RESTful fail. Interactions with a server must be entirely driven by hypermedia. The client does not need any prior knowledge of the service in order to use it, other than an entry point and of course basic understanding of the media type of the representations, at the very least enough to find and identify hyperlinks and link relations.

+

To give a simple example, if your service only works with the application/json media type then this constraint cannot be respected (as there are no concept of links in JSON) and thus your service isn't RESTful. This is the case for the majority of self-proclaimed REST services.

+

On the other hand if you create a JSON based media type that has a concept of links and link relations, then your service might be RESTful.

+

Respecting this constraint means that the entirety of the service becomes self-discoverable, not only the resources in it, but also the operations you can perform on it. This makes clients very thin as there is no need to implement anything specific to the service to operate on it.

+ diff --git a/docs/en/cowboy/2.3/guide/routing/index.html b/docs/en/cowboy/2.3/guide/routing/index.html index 5f1ef914..1a7eccc6 100644 --- a/docs/en/cowboy/2.3/guide/routing/index.html +++ b/docs/en/cowboy/2.3/guide/routing/index.html @@ -62,261 +62,181 @@

Routing

-

Cowboy does nothing by default.

-

To make Cowboy useful, you need to map URIs to Erlang modules that will -handle the requests. This is called routing.

-

When Cowboy receives a request, it tries to match the requested host and -path to the configured routes. When there’s a match, the route’s -associated handler is executed.

-

Routes need to be compiled before they can be used by Cowboy. -The result of the compilation is the dispatch rules.

-
+

Cowboy does nothing by default.

+

To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing.

+

When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there's a match, the route's associated handler is executed.

+

Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules.

Syntax

-
-

The general structure for the routes is defined as follow.

-
-
-
Routes = [Host1, Host2, ... HostN].
-

Each host contains matching rules for the host along with optional -constraints, and a list of routes for the path component.

-
-
-
Host1 = {HostMatch, PathsList}.
-Host2 = {HostMatch, Constraints, PathsList}.
-

The list of routes for the path component is defined similar to the -list of hosts.

-
-
-
PathsList = [Path1, Path2, ... PathN].
-

Finally, each path contains matching rules for the path along with -optional constraints, and gives us the handler module to be used -along with its initial state.

-
-
-
Path1 = {PathMatch, Handler, InitialState}.
-Path2 = {PathMatch, Constraints, Handler, InitialState}.
-

Continue reading to learn more about the match syntax and the optional -constraints.

-
-
-
+
Path1 = {PathMatch, Handler, InitialState}.
+Path2 = {PathMatch, Constraints, Handler, InitialState}.
+
+

Continue reading to learn more about the match syntax and the optional constraints.

Match syntax

-
-

The match syntax is used to associate host names and paths with their -respective handlers.

-

The match syntax is the same for host and path with a few subtleties. -Indeed, the segments separator is different, and the host is matched -starting from the last segment going to the first. All examples will -feature both host and path match rules and explain the differences -when encountered.

-

Excluding special values that we will explain at the end of this section, -the simplest match value is a host or a path. It can be given as either -a string() or a binary().

-
-
-
PathMatch1 = "/".
-PathMatch2 = "/path/to/resource".
-
-HostMatch1 = "cowboy.example.org".
-

As you can see, all paths defined this way must start with a slash -character. Note that these two paths are identical as far as routing -is concerned.

-
-
-
PathMatch2 = "/path/to/resource".
-PathMatch3 = "/path/to/resource/".
-

Hosts with and without a trailing dot are equivalent for routing. -Similarly, hosts with and without a leading dot are also equivalent.

-
-
-
HostMatch1 = "cowboy.example.org".
-HostMatch2 = "cowboy.example.org.".
-HostMatch3 = ".cowboy.example.org".
-

It is possible to extract segments of the host and path and to store -the values in the Req object for later use. We call these kind of -values bindings.

-

The syntax for bindings is very simple. A segment that begins with -the : character means that what follows until the end of the segment -is the name of the binding in which the segment value will be stored.

-
-
-
PathMatch = "/hats/:name/prices".
-HostMatch = ":subdomain.example.org".
-

If these two end up matching when routing, you will end up with two -bindings defined, subdomain and name, each containing the -segment value where they were defined. For example, the URL -http://test.example.org/hats/wild_cowboy_legendary/prices will -result in having the value test bound to the name subdomain -and the value wild_cowboy_legendary bound to the name name. -They can later be retrieved using cowboy_req:binding/{2,3}. The -binding name must be given as an atom.

-

There is a special binding name you can use to mimic the underscore -variable in Erlang. Any match against the _ binding will succeed -but the data will be discarded. This is especially useful for -matching against many domain names in one go.

-
-
-
HostMatch = "ninenines.:_".
-

Similarly, it is possible to have optional segments. Anything -between brackets is optional.

-
-
-
PathMatch = "/hats/[page/:number]".
-HostMatch = "[www.]ninenines.eu".
-

You can also have imbricated optional segments.

-
-
-
PathMatch = "/hats/[page/[:number]]".
-

You can retrieve the rest of the host or path using [...]. -In the case of hosts it will match anything before, in the case -of paths anything after the previously matched segments. It is -a special case of optional segments, in that it can have -zero, one or many segments. You can then find the segments using -cowboy_req:host_info/1 and cowboy_req:path_info/1 respectively. -They will be represented as a list of segments.

-
-
-
PathMatch = "/hats/[...]".
-HostMatch = "[...]ninenines.eu".
-

If a binding appears twice in the routing rules, then the match -will succeed only if they share the same value. This copies the -Erlang pattern matching behavior.

-
-
-
PathMatch = "/hats/:name/:name".
-

This is also true when an optional segment is present. In this -case the two values must be identical only if the segment is -available.

-
-
-
PathMatch = "/hats/:name/[:name]".
-

If a binding is defined in both the host and path, then they must -also share the same value.

-
-
-
PathMatch = "/:user/[...]".
-HostMatch = ":user.github.com".
-

Finally, there are two special match values that can be used. The -first is the atom '_' which will match any host or path.

-
-
-
PathMatch = '_'.
-HostMatch = '_'.
-

The second is the special host match "*" which will match the -wildcard path, generally used alongside the OPTIONS method.

-
-
-
HostMatch = "*".
-
- -
+
HostMatch = "*".
+

Constraints

-
-

After the matching has completed, the resulting bindings can be tested -against a set of constraints. Constraints are only tested when the -binding is defined. They run in the order you defined them. The match -will succeed only if they all succeed. If the match fails, then Cowboy -tries the next route in the list.

-

The format used for constraints is the same as match functions in -cowboy_req: they are provided as a list of fields which may have -one or more constraints. While the router accepts the same format, -it will skip fields with no constraints and will also ignore default -values, if any.

-

Read more about constraints.

-
- -
+

After the matching has completed, the resulting bindings can be tested against a set of constraints. Constraints are only tested when the binding is defined. They run in the order you defined them. The match will succeed only if they all succeed. If the match fails, then Cowboy tries the next route in the list.

+

The format used for constraints is the same as match functions in cowboy_req: they are provided as a list of fields which may have one or more constraints. While the router accepts the same format, it will skip fields with no constraints and will also ignore default values, if any.

+

Read more about constraints.

Compilation

-
-

The routes must be compiled before Cowboy can use them. The compilation -step normalizes the routes to simplify the code and speed up the -execution, but the routes are still looked up one by one in the end. -Faster compilation strategies could be to compile the routes directly -to Erlang code, but would require heavier dependencies.

-

To compile routes, just call the appropriate function:

-
-
-
Dispatch = cowboy_router:compile([
-    %% {HostMatch, list({PathMatch, Handler, InitialState})}
-    {'_', [{'_', my_handler, #{}}]}
+
Dispatch = cowboy_router:compile([
+    %% {HostMatch, list({PathMatch, Handler, InitialState})}
+    {'_', [{'_', my_handler, #{}}]}
 ]),
-%% Name, NbAcceptors, TransOpts, ProtoOpts
-cowboy:start_clear(my_http_listener,
-    [{port, 8080}],
-    #{env => #{dispatch => Dispatch}}
-).
-
-
-
+%% Name, NbAcceptors, TransOpts, ProtoOpts +cowboy:start_clear(my_http_listener, + [{port, 8080}], + #{env => #{dispatch => Dispatch}} +). +

Live update

-
-

You can use the cowboy:set_env/3 function for updating the dispatch -list used by routing. This will apply to all new connections accepted -by the listener:

-
-
-
Dispatch = cowboy_router:compile(Routes),
-cowboy:set_env(my_http_listener, dispatch, Dispatch).
-

Note that you need to compile the routes again before updating.

-
- +
Dispatch = cowboy_router:compile(Routes),
+cowboy:set_env(my_http_listener, dispatch, Dispatch).
+ +

Note that you need to compile the routes again before updating.

+ diff --git a/docs/en/cowboy/2.3/guide/specs/index.html b/docs/en/cowboy/2.3/guide/specs/index.html index 49ba1e1a..b16bd2fa 100644 --- a/docs/en/cowboy/2.3/guide/specs/index.html +++ b/docs/en/cowboy/2.3/guide/specs/index.html @@ -62,859 +62,345 @@

HTTP and other specifications

-

This chapter intends to list all the specification documents -for or related to HTTP.

-
+

This chapter intends to list all the specification documents for or related to HTTP.

HTTP

-
- -
+

Current

-
    -
  • -

    -CORS: Cross-Origin Resource Sharing -

    -
  • -
  • -

    -CSP2: Content Security Policy Level 2 -

    -
  • -
  • -

    -DNT: Tracking Preference Expression (DNT) -

    -
  • -
  • -

    -eventsource: Server-Sent Events -

    -
  • -
  • -

    -Form content types: Form content types -

    -
  • -
  • -

    -Preload: Preload -

    -
  • -
  • -

    -PROXY: The PROXY protocol -

    -
  • -
  • -

    -REST: Fielding’s Dissertation -

    -
  • -
  • -

    -RFC 1945: HTTP/1.0 -

    -
  • -
  • -

    -RFC 1951: DEFLATE Compressed Data Format Specification version 1.3 -

    -
  • -
  • -

    -RFC 1952: GZIP file format specification version 4.3 -

    -
  • -
  • -

    -RFC 2046: Multipart media type (in MIME Part Two: Media Types) -

    -
  • -
  • -

    -RFC 2295: Transparent Content Negotiation in HTTP -

    -
  • -
  • -

    -RFC 2296: HTTP Remote Variant Selection Algorithm: RVSA/1.0 -

    -
  • -
  • -

    -RFC 2817: Upgrading to TLS Within HTTP/1.1 -

    -
  • -
  • -

    -RFC 2818: HTTP Over TLS -

    -
  • -
  • -

    -RFC 3230: Instance Digests in HTTP -

    -
  • -
  • -

    -RFC 4559: SPNEGO-based Kerberos and NTLM HTTP Authentication in Microsoft Windows -

    -
  • -
  • -

    -RFC 5789: PATCH Method for HTTP -

    -
  • -
  • -

    -RFC 5843: Additional Hash Algorithms for HTTP Instance Digests -

    -
  • -
  • -

    -RFC 5861: HTTP Cache-Control Extensions for Stale Content -

    -
  • -
  • -

    -RFC 5988: Web Linking -

    -
  • -
  • -

    -RFC 6265: HTTP State Management Mechanism -

    -
  • -
  • -

    -RFC 6266: Use of the Content-Disposition Header Field -

    -
  • -
  • -

    -RFC 6454: The Web Origin Concept -

    -
  • -
  • -

    -RFC 6455: The WebSocket Protocol -

    -
  • -
  • -

    -RFC 6585: Additional HTTP Status Codes -

    -
  • -
  • -

    -RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage -

    -
  • -
  • -

    -RFC 6797: HTTP Strict Transport Security (HSTS) -

    -
  • -
  • -

    -RFC 6903: Additional Link Relation Types -

    -
  • -
  • -

    -RFC 7034: HTTP Header Field X-Frame-Options -

    -
  • -
  • -

    -RFC 7089: Time-Based Access to Resource States: Memento -

    -
  • -
  • -

    -RFC 7230: HTTP/1.1 Message Syntax and Routing -

    -
  • -
  • -

    -RFC 7231: HTTP/1.1 Semantics and Content -

    -
  • -
  • -

    -RFC 7232: HTTP/1.1 Conditional Requests -

    -
  • -
  • -

    -RFC 7233: HTTP/1.1 Range Requests -

    -
  • -
  • -

    -RFC 7234: HTTP/1.1 Caching -

    -
  • -
  • -

    -RFC 7235: HTTP/1.1 Authentication -

    -
  • -
  • -

    -RFC 7239: Forwarded HTTP Extension -

    -
  • -
  • -

    -RFC 7240: Prefer Header for HTTP -

    -
  • -
  • -

    -RFC 7469: Public Key Pinning Extension for HTTP -

    -
  • -
  • -

    -RFC 7486: HTTP Origin-Bound Authentication (HOBA) -

    -
  • -
  • -

    -RFC 7538: HTTP Status Code 308 (Permanent Redirect) -

    -
  • -
  • -

    -RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2) -

    -
  • -
  • -

    -RFC 7541: HPACK: Header Compression for HTTP/2 -

    -
  • -
  • -

    -RFC 7578: Returning Values from Forms: multipart/form-data -

    -
  • -
  • -

    -RFC 7615: HTTP Authentication-Info and Proxy-Authentication-Info Response Header Fields -

    -
  • -
  • -

    -RFC 7616: HTTP Digest Access Authentication -

    -
  • -
  • -

    -RFC 7617: The Basic HTTP Authentication Scheme -

    -
  • -
  • -

    -RFC 7639: The ALPN HTTP Header Field -

    -
  • -
  • -

    -RFC 7692: Compression Extensions for WebSocket -

    -
  • -
  • -

    -RFC 7694: HTTP Client-Initiated Content-Encoding -

    -
  • -
  • -

    -RFC 7725: An HTTP Status Code to Report Legal Obstacles -

    -
  • -
  • -

    -RFC 7804: Salted Challenge Response HTTP Authentication Mechanism -

    -
  • -
  • -

    -RFC 7838: HTTP Alternative Services -

    -
  • -
  • -

    -RFC 7932: Brotli Compressed Data Format -

    -
  • -
  • -

    -RFC 7936: Clarifying Registry Procedures for the WebSocket Subprotocol Name Registry -

    -
  • -
  • -

    -RFC 8053: HTTP Authentication Extensions for Interactive Clients -

    -
  • -
  • -

    -RFC 8164: Opportunistic Security for HTTP/2 -

    -
  • -
  • -

    -RFC 8187: Indicating Character Encoding and Language for HTTP Header Field Parameters -

    -
  • -
  • -

    -RFC 8188: Encrypted Content-Encoding for HTTP -

    -
  • -
  • -

    -RFC 8246: HTTP Immutable Responses -

    -
  • -
  • -

    -RFC 8297: An HTTP Status Code for Indicating Hints -

    -
  • -
  • -

    -RFC 8336: The ORIGIN HTTP/2 Frame -

    -
  • -
  • -

    -Webmention: Webmention -

    -
  • -
-
-
+
  • CORS: Cross-Origin Resource Sharing +
  • +
  • CSP2: Content Security Policy Level 2 +
  • +
  • DNT: Tracking Preference Expression (DNT) +
  • +
  • eventsource: Server-Sent Events +
  • +
  • Form content types: Form content types +
  • +
  • Preload: Preload +
  • +
  • PROXY: The PROXY protocol +
  • +
  • REST: Fielding's Dissertation +
  • +
  • RFC 1945: HTTP/1.0 +
  • +
  • RFC 1951: DEFLATE Compressed Data Format Specification version 1.3 +
  • +
  • RFC 1952: GZIP file format specification version 4.3 +
  • +
  • RFC 2046: Multipart media type (in MIME Part Two: Media Types) +
  • +
  • RFC 2295: Transparent Content Negotiation in HTTP +
  • +
  • RFC 2296: HTTP Remote Variant Selection Algorithm: RVSA/1.0 +
  • +
  • RFC 2817: Upgrading to TLS Within HTTP/1.1 +
  • +
  • RFC 2818: HTTP Over TLS +
  • +
  • RFC 3230: Instance Digests in HTTP +
  • +
  • RFC 4559: SPNEGO-based Kerberos and NTLM HTTP Authentication in Microsoft Windows +
  • +
  • RFC 5789: PATCH Method for HTTP +
  • +
  • RFC 5843: Additional Hash Algorithms for HTTP Instance Digests +
  • +
  • RFC 5861: HTTP Cache-Control Extensions for Stale Content +
  • +
  • RFC 5988: Web Linking +
  • +
  • RFC 6265: HTTP State Management Mechanism +
  • +
  • RFC 6266: Use of the Content-Disposition Header Field +
  • +
  • RFC 6454: The Web Origin Concept +
  • +
  • RFC 6455: The WebSocket Protocol +
  • +
  • RFC 6585: Additional HTTP Status Codes +
  • +
  • RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage +
  • +
  • RFC 6797: HTTP Strict Transport Security (HSTS) +
  • +
  • RFC 6903: Additional Link Relation Types +
  • +
  • RFC 7034: HTTP Header Field X-Frame-Options +
  • +
  • RFC 7089: Time-Based Access to Resource States: Memento +
  • +
  • RFC 7230: HTTP/1.1 Message Syntax and Routing +
  • +
  • RFC 7231: HTTP/1.1 Semantics and Content +
  • +
  • RFC 7232: HTTP/1.1 Conditional Requests +
  • +
  • RFC 7233: HTTP/1.1 Range Requests +
  • +
  • RFC 7234: HTTP/1.1 Caching +
  • +
  • RFC 7235: HTTP/1.1 Authentication +
  • +
  • RFC 7239: Forwarded HTTP Extension +
  • +
  • RFC 7240: Prefer Header for HTTP +
  • +
  • RFC 7469: Public Key Pinning Extension for HTTP +
  • +
  • RFC 7486: HTTP Origin-Bound Authentication (HOBA) +
  • +
  • RFC 7538: HTTP Status Code 308 (Permanent Redirect) +
  • +
  • RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2) +
  • +
  • RFC 7541: HPACK: Header Compression for HTTP/2 +
  • +
  • RFC 7578: Returning Values from Forms: multipart/form-data +
  • +
  • RFC 7615: HTTP Authentication-Info and Proxy-Authentication-Info Response Header Fields +
  • +
  • RFC 7616: HTTP Digest Access Authentication +
  • +
  • RFC 7617: The Basic HTTP Authentication Scheme +
  • +
  • RFC 7639: The ALPN HTTP Header Field +
  • +
  • RFC 7692: Compression Extensions for WebSocket +
  • +
  • RFC 7694: HTTP Client-Initiated Content-Encoding +
  • +
  • RFC 7725: An HTTP Status Code to Report Legal Obstacles +
  • +
  • RFC 7804: Salted Challenge Response HTTP Authentication Mechanism +
  • +
  • RFC 7838: HTTP Alternative Services +
  • +
  • RFC 7932: Brotli Compressed Data Format +
  • +
  • RFC 7936: Clarifying Registry Procedures for the WebSocket Subprotocol Name Registry +
  • +
  • RFC 8053: HTTP Authentication Extensions for Interactive Clients +
  • +
  • RFC 8164: Opportunistic Security for HTTP/2 +
  • +
  • RFC 8187: Indicating Character Encoding and Language for HTTP Header Field Parameters +
  • +
  • RFC 8188: Encrypted Content-Encoding for HTTP +
  • +
  • RFC 8246: HTTP Immutable Responses +
  • +
  • RFC 8297: An HTTP Status Code for Indicating Hints +
  • +
  • RFC 8336: The ORIGIN HTTP/2 Frame +
  • +
  • Webmention: Webmention +
  • +

Upcoming

- -
-
+

Informative

-
    -
  • -

    -Architecture of the World Wide Web -

    -
  • -
  • -

    -RFC 2936: HTTP MIME Type Handler Detection -

    -
  • -
  • -

    -RFC 2964: Use of HTTP State Management -

    -
  • -
  • -

    -RFC 3143: Known HTTP Proxy/Caching Problems -

    -
  • -
  • -

    -RFC 6202: Known Issues and Best Practices for the Use of Long Polling and Streaming in Bidirectional HTTP -

    -
  • -
  • -

    -RFC 6838: Media Type Specifications and Registration Procedures -

    -
  • -
  • -

    -RFC 7478: Web Real-Time Communication Use Cases and Requirements -

    -
  • -
-
-
+
  • Architecture of the World Wide Web +
  • +
  • RFC 2936: HTTP MIME Type Handler Detection +
  • +
  • RFC 2964: Use of HTTP State Management +
  • +
  • RFC 3143: Known HTTP Proxy/Caching Problems +
  • +
  • RFC 6202: Known Issues and Best Practices for the Use of Long Polling and Streaming in Bidirectional HTTP +
  • +
  • RFC 6838: Media Type Specifications and Registration Procedures +
  • +
  • RFC 7478: Web Real-Time Communication Use Cases and Requirements +
  • +
-
-
-
+

Seemingly obsolete

-
    -
  • -

    -RFC 2227: Simple Hit-Metering and Usage-Limiting for HTTP -

    -
  • -
  • -

    -RFC 2310: The Safe Response Header Field -

    -
  • -
  • -

    -RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) -

    -
  • -
  • -

    -RFC 2660: The Secure HyperText Transfer Protocol -

    -
  • -
  • -

    -RFC 2774: An HTTP Extension Framework -

    -
  • -
  • -

    -RFC 2965: HTTP State Management Mechanism (Cookie2) -

    -
  • -
  • -

    -RFC 3229: Delta encoding in HTTP -

    -
  • -
  • -

    -RFC 7168: The Hyper Text Coffee Pot Control Protocol for Tea Efflux Appliances (HTCPCP-TEA) -

    -
  • -
  • -

    -SPDY: SPDY Protocol -

    -
  • -
  • -

    -x-webkit-deflate-frame: Deprecated Websocket compression -

    -
  • -
-
-
-
-
+
  • RFC 2227: Simple Hit-Metering and Usage-Limiting for HTTP +
  • +
  • RFC 2310: The Safe Response Header Field +
  • +
  • RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) +
  • +
  • RFC 2660: The Secure HyperText Transfer Protocol +
  • +
  • RFC 2774: An HTTP Extension Framework +
  • +
  • RFC 2965: HTTP State Management Mechanism (Cookie2) +
  • +
  • RFC 3229: Delta encoding in HTTP +
  • +
  • RFC 7168: The Hyper Text Coffee Pot Control Protocol for Tea Efflux Appliances (HTCPCP-TEA) +
  • +
  • SPDY: SPDY Protocol +
  • +
  • x-webkit-deflate-frame: Deprecated Websocket compression +
  • +

URL

-
-
-
-
-
+

WebDAV

-
-
    -
  • -

    -RFC 3253: Versioning Extensions to WebDAV -

    -
  • -
  • -

    -RFC 3648: WebDAV Ordered Collections Protocol -

    -
  • -
  • -

    -RFC 3744: WebDAV Access Control Protocol -

    -
  • -
  • -

    -RFC 4316: Datatypes for WebDAV Properties -

    -
  • -
  • -

    -RFC 4331: Quota and Size Properties for DAV Collections -

    -
  • -
  • -

    -RFC 4437: WebDAV Redirect Reference Resources -

    -
  • -
  • -

    -RFC 4709: Mounting WebDAV Servers -

    -
  • -
  • -

    -RFC 4791: Calendaring Extensions to WebDAV (CalDAV) -

    -
  • -
  • -

    -RFC 4918: HTTP Extensions for WebDAV -

    -
  • -
  • -

    -RFC 5323: WebDAV SEARCH -

    -
  • -
  • -

    -RFC 5397: WebDAV Current Principal Extension -

    -
  • -
  • -

    -RFC 5689: Extended MKCOL for WebDAV -

    -
  • -
  • -

    -RFC 5842: Binding Extensions to WebDAV -

    -
  • -
  • -

    -RFC 5995: Using POST to Add Members to WebDAV Collections -

    -
  • -
  • -

    -RFC 6352: CardDAV: vCard Extensions to WebDAV -

    -
  • -
  • -

    -RFC 6578: Collection Synchronization for WebDAV -

    -
  • -
  • -

    -RFC 6638: Scheduling Extensions to CalDAV -

    -
  • -
  • -

    -RFC 6764: Locating Services for Calendaring Extensions to WebDAV (CalDAV) and vCard Extensions to WebDAV (CardDAV) -

    -
  • -
  • -

    -RFC 7809: Calendaring Extensions to WebDAV (CalDAV): Time Zones by Reference -

    -
  • -
  • -

    -RFC 7953: Calendar Availability -

    -
  • -
  • -

    -RFC 8144: Use of the Prefer Header Field in WebDAV -

    -
  • -
-
-
-
+
  • RFC 3253: Versioning Extensions to WebDAV +
  • +
  • RFC 3648: WebDAV Ordered Collections Protocol +
  • +
  • RFC 3744: WebDAV Access Control Protocol +
  • +
  • RFC 4316: Datatypes for WebDAV Properties +
  • +
  • RFC 4331: Quota and Size Properties for DAV Collections +
  • +
  • RFC 4437: WebDAV Redirect Reference Resources +
  • +
  • RFC 4709: Mounting WebDAV Servers +
  • +
  • RFC 4791: Calendaring Extensions to WebDAV (CalDAV) +
  • +
  • RFC 4918: HTTP Extensions for WebDAV +
  • +
  • RFC 5323: WebDAV SEARCH +
  • +
  • RFC 5397: WebDAV Current Principal Extension +
  • +
  • RFC 5689: Extended MKCOL for WebDAV +
  • +
  • RFC 5842: Binding Extensions to WebDAV +
  • +
  • RFC 5995: Using POST to Add Members to WebDAV Collections +
  • +
  • RFC 6352: CardDAV: vCard Extensions to WebDAV +
  • +
  • RFC 6578: Collection Synchronization for WebDAV +
  • +
  • RFC 6638: Scheduling Extensions to CalDAV +
  • +
  • RFC 6764: Locating Services for Calendaring Extensions to WebDAV (CalDAV) and vCard Extensions to WebDAV (CardDAV) +
  • +
  • RFC 7809: Calendaring Extensions to WebDAV (CalDAV): Time Zones by Reference +
  • +
  • RFC 7953: Calendar Availability +
  • +
  • RFC 8144: Use of the Prefer Header Field in WebDAV +
  • +

CoAP

-
-
    -
  • -

    -RFC 7252: The Constrained Application Protocol (CoAP) -

    -
  • -
  • -

    -RFC 7390: Group Communication for CoAP -

    -
  • -
  • -

    -RFC 7641: Observing Resources in CoAP -

    -
  • -
  • -

    -RFC 7650: A CoAP Usage for REsource LOcation And Discovery (RELOAD) -

    -
  • -
  • -

    -RFC 7959: Block-Wise Transfers in CoAP -

    -
  • -
  • -

    -RFC 7967: CoAP Option for No Server Response -

    -
  • -
  • -

    -RFC 8075: Guidelines for Mapping Implementations: HTTP to CoAP -

    -
  • -
  • -

    -RFC 8132: PATCH and FETCH Methods for CoAP -

    -
  • -
  • -

    -RFC 8323: CoAP over TCP, TLS, and WebSockets -

    -
  • -
-
-
+
  • RFC 7252: The Constrained Application Protocol (CoAP) +
  • +
  • RFC 7390: Group Communication for CoAP +
  • +
  • RFC 7641: Observing Resources in CoAP +
  • +
  • RFC 7650: A CoAP Usage for REsource LOcation And Discovery (RELOAD) +
  • +
  • RFC 7959: Block-Wise Transfers in CoAP +
  • +
  • RFC 7967: CoAP Option for No Server Response +
  • +
  • RFC 8075: Guidelines for Mapping Implementations: HTTP to CoAP +
  • +
  • RFC 8132: PATCH and FETCH Methods for CoAP +
  • +
  • RFC 8323: CoAP over TCP, TLS, and WebSockets +
  • +
+ diff --git a/docs/en/cowboy/2.3/guide/static_files/index.html b/docs/en/cowboy/2.3/guide/static_files/index.html index 5b5bbd0b..f3fe3254 100644 --- a/docs/en/cowboy/2.3/guide/static_files/index.html +++ b/docs/en/cowboy/2.3/guide/static_files/index.html @@ -62,173 +62,101 @@

Static files

-

Cowboy comes with a ready to use handler for serving static -files. It is provided as a convenience for serving files -during development.

-

For systems in production, consider using one of the many -Content Distribution Network (CDN) available on the market, -as they are the best solution for serving files.

-

The static handler can serve either one file or all files -from a given directory. The etag generation and mime types -can be configured.

-
+

Cowboy comes with a ready to use handler for serving static files. It is provided as a convenience for serving files during development.

+

For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files.

+

The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured.

Serve one file

-
-

You can use the static handler to serve one specific file -from an application’s private directory. This is particularly -useful to serve an index.html file when the client requests -the / path, for example. The path configured is relative -to the given application’s private directory.

-

The following rule will serve the file static/index.html -from the application my_app's priv directory whenever the -path / is accessed:

-
-
-
{"/", cowboy_static, {priv_file, my_app, "static/index.html"}}
-

You can also specify the absolute path to a file, or the -path to the file relative to the current directory:

-
-
-
{"/", cowboy_static, {file, "/var/www/index.html"}}
-
-
-
+
{"/", cowboy_static, {file, "/var/www/index.html"}}
+

Serve all files from a directory

-
-

You can also use the static handler to serve all files that -can be found in the configured directory. The handler will -use the path_info information to resolve the file location, -which means that your route must end with a [...] pattern -for it to work. All files are served, including the ones that -may be found in subfolders.

-

You can specify the directory relative to an application’s -private directory.

-

The following rule will serve any file found in the application -my_app's priv directory inside the static/assets folder -whenever the requested path begins with /assets/:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets"}}
-

You can also specify the absolute path to the directory or -set it relative to the current directory:

-
-
-
{"/assets/[...]", cowboy_static, {dir, "/var/www/assets"}}
-
- -
+
{"/assets/[...]", cowboy_static, {dir, "/var/www/assets"}}
+

Customize the mimetype detection

-
-

By default, Cowboy will attempt to recognize the mimetype -of your static files by looking at the extension.

-

You can override the function that figures out the mimetype -of the static files. It can be useful when Cowboy is missing -a mimetype you need to handle, or when you want to reduce -the list to make lookups faster. You can also give a -hard-coded mimetype that will be used unconditionally.

-

Cowboy comes with two functions built-in. The default -function only handles common file types used when building -Web applications. The other function is an extensive list -of hundreds of mimetypes that should cover almost any need -you may have. You can of course create your own function.

-

To use the default function, you should not have to configure -anything, as it is the default. If you insist, though, the -following will do the job:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{mimetypes, cow_mimetypes, web}]}}
-

As you can see, there is an optional field that may contain -a list of less used options, like mimetypes or etag. All option -types have this optional field.

-

To use the function that will detect almost any mimetype, -the following configuration will do:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{mimetypes, cow_mimetypes, all}]}}
-

You probably noticed the pattern by now. The configuration -expects a module and a function name, so you can use any -of your own functions instead:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{mimetypes, Module, Function}]}}
-

The function that performs the mimetype detection receives -a single argument that is the path to the file on disk. It -is recommended to return the mimetype in tuple form, although -a binary string is also allowed (but will require extra -processing). If the function can’t figure out the mimetype, -then it should return {<<"application">>, <<"octet-stream">>, []}.

-

When the static handler fails to find the extension, -it will send the file as application/octet-stream. -A browser receiving such file will attempt to download it -directly to disk.

-

Finally, the mimetype can be hard-coded for all files. -This is especially useful in combination with the file -and priv_file options as it avoids needless computation:

-
-
-
{"/", cowboy_static, {priv_file, my_app, "static/index.html",
-    [{mimetypes, {<<"text">>, <<"html">>, []}}]}}
-
- -
+
{"/", cowboy_static, {priv_file, my_app, "static/index.html",
+    [{mimetypes, {<<"text">>, <<"html">>, []}}]}}
+

Generate an etag

-
-

By default, the static handler will generate an etag header -value based on the size and modified time. This solution -can not be applied to all systems though. It would perform -rather poorly over a cluster of nodes, for example, as the -file metadata will vary from server to server, giving a -different etag on each server.

-

You can however change the way the etag is calculated:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{etag, Module, Function}]}}
-

This function will receive three arguments: the path to the -file on disk, the size of the file and the last modification -time. In a distributed setup, you would typically use the -file path to retrieve an etag value that is identical across -all your servers.

-

You can also completely disable etag handling:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{etag, false}]}}
-
- +
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
+    [{etag, false}]}}
+ + diff --git a/docs/en/cowboy/2.3/guide/streams/index.html b/docs/en/cowboy/2.3/guide/streams/index.html index 4c621525..7f936431 100644 --- a/docs/en/cowboy/2.3/guide/streams/index.html +++ b/docs/en/cowboy/2.3/guide/streams/index.html @@ -62,61 +62,23 @@

Streams

-

A stream is the set of messages that form an HTTP -request/response pair.

-

The term stream comes from HTTP/2. In Cowboy, it is -also used when talking about HTTP/1.1 or HTTP/1.0. -It should not be confused with streaming the request -or response body.

-

All versions of HTTP allow clients to initiate -streams. HTTP/2 is the only one also allowing servers, -through its server push feature. Both client and -server-initiated streams go through the same process -in Cowboy.

-
+

A stream is the set of messages that form an HTTP request/response pair.

+

The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body.

+

All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy.

Stream handlers

-
-

Stream handlers must implement five different callbacks. -Four of them are directly related; one is special.

-

All callbacks receives the stream ID as first argument.

-

Most of them can return a list of commands to be executed -by Cowboy. When callbacks are chained, it is possible to -intercept and modify these commands. This can be useful -for modifying responses for example.

-

The init/3 callback is invoked when a new request -comes in. It receives the Req object and the protocol options -for this listener.

-

The data/4 callback is invoked when data from the request -body is received. It receives both this data and a flag -indicating whether more is to be expected.

-

The info/3 callback is invoked when an Erlang message is -received for this stream. They will typically be messages -sent by the request process.

-

Finally the terminate/3 callback is invoked with the -terminate reason for the stream. The return value is ignored. -Note that as with all terminate callbacks in Erlang, there -is no strong guarantee that it will be called.

-

The special callback early_error/5 is called when an error -occurs before the request headers were fully received and -Cowboy is sending a response. It receives the partial Req -object, the error reason, the protocol options and the response -Cowboy will send. This response must be returned, possibly -modified.

-
-
-
+

Stream handlers must implement five different callbacks. Four of them are directly related; one is special.

+

All callbacks receives the stream ID as first argument.

+

Most of them can return a list of commands to be executed by Cowboy. When callbacks are chained, it is possible to intercept and modify these commands. This can be useful for modifying responses for example.

+

The init/3 callback is invoked when a new request comes in. It receives the Req object and the protocol options for this listener.

+

The data/4 callback is invoked when data from the request body is received. It receives both this data and a flag indicating whether more is to be expected.

+

The info/3 callback is invoked when an Erlang message is received for this stream. They will typically be messages sent by the request process.

+

Finally the terminate/3 callback is invoked with the terminate reason for the stream. The return value is ignored. Note that as with all terminate callbacks in Erlang, there is no strong guarantee that it will be called.

+

The special callback early_error/5 is called when an error occurs before the request headers were fully received and Cowboy is sending a response. It receives the partial Req object, the error reason, the protocol options and the response Cowboy will send. This response must be returned, possibly modified.

Built-in handlers

-
-

Cowboy comes with two handlers.

-

cowboy_stream_h is the default stream handler. -It is the core of much of the functionality of Cowboy. -All chains of stream handlers should call it last.

-

cowboy_compress_h will automatically compress -responses when possible. It is not enabled by default. -It is a good example for writing your own handlers -that will modify responses.

-
-
+

Cowboy comes with two handlers.

+

cowboy_stream_h is the default stream handler. It is the core of much of the functionality of Cowboy. All chains of stream handlers should call it last.

+

cowboy_compress_h will automatically compress responses when possible. It is not enabled by default. It is a good example for writing your own handlers that will modify responses.

+ diff --git a/docs/en/cowboy/2.3/guide/ws_handlers/index.html b/docs/en/cowboy/2.3/guide/ws_handlers/index.html index ab028875..6fca9cf9 100644 --- a/docs/en/cowboy/2.3/guide/ws_handlers/index.html +++ b/docs/en/cowboy/2.3/guide/ws_handlers/index.html @@ -62,297 +62,190 @@

Websocket handlers

-

Websocket handlers provide an interface for upgrading HTTP/1.1 -connections to Websocket and sending or receiving frames on -the Websocket connection.

-

As Websocket connections are established through the HTTP/1.1 -upgrade mechanism, Websocket handlers need to be able to first -receive the HTTP request for the upgrade, before switching to -Websocket and taking over the connection. They can then receive -or send Websocket frames, handle incoming Erlang messages or -close the connection.

-
+

Websocket handlers provide an interface for upgrading HTTP/1.1 connections to Websocket and sending or receiving frames on the Websocket connection.

+

As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection.

Upgrade

-
-

The init/2 callback is called when the request is received. -To establish a Websocket connection, you must switch to the -cowboy_websocket module:

-
-
-
init(Req, State) ->
-    {cowboy_websocket, Req, State}.
-

Cowboy will perform the Websocket handshake immediately. Note -that the handshake will fail if the client did not request an -upgrade to Websocket.

-

The Req object becomes unavailable after this function returns. -Any information required for proper execution of the Websocket -handler must be saved in the state.

-
-
-
-

Subprotocol

-
-

The client may provide a list of Websocket subprotocols it -supports in the sec-websocket-protocol header. The server must -select one of them and send it back to the client or the -handshake will fail.

-

For example, a client could understand both STOMP and MQTT over -Websocket, and provide the header:

-
-
-
sec-websocket-protocol: v12.stomp, mqtt
+
init(Req, State) ->
+    {cowboy_websocket, Req, State}.
-

If the server only understands MQTT it can return:

-
-
-
sec-websocket-protocol: mqtt
-
-

This selection must be done in init/2. An example usage could -be:

-
-
-
init(Req0, State) ->
-    case cowboy_req:parse_header(<<"sec-websocket-protocol">>, Req0) of
-        undefined ->
-            {cowboy_websocket, Req0, State};
-        Subprotocols ->
-            case lists:keymember(<<"mqtt">>, 1, Subprotocols) of
-                true ->
-                    Req = cowboy_req:set_resp_header(<<"sec-websocket-protocol">>,
-                        <<"mqtt">>, Req0),
-                    {cowboy_websocket, Req, State};
-                false ->
-                    Req = cowboy_req:reply(400, Req0),
-                    {ok, Req, State}
-            end
-    end.
-
-
-
+
init(Req0, State) ->
+    case cowboy_req:parse_header(<<"sec-websocket-protocol">>, Req0) of
+        undefined ->
+            {cowboy_websocket, Req0, State};
+        Subprotocols ->
+            case lists:keymember(<<"mqtt">>, 1, Subprotocols) of
+                true ->
+                    Req = cowboy_req:set_resp_header(<<"sec-websocket-protocol">>,
+                        <<"mqtt">>, Req0),
+                    {cowboy_websocket, Req, State};
+                false ->
+                    Req = cowboy_req:reply(400, Req0),
+                    {ok, Req, State}
+            end
+    end.
+

Post-upgrade initialization

-
-

Cowboy has separate processes for handling the connection -and requests. Because Websocket takes over the connection, -the Websocket protocol handling occurs in a different -process than the request handling.

-

This is reflected in the different callbacks Websocket -handlers have. The init/2 callback is called from the -temporary request process and the websocket_ callbacks -from the connection process.

-

This means that some initialization cannot be done from -init/2. Anything that would require the current pid, -or be tied to the current pid, will not work as intended. -The optional websocket_init/1 can be used instead:

-
-
-
websocket_init(State) ->
-    erlang:start_timer(1000, self(), <<"Hello!">>),
-    {ok, State}.
-

All Websocket callbacks share the same return values. This -means that we can send frames to the client right after -the upgrade:

-
-
-
websocket_init(State) ->
-    {reply, {text, <<"Hello!">>}, State}.
-
- -
+
websocket_init(State) ->
+    {reply, {text, <<"Hello!">>}, State}.
+

Receiving frames

-
-

Cowboy will call websocket_handle/2 whenever a text, binary, -ping or pong frame arrives from the client.

-

The handler can handle or ignore the frames. It can also -send frames back to the client or stop the connection.

-

The following snippet echoes back any text frame received and -ignores all others:

-
-
-
websocket_handle(Frame = {text, _}, State) ->
-    {reply, Frame, State};
-websocket_handle(_Frame, State) ->
-    {ok, State}.
-

Note that ping and pong frames require no action from the -handler as Cowboy will automatically reply to ping frames. -They are provided for informative purposes only.

-
- -
+
websocket_handle(Frame = {text, _}, State) ->
+    {reply, Frame, State};
+websocket_handle(_Frame, State) ->
+    {ok, State}.
+
+

Note that ping and pong frames require no action from the handler as Cowboy will automatically reply to ping frames. They are provided for informative purposes only.

Receiving Erlang messages

-
-

Cowboy will call websocket_info/2 whenever an Erlang message -arrives.

-

The handler can handle or ignore the messages. It can also -send frames to the client or stop the connection.

-

The following snippet forwards log messages to the client -and ignores all others:

-
-
-
websocket_info({log, Text}, State) ->
-    {reply, {text, Text}, State};
-websocket_info(_Info, State) ->
-    {ok, State}.
-
- -
+
websocket_info({log, Text}, State) ->
+    {reply, {text, Text}, State};
+websocket_info(_Info, State) ->
+    {ok, State}.
+

Sending frames

-
-

All websocket_ callbacks share return values. They may -send zero, one or many frames to the client.

-

To send nothing, just return an ok tuple:

-
-
+ + +

All websocket_ callbacks share return values. They may send zero, one or many frames to the client.

+

To send nothing, just return an ok tuple:

+
-
websocket_info(_Info, State) ->
-    {ok, State}.
-

To send one frame, return a reply tuple with the frame to send:

-
-
-
websocket_info(_Info, State) ->
-    {reply, {text, <<"Hello!">>}, State}.
-

You can send frames of any type: text, binary, ping, pong -or close frames.

-

To send many frames at once, return a reply tuple with the -list of frames to send:

-
-
-
websocket_info(_Info, State) ->
-    {reply, [
-        {text, "Hello"},
-        {text, <<"world!">>},
-        {binary, <<0:8000>>}
-    ], State}.
-

They are sent in the given order.

-
-
-
+
websocket_info(_Info, State) ->
+    {reply, [
+        {text, "Hello"},
+        {text, <<"world!">>},
+        {binary, <<0:8000>>}
+    ], State}.
+
+

They are sent in the given order.

Keeping the connection alive

-
-

Cowboy will automatically respond to ping frames sent by -the client. They are still forwarded to the handler for -informative purposes, but no further action is required.

-

Cowboy does not send ping frames itself. The handler can -do it if required. A better solution in most cases is to -let the client handle pings. Doing it from the handler -would imply having an additional timer per connection and -this can be a considerable cost for servers that need to -handle large numbers of connections.

-

Cowboy can be configured to close idle connections -automatically. It is highly recommended to configure -a timeout here, to avoid having processes linger longer -than needed.

-

The init/2 callback can set the timeout to be used -for the connection. For example, this would make Cowboy -close connections idle for more than 30 seconds:

-
-
-
init(Req, State) ->
-    {cowboy_websocket, Req, State, #{
-        idle_timeout => 30000}}.
-

This value cannot be changed once it is set. It defaults to -60000.

-
- -
+
init(Req, State) ->
+    {cowboy_websocket, Req, State, #{
+        idle_timeout => 30000}}.
+
+

This value cannot be changed once it is set. It defaults to 60000.

Limiting frame sizes

-
-

Cowboy accepts frames of any size by default. You should -limit the size depending on what your handler may handle. -You can do this via the init/2 callback:

-
-
-
init(Req, State) ->
-    {cowboy_websocket, Req, State, #{
-        max_frame_size => 8000000}}.
-

The lack of limit is historical. A future version of -Cowboy will have a more reasonable default.

-
- -
+
init(Req, State) ->
+    {cowboy_websocket, Req, State, #{
+        max_frame_size => 8000000}}.
+
+

The lack of limit is historical. A future version of Cowboy will have a more reasonable default.

Saving memory

-
-

The Websocket connection process can be set to hibernate -after the callback returns.

-

Simply add an hibernate field to the ok or reply tuples:

-
-
-
websocket_init(State) ->
-    {ok, State, hibernate}.
-
-websocket_handle(_Frame, State) ->
-    {ok, State, hibernate}.
-
-websocket_info(_Info, State) ->
-    {reply, {text, <<"Hello!">>}, State, hibernate}.
-

It is highly recommended to write your handlers with -hibernate enabled, as this allows to greatly reduce the -memory usage. Do note however that an increase in the -CPU usage or latency can be observed instead, in particular -for the more busy connections.

-
- -
+
websocket_init(State) ->
+    {ok, State, hibernate}.
+
+websocket_handle(_Frame, State) ->
+    {ok, State, hibernate}.
+
+websocket_info(_Info, State) ->
+    {reply, {text, <<"Hello!">>}, State, hibernate}.
+
+

It is highly recommended to write your handlers with hibernate enabled, as this allows to greatly reduce the memory usage. Do note however that an increase in the CPU usage or latency can be observed instead, in particular for the more busy connections.

Closing the connection

-
-

The connection can be closed at any time, either by telling -Cowboy to stop it or by sending a close frame.

-

To tell Cowboy to close the connection, use a stop tuple:

-
-
-
websocket_info(_Info, State) ->
-    {stop, State}.
-

Sending a close frame will immediately initiate the closing -of the Websocket connection. Note that when sending a list of -frames that include a close frame, any frame found after the -close frame will not be sent.

-

The following example sends a close frame with a reason message:

-
-
-
websocket_info(_Info, State) ->
-    {reply, {close, 1000, <<"some-reason">>}, State}.
-
- +
websocket_info(_Info, State) ->
+    {reply, {close, 1000, <<"some-reason">>}, State}.
+ + diff --git a/docs/en/cowboy/2.3/guide/ws_protocol/index.html b/docs/en/cowboy/2.3/guide/ws_protocol/index.html index b6748a82..6f6c593a 100644 --- a/docs/en/cowboy/2.3/guide/ws_protocol/index.html +++ b/docs/en/cowboy/2.3/guide/ws_protocol/index.html @@ -62,70 +62,22 @@

The Websocket protocol

-

This chapter explains what Websocket is and why it is -a vital component of soft realtime Web applications.

-
+

This chapter explains what Websocket is and why it is a vital component of soft realtime Web applications.

Description

-
-

Websocket is an extension to HTTP that emulates plain TCP -connections between the client, typically a Web browser, -and the server. It uses the HTTP Upgrade mechanism to -establish the connection.

-

Websocket connections are fully asynchronous, unlike -HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the -server can only initiate streams in response to requests). -With Websocket, the client and the server can both send -frames at any time without any restriction. It is closer -to TCP than any of the HTTP protocols.

-

Websocket is an IETF standard. Cowboy supports the standard -and all drafts that were previously implemented by browsers, -excluding the initial flawed draft sometimes known as -"version 0".

-
-
-
+

Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection.

+

Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). With Websocket, the client and the server can both send frames at any time without any restriction. It is closer to TCP than any of the HTTP protocols.

+

Websocket is an IETF standard. Cowboy supports the standard and all drafts that were previously implemented by browsers, excluding the initial flawed draft sometimes known as "version 0".

Websocket vs HTTP/2

-
-

For a few years Websocket was the only way to have a -bidirectional asynchronous connection with the server. -This changed when HTTP/2 was introduced. While HTTP/2 -requires the client to first perform a request before -the server can push data, this is only a minor restriction -as the client can do so just as it connects.

-

Websocket was designed as a kind-of-TCP channel to a -server. It only defines the framing and connection -management and lets the developer implement a protocol -on top of it. For example you could implement IRC over -Websocket and use a Javascript IRC client to speak to -the server.

-

HTTP/2 on the other hand is just an improvement over -the HTTP/1.1 connection and request/response mechanism. -It has the same semantics as HTTP/1.1.

-

If all you need is to access an HTTP API, then HTTP/2 -should be your first choice. On the other hand, if what -you need is a different protocol, then you can use -Websocket to implement it.

-
-
-
+

For a few years Websocket was the only way to have a bidirectional asynchronous connection with the server. This changed when HTTP/2 was introduced. While HTTP/2 requires the client to first perform a request before the server can push data, this is only a minor restriction as the client can do so just as it connects.

+

Websocket was designed as a kind-of-TCP channel to a server. It only defines the framing and connection management and lets the developer implement a protocol on top of it. For example you could implement IRC over Websocket and use a Javascript IRC client to speak to the server.

+

HTTP/2 on the other hand is just an improvement over the HTTP/1.1 connection and request/response mechanism. It has the same semantics as HTTP/1.1.

+

If all you need is to access an HTTP API, then HTTP/2 should be your first choice. On the other hand, if what you need is a different protocol, then you can use Websocket to implement it.

Implementation

-
-

Cowboy implements Websocket as a protocol upgrade. Once the -upgrade is performed from the init/2 callback, Cowboy -switches to Websocket. Please consult the next chapter for -more information on initiating and handling Websocket -connections.

-

The implementation of Websocket in Cowboy is validated using -the Autobahn test suite, which is an extensive suite of tests -covering all aspects of the protocol. Cowboy passes the -suite with 100% success, including all optional tests.

-

Cowboy’s Websocket implementation also includes the -permessage-deflate and x-webkit-deflate-frame compression -extensions.

-

Cowboy will automatically use compression when the -compress option is returned from the init/2 function.

-
-
+

Cowboy implements Websocket as a protocol upgrade. Once the upgrade is performed from the init/2 callback, Cowboy switches to Websocket. Please consult the next chapter for more information on initiating and handling Websocket connections.

+

The implementation of Websocket in Cowboy is validated using the Autobahn test suite, which is an extensive suite of tests covering all aspects of the protocol. Cowboy passes the suite with 100% success, including all optional tests.

+

Cowboy's Websocket implementation also includes the permessage-deflate and x-webkit-deflate-frame compression extensions.

+

Cowboy will automatically use compression when the compress option is returned from the init/2 function.

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy.set_env/index.html b/docs/en/cowboy/2.3/manual/cowboy.set_env/index.html index 1b3a9279..89788f69 100644 --- a/docs/en/cowboy/2.3/manual/cowboy.set_env/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy.set_env/index.html @@ -62,117 +62,59 @@

cowboy:set_env(3)

-

Name

-
-

cowboy:set_env - Update a listener’s environment value

-
-
-
+

cowboy:set_env - Update a listener's environment value

Description

-
-
-
-
set_env(Name  :: ranch:ref(),
-        Key   :: atom(),
-        Value :: any())
-    -> ok
-

Set or update an environment value for a previously started -listener.

-

This is most useful for updating the routes dynamically, -without having to restart the listener.

-

The new value will only be available to new connections. -Pre-existing connections will still use the old value.

-
-
-
+
set_env(Name  :: ranch:ref(),
+        Key   :: atom(),
+        Value :: any())
+    -> ok
+
+

Set or update an environment value for a previously started listener.

+

This is most useful for updating the routes dynamically, without having to restart the listener.

+

The new value will only be available to new connections. Pre-existing connections will still use the old value.

Arguments

-
-
-
-Name -
-
-

-The name of the listener to update. -

-

The name of the listener is the first argument given to the -cowboy:start_clear(3), -cowboy:start_tls(3) or -ranch:start_listener(3) function.

+
Name
+

The name of the listener to update.

+

The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function.

-
-Key -
-
-

-The key in the environment map. Common keys include dispatch -and middlewares. -

+
Key
+

The key in the environment map. Common keys include dispatch and middlewares.

-
-Value -
-
-

-The new value. -

-

The type of the value differs depending on the key.

+
Value
+

The new value.

+

The type of the value differs depending on the key.

-
-
- -
+

Return value

-
-

The atom ok is returned on success.

-

An exit:badarg exception is thrown when the listener does -not exist.

-
-
-
+

The atom ok is returned on success.

+

An exit:badarg exception is thrown when the listener does not exist.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Update a listener’s routes
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []},
-        {"/ws", websocket_h, []}
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []},
+        {"/ws", websocket_h, []}
     ]}
 ]),
 
-cowboy:set_env(example, dispatch, Dispatch).
-
-
-
+cowboy:set_env(example, dispatch, Dispatch). +

See also

- - +

cowboy(3), cowboy:start_clear(3), cowboy:start_tls(3), ranch:set_protocol_options(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy.start_clear/index.html b/docs/en/cowboy/2.3/manual/cowboy.start_clear/index.html index 9096c18c..58145cfc 100644 --- a/docs/en/cowboy/2.3/manual/cowboy.start_clear/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy.start_clear/index.html @@ -62,148 +62,77 @@

cowboy:start_clear(3)

-

Name

-
-

cowboy:start_clear - Listen for connections using plain TCP

-
-
-
+

cowboy:start_clear - Listen for connections using plain TCP

Description

-
-
-
-
start_clear(Name          :: ranch:ref(),
-            TransportOpts :: ranch_tcp:opts(),
-            ProtocolOpts  :: opts())
-    -> {ok, ListenerPid :: pid()}
-     | {error, any()}
-

Start listening for connections over a clear TCP channel.

-

Both HTTP/1.1 and HTTP/2 are supported on this listener. -HTTP/2 has two methods of establishing a connection over -a clear TCP channel. Both the upgrade and the prior knowledge -methods are supported.

-
-
-
+
start_clear(Name          :: ranch:ref(),
+            TransportOpts :: ranch_tcp:opts(),
+            ProtocolOpts  :: opts())
+    -> {ok, ListenerPid :: pid()}
+     | {error, any()}
+
+

Start listening for connections over a clear TCP channel.

+

Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported.

Arguments

-
-
-
-Name -
-
-

-The listener name is used to refer to this listener in -future calls, for example when stopping it or when -updating the routes defined. -

-

It can be any Erlang term. An atom is generally good enough, -for example api, my_app_clear or my_app_tls.

+
Name
+

The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined.

+

It can be any Erlang term. An atom is generally good enough, for example api, my_app_clear or my_app_tls.

-
-TransportOpts -
-
-

-The transport options are where the TCP options, including -the listener’s port number, are defined. Transport options -are provided as a list of keys and values, for example -[{port, 8080}]. -

-

The available options are documented in the -ranch_tcp(3) manual.

+
TransportOpts
+

The transport options are where the TCP options, including the listener's port number, are defined. Transport options are provided as a list of keys and values, for example [{port, 8080}].

+

The available options are documented in the ranch_tcp(3) manual.

-
-ProtocolOpts -
-
-

-The protocol options are in a map containing all the options for -the different protocols that may be involved when connecting -to the listener, including HTTP/1.1 and HTTP/2. -

-

The HTTP/1.1 options are documented in the -cowboy_http(3) manual; -and the HTTP/2 options in -cowboy_http2(3).

+
ProtocolOpts
+

The protocol options are in a map containing all the options for the different protocols that may be involved when connecting to the listener, including HTTP/1.1 and HTTP/2.

+

The HTTP/1.1 options are documented in the cowboy_http(3) manual; and the HTTP/2 options in cowboy_http2(3).

-
-
- -
+

Return value

-
-

An ok tuple is returned on success. It contains the pid of -the top-level supervisor for the listener.

-

An error tuple is returned on error. The error reason may -be any Erlang term.

-

A common error is eaddrinuse. It indicates that the port -configured for Cowboy is already in use.

-
-
-
+

An ok tuple is returned on success. It contains the pid of the top-level supervisor for the listener.

+

An error tuple is returned on error. The error reason may be any Erlang term.

+

A common error is eaddrinuse. It indicates that the port configured for Cowboy is already in use.

Changelog

-
-
    -
  • -

    -2.0: HTTP/2 support added. -

    +
    • 2.0: HTTP/2 support added.
    • -
    • -

      -2.0: Function introduced. Replaces cowboy:start_http/4. -

      +
    • 2.0: Function introduced. Replaces cowboy:start_http/4.
    • -
-
-
-
+

Examples

-
-
-
Start a listener
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []}
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []}
     ]}
 ]),
 
-{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{
-    env => #{dispatch => Dispatch}
-}).
-
-
Start a listener on a random port
-
-
Name = example,
+
Name = example,
 
-{ok, _} = cowboy:start_clear(Name, [], #{
-    env => #{dispatch => Dispatch}
+{ok, _} = cowboy:start_clear(Name, [], #{
+    env => #{dispatch => Dispatch}
 }),
 
-Port = ranch:get_port(Name).
-
-
-
+Port = ranch:get_port(Name). +

See also

- - +

cowboy(3), cowboy:start_tls(3), cowboy:stop_listener(3), ranch(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy.start_tls/index.html b/docs/en/cowboy/2.3/manual/cowboy.start_tls/index.html index 08f92c46..41f1c02f 100644 --- a/docs/en/cowboy/2.3/manual/cowboy.start_tls/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy.start_tls/index.html @@ -62,153 +62,82 @@

cowboy:start_tls(3)

-

Name

-
-

cowboy:start_tls - Listen for connections using TLS

-
-
-
+

cowboy:start_tls - Listen for connections using TLS

Description

-
-
-
-
start_tls(Name          :: ranch:ref(),
-          TransportOpts :: ranch_ssl:opts(),
-          ProtocolOpts  :: opts())
-    -> {ok, ListenerPid :: pid()}
-     | {error, any()}
-

Start listening for connections over a secure TLS channel.

-

Both HTTP/1.1 and HTTP/2 are supported on this listener. -The ALPN TLS extension must be used to initiate an HTTP/2 -connection.

-
-
-
+
start_tls(Name          :: ranch:ref(),
+          TransportOpts :: ranch_ssl:opts(),
+          ProtocolOpts  :: opts())
+    -> {ok, ListenerPid :: pid()}
+     | {error, any()}
+
+

Start listening for connections over a secure TLS channel.

+

Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection.

Arguments

-
-
-
-Name -
-
-

-The listener name is used to refer to this listener in -future calls, for example when stopping it or when -updating the routes defined. -

-

It can be any Erlang term. An atom is generally good enough, -for example api, my_app_clear or my_app_tls.

+
Name
+

The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined.

+

It can be any Erlang term. An atom is generally good enough, for example api, my_app_clear or my_app_tls.

-
-TransportOpts -
-
-

-The transport options are where the TCP options, including -the listener’s port number, are defined. They also contain -the TLS options, like the server’s certificate. Transport options -are provided as a list of keys and values, for example -[{port, 8443}, {certfile, "path/to/cert.pem"}]. -

-

The available options are documented in the -ranch_ssl(3) manual.

+
TransportOpts
+

The transport options are where the TCP options, including the listener's port number, are defined. They also contain the TLS options, like the server's certificate. Transport options are provided as a list of keys and values, for example [{port, 8443}, {certfile, "path/to/cert.pem"}].

+

The available options are documented in the ranch_ssl(3) manual.

-
-ProtocolOpts -
-
-

-The protocol options are in a map containing all the options for -the different protocols that may be involved when connecting -to the listener, including HTTP/1.1 and HTTP/2. -

-

The HTTP/1.1 options are documented in the -cowboy_http(3) manual; -and the HTTP/2 options in -cowboy_http2(3).

+
ProtocolOpts
+

The protocol options are in a map containing all the options for the different protocols that may be involved when connecting to the listener, including HTTP/1.1 and HTTP/2.

+

The HTTP/1.1 options are documented in the cowboy_http(3) manual; and the HTTP/2 options in cowboy_http2(3).

-
-
- -
+

Return value

-
-

An ok tuple is returned on success. It contains the pid of -the top-level supervisor for the listener.

-

An error tuple is returned on error. The error reason may -be any Erlang term.

-

A common error is eaddrinuse. It indicates that the port -configured for Cowboy is already in use.

-
-
-
+

An ok tuple is returned on success. It contains the pid of the top-level supervisor for the listener.

+

An error tuple is returned on error. The error reason may be any Erlang term.

+

A common error is eaddrinuse. It indicates that the port configured for Cowboy is already in use.

Changelog

-
-
    -
  • -

    -2.0: HTTP/2 support added. -

    +
    • 2.0: HTTP/2 support added.
    • -
    • -

      -2.0: Function introduced. Replaces cowboy:start_https/4. -

      +
    • 2.0: Function introduced. Replaces cowboy:start_https/4.
    • -
-
-
-
+

Examples

-
-
-
Start a listener
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []}
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []}
     ]}
 ]),
 
-{ok, _} = cowboy:start_tls(example, [
-    {port, 8443},
-    {cert, "path/to/cert.pem"}
+{ok, _} = cowboy:start_tls(example, [
+    {port, 8443},
+    {cert, "path/to/cert.pem"}
 ], #{
-    env => #{dispatch => Dispatch}
-}).
-
-
Start a listener on a random port
-
-
Name = example,
+
Name = example,
 
-{ok, _} = cowboy:start_tls(Name, [
-    {cert, "path/to/cert.pem"}
+{ok, _} = cowboy:start_tls(Name, [
+    {cert, "path/to/cert.pem"}
 ], #{
-    env => #{dispatch => Dispatch}
+    env => #{dispatch => Dispatch}
 }),
 
-Port = ranch:get_port(Name).
-
-
-
+Port = ranch:get_port(Name). +

See also

- - +

cowboy(3), cowboy:start_clear(3), cowboy:stop_listener(3), ranch(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy.stop_listener/index.html b/docs/en/cowboy/2.3/manual/cowboy.stop_listener/index.html index 0fc6df10..8fbdeef2 100644 --- a/docs/en/cowboy/2.3/manual/cowboy.stop_listener/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy.stop_listener/index.html @@ -62,87 +62,42 @@

cowboy:stop_listener(3)

-

Name

-
-

cowboy:stop_listener - Stop the given listener

-
-
-
+

cowboy:stop_listener - Stop the given listener

Description

-
-
-
-
stop_listener(Name :: ranch:ref())
-    -> ok | {error, not_found}.
-

Stop a previously started listener.

- -
-
-
+
stop_listener(Name :: ranch:ref())
+    -> ok | {error, not_found}.
+
+

Stop a previously started listener.

+

Alias of ranch:stop_listener(3).

Arguments

-
-
-
-Name -
-
-

-The name of the listener to be stopped. -

-

The name of the listener is the first argument given to the -cowboy:start_clear(3), -cowboy:start_tls(3) or -ranch:start_listener(3) function.

+
Name
+

The name of the listener to be stopped.

+

The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function.

-
-
- -
+

Return value

-
-

The atom ok is returned on success.

-

The {error, not_found} tuple is returned when the listener -does not exist.

-
-
-
+

The atom ok is returned on success.

+

The {error, not_found} tuple is returned when the listener does not exist.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Stop a listener
-
-
ok = cowboy:stop_listener(example).
-
-
-
+
ok = cowboy:stop_listener(example).
+

See also

- - +

cowboy(3), cowboy:start_clear(3), cowboy:start_tls(3), ranch(3), ranch:start_listener(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy/index.html b/docs/en/cowboy/2.3/manual/cowboy/index.html index 0b551dfa..9ea56c9e 100644 --- a/docs/en/cowboy/2.3/manual/cowboy/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy/index.html @@ -62,129 +62,76 @@

cowboy(3)

-

Name

-
-

cowboy - HTTP server

-
-
-
+

cowboy - HTTP server

Description

-
-

The module cowboy provides convenience functions for -manipulating Ranch listeners.

-
-
-
+

The module cowboy provides convenience functions for manipulating Ranch listeners.

Exports

-
-
-
-
-
+

Types

-
-

fields()

-
-
-
fields() :: [Name
-           | {Name, Constraints}
-           | {Name, Constraints, Default}]
-
-Name        :: atom()
-Constraints :: Constraint | [Constraint]
-Constraint  :: cowboy_constraints:constraint()
-Default     :: any()
-

Fields description for match operations.

-

This type is used in cowboy_router(3) -for matching bindings and in the match functions found in -cowboy_req(3).

-
-
+
fields() :: [Name
+           | {Name, Constraints}
+           | {Name, Constraints, Default}]
+
+Name        :: atom()
+Constraints :: Constraint | [Constraint]
+Constraint  :: cowboy_constraints:constraint()
+Default     :: any()
+
+

Fields description for match operations.

+

This type is used in cowboy_router(3) for matching bindings and in the match functions found in cowboy_req(3).

http_headers()

-
-
-
http_headers() :: #{binary() => iodata()}
-

HTTP headers.

-
-
+
http_headers() :: #{binary() => iodata()}
+
+

HTTP headers.

http_status()

-
-
-
http_status() :: non_neg_integer() | binary()
-

HTTP response status.

-

A binary status can be used to set a reason phrase. Note -however that HTTP/2 only sends the status code and drops -the reason phrase entirely.

- -
+
http_status() :: non_neg_integer() | binary()
+
+

HTTP response status.

+

A binary status can be used to set a reason phrase. Note however that HTTP/2 only sends the status code and drops the reason phrase entirely.

http_version()

-
-
-
http_version() :: 'HTTP/2' | 'HTTP/1.1' | 'HTTP/1.0'
-

HTTP version.

-

Note that semantically, HTTP/1.1 and HTTP/2 are equivalent.

- -
+
http_version() :: 'HTTP/2' | 'HTTP/1.1' | 'HTTP/1.0'
+
+

HTTP version.

+

Note that semantically, HTTP/1.1 and HTTP/2 are equivalent.

opts()

-
-
-
opts() :: map()
-

Options for the HTTP/1.1, HTTP/2 and Websocket protocols.

-

The protocol options are in a map containing all the options for -the different protocols that may be involved when connecting -to the listener, including HTTP/1.1 and HTTP/2.

-

The HTTP/1.1 options are documented in the -cowboy_http(3) manual -and the HTTP/2 options in -cowboy_http2(3).

- - - -
+
opts() :: map()
+
+

Options for the HTTP/1.1, HTTP/2 and Websocket protocols.

+

The protocol options are in a map containing all the options for the different protocols that may be involved when connecting to the listener, including HTTP/1.1 and HTTP/2.

+

The HTTP/1.1 options are documented in the cowboy_http(3) manual and the HTTP/2 options in cowboy_http2(3).

See also

- - +

cowboy(7), ranch(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_app/index.html b/docs/en/cowboy/2.3/manual/cowboy_app/index.html index 906a1178..9512bd6a 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_app/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_app/index.html @@ -62,171 +62,77 @@

cowboy(7)

-

Name

-
-

cowboy - Small, fast, modern HTTP server for Erlang/OTP

-
-
-
+

cowboy - Small, fast, modern HTTP server for Erlang/OTP

Description

-
-

Cowboy is an HTTP server for Erlang/OTP with support for the -HTTP/1.1, HTTP/2 and Websocket protocols.

-

Cowboy aims to provide a complete HTTP stack. This includes -the implementation of the HTTP RFCs but also any directly -related standards, like Websocket or Server-Sent Events.

-
-
-
+

Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols.

+

Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events.

Modules

-
-

Functions:

-
-

Protocols:

-
+

Protocols:

+
-

Handlers:

-
+

Handlers:

+
-

Behaviors:

-
+

Behaviors:

+
-

Middlewares:

-
+

Middlewares:

+
-
-
-
+ +

Dependencies

-
-
    -
  • -

    -ranch(7) - Socket acceptor pool for TCP protocols -

    +
    • ranch(7) - Socket acceptor pool for TCP protocols
    • -
    • -

      -cowlib(7) - Support library for manipulating Web protocols -

      +
    • cowlib(7) - Support library for manipulating Web protocols
    • -
    • -

      -ssl - Secure communication over sockets -

      +
    • ssl - Secure communication over sockets
    • -
    • -

      -crypto - Crypto functions -

      +
    • crypto - Crypto functions
    • -
-

All these applications must be started before the cowboy -application. To start Cowboy and all dependencies at once:

-
-
-
{ok, _} = application:ensure_all_started(cowboy).
-
-
-
+
{ok, _} = application:ensure_all_started(cowboy).
+

Environment

-
-

The cowboy application does not define any application -environment configuration parameters.

-
- -
+

The cowboy application does not define any application environment configuration parameters.

See also

- -
+

ranch(7), cowlib(7)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_constraints.int/index.html b/docs/en/cowboy/2.3/manual/cowboy_constraints.int/index.html index 6153fcbf..67a2c938 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_constraints.int/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_constraints.int/index.html @@ -62,92 +62,52 @@

cowboy_constraints:int(3)

-

Name

-
-

cowboy_constraints:int - Integer constraint

-
-
-
+

cowboy_constraints:int - Integer constraint

Description

-
-

Constraint functions implement a number of different operations.

-
-
-
int(forward, Bin) -> {ok, Int} | {error, not_an_integer}
+
int(forward, Bin) -> {ok, Int} | {error, not_an_integer}
 
-Bin :: binary()
-Int :: integer()
-

Validate and convert the text representation of an integer.

-
-
-
int(reverse, Int) -> {ok, Bin} | {error, not_an_integer}
-

Convert an integer back to its text representation.

-
-
-
int(format_error, Error) -> HumanReadable
+
int(format_error, Error) -> HumanReadable
 
-Error         :: {not_an_integer, Bin | Int}
-HumanReadable :: iolist()
-

Generate a human-readable error message.

-
-
-
+Error :: {not_an_integer, Bin | Int} +HumanReadable :: iolist() +
+

Generate a human-readable error message.

Arguments

-
-

Arguments vary depending on the operation. Constraint -functions always take the operation type as first argument, -and the value as second argument.

-
- -
+

Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument.

Return value

-
-

The return value varies depending on the operation.

-
-
-
+

The return value varies depending on the operation.

Changelog

-
-
    -
  • -

    -2.0: Interface modified to allow for a variety of operations. -

    +
    • 2.0: Interface modified to allow for a variety of operations.
    • -
    • -

      -1.0: Constraint introduced. -

      +
    • 1.0: Constraint introduced.
    • -
-
-
-
+

Examples

-
-

This function is not meant to be called directly.

-
-
-
+

This function is not meant to be called directly.

See also

- -
+

cowboy_constraints(3), cowboy_constraints:nonempty(3), cowboy_router(3), cowboy_req:match_cookies(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_constraints.nonempty/index.html b/docs/en/cowboy/2.3/manual/cowboy_constraints.nonempty/index.html index cc14ce3c..8578be2c 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_constraints.nonempty/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_constraints.nonempty/index.html @@ -62,91 +62,51 @@

cowboy_constraints:nonempty(3)

-

Name

-
-

cowboy_constraints:nonempty - Non-empty constraint

-
-
-
+

cowboy_constraints:nonempty - Non-empty constraint

Description

-
-

Constraint functions implement a number of different operations.

-
-
-
nonempty(forward | reverse, <<>>) -> {error, empty}
-

Reject empty values.

-
-
-
nonempty(forward | reverse, Bin) -> {ok, Bin}
+
nonempty(forward | reverse, Bin) -> {ok, Bin}
 
-Bin :: binary()
-

Accept any other binary values.

-
-
-
nonempty(format_error, Error) -> HumanReadable
+
nonempty(format_error, Error) -> HumanReadable
 
-Error         :: {empty, Bin}
-HumanReadable :: iolist()
-

Generate a human-readable error message.

-
-
-
+Error :: {empty, Bin} +HumanReadable :: iolist() +
+

Generate a human-readable error message.

Arguments

-
-

Arguments vary depending on the operation. Constraint -functions always take the operation type as first argument, -and the value as second argument.

-
- -
+

Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument.

Return value

-
-

The return value varies depending on the operation.

-
-
-
+

The return value varies depending on the operation.

Changelog

-
-
    -
  • -

    -2.0: Interface modified to allow for a variety of operations. -

    +
    • 2.0: Interface modified to allow for a variety of operations.
    • -
    • -

      -1.0: Constraint introduced. -

      +
    • 1.0: Constraint introduced.
    • -
-
-
-
+

Examples

-
-

This function is not meant to be called directly.

-
-
-
+

This function is not meant to be called directly.

See also

- -
+

cowboy_constraints(3), cowboy_constraints:int(3), cowboy_router(3), cowboy_req:match_cookies(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_constraints/index.html b/docs/en/cowboy/2.3/manual/cowboy_constraints/index.html index 6de9597b..8f0ebbbf 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_constraints/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_constraints/index.html @@ -62,84 +62,43 @@

cowboy_constraints(3)

-

Name

-
-

cowboy_constraints - Constraints

-
-
-
+

cowboy_constraints - Constraints

Description

-
-

The module cowboy_constraints defines the built-in -constraints in Cowboy and provides an interface for -manipulating these constraints.

-

Constraints are functions that define what type of -input is allowed. They are used throughout Cowboy, -from the router to query strings to cookies.

-
-
-
+

The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints.

+

Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies.

Exports

-
-

Built-in constraints:

-
-
-
-
+

Types

-
-

constraint()

-
-
-
constraint() :: int | nonempty | fun()
-

A constraint function.

-

The atom constraints are built-in, see the corresponding -function in the exports list above.

-
-
+
constraint() :: int | nonempty | fun()
+
+

A constraint function.

+

The atom constraints are built-in, see the corresponding function in the exports list above.

reason()

-
-
-
reason() :: {constraint(), Reason, Value}
-
-Reason :: any()
-Value  :: any()
-

Reason for the constraint failure.

-

It includes the constraint function in question, -a machine-readable error reason and the value that -made the constraint fail.

-
- - -
+
reason() :: {constraint(), Reason, Value}
+
+Reason :: any()
+Value  :: any()
+
+

Reason for the constraint failure.

+

It includes the constraint function in question, a machine-readable error reason and the value that made the constraint fail.

See also

- - +

cowboy(7), cowboy(3), cowboy_router(3), cowboy_req:match_cookies(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_handler.terminate/index.html b/docs/en/cowboy/2.3/manual/cowboy_handler.terminate/index.html index dd9d24f4..c1050fa3 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_handler.terminate/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_handler.terminate/index.html @@ -62,109 +62,54 @@

cowboy_handler:terminate(3)

-

Name

-
-

cowboy_handler:terminate - Terminate the handler

-
-
-
+

cowboy_handler:terminate - Terminate the handler

Description

-
-
-
-
terminate(Reason, PartialReq, State, Handler) -> ok
-
-Reason     :: any()
-PartialReq :: map()
-State      :: any()
-Handler    :: module()
-

Call the optional terminate callback if it is defined.

-

Make sure to use this function at the end of the execution -of modules that implement custom handler behaviors.

-
-
-
+
terminate(Reason, PartialReq, State, Handler) -> ok
+
+Reason     :: any()
+PartialReq :: map()
+State      :: any()
+Handler    :: module()
+
+

Call the optional terminate callback if it is defined.

+

Make sure to use this function at the end of the execution of modules that implement custom handler behaviors.

Arguments

-
-
-
-Reason -
-
-

-Reason for termination. -

+
Reason
+

Reason for termination.

-
-PartialReq -
-
-

-The Req object. -

-

It is possible to remove fields from the Req object to save memory -when the handler has no concept of requests/responses. The only -requirement is that a map is provided.

+
PartialReq
+

The Req object.

+

It is possible to remove fields from the Req object to save memory when the handler has no concept of requests/responses. The only requirement is that a map is provided.

-
-State -
-
-

-Handler state. -

+
State
+

Handler state.

-
-Handler -
-
-

-Handler module. -

+
Handler
+

Handler module.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Terminate a handler normally
-
-
cowboy_handler:terminate(normal, Req, State, Handler).
-
-
-
+
cowboy_handler:terminate(normal, Req, State, Handler).
+

See also

- - +

cowboy_handler(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_handler/index.html b/docs/en/cowboy/2.3/manual/cowboy_handler/index.html index 88eed6c6..def10074 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_handler/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_handler/index.html @@ -62,96 +62,46 @@

cowboy_handler(3)

-

Name

-
-

cowboy_handler - Plain HTTP handlers

-
-
-
+

cowboy_handler - Plain HTTP handlers

Description

-
-

The cowboy_handler middleware executes the handler selected -by the router or any other preceding middleware.

-

This middleware takes the handler module and initial state -from the handler and handler_opts environment values, -respectively. On completion, it adds a result value to -the middleware environment, containing the return value -of the terminate/3 callback (if defined) and ok otherwise.

-

This module also defines a callback interface for handling -HTTP requests.

-
-
-
+

The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware.

+

This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise.

+

This module also defines a callback interface for handling HTTP requests.

Callbacks

-
-

Plain HTTP handlers implement the following interface:

-
-
-
init(Req, State) -> {ok, Req, State}
-
-terminate(Reason, Req, State) -> ok  %% optional
-
-Req    :: cowboy_req:req()
-State  :: any()
-Reason :: normal
-        | {crash, error | exit | throw, any()}
-

These two callbacks are common to all handlers.

-

Plain HTTP handlers do all their work in the init/2 -callback. Returning ok terminates the handler. If no -response is sent, Cowboy will send a 204 No Content.

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the handler. -Cowboy will terminate the process right after this. There -is no need to perform any cleanup in this callback.

-

The following terminate reasons are defined for plain HTTP -handlers:

-
-
-normal -
-
-

- The connection was closed normally. -

+
init(Req, State) -> {ok, Req, State}
+
+terminate(Reason, Req, State) -> ok  %% optional
+
+Req    :: cowboy_req:req()
+State  :: any()
+Reason :: normal
+        | {crash, error | exit | throw, any()}
+
+

These two callbacks are common to all handlers.

+

Plain HTTP handlers do all their work in the init/2 callback. Returning ok terminates the handler. If no response is sent, Cowboy will send a 204 No Content.

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the handler. Cowboy will terminate the process right after this. There is no need to perform any cleanup in this callback.

+

The following terminate reasons are defined for plain HTTP handlers:

+
normal
+

The connection was closed normally.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
- - -
+

Exports

-
-

The following function should be called by modules implementing -custom handlers to execute the optional terminate callback:

-
-
-
-
+

See also

- -
+

cowboy(7)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_http/index.html b/docs/en/cowboy/2.3/manual/cowboy_http/index.html index 12b29e27..4268bfef 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_http/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_http/index.html @@ -62,255 +62,116 @@

cowboy_http(3)

-

Name

-
-

cowboy_http - HTTP/1.1

-
-
-
+

cowboy_http - HTTP/1.1

Description

-
-

The module cowboy_http implements HTTP/1.1 and HTTP/1.0 -as a Ranch protocol.

-
-
-
+

The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol.

Options

-
-
-
+ +
-
opts() :: #{
-    connection_type         => worker | supervisor,
-    env                     => cowboy_middleware:env(),
-    idle_timeout            => timeout(),
-    inactivity_timeout      => timeout(),
-    max_empty_lines         => non_neg_integer(),
-    max_header_name_length  => non_neg_integer(),
-    max_header_value_length => non_neg_integer(),
-    max_headers             => non_neg_integer(),
-    max_keepalive           => non_neg_integer(),
-    max_method_length       => non_neg_integer(),
-    max_request_line_length => non_neg_integer(),
-    max_skip_body_length    => non_neg_integer(),
-    middlewares             => [module()],
-    request_timeout         => timeout(),
-    shutdown_timeout        => timeout(),
-    stream_handlers         => [module()]
-}
-

Configuration for the HTTP/1.1 protocol.

-

This configuration is passed to Cowboy when starting listeners -using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

-

It can be updated without restarting listeners using the -Ranch functions ranch:get_protocol_options/1 and -ranch:set_protocol_options/2.

-

The default value is given next to the option name:

-
-
-connection_type (supervisor) -
-
-

- Whether the connection process also acts as a supervisor. -

-
-
-env (#{}) -
-
-

- Middleware environment. -

-
-
-idle_timeout (60000) -
-
-

- Time in ms with no data received before Cowboy closes the connection. -

-
-
-inactivity_timeout (300000) -
-
-

- Time in ms with nothing received at all before Cowboy closes the connection. -

-
-
-max_empty_lines (5) -
-
-

- Maximum number of empty lines before a request. -

-
-
-max_header_name_length (64) -
-
-

- Maximum length of header names. -

-
-
-max_header_value_length (4096) -
-
-

- Maximum length of header values. -

-
-
-max_headers (100) -
-
-

- Maximum number of headers allowed per request. -

-
-
-max_keepalive (100) -
-
-

- Maximum number of requests allowed per connection. -

-
-
-max_method_length (32) -
-
-

- Maximum length of the method. -

-
-
-max_request_line_length (8000) -
-
-

- Maximum length of the request line. -

-
-
-max_skip_body_length (1000000) -
-
-

- Maximum length Cowboy is willing to skip when the user code did not read the body fully. - When the remaining length is too large or unknown Cowboy will close the connection. -

-
-
-middlewares ([cowboy_router, cowboy_handler]) -
-
-

- Middlewares to run for every request. -

-
-
-request_timeout (5000) -
-
-

- Time in ms with no requests before Cowboy closes the connection. -

-
-
-shutdown_timeout (5000) -
-
-

- Time in ms Cowboy will wait for child processes to shut down before killing them. -

-
-
-stream_handlers ([cowboy_stream_h]) -
-
-

- Ordered list of stream handlers that will handle all stream events. -

-
-
-
-
-
+
opts() :: #{
+    connection_type         => worker | supervisor,
+    env                     => cowboy_middleware:env(),
+    idle_timeout            => timeout(),
+    inactivity_timeout      => timeout(),
+    max_empty_lines         => non_neg_integer(),
+    max_header_name_length  => non_neg_integer(),
+    max_header_value_length => non_neg_integer(),
+    max_headers             => non_neg_integer(),
+    max_keepalive           => non_neg_integer(),
+    max_method_length       => non_neg_integer(),
+    max_request_line_length => non_neg_integer(),
+    max_skip_body_length    => non_neg_integer(),
+    middlewares             => [module()],
+    request_timeout         => timeout(),
+    shutdown_timeout        => timeout(),
+    stream_handlers         => [module()]
+}
+
+

Configuration for the HTTP/1.1 protocol.

+

This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

+

It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2.

+

The default value is given next to the option name:

+
connection_type (supervisor)
+

Whether the connection process also acts as a supervisor.

+
+
env (#{})
+

Middleware environment.

+
+
idle_timeout (60000)
+

Time in ms with no data received before Cowboy closes the connection.

+
+
inactivity_timeout (300000)
+

Time in ms with nothing received at all before Cowboy closes the connection.

+
+
max_empty_lines (5)
+

Maximum number of empty lines before a request.

+
+
max_header_name_length (64)
+

Maximum length of header names.

+
+
max_header_value_length (4096)
+

Maximum length of header values.

+
+
max_headers (100)
+

Maximum number of headers allowed per request.

+
+
max_keepalive (100)
+

Maximum number of requests allowed per connection.

+
+
max_method_length (32)
+

Maximum length of the method.

+
+
max_request_line_length (8000)
+

Maximum length of the request line.

+
+
max_skip_body_length (1000000)
+

Maximum length Cowboy is willing to skip when the user code did not read the body fully. When the remaining length is too large or unknown Cowboy will close the connection.

+
+
middlewares ([cowboy_router, cowboy_handler])
+

Middlewares to run for every request.

+
+
request_timeout (5000)
+

Time in ms with no requests before Cowboy closes the connection.

+
+
shutdown_timeout (5000)
+

Time in ms Cowboy will wait for child processes to shut down before killing them.

+
+
stream_handlers ([cowboy_stream_h])
+

Ordered list of stream handlers that will handle all stream events.

+
+

Changelog

-
-
    -
  • -

    -2.2: The max_skip_body_length option was added. -

    +
    • 2.2: The max_skip_body_length option was added.
    • -
    • -

      -2.0: The timeout option was renamed request_timeout. -

      +
    • 2.0: The timeout option was renamed request_timeout.
    • -
    • -

      -2.0: The idle_timeout, inactivity_timeout and shutdown_timeout options were added. -

      +
    • 2.0: The idle_timeout, inactivity_timeout and shutdown_timeout options were added.
    • -
    • -

      -2.0: The max_method_length option was added. -

      +
    • 2.0: The max_method_length option was added.
    • -
    • -

      -2.0: The max_request_line_length default was increased from 4096 to 8000. -

      +
    • 2.0: The max_request_line_length default was increased from 4096 to 8000.
    • -
    • -

      -2.0: The connection_type option was added. -

      +
    • 2.0: The connection_type option was added.
    • -
    • -

      -2.0: The env option is now a map instead of a proplist. -

      +
    • 2.0: The env option is now a map instead of a proplist.
    • -
    • -

      -2.0: The stream_handlers option was added. -

      +
    • 2.0: The stream_handlers option was added.
    • -
    • -

      -2.0: The compress option was removed in favor of the cowboy_compress_h stream handler. -

      +
    • 2.0: The compress option was removed in favor of the cowboy_compress_h stream handler.
    • -
    • -

      -2.0: Options are now a map instead of a proplist. -

      +
    • 2.0: Options are now a map instead of a proplist.
    • -
    • -

      -2.0: Protocol introduced. Replaces cowboy_protocol. -

      +
    • 2.0: Protocol introduced. Replaces cowboy_protocol.
    • -
-
-
- +

cowboy(7), cowboy_http2(3), cowboy_websocket(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_http2/index.html b/docs/en/cowboy/2.3/manual/cowboy_http2/index.html index 90954f46..dd72ba7f 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_http2/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_http2/index.html @@ -62,123 +62,60 @@

cowboy_http2(3)

-

Name

-
-

cowboy_http2 - HTTP/2

-
-
-
+

cowboy_http2 - HTTP/2

Description

-
-

The module cowboy_http2 implements HTTP/2 -as a Ranch protocol.

-
-
-
+

The module cowboy_http2 implements HTTP/2 as a Ranch protocol.

Options

-
-
-
+ +
-
opts() :: #{
-    connection_type    => worker | supervisor,
-    env                => cowboy_middleware:env(),
-    inactivity_timeout => timeout(),
-    middlewares        => [module()],
-    preface_timeout    => timeout(),
-    shutdown_timeout   => timeout(),
-    stream_handlers    => [module()]
-}
-

Configuration for the HTTP/2 protocol.

-

This configuration is passed to Cowboy when starting listeners -using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

-

It can be updated without restarting listeners using the -Ranch functions ranch:get_protocol_options/1 and -ranch:set_protocol_options/2.

-

The default value is given next to the option name:

-
-
-connection_type (supervisor) -
-
-

- Whether the connection process also acts as a supervisor. -

+
opts() :: #{
+    connection_type    => worker | supervisor,
+    env                => cowboy_middleware:env(),
+    inactivity_timeout => timeout(),
+    middlewares        => [module()],
+    preface_timeout    => timeout(),
+    shutdown_timeout   => timeout(),
+    stream_handlers    => [module()]
+}
+
+

Configuration for the HTTP/2 protocol.

+

This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

+

It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2.

+

The default value is given next to the option name:

+
connection_type (supervisor)
+

Whether the connection process also acts as a supervisor.

-
-env (#{}) -
-
-

- Middleware environment. -

+
env (#{})
+

Middleware environment.

-
-inactivity_timeout (300000) -
-
-

- Time in ms with nothing received at all before Cowboy closes the connection. -

+
inactivity_timeout (300000)
+

Time in ms with nothing received at all before Cowboy closes the connection.

-
-middlewares ([cowboy_router, cowboy_handler]) -
-
-

- Middlewares to run for every request. -

+
middlewares ([cowboy_router, cowboy_handler])
+

Middlewares to run for every request.

-
-preface_timeout (5000) -
-
-

- Time in ms Cowboy is willing to wait for the connection preface. -

+
preface_timeout (5000)
+

Time in ms Cowboy is willing to wait for the connection preface.

-
-shutdown_timeout (5000) -
-
-

- Time in ms Cowboy will wait for child processes to shut down before killing them. -

+
shutdown_timeout (5000)
+

Time in ms Cowboy will wait for child processes to shut down before killing them.

-
-stream_handlers ([cowboy_stream_h]) -
-
-

- Ordered list of stream handlers that will handle all stream events. -

+
stream_handlers ([cowboy_stream_h])
+

Ordered list of stream handlers that will handle all stream events.

-
-
-
-
+

Changelog

-
-
    -
  • -

    -2.0: Protocol introduced. -

    +
    • 2.0: Protocol introduced.
    • -
-
-
- +

cowboy(7), cowboy_http(3), cowboy_websocket(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_loop/index.html b/docs/en/cowboy/2.3/manual/cowboy_loop/index.html index 2b9b57ff..d4e2f459 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_loop/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_loop/index.html @@ -62,120 +62,60 @@

cowboy_loop(3)

-

Name

-
-

cowboy_loop - Loop handlers

-
-
-
+

cowboy_loop - Loop handlers

Description

-
-

The module cowboy_loop defines a callback interface for -long running HTTP connections.

-

You should switch to this behavior for long polling, -server-sent events and similar long-running requests.

-

There are generally two usage patterns:

-
    -
  • -

    -Loop until receiving a specific message, then send - a response and stop execution (for example long polling); -

    +

    The module cowboy_loop defines a callback interface for long running HTTP connections.

    +

    You should switch to this behavior for long polling, server-sent events and similar long-running requests.

    +

    There are generally two usage patterns:

    +
    • Loop until receiving a specific message, then send a response and stop execution (for example long polling);
    • -
    • -

      -Or initiate a response in init/2 and stream the - body in info/3 as necessary (for example server-sent events). -

      +
    • Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events).
    • -
-
-
-
+

Callbacks

-
-

Loop handlers implement the following interface:

-
-
-
init(Req, State)
-    -> {cowboy_loop, Req, State}
-     | {cowboy_loop, Req, State, hibernate}
-
-info(Info, Req, State)
-    -> {ok, Req, State}
-     | {ok, Req, State, hibernate}
-     | {stop, Req, State}
-
-terminate(Reason, Req, State) -> ok  %% optional
-
-Req    :: cowboy_req:req()
-State  :: any()
-Info   :: any()
-Reason :: stop
-        | {crash, error | exit | throw, any()}
-

The init/2 callback is common to all handlers. To switch -to the loop behavior, it must return cowboy_loop as the -first element of the tuple.

-

The info/3 callback will be called for every Erlang message -received. It may choose to continue the receive loop or stop -it.

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the handler. -Cowboy will terminate the process right after this. There -is no need to perform any cleanup in this callback.

-

The following terminate reasons are defined for loop handlers:

-
-
-stop -
-
-

- The handler requested to close the connection by returning - a stop tuple. -

+
init(Req, State)
+    -> {cowboy_loop, Req, State}
+     | {cowboy_loop, Req, State, hibernate}
+
+info(Info, Req, State)
+    -> {ok, Req, State}
+     | {ok, Req, State, hibernate}
+     | {stop, Req, State}
+
+terminate(Reason, Req, State) -> ok  %% optional
+
+Req    :: cowboy_req:req()
+State  :: any()
+Info   :: any()
+Reason :: stop
+        | {crash, error | exit | throw, any()}
+
+

The init/2 callback is common to all handlers. To switch to the loop behavior, it must return cowboy_loop as the first element of the tuple.

+

The info/3 callback will be called for every Erlang message received. It may choose to continue the receive loop or stop it.

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the handler. Cowboy will terminate the process right after this. There is no need to perform any cleanup in this callback.

+

The following terminate reasons are defined for loop handlers:

+
stop
+

The handler requested to close the connection by returning a stop tuple.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
- - -
+

Changelog

-
-
    -
  • -

    -2.0: Loop handlers no longer need to handle overflow/timeouts. -

    +
    • 2.0: Loop handlers no longer need to handle overflow/timeouts.
    • -
    • -

      -1.0: Behavior introduced. -

      +
    • 1.0: Behavior introduced.
    • -
-
-
-
+

See also

- -
+

cowboy(7), cowboy_handler(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_middleware/index.html b/docs/en/cowboy/2.3/manual/cowboy_middleware/index.html index 200af7f6..7dc3e2bf 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_middleware/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_middleware/index.html @@ -62,115 +62,56 @@

cowboy_middleware(3)

-

Name

-
-

cowboy_middleware - Middlewares

-
-
-
+

cowboy_middleware - Middlewares

Description

-
-

The module cowboy_middleware defines a callback interface for -Cowboy middlewares.

-

Middlewares process the request sequentially in the order they -are configured.

-
-
-
+

The module cowboy_middleware defines a callback interface for Cowboy middlewares.

+

Middlewares process the request sequentially in the order they are configured.

Callbacks

-
-

Middlewares implement the following interface:

-
-
-
execute(Req, Env)
-    -> {ok, Req, Env}
-     | {suspend, module(), atom(), [any()]}
-     | {stop, Req}
-
-Req :: cowboy_req:req()
-Env :: cowboy_middleware:env()
-

The execute/2 is the only callback that needs to be -implemented. It must execute the middleware and return -with instructions for Cowboy.

-
-
-ok -
-
-

-Cowboy should continue processing the request using the -returned Req object and environment. -

+
execute(Req, Env)
+    -> {ok, Req, Env}
+     | {suspend, module(), atom(), [any()]}
+     | {stop, Req}
+
+Req :: cowboy_req:req()
+Env :: cowboy_middleware:env()
+
+

The execute/2 is the only callback that needs to be implemented. It must execute the middleware and return with instructions for Cowboy.

+
ok
+

Cowboy should continue processing the request using the returned Req object and environment.

-
-suspend -
-
-

-Cowboy will hibernate the process. When resuming, Cowboy -will apply the returned module, function and arguments. -

+
suspend
+

Cowboy will hibernate the process. When resuming, Cowboy will apply the returned module, function and arguments.

-
-stop -
-
-

-Cowboy will stop middleware execution. No other middleware -will be executed. This effectively ends the processing of -the request. -

+
stop
+

Cowboy will stop middleware execution. No other middleware will be executed. This effectively ends the processing of the request.

-
- - -
+

Types

-
-

env()

-
-
-
env() :: #{atom() => any()}
-

Middleware environment.

-

A new environment is created for every request. The initial -environment contained the user configured environment values -(like dispatch for example) plus the listener value which -contains the name of the listener for this connection.

-

Middlewares may modify the environment as necessary.

-
-
-
-
+
env() :: #{atom() => any()}
+
+

Middleware environment.

+

A new environment is created for every request. The initial environment contained the user configured environment values (like dispatch for example) plus the listener value which contains the name of the listener for this connection.

+

Middlewares may modify the environment as necessary.

Changelog

-
-
    -
  • -

    -2.0: The env type is now a map instead of a proplist. -

    +
    • 2.0: The env type is now a map instead of a proplist.
    • -
    • -

      -1.0: Behavior introduced. -

      +
    • 1.0: Behavior introduced.
    • -
-
- -
+

See also

- -
+

cowboy(7)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.binding/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.binding/index.html index 16e29645..46822b72 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.binding/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.binding/index.html @@ -62,116 +62,60 @@

cowboy_req:binding(3)

-

Name

-
-

cowboy_req:binding - Access a value bound from the route

-
-
-
+

cowboy_req:binding - Access a value bound from the route

Description

-
-
-
-
binding(Name, Req)          -> binding(Name, Req, undefined)
-binding(Name, Req, Default) -> any() | Default
-
-Name    :: atom()
-Req     :: cowboy_req:req()
-Default :: any()
-

Return the value for the given binding.

-
-
-
+
binding(Name, Req)          -> binding(Name, Req, undefined)
+binding(Name, Req, Default) -> any() | Default
+
+Name    :: atom()
+Req     :: cowboy_req:req()
+Default :: any()
+
+

Return the value for the given binding.

Arguments

-
-
-
-Name -
-
-

-Desired binding name as an atom. -

+
Name
+

Desired binding name as an atom.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the binding is missing. -

+
Default
+

Default value returned when the binding is missing.

-
-
- -
+

Return value

-
-

By default the value is a case sensitive binary string, however -constraints may change the type of this value (for example -automatically converting numbers to integer).

-
-
-
+

By default the value is a case sensitive binary string, however constraints may change the type of this value (for example automatically converting numbers to integer).

Changelog

-
-
    -
  • -

    -2.0: Only the value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the username from the path
-
-
%% Route is "/users/:user"
-Username = cowboy_req:binding(user, Req).
-
-
Get the branch name, with a default
-
-
%% Route is "/log[/:branch]"
-Branch = cowboy_req:binding(branch, Req, <<"master">>)
-
-
-
+
%% Route is "/log[/:branch]"
+Branch = cowboy_req:binding(branch, Req, <<"master">>)
+

See also

- - +

cowboy_req(3), cowboy_req:bindings(3), cowboy_req:host_info(3), cowboy_req:path_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.bindings/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.bindings/index.html index 8bbcd4aa..0054626b 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.bindings/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.bindings/index.html @@ -62,86 +62,40 @@

cowboy_req:bindings(3)

-

Name

-
-

cowboy_req:bindings - Access all values bound from the route

-
-
-
+

cowboy_req:bindings - Access all values bound from the route

Description

-
-
-
-
bindings(Req :: cowboy_req:req()) -> cowboy_router:bindings()
-

Return a map containing all bindings.

-
-
-
+
bindings(Req :: cowboy_req:req()) -> cowboy_router:bindings()
+
+

Return a map containing all bindings.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

By default values are case sensitive binary strings, however -constraints may change the type of this value (for example -automatically converting numbers to integer).

-
-
-
+

By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer).

Changelog

-
-
    -
  • -

    -2.0: Only the values are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the values are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get all bindings
-
-
Bindings = cowboy_req:bindings(Req).
-
-
-
+
Bindings = cowboy_req:bindings(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:host_info(3), cowboy_req:path_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.body_length/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.body_length/index.html index 262456a0..9818d81e 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.body_length/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.body_length/index.html @@ -62,89 +62,41 @@

cowboy_req:body_length(3)

-

Name

-
-

cowboy_req:body_length - Body length

-
-
-
+

cowboy_req:body_length - Body length

Description

-
-
-
-
body_length(Req :: cowboy_req:req()) -> undefined | non_neg_integer()
-

Return the length of the request body.

-

The length is not always known before reading the body. -In those cases Cowboy will return undefined. The body -length is available after the body has been fully read.

-
-
-
+
body_length(Req :: cowboy_req:req()) -> undefined | non_neg_integer()
+
+

Return the length of the request body.

+

The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The length of the request body, or undefined if it is -not known.

-
-
-
+

The length of the request body, or undefined if it is not known.

Changelog

-
-
    -
  • -

    -2.0: Only the length is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the length is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the body length
-
-
Length = cowboy_req:body_length(Req).
-
-
-
+
Length = cowboy_req:body_length(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.cert/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.cert/index.html index e6cc2839..699bd3fe 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.cert/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.cert/index.html @@ -62,104 +62,60 @@

cowboy_req:cert(3)

-

Name

-
-

cowboy_req:cert - Client TLS certificate

-
-
-
+

cowboy_req:cert - Client TLS certificate

Description

-
-
-
-
cert(Req :: cowboy_req:req()) -> binary() | undefined
-

Return the peer’s TLS certificate.

-

Using the default configuration this function will always return -undefined. You need to explicitly configure Cowboy to request -the client certificate. To do this you need to set the verify -transport option to verify_peer:

-
-
-
{ok, _} = cowboy:start_tls(example, [
-    {port, 8443},
-    {cert, "path/to/cert.pem"},
-    {verify, verify_peer}
+
{ok, _} = cowboy:start_tls(example, [
+    {port, 8443},
+    {cert, "path/to/cert.pem"},
+    {verify, verify_peer}
 ], #{
-    env => #{dispatch => Dispatch}
-}).
-

You may also want to customize the verify_fun function. Please -consult the ssl application’s manual for more details.

-

TCP connections do not allow a certificate and this function -will therefore always return undefined.

-

The certificate can also be obtained using pattern matching:

-
-
-
#{cert := Cert} = Req.
-
-
-
+
#{cert := Cert} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The client TLS certificate.

-
-
-
+

The client TLS certificate.

Changelog

-
-
    -
  • -

    -2.1: Function introduced. -

    +
    • 2.1: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the client TLS certificate.
-
-
Cert = cowboy_req:cert(Req).
-
-
-
+
Cert = cowboy_req:cert(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:peer(3), cowboy_req:sock(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.delete_resp_header/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.delete_resp_header/index.html index 64cd7b63..3fbe5288 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.delete_resp_header/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.delete_resp_header/index.html @@ -62,95 +62,45 @@

cowboy_req:delete_resp_header(3)

-

Name

-
-

cowboy_req:delete_resp_header - Delete a response header

-
-
-
+

cowboy_req:delete_resp_header - Delete a response header

Description

-
-
-
-
delete_resp_header(Name, Req :: cowboy_req:req()) -> Req
+
delete_resp_header(Name, Req :: cowboy_req:req()) -> Req
 
-Name :: binary()  %% lowercase; case insensitive
-

Delete the given response header.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+Name :: binary() %% lowercase; case insensitive +
+

Delete the given response header.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Name -
-
-

-Header name as a lowercase binary string. -

+
Name
+

Header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the header will still be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the header will still be sent in the response.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Remove the content-type header from the response
-
-
Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),
-
-
-
+
Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:has_resp_header(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.has_body/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.has_body/index.html index 1de52c2a..de71a7c7 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.has_body/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.has_body/index.html @@ -62,80 +62,38 @@

cowboy_req:has_body(3)

-

Name

-
-

cowboy_req:has_body - Is there a request body?

-
-
-
+

cowboy_req:has_body - Is there a request body?

Description

-
-
-
-
has_body(Req :: cowboy_req:req()) -> boolean()
-

Return whether the request has a body.

-
-
-
+
has_body(Req :: cowboy_req:req()) -> boolean()
+
+

Return whether the request has a body.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A boolean indicating whether the request has a body.

-
-
-
+

A boolean indicating whether the request has a body.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Ensure the request has a body
-
-
true = cowboy_req:has_body(Req).
-
-
-
+
true = cowboy_req:has_body(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.has_resp_body/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.has_resp_body/index.html index 2426ed09..914ca182 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.has_resp_body/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.has_resp_body/index.html @@ -62,82 +62,43 @@

cowboy_req:has_resp_body(3)

-

Name

-
-

cowboy_req:has_resp_body - Is there a response body?

-
-
-
+

cowboy_req:has_resp_body - Is there a response body?

Description

-
-
-
-
has_resp_body(Req :: cowboy_req:req()) -> boolean()
-

Return whether a response body has been set.

-
-
-
+
has_resp_body(Req :: cowboy_req:req()) -> boolean()
+
+

Return whether a response body has been set.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A boolean indicating whether a response body has been set.

-

This function will return false when an empty response -body has been set.

-
-
-
+

A boolean indicating whether a response body has been set.

+

This function will return false when an empty response body has been set.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Check whether a body has been set
-
-
false = cowboy_req:has_resp_body(Req0),
-Req1 = cowboy_req:set_resp_body(<<"Hello!">>, Req0),
-true = cowboy_req:has_resp_body(Req1),
-Req = cowboy_req:set_resp_body(<<>>, Req1),
-false = cowboy_req:has_resp_body(Req).
-
-
-
+
false = cowboy_req:has_resp_body(Req0),
+Req1 = cowboy_req:set_resp_body(<<"Hello!">>, Req0),
+true = cowboy_req:has_resp_body(Req1),
+Req = cowboy_req:set_resp_body(<<>>, Req1),
+false = cowboy_req:has_resp_body(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_body(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.has_resp_header/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.has_resp_header/index.html index 769cd656..fdd8112d 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.has_resp_header/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.has_resp_header/index.html @@ -62,95 +62,46 @@

cowboy_req:has_resp_header(3)

-

Name

-
-

cowboy_req:has_resp_header - Is the given response header set?

-
-
-
+

cowboy_req:has_resp_header - Is the given response header set?

Description

-
-
-
-
has_resp_header(Name, Req :: cowboy_req:req()) -> boolean()
+
has_resp_header(Name, Req :: cowboy_req:req()) -> boolean()
 
-Name :: binary()  %% lowercase; case insensitive
-

Return whether the given response header has been set.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+Name :: binary() %% lowercase; case insensitive +
+

Return whether the given response header has been set.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Name -
-
-

-Header name as a lowercase binary string. -

+
Name
+

Header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A boolean indicating whether the given response header has been set.

-
-
-
+

A boolean indicating whether the given response header has been set.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Check whether the content-type header has been set
-
-
false = cowboy_req:has_resp_header(<<"content-type">>, Req0),
-Req = cowboy_req:set_resp_header(<<"content-type">>, <<"text/html">>, Req0),
-true = cowboy_req:has_resp_header(<<"content-type">>, Req).
-
-
-
+
false = cowboy_req:has_resp_header(<<"content-type">>, Req0),
+Req = cowboy_req:set_resp_header(<<"content-type">>, <<"text/html">>, Req0),
+true = cowboy_req:has_resp_header(<<"content-type">>, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3), cowboy_req:delete_resp_header(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.header/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.header/index.html index 37651c85..b7c45c53 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.header/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.header/index.html @@ -62,122 +62,67 @@

cowboy_req:header(3)

-

Name

-
-

cowboy_req:header - HTTP header

-
-
-
+

cowboy_req:header - HTTP header

Description

-
-
-
-
header(Name, Req)          -> header(Name, Req, undefined)
-header(Name, Req, Default) -> binary() | Default
-
-Name    :: binary()          %% lowercase; case insensitive
-Req     :: cowboy_req:req()
-Default :: any()
-

Return the value for the given HTTP header.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Headers can also be obtained using pattern matching:

-
-
-
#{headers := #{Name := Value}} = Req.
-

Note that this snippet will crash if the header is missing.

-
-
-
+
#{headers := #{Name := Value}} = Req.
+
+

Note that this snippet will crash if the header is missing.

Arguments

-
-
-
-Name -
-
-

-Desired HTTP header name as a lowercase binary string. -

+
Name
+

Desired HTTP header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the header is missing. -

+
Default
+

Default value returned when the header is missing.

-
-
- -
+

Return value

-
-

The header value is returned as a binary string. When the -header is missing, the default argument is returned.

-
-
-
+

The header value is returned as a binary string. When the header is missing, the default argument is returned.

Changelog

-
-
    -
  • -

    -2.0: Only the header value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the header value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the accept header
-
-
Accept = cowboy_req:header(<<"accept">>, Req).
-
-
Get the content-length header with a default value
-
-
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).
-
-
-
+
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).
+

See also

- - +

cowboy_req(3), cowboy_req:headers(3), cowboy_req:parse_header(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.headers/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.headers/index.html index be20a74b..5b8af10f 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.headers/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.headers/index.html @@ -62,90 +62,47 @@

cowboy_req:headers(3)

-

Name

-
-

cowboy_req:headers - HTTP headers

-
-
-
+

cowboy_req:headers - HTTP headers

Description

-
-
-
-
headers(Req :: cowboy_req:req()) -> cowboy:http_headers()
-

Return all request headers.

-

Request headers can also be obtained using pattern matching:

-
-
-
#{headers := Headers} = Req.
-
-
-
+
#{headers := Headers} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Headers are returned as a map with keys being lowercase -binary strings, and values as binary strings.

-
-
-
+

Headers are returned as a map with keys being lowercase binary strings, and values as binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the headers are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the headers are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get all headers
-
-
Headers = cowboy_req:headers(Req).
-
-
-
+
Headers = cowboy_req:headers(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:header(3), cowboy_req:parse_header(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.host/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.host/index.html index 11f1f6c2..25e40330 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.host/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.host/index.html @@ -62,91 +62,47 @@

cowboy_req:host(3)

-

Name

-
-

cowboy_req:host - URI host name

-
-
-
+

cowboy_req:host - URI host name

Description

-
-
-
-
host(Req :: cowboy_req:req()) -> Host :: binary()
-

Return the host name of the effective request URI.

-

The host name can also be obtained using pattern matching:

-
-
-
#{host := Host} = Req.
-
-
-
+
#{host := Host} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The host name is returned as a lowercase binary string. -It is case insensitive.

-
-
-
+

The host name is returned as a lowercase binary string. It is case insensitive.

Changelog

-
-
    -
  • -

    -2.0: Only the host name is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the host name is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s host name
-
-
Host = cowboy_req:host(Req).
-
-
-
+
Host = cowboy_req:host(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:host_info(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.host_info/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.host_info/index.html index 17a45108..eb9336d0 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.host_info/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.host_info/index.html @@ -62,87 +62,41 @@

cowboy_req:host_info(3)

-

Name

-
-

cowboy_req:host_info - Access the route’s heading host segments

-
-
-
+

cowboy_req:host_info - Access the route's heading host segments

Description

-
-
-
-
host_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
-

Return the tokens for the heading host segments.

-

This is the part of the host name that was matched using -the ... notation.

-
-
-
+
host_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
+
+

Return the tokens for the heading host segments.

+

This is the part of the host name that was matched using the ... notation.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The tokens are returned as a list of case insensitive -binary strings.

-
-
-
+

The tokens are returned as a list of case insensitive binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the tokens are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the host_info tokens
-
-
HostInfo = cowboy_req:host_info(Req).
-
-
-
+
HostInfo = cowboy_req:host_info(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:path_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.inform/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.inform/index.html index a94d8fe5..66a0f468 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.inform/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.inform/index.html @@ -62,125 +62,66 @@

cowboy_req:inform(3)

-

Name

-
-

cowboy_req:inform - Send an informational response

-
-
-
+

cowboy_req:inform - Send an informational response

Description

-
-
-
-
inform(Status, Req :: cowboy_req:req())
-    -> inform(StatusCode, #{}, Req)
-
-inform(Status, Headers, Req :: cowboy_req:req())
-    -> ok
-
-Status  :: cowboy:http_status()
-Headers :: cowboy:http_headers()
-

Send an informational response.

-

Informational responses use a status code between 100 and 199. -They cannot include a body. This function will not use any -of the previously set headers. All headers to be sent must -be given directly.

-

Any number of informational responses can be sent as long as -they are sent before the proper response. Attempting to use -this function after sending a normal response will result -in an error.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+
inform(Status, Req :: cowboy_req:req())
+    -> inform(StatusCode, #{}, Req)
+
+inform(Status, Headers, Req :: cowboy_req:req())
+    -> ok
+
+Status  :: cowboy:http_status()
+Headers :: cowboy:http_headers()
+
+

Send an informational response.

+

Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly.

+

Any number of informational responses can be sent as long as they are sent before the proper response. Attempting to use this function after sending a normal response will result in an error.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Status -
-
-

-The status code for the response. -

+
Status
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Req -
-
-

-The Req object. -

+
+

Header names must be given as lowercase binary strings.

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.1: Function introduced. -

    +
    • 2.1: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Send an informational response
-
-
Req = cowboy_req:inform(102, Req0).
-
-
Send an informational response with headers
-
-
Req = cowboy_req:inform(103, #{
-    <<"link">> => <<"</style.css>; rel=preload; as=style">>,
-    <<"link">> => <<"</script.js>; rel=preload; as=script">>
-}, Req0).
-
-
-
+
Req = cowboy_req:inform(103, #{
+    <<"link">> => <<"</style.css>; rel=preload; as=style">>,
+    <<"link">> => <<"</script.js>; rel=preload; as=script">>
+}, Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:reply(3), cowboy_req:stream_reply(3), cowboy_req:push(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.match_cookies/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.match_cookies/index.html index 251bd7e2..7403f023 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.match_cookies/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.match_cookies/index.html @@ -62,123 +62,67 @@

cowboy_req:match_cookies(3)

-

Name

-
-

cowboy_req:match_cookies - Match cookies against constraints

-
-
-
+

cowboy_req:match_cookies - Match cookies against constraints

Description

-
-
-
-
match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req())
-    -> #{atom() => any()}
-

Parse the cookies and match specific values against -constraints.

-

Cowboy will only return the cookie values specified in the -fields list, and ignore all others. Fields can be either -the name of the cookie requested; the name along with a -list of constraints; or the name, a list of constraints -and a default value in case the cookie is missing.

-

This function will crash if the cookie is missing and no -default value is provided. This function will also crash -if a constraint fails.

-

The name of the cookie must be provided as an atom. The -key of the returned map will be that atom. The value may -be converted through the use of constraints, making this -function able to extract, validate and convert values all -in one step.

-
-
-
+
match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req())
+    -> #{atom() => any()}
+
+

Parse the cookies and match specific values against constraints.

+

Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing.

+

This function will crash if the cookie is missing and no default value is provided. This function will also crash if a constraint fails.

+

The name of the cookie must be provided as an atom. The key of the returned map will be that atom. The value may be converted through the use of constraints, making this function able to extract, validate and convert values all in one step.

Arguments

-
-
-
-Fields -
-
-

-Cookies to retrieve. -

-

See cowboy(3) for a complete description.

+
Fields
+

Cookies to retrieve.

+

See cowboy(3) for a complete description.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Desired values are returned as a map. The key is the atom -that was given in the list of fields, and the value is the -optionally converted value after applying constraints.

-

The map contains the same keys that were given in the fields.

-

An exception is triggered when the match fails.

-
-
-
+

Desired values are returned as a map. The key is the atom that was given in the list of fields, and the value is the optionally converted value after applying constraints.

+

The map contains the same keys that were given in the fields.

+

An exception is triggered when the match fails.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Match fields
-
-
%% ID and Lang are binaries.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_cookies([id, lang], Req).
-
-
Match fields and apply constraints
-
-
%% ID is an integer and Lang a non-empty binary.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_cookies([{id, int}, {lang, nonempty}], Req).
-
-
Match fields with default values
-
-
#{lang := Lang}
-    = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
-
-
-
+
#{lang := Lang}
+    = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
+

See also

- - +

cowboy_req(3), cowboy_req:parse_cookies(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.match_qs/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.match_qs/index.html index 14396da6..a5eaf848 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.match_qs/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.match_qs/index.html @@ -62,123 +62,67 @@

cowboy_req:match_qs(3)

-

Name

-
-

cowboy_req:match_qs - Match the query string against constraints

-
-
-
+

cowboy_req:match_qs - Match the query string against constraints

Description

-
-
-
-
match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req())
-    -> #{atom() => any()}
-

Parse the query string and match specific values against -constraints.

-

Cowboy will only return the query string values specified -in the fields list, and ignore all others. Fields can be -either the key requested; the key along with a list of -constraints; or the key, a list of constraints and a -default value in case the key is missing.

-

This function will crash if the key is missing and no -default value is provided. This function will also crash -if a constraint fails.

-

The key must be provided as an atom. The key of the -returned map will be that atom. The value may be converted -through the use of constraints, making this function able -to extract, validate and convert values all in one step.

-
-
-
+
match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req())
+    -> #{atom() => any()}
+
+

Parse the query string and match specific values against constraints.

+

Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing.

+

This function will crash if the key is missing and no default value is provided. This function will also crash if a constraint fails.

+

The key must be provided as an atom. The key of the returned map will be that atom. The value may be converted through the use of constraints, making this function able to extract, validate and convert values all in one step.

Arguments

-
-
-
-Fields -
-
-

-Fields to retrieve from the query string. -

-

See cowboy(3) for a complete description.

+
Fields
+

Fields to retrieve from the query string.

+

See cowboy(3) for a complete description.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Desired values are returned as a map. The key is the atom -that was given in the list of fields, and the value is the -optionally converted value after applying constraints.

-

The map contains the same keys that were given in the fields.

-

An exception is triggered when the match fails.

-
-
-
+

Desired values are returned as a map. The key is the atom that was given in the list of fields, and the value is the optionally converted value after applying constraints.

+

The map contains the same keys that were given in the fields.

+

An exception is triggered when the match fails.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Match fields
-
-
%% ID and Lang are binaries.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_qs([id, lang], Req).
-
-
Match fields and apply constraints
-
-
%% ID is an integer and Lang a non-empty binary.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req).
-
-
Match fields with default values
-
-
#{lang := Lang}
-    = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
-
-
-
+
#{lang := Lang}
+    = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
+

See also

- - +

cowboy_req(3), cowboy_req:qs(3), cowboy_req:parse_qs(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.method/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.method/index.html index 38140e1f..514abc5e 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.method/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.method/index.html @@ -62,100 +62,58 @@

cowboy_req:method(3)

-

Name

-
-

cowboy_req:method - HTTP method

-
-
-
+

cowboy_req:method - HTTP method

Description

-
-
-
-
method(Req :: cowboy_req:req()) -> Method :: binary()
-

Return the request’s HTTP method.

-

The method can also be obtained using pattern matching:

-
-
-
#{method := Method} = Req.
-
-
-
+
#{method := Method} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The request’s HTTP method is returned as a binary string. -While methods are case sensitive, standard methods are -always uppercase.

-
-
-
+

The request's HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase.

Changelog

-
-
    -
  • -

    -2.0: Only the method is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the method is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Ensure the request’s method is GET
-
-
<<"GET">> = cowboy_req:method(Req).
-
-
Allow methods from list
-
-
init(Req, State) ->
-    case lists:member(cowboy_req:method(Req), [<<"GET">>, <<"POST">>]) of
-        true -> handle(Req, State);
-        false -> method_not_allowed(Req, State)
-    end.
-
-
-
+
init(Req, State) ->
+    case lists:member(cowboy_req:method(Req), [<<"GET">>, <<"POST">>]) of
+        true -> handle(Req, State);
+        false -> method_not_allowed(Req, State)
+    end.
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.parse_cookies/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.parse_cookies/index.html index 813c331f..855d20ad 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.parse_cookies/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.parse_cookies/index.html @@ -62,91 +62,47 @@

cowboy_req:parse_cookies(3)

-

Name

-
-

cowboy_req:parse_cookies - Parse cookie headers

-
-
-
+

cowboy_req:parse_cookies - Parse cookie headers

Description

-
-
-
-
parse_cookies(Req) -> [{Name, Value}]
-
-Name  :: binary() %% case sensitive
-Value :: binary() %% case sensitive
-

Parse cookie headers.

- -

When the cookie header is missing, [] is returned.

-

While an empty cookie header is not valid, some clients do -send it. Cowboy will in this case also return [].

-
-
-
+
parse_cookies(Req) -> [{Name, Value}]
+
+Name  :: binary() %% case sensitive
+Value :: binary() %% case sensitive
+
+

Parse cookie headers.

+

Alias for cowboy_req:parse_header(<<"cookie">>, Req).

+

When the cookie header is missing, [] is returned.

+

While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return [].

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The cookies are returned as a list of key/values. Keys and -values are case sensitive binary strings.

-
-
-
+

The cookies are returned as a list of key/values. Keys and values are case sensitive binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces cookie/2,3 and cookies/1. -

      +
    • 2.0: Function introduced. Replaces cookie/2,3 and cookies/1.
    • -
-
-
-
+

Examples

-
-
-
Look for a specific cookie
-
-
Cookies = cowboy_req:parse_cookies(Req),
-{_, Token} = lists:keyfind(<<"token">>, 1, Cookies).
-
-
-
+
Cookies = cowboy_req:parse_cookies(Req),
+{_, Token} = lists:keyfind(<<"token">>, 1, Cookies).
+

See also

- - +

cowboy_req(3), cowboy_req:parse_header(3), cowboy_req:match_cookies(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.parse_header/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.parse_header/index.html index c199e91b..93cff336 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.parse_header/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.parse_header/index.html @@ -62,283 +62,218 @@

cowboy_req:parse_header(3)

-

Name

-
-

cowboy_req:parse_header - Parse the given HTTP header

-
-
-
+

cowboy_req:parse_header - Parse the given HTTP header

Description

-
-
-
-
parse_header(Name, Req)          -> ParsedValue | Default
-parse_header(Name, Req, Default) -> ParsedValue | Default
-
-Name        :: binary()
-Req         :: cowboy_req:req()
-ParsedValue :: any()
-Default     :: any()
-

Parse the given HTTP header.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

The type of the parsed value varies depending on -the header. Similarly, the default value when calling -cowboy_req:parse_header/2 differs depending on the -header.

-
-
-
+
parse_header(Name, Req)          -> ParsedValue | Default
+parse_header(Name, Req, Default) -> ParsedValue | Default
+
+Name        :: binary()
+Req         :: cowboy_req:req()
+ParsedValue :: any()
+Default     :: any()
+
+

Parse the given HTTP header.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

The type of the parsed value varies depending on the header. Similarly, the default value when calling cowboy_req:parse_header/2 differs depending on the header.

Arguments

-
-
-
-Name -
-
-

-Desired HTTP header name as a lowercase binary string. -

+
Name
+

Desired HTTP header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the header is missing. -

+
Default
+

Default value returned when the header is missing.

-
-
- -
+

Return value

-
-

The parsed header value varies depending on the header. -When the header is missing, the default argument is returned.

-
-
-
+

The parsed header value varies depending on the header. When the header is missing, the default argument is returned.

Headers

-
-

The following snippets detail the types returned by the -different headers. Unless mentioned otherwise, the -default value when the header is missing will be undefined:

-
-
accept
-
-
parse_header(<<"accept">>, Req)
-    -> [{{Type, SubType, Params}, Quality, AcceptExt}]
-
-Type      :: binary()               %% case insensitive
-SubType   :: binary()               %% case insensitive
-Params    :: [{Key, Value}]
-Quality   :: 0..1000
-AcceptExt :: [Key | {Key, Value}]
-Key       :: binary()               %% case insensitive
-Value     :: binary()               %% case sensitive
-
-
accept-charset, accept-encoding and accept-language
-
-
parse_header(Name, Req) -> [{Value, Quality}]
-
-Name    :: <<"accept-charset">>
-         | <<"accept-encoding">>
-         | <<"accept-language">>
-Value   :: binary()                 %% case insensitive
-Quality :: 0..1000
-
-
authorization
-
-
parse_header(<<"authorization">>, Req)
-    -> {basic, Username :: binary(), Password :: binary()}
-     | {bearer, Token :: binary()}
-     | {digest, [{Key :: binary(), Value :: binary()}]}
-
-
content-length
-
+
content-length
+
-
parse_header(<<"content-length">>, Req) -> non_neg_integer()
-

When the content-length header is missing, 0 is returned.

-
-
content-type
-
-
parse_header(<<"content-type">>, Req)
-    -> {Type, SubType, Params}
-
-Type      :: binary()               %% case insensitive
-SubType   :: binary()               %% case insensitive
-Params    :: [{Key, Value}]
-Key       :: binary()               %% case insensitive
-Value     :: binary()               %% case sensitive;
-

Note that the value for the charset parameter is case insensitive -and returned as a lowercase binary string.

-
-
cookie
-
-
parse_header(<<"cookie">>, Req) -> [{Name, Value}]
-
-Name  :: binary()                   %% case sensitive
-Value :: binary()                   %% case sensitive
-

When the cookie header is missing, [] is returned.

-

While an empty cookie header is not valid, some clients do -send it. Cowboy will in this case also return [].

-
-
expect
-
-
parse_header(<<"expect">>, Req) -> continue
-
-
if-match and if-none-match
-
-
parse_header(Name, Req)
-    -> '*' | [{weak | strong, OpaqueTag}]
-
-Name      :: <<"if-match">>
-           | <<"if-none-match">>
-OpaqueTag :: binary()               %% case sensitive
-
-
if-modified-since and if-unmodified-since
-
-
parse_header(Name, Req) -> calendar:datetime()
-
-
range
-
-
parse_header(<<"range">>, Req) -> {From, To} | Final
-
-From  :: non_neg_integer()
-To    :: non_neg_integer() | infinity
-Final :: neg_integer()
-
-
sec-websocket-extensions
-
-
parse_header(<<"sec-websocket-extensions">>, Req)
-    -> [{Extension, Params}]
-
-Extension :: binary()               %% case sensitive
-Params    :: [Key | {Key, Value}]
-Key       :: binary()               %% case sensitive
-Value     :: binary()               %% case sensitive
-
-
sec-websocket-protocol and upgrade
-
-
parse_header(Name, Req) -> [Token]
-
-Name  :: <<"sec-websocket-protocol">>
-       | <<"upgrade">>
-Token :: binary()                   %% case insensitive
-
-
x-forwarded-for
-
-
parse_header(<<"x-forwarded-for">>, Req) -> [Token]
+
parse_header(<<"x-forwarded-for">>, Req) -> [Token]
 
-Token :: binary()                   %% case sensitive
-
-
Unknown headers
-
-
parse_header(_, Req) -> {undefined, RawValue}
-
-
-
+
parse_header(_, Req) -> {undefined, RawValue}
+

Changelog

-
-
    -
  • -

    -2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Parse the accept header with a custom default value
-
-
%% Accept everything when header is missing.
-Accept = cowboy_req:parse_header(<<"accept">>, Req,
-    [{{ <<"*">>, <<"*">>, []}, 1000, []}]).
-
-
Parse the content-length header
-
-
%% Default content-length is 0.
-Length = cowboy_req:header(<<"content-length">>, Req).
-
-
-
+
%% Default content-length is 0.
+Length = cowboy_req:header(<<"content-length">>, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:header(3), cowboy_req:headers(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.parse_qs/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.parse_qs/index.html index 9894f0de..69f99f1b 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.parse_qs/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.parse_qs/index.html @@ -62,117 +62,55 @@

cowboy_req:parse_qs(3)

-

Name

-
-

cowboy_req:parse_qs - Parse the query string

-
-
-
+

cowboy_req:parse_qs - Parse the query string

Description

-
-
-
-
parse_qs(Req :: cowboy_req:req())
-    -> [{Key :: binary(), Value :: binary() | true}]
-

Parse the query string as a list of key/value pairs.

-
-
-
+
parse_qs(Req :: cowboy_req:req())
+    -> [{Key :: binary(), Value :: binary() | true}]
+
+

Parse the query string as a list of key/value pairs.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The parsed query string is returned as a list of key/value pairs. -The key is a binary string. The value is either a binary string, -or the atom true. Both key and value are case sensitive.

-

The atom true is returned when a key is present in the query -string without a value. For example, in the following URIs -the key <<"edit">> will always have the value true:

-
    -
  • -

    -/posts/42?edit -

    +

    The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. Both key and value are case sensitive.

    +

    The atom true is returned when a key is present in the query string without a value. For example, in the following URIs the key <<"edit">> will always have the value true:

    +
    • /posts/42?edit
    • -
    • -

      -/posts/42?edit&exclusive=1 -

      +
    • /posts/42?edit&exclusive=1
    • -
    • -

      -/posts/42?exclusive=1&edit -

      +
    • /posts/42?exclusive=1&edit
    • -
    • -

      -/posts/42?exclusive=1&edit&from=web -

      +
    • /posts/42?exclusive=1&edit&from=web
    • -
-
-
-
+

Changelog

-
-
    -
  • -

    -2.0: The parsed value is not longer cached in the Req object. -

    +
    • 2.0: The parsed value is not longer cached in the Req object.
    • -
    • -

      -2.0: Only the parsed query string is returned, it is no longer wrapped in a tuple. -

      +
    • 2.0: Only the parsed query string is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces qs_val/1 and qs_vals/1. -

      +
    • 2.0: Function introduced. Replaces qs_val/1 and qs_vals/1.
    • -
-
-
-
+

Examples

-
-
-
Parse the query string and convert the keys to atoms
-
-
ParsedQs = cowboy_req:parse_qs(Req),
-AtomsQs = [{binary_to_existing_atom(K, latin1), V}
-    || {K, V} <- ParsedQs].
-
-
-
+
ParsedQs = cowboy_req:parse_qs(Req),
+AtomsQs = [{binary_to_existing_atom(K, latin1), V}
+    || {K, V} <- ParsedQs].
+

See also

- - +

cowboy_req(3), cowboy_req:qs(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.path/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.path/index.html index bc55a705..9432bc45 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.path/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.path/index.html @@ -62,90 +62,47 @@

cowboy_req:path(3)

-

Name

-
-

cowboy_req:path - URI path

-
-
-
+

cowboy_req:path - URI path

Description

-
-
-
-
path(Req :: cowboy_req:req()) -> Path :: binary()
-

Return the path of the effective request URI.

-

The path can also be obtained using pattern matching:

-
-
-
#{path := Path} = Req.
-
-
-
+
#{path := Path} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The path is returned as a binary string. It is case sensitive.

-
-
-
+

The path is returned as a binary string. It is case sensitive.

Changelog

-
-
    -
  • -

    -2.0: Only the path is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the path is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s path
-
-
Path = cowboy_req:path(Req).
-
-
-
+
Path = cowboy_req:path(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:path_info(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.path_info/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.path_info/index.html index 328ae0c5..e03ef029 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.path_info/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.path_info/index.html @@ -62,87 +62,41 @@

cowboy_req:path_info(3)

-

Name

-
-

cowboy_req:path_info - Access the route’s trailing path segments

-
-
-
+

cowboy_req:path_info - Access the route's trailing path segments

Description

-
-
-
-
path_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
-

Return the tokens for the trailing path segments.

-

This is the part of the host name that was matched using -the ... notation.

-
-
-
+
path_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
+
+

Return the tokens for the trailing path segments.

+

This is the part of the host name that was matched using the ... notation.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The tokens are returned as a list of case sensitive -binary strings.

-
-
-
+

The tokens are returned as a list of case sensitive binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the tokens are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the path_info tokens
-
-
PathInfo = cowboy_req:path_info(Req).
-
-
-
+
PathInfo = cowboy_req:path_info(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:host_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.peer/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.peer/index.html index 46d2262b..f9ec4efb 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.peer/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.peer/index.html @@ -62,98 +62,51 @@

cowboy_req:peer(3)

-

Name

-
-

cowboy_req:peer - Peer address and port

-
-
-
+

cowboy_req:peer - Peer address and port

Description

-
-
-
-
peer(Req :: cowboy_req:req()) -> Info
+
peer(Req :: cowboy_req:req()) -> Info
 
-Info :: {inet:ip_address(), inet:port_number()}
-

Return the peer’s IP address and port number.

-

The peer information can also be obtained using pattern matching:

-
-
-
#{peer := {IP, Port}} = Req.
-
-
-
+
#{peer := {IP, Port}} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The peer’s IP address and port number.

-

The peer is not necessarily the client’s IP address and port. -It is the IP address of the endpoint connecting directly to -the server, which may be a gateway or a proxy.

-

The forwarded header can be used to get better information -about the different endpoints from the client to the server. -Note however that it is only informative; there is no reliable -way of determining the source of an HTTP request.

-
-
-
+

The peer's IP address and port number.

+

The peer is not necessarily the client's IP address and port. It is the IP address of the endpoint connecting directly to the server, which may be a gateway or a proxy.

+

The forwarded header can be used to get better information about the different endpoints from the client to the server. Note however that it is only informative; there is no reliable way of determining the source of an HTTP request.

Changelog

-
-
    -
  • -

    -2.0: Only the peer is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the peer is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the peer IP address and port number.
-
-
{IP, Port} = cowboy_req:peer(Req).
-
-
-
+
{IP, Port} = cowboy_req:peer(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:sock(3), cowboy_req:cert(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.port/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.port/index.html index 4d9e6fc7..4e32535c 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.port/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.port/index.html @@ -62,90 +62,48 @@

cowboy_req:port(3)

-

Name

-
-

cowboy_req:port - URI port number

-
-
-
+

cowboy_req:port - URI port number

Description

-
-
-
-
port(Req :: cowboy_req:req()) -> Port :: inet:port_number()
-

Return the port number of the effective request URI.

-

Note that the port number returned by this function is obtained -by parsing the host header. It may be different from the port -the peer used to connect to Cowboy.

-

The port number can also be obtained using pattern matching:

-
-
-
#{port := Port} = Req.
-
-
-
+
#{port := Port} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The port number is returned as an integer.

-
-
-
+

The port number is returned as an integer.

Changelog

-
-
    -
  • -

    -2.0: Only the port number is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the port number is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s port number
-
-
Port = cowboy_req:port(Req).
-
-
-
+
Port = cowboy_req:port(Req).
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.push/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.push/index.html index ac272086..e1238d72 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.push/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.push/index.html @@ -62,142 +62,74 @@

cowboy_req:push(3)

-

Name

-
-

cowboy_req:push - Push a resource to the client

-
-
-
+

cowboy_req:push - Push a resource to the client

Description

-
-
-
-
push(Path, Headers, Req :: cowboy_req:req())
-    -> push(Path, Headers, Req, #{})
-
-push(Path, Headers, Req :: cowboy_req:req(), Opts)
-    -> ok
-
-Path    :: iodata()                %% case sensitive
-Headers :: cowboy:http_headers()
-Opts    :: cowboy_req:push_opts()
-

Push a resource to the client.

-

Cowboy handles push requests the same way as if they came -from the client, including the creation of a request handling -process, routing and middlewares and so on.

-

This function does nothing when the HTTP/1.1 protocol is -used. You may call it safely without first checking whether -the connection uses HTTP/2.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Note that the headers must be the headers the client is expected -to send if it were to perform the request. They are therefore -request headers, and not response headers.

-

By default, Cowboy will use the GET method, an empty query string, -and take the scheme, host and port directly from the current -request’s URI. You can override them by passing options.

-

It is not possible to push resources after sending a response. -Any attempt will result in an error.

-
-
-
+
push(Path, Headers, Req :: cowboy_req:req())
+    -> push(Path, Headers, Req, #{})
+
+push(Path, Headers, Req :: cowboy_req:req(), Opts)
+    -> ok
+
+Path    :: iodata()                %% case sensitive
+Headers :: cowboy:http_headers()
+Opts    :: cowboy_req:push_opts()
+
+

Push a resource to the client.

+

Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on.

+

This function does nothing when the HTTP/1.1 protocol is used. You may call it safely without first checking whether the connection uses HTTP/2.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Note that the headers must be the headers the client is expected to send if it were to perform the request. They are therefore request headers, and not response headers.

+

By default, Cowboy will use the GET method, an empty query string, and take the scheme, host and port directly from the current request's URI. You can override them by passing options.

+

It is not possible to push resources after sending a response. Any attempt will result in an error.

Arguments

-
-
-
-Path -
-
-

-The status code for the response. -

+
Path
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Req -
-
-

-The Req object. -

+
+

Header names must be given as lowercase binary strings.

+
Req
+

The Req object.

-
-Opts -
-
-

-Customize the HTTP method or the URI scheme, host, port -or query string. -

+
Opts
+

Customize the HTTP method or the URI scheme, host, port or query string.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Push a resource
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, Req),
-
-
Push a resource with a custom host
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, #{host => <<"cdn.example.org">>}, Req),
-
-
-
+
cowboy_req:push("/static/style.css", #{
+    <<"accept">> => <<"text/css">>
+}, #{host => <<"cdn.example.org">>}, Req),
+

See also

- - +

cowboy_req(3), cowboy_req:inform(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.qs/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.qs/index.html index 352719b5..482047e2 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.qs/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.qs/index.html @@ -62,89 +62,47 @@

cowboy_req:qs(3)

-

Name

-
-

cowboy_req:qs - URI query string

-
-
-
+

cowboy_req:qs - URI query string

Description

-
-
-
-
qs(Req :: cowboy_req:req()) -> Qs :: binary()
-

Return the query string of the effective request URI.

-

The query string can also be obtained using pattern matching:

-
-
-
#{qs := Qs} = Req.
-
-
-
+
#{qs := Qs} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The query string is returned as a binary string. It is case sensitive.

-
-
-
+

The query string is returned as a binary string. It is case sensitive.

Changelog

-
-
    -
  • -

    -2.0: Only the query string is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the query string is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s query string
-
-
Qs = cowboy_req:qs(Req).
-
-
-
+
Qs = cowboy_req:qs(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:parse_qs(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.read_body/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.read_body/index.html index deceb1ec..d74da7da 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.read_body/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.read_body/index.html @@ -62,143 +62,72 @@

cowboy_req:read_body(3)

-

Name

-
-

cowboy_req:read_body - Read the request body

-
-
-
+

cowboy_req:read_body - Read the request body

Description

-
-
-
-
read_body(Req :: cowboy_req:req())
-    -> read_body(Req, #{})
-
-read_body(Req :: cowboy_req:req(), Opts)
-    -> {ok,   Data :: binary(), Req}
-     | {more, Data :: binary(), Req}
-
-Opts :: cowboy_req:read_body_opts()
-

Read the request body.

-

This function reads a chunk of the request body. A more tuple -is returned when more data remains to be read. Call the function -repeatedly until an ok tuple is returned to read the entire body.

-

An ok tuple with empty data is returned when the request has no body, -or when calling this function again after the body has already -been read. It is therefore safe to call this function directly. -Note that the body can only be read once.

-

This function reads the request body from the connection process. -The connection process is responsible for reading from the socket. -The exact behavior varies depending on the protocol.

-

The options therefore are only related to the communication -between the request process and the connection process.

-

Cowboy will automatically handle protocol details including -the expect header, chunked transfer-encoding and others.

-

Once the body has been read fully, Cowboy sets the content-length -header if it was not previously provided.

-
-
-
+
read_body(Req :: cowboy_req:req())
+    -> read_body(Req, #{})
+
+read_body(Req :: cowboy_req:req(), Opts)
+    -> {ok,   Data :: binary(), Req}
+     | {more, Data :: binary(), Req}
+
+Opts :: cowboy_req:read_body_opts()
+
+

Read the request body.

+

This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body.

+

An ok tuple with empty data is returned when the request has no body, or when calling this function again after the body has already been read. It is therefore safe to call this function directly. Note that the body can only be read once.

+

This function reads the request body from the connection process. The connection process is responsible for reading from the socket. The exact behavior varies depending on the protocol.

+

The options therefore are only related to the communication between the request process and the connection process.

+

Cowboy will automatically handle protocol details including the expect header, chunked transfer-encoding and others.

+

Once the body has been read fully, Cowboy sets the content-length header if it was not previously provided.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. -

-

The length option can be used to request smaller or bigger -chunks of data to be sent. It is a best effort approach, Cowboy -may send more data than configured on occasions. It defaults -to 8MB.

-

The period indicates how long the connection process will wait -before it provides us with the data it received. It defaults -to 15 seconds.

-

The connection process sends data to the request process when -either the length of data or the period of time is reached.

-

The timeout option is a safeguard in case the connection -process becomes unresponsive. The function will crash if no -message was received in that interval. The timeout should be -larger than the period. It defaults to the period + 1 second.

+
Opts
+

A map of body reading options.

+

The length option can be used to request smaller or bigger chunks of data to be sent. It is a best effort approach, Cowboy may send more data than configured on occasions. It defaults to 8MB.

+

The period indicates how long the connection process will wait before it provides us with the data it received. It defaults to 15 seconds.

+

The connection process sends data to the request process when either the length of data or the period of time is reached.

+

The timeout option is a safeguard in case the connection process becomes unresponsive. The function will crash if no message was received in that interval. The timeout should be larger than the period. It defaults to the period
1 second.

-
-
- -
+

Return value

-
-

A more tuple is returned when there are more data to be read.

-

An ok tuple is returned when there are no more data to be read, -either because this is the last chunk of data, the body has already -been read, or there was no body to begin with.

-

The data is always returned as a binary.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

A more tuple is returned when there are more data to be read.

+

An ok tuple is returned when there are no more data to be read, either because this is the last chunk of data, the body has already been read, or there was no body to begin with.

+

The data is always returned as a binary.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces body/1,2. -

    +
    • 2.0: Function introduced. Replaces body/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read the entire body
-
-
read_body(Req0, Acc) ->
-    case cowboy_req:read_body(Req0) of
-        {ok, Data, Req} -> {ok, << Acc/binary, Data/binary >>, Req};
-        {more, Data, Req} -> read_body(Req, << Acc/binary, Data/binary >>)
-    end.
-
-
Read the body in small chunks
-
-
cowboy_req:read_body(Req, #{length => 64000}).
-
-
-
+
cowboy_req:read_body(Req, #{length => 64000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.read_part/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.read_part/index.html index 4a9fa13d..0fa219b0 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.read_part/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.read_part/index.html @@ -62,162 +62,94 @@

cowboy_req:read_part(3)

-

Name

-
-

cowboy_req:read_part - Read the next multipart headers

-
-
-
+

cowboy_req:read_part - Read the next multipart headers

Description

-
-
-
-
read_part(Req :: cowboy_req:req())
-    -> read_part(Req, #{})
-
-read_part(Req :: cowboy_req:req(), Opts)
-    -> {ok, Headers, Req} | {done, Req}
-
-Opts    :: cowboy_req:read_body_opts()
-Headers :: #{binary() => binary()}
-

Read the next part of a multipart body.

-

This function reads the request body and parses it as -multipart. Each parts of a multipart representation have -their own headers and body. This function parses and returns -headers. Examples of multipart media types are -multipart/form-data and multipart/byteranges.

-

Cowboy will skip any data remaining until the beginning of -the next part. This includes the preamble to the multipart -message but also the body of a previous part if it hasn’t -been read. Both are skipped automatically when calling this -function.

-

Cowboy will read the body before parsing in chunks of size -up to 64KB, with a period of 5 seconds. This is tailored for -reading part headers and might not be the most efficient for -skipping the previous part’s body.

-

The headers returned are MIME headers, NOT HTTP headers. -They can be parsed using the functions from the cow_multipart -module. In addition, the cow_multipart:form_data/1 function -can be used to quickly extract information from multipart/form-data -representations.

-

Once a part has been read, it can not be read again.

-

Once the body has been read, Cowboy sets the content-length -header if it was not previously provided.

-
-
-
+
read_part(Req :: cowboy_req:req())
+    -> read_part(Req, #{})
+
+read_part(Req :: cowboy_req:req(), Opts)
+    -> {ok, Headers, Req} | {done, Req}
+
+Opts    :: cowboy_req:read_body_opts()
+Headers :: #{binary() => binary()}
+
+

Read the next part of a multipart body.

+

This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. Examples of multipart media types are multipart/form-data and multipart/byteranges.

+

Cowboy will skip any data remaining until the beginning of the next part. This includes the preamble to the multipart message but also the body of a previous part if it hasn't been read. Both are skipped automatically when calling this function.

+

Cowboy will read the body before parsing in chunks of size up to 64KB, with a period of 5 seconds. This is tailored for reading part headers and might not be the most efficient for skipping the previous part's body.

+

The headers returned are MIME headers, NOT HTTP headers. They can be parsed using the functions from the cow_multipart module. In addition, the cow_multipart:form_data/1 function can be used to quickly extract information from multipart/form-data representations.

+ +

Once a part has been read, it can not be read again.

+

Once the body has been read, Cowboy sets the content-length header if it was not previously provided.

+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. Please refer to -cowboy_req:read_body(3) -for details about each option. -

-

This function defaults the length to 64KB and the period -to 5 seconds.

+
Opts
+

A map of body reading options. Please refer to cowboy_req:read_body(3) for details about each option.

+

This function defaults the length to 64KB and the period to 5 seconds.

-
-
- -
+

Return value

-
-

An ok tuple is returned containing the next part’s headers -as a map.

-

A done tuple is returned if there are no more parts to read.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

An ok tuple is returned containing the next part's headers as a map.

+

A done tuple is returned if there are no more parts to read.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces part/1,2. -

    +
    • 2.0: Function introduced. Replaces part/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read all parts
-
-
acc_multipart(Req0, Acc) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, Headers, Req1} ->
-            {ok, Body, Req} = stream_body(Req1, <<>>),
-            acc_multipart(Req, [{Headers, Body}|Acc]);
-        {done, Req} ->
-            {lists:reverse(Acc), Req}
-    end.
-
-stream_body(Req0, Acc) ->
-    case cowboy_req:read_part_body(Req0) of
-        {more, Data, Req} ->
-            stream_body(Req, << Acc/binary, Data/binary >>);
-        {ok, Data, Req} ->
-            {ok, << Acc/binary, Data/binary >>, Req}
-    end.
-
-
Read all part headers, skipping bodies
-
-
skip_body_multipart(Req0, Acc) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, Headers, Req} ->
-            skip_body_multipart(Req, [Headers|Acc]);
-        {done, Req} ->
-            {lists:reverse(Acc), Req}
-    end.
-
-
Read a part header in larger chunks
-
-
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).
-
-
-
+
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.read_part_body/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.read_part_body/index.html index 21947796..d08ee13e 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.read_part_body/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.read_part_body/index.html @@ -62,130 +62,70 @@

cowboy_req:read_part_body(3)

-

Name

-
-

cowboy_req:read_part_body - Read the current part’s body

-
-
-
+

cowboy_req:read_part_body - Read the current part's body

Description

-
-
-
-
read_part_body(Req :: cowboy_req:req())
-    -> read_part_body(Req, #{})
-
-read_part_body(Req :: cowboy_req:req(), Opts)
-    -> {ok,   Data :: binary(), Req}
-     | {more, Data :: binary(), Req}
-
-Opts :: cowboy_req:read_body_opts()
-

Read the body of the current part of the multipart message.

-

This function reads the request body and parses it as -multipart. Each parts of a multipart representation have -their own headers and body. This function returns the -body of the current part. Examples of multipart media types -are multipart/form-data and multipart/byteranges.

-

This function reads a chunk of the part’s body. A more tuple -is returned when more data remains to be read. Call the function -repeatedly until an ok tuple is returned to read the entire body.

-

Once a part has been read, it can not be read again.

-

Once the body has been read, Cowboy sets the content-length -header if it was not previously provided.

-
-
-
+
read_part_body(Req :: cowboy_req:req())
+    -> read_part_body(Req, #{})
+
+read_part_body(Req :: cowboy_req:req(), Opts)
+    -> {ok,   Data :: binary(), Req}
+     | {more, Data :: binary(), Req}
+
+Opts :: cowboy_req:read_body_opts()
+
+

Read the body of the current part of the multipart message.

+

This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function returns the body of the current part. Examples of multipart media types are multipart/form-data and multipart/byteranges.

+

This function reads a chunk of the part's body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body.

+

Once a part has been read, it can not be read again.

+

Once the body has been read, Cowboy sets the content-length header if it was not previously provided.

+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. Please refer to -cowboy_req:read_body(3) -for details about each option. -

-

This function uses the same default options as the -cowboy_req:read_body(3) -function.

+
Opts
+

A map of body reading options. Please refer to cowboy_req:read_body(3) for details about each option.

+

This function uses the same default options as the cowboy_req:read_body(3) function.

-
-
- -
+

Return value

-
-

A more tuple is returned when there are more data to be read.

-

An ok tuple is returned when there are no more data to be read.

-

The data is always returned as a binary.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

A more tuple is returned when there are more data to be read.

+

An ok tuple is returned when there are no more data to be read.

+

The data is always returned as a binary.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces part_body/1,2. -

    +
    • 2.0: Function introduced. Replaces part_body/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read a full part’s body
-
-
stream_body(Req0, Acc) ->
-    case cowboy_req:read_part_body(Req0) of
-        {more, Data, Req} ->
-            stream_body(Req, << Acc/binary, Data/binary >>);
-        {ok, Data, Req} ->
-            {ok, << Acc/binary, Data/binary >>, Req}
-    end.
-
-
Ensure a part’s body is smaller than 64KB
-
-
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).
-
-
-
+
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.read_urlencoded_body/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.read_urlencoded_body/index.html index 23b33f3e..7f229d60 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.read_urlencoded_body/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.read_urlencoded_body/index.html @@ -62,126 +62,64 @@

cowboy_req:read_urlencoded_body(3)

-

Name

-
-

cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body

-
-
-
+

cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body

Description

-
-
-
-
read_urlencoded_body(Req :: cowboy_req:req())
-    -> read_urlencoded_body(Req, #{})
-
-read_urlencoded_body(Req :: cowboy_req:req(), Opts)
-    -> {ok, Body, Req}
-
-Opts :: cowboy_req:read_body_opts()
-Body :: [{Key :: binary(), Value :: binary() | true}]
-

Read and parse a urlencoded request body.

-

This function reads the request body and parses it as -application/x-www-form-urlencoded. It returns a list -of key/values.

-

The urlencoded media type is used by Web browsers when -submitting HTML forms using the POST method.

-

Cowboy needs to read the full body before parsing. By default -it will read bodies of size up to 64KB. It is possible to -provide options to read larger bodies if required.

-

Cowboy will automatically handle protocol details including -the expect header, chunked transfer-encoding and others.

-

Once the body has been read, Cowboy sets the content-length -header if it was not previously provided.

-

This function can only be called once. Calling it again will -result in undefined behavior.

-
-
-
+
read_urlencoded_body(Req :: cowboy_req:req())
+    -> read_urlencoded_body(Req, #{})
+
+read_urlencoded_body(Req :: cowboy_req:req(), Opts)
+    -> {ok, Body, Req}
+
+Opts :: cowboy_req:read_body_opts()
+Body :: [{Key :: binary(), Value :: binary() | true}]
+
+

Read and parse a urlencoded request body.

+

This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values.

+

The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method.

+

Cowboy needs to read the full body before parsing. By default it will read bodies of size up to 64KB. It is possible to provide options to read larger bodies if required.

+

Cowboy will automatically handle protocol details including the expect header, chunked transfer-encoding and others.

+

Once the body has been read, Cowboy sets the content-length header if it was not previously provided.

+

This function can only be called once. Calling it again will result in undefined behavior.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. Please refer to -cowboy_req:read_body(3) -for details about each option. -

-

This function defaults the length to 64KB and the period -to 5 seconds.

+
Opts
+

A map of body reading options. Please refer to cowboy_req:read_body(3) for details about each option.

+

This function defaults the length to 64KB and the period to 5 seconds.

-
-
- -
+

Return value

-
-

An ok tuple is returned containing a list of key/values found -in the body.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

An ok tuple is returned containing a list of key/values found in the body.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces body_qs/1,2. -

    +
    • 2.0: Function introduced. Replaces body_qs/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read a urlencoded body
-
-
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0),
-{_, Lang} = lists:keyfind(<<"lang">>, 1, Body).
-
-
Allow large urlencoded bodies
-
-
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).
-
-
-
+
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.reply/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.reply/index.html index 602df6ad..564db588 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.reply/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.reply/index.html @@ -62,165 +62,87 @@

cowboy_req:reply(3)

-

Name

-
-

cowboy_req:reply - Send the response

-
-
-
+

cowboy_req:reply - Send the response

Description

-
-
-
-
reply(Status, Req :: cowboy_req:req())
-    -> reply(StatusCode, #{}, Req)
-
-reply(Status, Headers, Req :: cowboy_req:req())
-    -> Req
-
-reply(Status, Headers, Body, Req :: cowboy_req:req())
-    -> Req
-
-Status  :: cowboy:http_status()
-Headers :: cowboy:http_headers()
-Body    :: cowboy_req:resp_body()
-

Send the response.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may overwrite those set by set_resp_header/3 -and set_resp_headers/2.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-

The reply/2,3 functions will send the body set previously, -if any. The reply/4 function always sends the given body, -overriding any previously set.

-

You do not need to set the content-length header when -sending a response body. Cowboy takes care of it automatically. -You should however provide a content-type header.

-

No further data can be transmitted after this function -returns. This includes the push mechanism. Attempting to -send two replies, or to push resources after a reply has -been sent, will result in an error.

-
-
-
+
reply(Status, Req :: cowboy_req:req())
+    -> reply(StatusCode, #{}, Req)
+
+reply(Status, Headers, Req :: cowboy_req:req())
+    -> Req
+
+reply(Status, Headers, Body, Req :: cowboy_req:req())
+    -> Req
+
+Status  :: cowboy:http_status()
+Headers :: cowboy:http_headers()
+Body    :: cowboy_req:resp_body()
+
+

Send the response.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3 and set_resp_headers/2.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

+

The reply/2,3 functions will send the body set previously, if any. The reply/4 function always sends the given body, overriding any previously set.

+

You do not need to set the content-length header when sending a response body. Cowboy takes care of it automatically. You should however provide a content-type header.

+

No further data can be transmitted after this function returns. This includes the push mechanism. Attempting to send two replies, or to push resources after a reply has been sent, will result in an error.

Arguments

-
-
-
-Status -
-
-

-The status code for the response. -

+
Status
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Body -
-
-

-The body can be either a binary value, an iolist or a -sendfile tuple telling Cowboy to send the contents of -a file. -

+
+

Header names must be given as lowercase binary strings.

+
Body
+

The body can be either a binary value, an iolist or a sendfile tuple telling Cowboy to send the contents of a file.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object should be used from that point onward -as it contains updated information about the state of the request.

-
-
-
+

A new Req object is returned.

+

The returned Req object should be used from that point onward as it contains updated information about the state of the request.

Changelog

-
-
    -
  • -

    -2.0: Only the Req is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the Req is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Reply
-
-
Req = cowboy_req:reply(404, Req0).
-
-
Reply with custom headers
-
-
Req = cowboy_req:reply(401, #{
-    <<"www-authenticate">> => <<"Basic realm=\"erlang.org\"">>
-}, Req0).
-
-
Reply with custom headers and a body
-
-
Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, "Hello world!", Req0).
-
-
-
+
Req = cowboy_req:reply(200, #{
+    <<"content-type">> => <<"text/plain">>
+}, "Hello world!", Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:set_resp_body(3), cowboy_req:inform(3), cowboy_req:stream_reply(3), cowboy_req:push(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.resp_header/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.resp_header/index.html index 1c82f05d..cf70d271 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.resp_header/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.resp_header/index.html @@ -62,113 +62,58 @@

cowboy_req:resp_header(3)

-

Name

-
-

cowboy_req:resp_header - Response header

-
-
-
+

cowboy_req:resp_header - Response header

Description

-
-
-
-
resp_header(Name, Req)          -> resp_header(Name, Req, undefined)
-resp_header(Name, Req, Default) -> binary() | Default
-
-Name    :: binary()          %% lowercase; case insensitive
-Req     :: cowboy_req:req()
-Default :: any()
-

Return the value for the given response header.

-

The response header must have been set previously using -cowboy_req:set_resp_header(3) or -cowboy_req:set_resp_headers(3).

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+
resp_header(Name, Req)          -> resp_header(Name, Req, undefined)
+resp_header(Name, Req, Default) -> binary() | Default
+
+Name    :: binary()          %% lowercase; case insensitive
+Req     :: cowboy_req:req()
+Default :: any()
+
+

Return the value for the given response header.

+

The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3).

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Name -
-
-

-Desired response header name as a lowercase binary string. -

+
Name
+

Desired response header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the header is missing. -

+
Default
+

Default value returned when the header is missing.

-
-
- -
+

Return value

-
-

The header value is returned as a binary string. When the -header is missing, the default argument is returned.

-
-
-
+

The header value is returned as a binary string. When the header is missing, the default argument is returned.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the content-type response header
-
-
Type = cowboy_req:resp_header(<<"content-type">>, Req).
-
-
Get the content-type response header with a default value
-
-
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).
-
-
-
+
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).
+

See also

- - +

cowboy_req(3), cowboy_req:resp_headers(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.resp_headers/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.resp_headers/index.html index dcd1aca6..19110153 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.resp_headers/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.resp_headers/index.html @@ -62,79 +62,38 @@

cowboy_req:resp_headers(3)

-

Name

-
-

cowboy_req:resp_headers - Response headers

-
-
-
+

cowboy_req:resp_headers - Response headers

Description

-
-
-
-
resp_headers(Req :: cowboy_req:req()) -> cowboy:http_headers()
-

Return all response headers.

-
-
-
+
resp_headers(Req :: cowboy_req:req()) -> cowboy:http_headers()
+
+

Return all response headers.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Headers are returned as a map with keys being lowercase -binary strings, and values as binary strings.

-
-
-
+

Headers are returned as a map with keys being lowercase binary strings, and values as binary strings.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get all response headers
-
-
Headers = cowboy_req:resp_headers(Req).
-
-
-
+
Headers = cowboy_req:resp_headers(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:resp_header(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.scheme/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.scheme/index.html index 4c83810f..94763a2c 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.scheme/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.scheme/index.html @@ -62,89 +62,52 @@

cowboy_req:scheme(3)

-

Name

-
-

cowboy_req:scheme - URI scheme

-
-
-
+

cowboy_req:scheme - URI scheme

Description

-
-
-
-
scheme(Req :: cowboy_req:req()) -> Scheme :: binary()
-

Return the scheme of the effective request URI.

-

The scheme can also be obtained using pattern matching:

-
-
-
#{scheme := Scheme} = Req.
-
-
-
+
#{scheme := Scheme} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The scheme is returned as a binary. It is case insensitive.

-

Cowboy will only set the scheme to <<"http">> or <<"https">>.

-
-
-
+

The scheme is returned as a binary. It is case insensitive.

+

Cowboy will only set the scheme to <<"http">> or <<"https">>.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Redirect HTTP to HTTPS
-
-
init(Req0=#{scheme := <<"http">>}, State) ->
-    Req = cowboy_req:reply(302, #{
-        <<"location">> => cowboy_req:uri(Req, #{scheme => <<"https">>})
-    }, Req0),
-    {ok, Req, State};
-init(Req, State) ->
-    {cowboy_rest, Req, State}.
-
-
-
+
init(Req0=#{scheme := <<"http">>}, State) ->
+    Req = cowboy_req:reply(302, #{
+        <<"location">> => cowboy_req:uri(Req, #{scheme => <<"https">>})
+    }, Req0),
+    {ok, Req, State};
+init(Req, State) ->
+    {cowboy_rest, Req, State}.
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_body/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_body/index.html index da393ed3..f48bf4be 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_body/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_body/index.html @@ -62,138 +62,79 @@

cowboy_req:set_resp_body(3)

-

Name

-
-

cowboy_req:set_resp_body - Set the response body

-
-
-
+

cowboy_req:set_resp_body - Set the response body

Description

-
-
-
-
set_resp_body(Body, Req :: cowboy_req:req())
-        -> Req
-
-Body :: cowboy_req:resp_body()
-

Set the response body.

-

The response body will be sent when a reply is initiated. -Note that the functions stream_reply/2,3 and reply/4 -will override the body set by this function.

-

This function can also be used to remove a response body -that was set previously. To do so, simply call this function -with an empty body.

-
-
-
+
set_resp_body(Body, Req :: cowboy_req:req())
+	-> Req
+
+Body :: cowboy_req:resp_body()
+
+

Set the response body.

+

The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function.

+

This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body.

Arguments

-
-
-
-Body -
-
-

-The body can be either a binary value, an iolist or a -sendfile tuple telling Cowboy to send the contents of -a file. -

+
Body
+

The body can be either a binary value, an iolist or a sendfile tuple telling Cowboy to send the contents of a file.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the body will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the body will not be sent in the response.

Changelog

-
-
    -
  • -

    -2.0: The function now accepts a sendfile tuple. -

    +
    • 2.0: The function now accepts a sendfile tuple.
    • -
    • -

      -2.0: The set_resp_body_fun/2,3 functions were removed. -

      +
    • 2.0: The set_resp_body_fun/2,3 functions were removed.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set the response body
-
-
Req = cowboy_req:set_resp_body(<<"Hello world!">>, Req0).
-
-
Set the response body as an iolist
-
-
Req = cowboy_req:set_resp_body([
-    "<html><head><title>",
-    page_title(),
-    "</title></head><body>",
-    page_body(),
-    "</body></html>"
-], Req0).
-
-
Tell Cowboy to send data from a file
-
-
{ok, #file_info{size=Size}} = file:read_file_info(Filename),
-Req = cowboy_req:set_resp_body({sendfile, 0, Size, Filename}, Req0).
-
-
Clear any previously set response body
-
-
Req = cowboy_req:set_resp_body(<<>>, Req0).
-
-
-
+
Req = cowboy_req:set_resp_body(<<>>, Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_cookie/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_cookie/index.html index d26cd71d..f539ceda 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_cookie/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_cookie/index.html @@ -62,167 +62,104 @@

cowboy_req:set_resp_cookie(3)

-

Name

-
-

cowboy_req:set_resp_cookie - Set a cookie

-
-
-
+

cowboy_req:set_resp_cookie - Set a cookie

Description

-
-
-
-
set_resp_cookie(Name, Value, Req :: cowboy_req:req())
-    -> set_resp_cookie(Name, Value, [], Req)
-
-set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts)
-    -> Req
-
-Name  :: binary()                  %% case sensitive
-Value :: iodata()                  %% case sensitive
-Opts  :: cow_cookie:cookie_opts()
-

Set a cookie to be sent with the response.

-

Note that cookie names are case sensitive.

-
-
-
+
set_resp_cookie(Name, Value, Req :: cowboy_req:req())
+    -> set_resp_cookie(Name, Value, [], Req)
+
+set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts)
+    -> Req
+
+Name  :: binary()                  %% case sensitive
+Value :: iodata()                  %% case sensitive
+Opts  :: cow_cookie:cookie_opts()
+
+

Set a cookie to be sent with the response.

+

Note that cookie names are case sensitive.

Arguments

-
-
-
-Name -
-
-

-Cookie name. -

+
Name
+

Cookie name.

-
-Value -
-
-

-Cookie value. -

+
Value
+

Cookie value.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-Cookie options. -

+
Opts
+

Cookie options.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the cookie will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the cookie will not be sent in the response.

Changelog

-
-
    -
  • -

    -2.0: set_resp_cookie/3 introduced as an alias to set_resp_cookie/4 with no options. -

    +
    • 2.0: set_resp_cookie/3 introduced as an alias to set_resp_cookie/4 with no options.
    • -
    • -

      -2.0: The first argument type is now binary() instead of iodata(). -

      +
    • 2.0: The first argument type is now binary() instead of iodata().
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set a session cookie
-
-
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0).
-
-
Set a cookie with an expiration time
-
-
Req = cowboy_req:set_resp_cookie(<<"lang">>, <<"fr-FR">>,
-    Req0, #{max_age => 3600}).
-
-
Delete a cookie
-
-
Req = cowboy_req:set_resp_cookie(<<"sessionid">>, <<>>,
-    Req0, #{max_age => 0}).
-
-
Set a cookie for a specific domain and path
-
-
Req = cowboy_req:set_resp_cookie(<<"inaccount">>, <<"1">>,
-    Req0, #{domain => "my.example.org", path => "/account"}).
-
-
Restrict a cookie to HTTPS
-
-
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID,
-    Req0, #{secure => true}).
-
-
Restrict a cookie to HTTP
-
-
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID,
-    Req0, #{http_only => true}).
-
-
-
+
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
+Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID,
+    Req0, #{http_only => true}).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_header/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_header/index.html index 5877b7f5..fad10beb 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_header/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_header/index.html @@ -62,121 +62,60 @@

cowboy_req:set_resp_header(3)

-

Name

-
-

cowboy_req:set_resp_header - Set a response header

-
-
-
+

cowboy_req:set_resp_header - Set a response header

Description

-
-
-
-
set_resp_header(Name, Value, Req :: cowboy_req:req())
-        -> Req
-
-Name  :: binary()  %% lowercase; case insensitive
-Value :: iodata()  %% case depends on header
-

Set a header to be sent with the response.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may be overwritten by those set from the -reply functions.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-
-
-
+
set_resp_header(Name, Value, Req :: cowboy_req:req())
+	-> Req
+
+Name  :: binary()  %% lowercase; case insensitive
+Value :: iodata()  %% case depends on header
+
+

Set a header to be sent with the response.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

Arguments

-
-
-
-Name -
-
-

-Header name as a lowercase binary string. -

+
Name
+

Header name as a lowercase binary string.

-
-Value -
-
-

-Header value. -

+
Value
+

Header value.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the header will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the header will not be sent in the response.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set a header in the response
-
-
Req = cowboy_req:set_resp_header(<<"allow">>, "GET", Req0).
-
-
Construct a header using iolists
-
-
Req = cowboy_req:set_resp_header(<<"allow">>,
-    [allowed_methods(), ", OPTIONS"], Req0).
-
-
-
+
Req = cowboy_req:set_resp_header(<<"allow">>,
+    [allowed_methods(), ", OPTIONS"], Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_headers(3), cowboy_req:has_resp_header(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3), cowboy_req:delete_resp_header(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_headers/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_headers/index.html index 9b76cc9f..e22407e6 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_headers/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_headers/index.html @@ -62,109 +62,51 @@

cowboy_req:set_resp_headers(3)

-

Name

-
-

cowboy_req:set_resp_headers - Set several response headers

-
-
-
+

cowboy_req:set_resp_headers - Set several response headers

Description

-
-
-
-
set_resp_headers(Headers, Req :: cowboy_req:req())
-    -> Req
-
-Headers :: cowboy:http_headers()
-

Set several headers to be sent with the response.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may be overwritten by those set from the -reply functions. Likewise, headers set by this function may -overwrite headers that were set previously.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-
-
-
+
set_resp_headers(Headers, Req :: cowboy_req:req())
+    -> Req
+
+Headers :: cowboy:http_headers()
+
+

Set several headers to be sent with the response.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. Likewise, headers set by this function may overwrite headers that were set previously.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

Arguments

-
-
-
-Headers -
-
-

-Headers as a map with keys being lowercase binary strings, -and values as binary strings. -

+
Headers
+

Headers as a map with keys being lowercase binary strings, and values as binary strings.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the headers will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the headers will not be sent in the response.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set several response headers
-
-
Req = cowboy_req:set_resp_headers(#{
-    <<"content-type">>     => <<"text/html">>,
-    <<"content-encoding">> => <<"gzip">>
-}, Req0).
-
-
-
+
Req = cowboy_req:set_resp_headers(#{
+    <<"content-type">>     => <<"text/html">>,
+    <<"content-encoding">> => <<"gzip">>
+}, Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_header(3), cowboy_req:has_resp_header(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3), cowboy_req:delete_resp_header(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.sock/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.sock/index.html index 8441d5cb..ca729f96 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.sock/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.sock/index.html @@ -62,86 +62,47 @@

cowboy_req:sock(3)

-

Name

-
-

cowboy_req:sock - Socket address and port

-
-
-
+

cowboy_req:sock - Socket address and port

Description

-
-
-
-
sock(Req :: cowboy_req:req()) -> Info
+
sock(Req :: cowboy_req:req()) -> Info
 
-Info :: {inet:ip_address(), inet:port_number()}
-

Return the socket’s IP address and port number.

-

The socket information can also be obtained using pattern matching:

-
-
-
#{sock := {IP, Port}} = Req.
-
-
-
+
#{sock := {IP, Port}} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The socket’s local IP address and port number.

-
-
-
+

The socket's local IP address and port number.

Changelog

-
-
    -
  • -

    -2.1: Function introduced. -

    +
    • 2.1: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the socket’s IP address and port number.
-
-
{IP, Port} = cowboy_req:sock(Req).
-
-
-
+
{IP, Port} = cowboy_req:sock(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:peer(3), cowboy_req:cert(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.stream_body/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.stream_body/index.html index 350c7e27..cd264e0d 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.stream_body/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.stream_body/index.html @@ -62,119 +62,56 @@

cowboy_req:stream_body(3)

-

Name

-
-

cowboy_req:stream_body - Stream the response body

-
-
-
+

cowboy_req:stream_body - Stream the response body

Description

-
-
-
-
stream_body(Data, IsFin, Req :: cowboy_req:req()) -> ok
-
-Data  :: iodata()
-IsFin :: fin | nofin
-

Stream the response body.

-

This function may be called as many times as needed after -initiating a response using the -cowboy_req:stream_reply(3) -function.

-

The second argument indicates if this call is the final -call. Use the nofin value until you know no more data -will be sent. The final call should use fin (possibly -with an empty data value) or be a call to the -cowboy_req:stream_trailers(3) -function.

-

Note that not using fin for the final call is not an -error; Cowboy will take care of it when the request -handler terminates if needed. Depending on the resource -it may however be more efficient to do it as early as -possible.

-

You do not need to handle HEAD requests specifically as -Cowboy will ensure no data is sent when you call this function.

-
-
-
+
stream_body(Data, IsFin, Req :: cowboy_req:req()) -> ok
+
+Data  :: iodata()
+IsFin :: fin | nofin
+
+

Stream the response body.

+

This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function.

+

The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. The final call should use fin (possibly with an empty data value) or be a call to the cowboy_req:stream_trailers(3) function.

+

Note that not using fin for the final call is not an error; Cowboy will take care of it when the request handler terminates if needed. Depending on the resource it may however be more efficient to do it as early as possible.

+

You do not need to handle HEAD requests specifically as Cowboy will ensure no data is sent when you call this function.

Arguments

-
-
-
-Data -
-
-

-The data to be sent. -

+
Data
+

The data to be sent.

-
-IsFin -
-
-

-A flag indicating whether this is the final piece of data -to be sent. -

+
IsFin
+

A flag indicating whether this is the final piece of data to be sent.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces chunk/2. -

    +
    • 2.0: Function introduced. Replaces chunk/2.
    • -
-
-
-
+

Examples

-
-
-
Stream the response body
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, Req0),
-cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
-timer:sleep(1000),
-cowboy_req:stream_body(<<"World!\n">>, fin, Req).
-
-
-
+
Req = cowboy_req:stream_reply(200, #{
+    <<"content-type">> => <<"text/plain">>
+}, Req0),
+cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
+timer:sleep(1000),
+cowboy_req:stream_body(<<"World!\n">>, fin, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:stream_reply(3), cowboy_req:stream_trailers(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.stream_reply/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.stream_reply/index.html index 711b4595..a791e1ae 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.stream_reply/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.stream_reply/index.html @@ -62,152 +62,76 @@

cowboy_req:stream_reply(3)

-

Name

-
-

cowboy_req:stream_reply - Send the response headers

-
-
-
+

cowboy_req:stream_reply - Send the response headers

Description

-
-
-
-
stream_reply(Status, Req :: cowboy_req:req())
-    -> stream_reply(StatusCode, #{}, Req)
-
-stream_reply(Status, Headers, Req :: cowboy_req:req())
-    -> Req
-
-Status  :: cowboy:http_status()
-Headers :: cowboy:http_headers()
-

Send the response headers.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may overwrite those set by set_resp_header/3.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-

If a response body was set before calling this function, -it will not be sent.

-

Use cowboy_req:stream_body(3) -to stream the response body and optionally -cowboy_req:stream_trailers(3) -to send response trailer field values.

-

You may want to set the content-length header when using -this function, if it is known in advance. This will allow -clients using HTTP/2 and HTTP/1.0 to process the response -more efficiently.

-

The streaming method varies depending on the protocol being -used. HTTP/2 will use the usual DATA frames. HTTP/1.1 will -use chunked transfer-encoding. HTTP/1.0 will send the body -unmodified and close the connection at the end if no -content-length was set.

-

It is not possible to push resources after this function -returns. Any attempt will result in an error.

-
-
-
+
stream_reply(Status, Req :: cowboy_req:req())
+    -> stream_reply(StatusCode, #{}, Req)
+
+stream_reply(Status, Headers, Req :: cowboy_req:req())
+    -> Req
+
+Status  :: cowboy:http_status()
+Headers :: cowboy:http_headers()
+
+

Send the response headers.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

+

If a response body was set before calling this function, it will not be sent.

+

Use cowboy_req:stream_body(3) to stream the response body and optionally cowboy_req:stream_trailers(3) to send response trailer field values.

+

You may want to set the content-length header when using this function, if it is known in advance. This will allow clients using HTTP/2 and HTTP/1.0 to process the response more efficiently.

+

The streaming method varies depending on the protocol being used. HTTP/2 will use the usual DATA frames. HTTP/1.1 will use chunked transfer-encoding. HTTP/1.0 will send the body unmodified and close the connection at the end if no content-length was set.

+

It is not possible to push resources after this function returns. Any attempt will result in an error.

Arguments

-
-
-
-Status -
-
-

-The status code for the response. -

+
Status
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Req -
-
-

-The Req object. -

+
+

Header names must be given as lowercase binary strings.

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward -in order to be able to stream the response body.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward in order to be able to stream the response body.

Changelog

-
-
    -
  • -

    -2.0: Only the Req is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the Req is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces chunked_reply/1,2. -

      +
    • 2.0: Function introduced. Replaces chunked_reply/1,2.
    • -
-
-
-
+

Examples

-
-
-
Initiate the response
-
-
Req = cowboy_req:stream_reply(200, Req0).
-
-
Stream the response with custom headers
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, Req0),
-cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
-timer:sleep(1000),
-cowboy_req:stream_body(<<"World!\n">>, fin, Req).
-
-
-
+
Req = cowboy_req:stream_reply(200, #{
+    <<"content-type">> => <<"text/plain">>
+}, Req0),
+cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
+timer:sleep(1000),
+cowboy_req:stream_body(<<"World!\n">>, fin, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:inform(3), cowboy_req:reply(3), cowboy_req:stream_body(3), cowboy_req:stream_trailers(3), cowboy_req:push(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.stream_trailers/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.stream_trailers/index.html index c65aa4ef..f1840c58 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.stream_trailers/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.stream_trailers/index.html @@ -62,107 +62,55 @@

cowboy_req:stream_trailers(3)

-

Name

-
-

cowboy_req:stream_trailers - Send the response trailers

-
-
-
+

cowboy_req:stream_trailers - Send the response trailers

Description

-
-
-
-
stream_trailers(Trailers, Req :: cowboy_req:req()) -> ok
-
-Trailers :: cowboy:http_headers()
-

Send the response trailers and terminate the stream.

-

This function can only be called once, after initiating -a response using -cowboy_req:stream_reply(3) -and sending zero or more body chunks using -cowboy_req:stream_body(3) -with the nofin argument set. The function stream_trailers/2 -implies fin and automatically terminate the response.

-

You must list all field names sent in trailers in the -trailer header, otherwise they might be dropped by intermediaries -or clients.

-
-
-
+
stream_trailers(Trailers, Req :: cowboy_req:req()) -> ok
+
+Trailers :: cowboy:http_headers()
+
+

Send the response trailers and terminate the stream.

+

This function can only be called once, after initiating a response using cowboy_req:stream_reply(3) and sending zero or more body chunks using cowboy_req:stream_body(3) with the nofin argument set. The function stream_trailers/2 implies fin and automatically terminate the response.

+

You must list all field names sent in trailers in the trailer header, otherwise they might be dropped by intermediaries or clients.

Arguments

-
-
-
-Trailers -
-
-

-Trailer field values to be sent. -

+
Trailers
+

Trailer field values to be sent.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.2: Function introduced. -

    +
    • 2.2: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Stream a response body with trailers
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/plain">>,
-    <<"trailer">> => <<"expires, content-md5">>
-}, Req0),
-cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
-timer:sleep(1000),
-cowboy_req:stream_body(<<"World!\n">>, nofin, Req).
-cowboy_req:stream_trailers(#{
-    <<"expires">> => <<"Sun, 10 Dec 2017 19:13:47 GMT">>,
-    <<"content-md5">> => <<"fbf68a8e34b2ded53bba54e68794b4fe">>
-}, Req).
-
-
-
+
Req = cowboy_req:stream_reply(200, #{
+    <<"content-type">> => <<"text/plain">>,
+    <<"trailer">> => <<"expires, content-md5">>
+}, Req0),
+cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
+timer:sleep(1000),
+cowboy_req:stream_body(<<"World!\n">>, nofin, Req).
+cowboy_req:stream_trailers(#{
+    <<"expires">> => <<"Sun, 10 Dec 2017 19:13:47 GMT">>,
+    <<"content-md5">> => <<"fbf68a8e34b2ded53bba54e68794b4fe">>
+}, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:stream_reply(3), cowboy_req:stream_body(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.uri/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.uri/index.html index 90a435e3..73ab872d 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.uri/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.uri/index.html @@ -62,177 +62,106 @@

cowboy_req:uri(3)

-

Name

-
-

cowboy_req:uri - Reconstructed URI

-
-
-
+

cowboy_req:uri - Reconstructed URI

Description

-
-
-
-
uri(Req :: cowboy_req:req())       -> uri(Req, #{})
-uri(Req :: cowboy_req:req(), Opts) -> URI :: iodata()
-
-Opts :: #{
-    scheme   => iodata()           | undefined,
-    host     => iodata()           | undefined,
-    port     => inet:port_number() | undefined,
-    path     => iodata()           | undefined,
-    qs       => iodata()           | undefined,
-    fragment => iodata()           | undefined
-}
-

Reconstruct the effective request URI, optionally modifying components.

-

By default Cowboy will build a URI using the components found -in the request. Options allow disabling or replacing individual -components.

-
-
-
+
uri(Req :: cowboy_req:req())       -> uri(Req, #{})
+uri(Req :: cowboy_req:req(), Opts) -> URI :: iodata()
+
+Opts :: #{
+    scheme   => iodata()           | undefined,
+    host     => iodata()           | undefined,
+    port     => inet:port_number() | undefined,
+    path     => iodata()           | undefined,
+    qs       => iodata()           | undefined,
+    fragment => iodata()           | undefined
+}
+
+

Reconstruct the effective request URI, optionally modifying components.

+

By default Cowboy will build a URI using the components found in the request. Options allow disabling or replacing individual components.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-Map for overriding individual components. -

-

To replace a component, provide its new value as a binary -string or an iolist. To disable a component, set its value -to undefined.

-

As this function always returns a valid URI, there are some -things to note:

-
    -
  • -

    -Disabling the host also disables the scheme and port. -

    +
    Opts
    +

    Map for overriding individual components.

    +

    To replace a component, provide its new value as a binary string or an iolist. To disable a component, set its value to undefined.

    +

    As this function always returns a valid URI, there are some things to note:

    +
    • Disabling the host also disables the scheme and port.
    • -
    • -

      -There is no fragment component by default as these are - not sent with the request. -

      +
    • There is no fragment component by default as these are not sent with the request.
    • -
    • -

      -The port number may not appear in the resulting URI if - it is the default port for the given scheme (http: 80; https: 443). -

      +
    • The port number may not appear in the resulting URI if it is the default port for the given scheme (http: 80; https: 443).
    • -
+
-
-
- -
+

Return value

-
-

The reconstructed URI is returned as an iolist or a binary string.

-
-
-
+

The reconstructed URI is returned as an iolist or a binary string.

Changelog

-
-
    -
  • -

    -2.0: Individual components can be replaced or disabled. -

    +
    • 2.0: Individual components can be replaced or disabled.
    • -
    • -

      -2.0: Only the URI is returned, it is no longer wrapped in a tuple. -

      +
    • 2.0: Only the URI is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces host_url/1 and url/1. -

      +
    • 2.0: Function introduced. Replaces host_url/1 and url/1.
    • -
-
-
-
+

Examples

-
-

With an effective request URI http://example.org/path/to/res?edit=1 -we can have:

-
-
Protocol relative form
-
-
%% //example.org/path/to/res?edit=1
-cowboy_req:uri(Req, #{scheme => undefined}).
-
-
Serialized origin for use in the origin header
-
-
%% http://example.org
-cowboy_req:uri(Req, #{path => undefined, qs => undefined}).
-
-
HTTP/1.1 origin form (path and query string only)
-
-
%% /path/to/res?edit=1
-cowboy_req:uri(Req, #{host => undefined}).
-
-
Add a fragment to the URI
-
-
%% http://example.org/path/to/res?edit=1#errors
-cowboy_req:uri(Req, #{fragment => <<"errors">>}).
-
-
Ensure the scheme is HTTPS
-
-
%% https://example.org/path/to/res?edit=1
-cowboy_req:uri(Req, #{scheme => <<"https">>}).
-
-
Convert the URI to a binary string
-
-
iolist_to_binary(cowboy_req:uri(Req)).
-
-
-
+
iolist_to_binary(cowboy_req:uri(Req)).
+

See also

- - +

cowboy_req(3), cowboy_req:scheme(3), cowboy_req:host(3), cowboy_req:port(3), cowboy_req:path(3), cowboy_req:qs(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req.version/index.html b/docs/en/cowboy/2.3/manual/cowboy_req.version/index.html index 82d3d006..4fb41dc0 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req.version/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req.version/index.html @@ -62,88 +62,47 @@

cowboy_req:version(3)

-

Name

-
-

cowboy_req:version - HTTP version

-
-
-
+

cowboy_req:version - HTTP version

Description

-
-
-
-
version(Req :: cowboy_req:req()) -> Version :: cowboy:http_version()
-

Return the HTTP version used for the request.

-

The version can also be obtained using pattern matching:

-
-
-
#{version := Version} = Req.
-
-
-
+
#{version := Version} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The HTTP version used for the request is returned as an -atom. It is provided for informative purposes only.

-
-
-
+

The HTTP version used for the request is returned as an atom. It is provided for informative purposes only.

Changelog

-
-
    -
  • -

    -2.0: Only the version is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the version is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the HTTP version
-
-
Version = cowboy_req:version(Req).
-
-
-
+
Version = cowboy_req:version(Req).
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_req/index.html b/docs/en/cowboy/2.3/manual/cowboy_req/index.html index 3f577b0e..72291d4b 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_req/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_req/index.html @@ -62,414 +62,218 @@

cowboy_req(3)

-

Name

-
-

cowboy_req - HTTP request and response

-
-
-
+

cowboy_req - HTTP request and response

Description

-
-

The module cowboy_req provides functions to access, manipulate -and respond to requests.

-

There are four types of functions in this module. They can be -differentiated by their name and their return type:

-
- ---- - - - - - - - - - - - +

The module cowboy_req provides functions to access, manipulate and respond to requests.

+

There are four types of functions in this module. They can be differentiated by their name and their return type:

+
Type Name pattern Return type

access

no verb, parse_*, match_*

Value

+ + + + + + - - - - + + + - - - - + + + - - - - + + + - -
TypeName patternReturn type
accessno verb, parse_*, match_*Value

question

has_*

boolean()

questionhas_*boolean()

modification

set_*

Req

modificationset_*Req

action

any other verb

ok | {Result, Value, Req}

actionany other verbok | {Result, Value, Req}
-
-

Any Req returned must be used in place of the one passed as -argument. Functions that perform an action in particular write -state in the Req object to make sure you are using the function -correctly. For example, it’s only possible to send one response, -and to read the body once.

-
-
-
+ +

Any Req returned must be used in place of the one passed as argument. Functions that perform an action in particular write state in the Req object to make sure you are using the function correctly. For example, it's only possible to send one response, and to read the body once.

Exports

-
-

Connection:

-
-

Raw request:

-
-

Processed request:

-
-

Request body:

-
-

Response:

-
-
-
-
+

Connection:

+ +

Raw request:

+ +

Processed request:

+ +

Request body:

+ +

Response:

+

Types

-
-

push_opts()

-
-
-
push_opts() :: #{
-    method => binary(),            %% case sensitive
-    scheme => binary(),            %% lowercase; case insensitive
-    host   => binary(),            %% lowercase; case insensitive
-    port   => inet:port_number(),
-    qs     => binary()             %% case sensitive
-}
-

Push options.

-

By default, Cowboy will use the GET method, an empty query string, -and take the scheme, host and port directly from the current -request’s URI.

-
-
+
push_opts() :: #{
+    method => binary(),            %% case sensitive
+    scheme => binary(),            %% lowercase; case insensitive
+    host   => binary(),            %% lowercase; case insensitive
+    port   => inet:port_number(),
+    qs     => binary()             %% case sensitive
+}
+
+

Push options.

+

By default, Cowboy will use the GET method, an empty query string, and take the scheme, host and port directly from the current request's URI.

read_body_opts()

-
-
-
read_body_opts() :: #{
-    length  => non_neg_integer(),
-    period  => non_neg_integer(),
-    timeout => timeout()
-}
-

Body reading options.

-

The defaults are function-specific.

-
-
+
read_body_opts() :: #{
+    length  => non_neg_integer(),
+    period  => non_neg_integer(),
+    timeout => timeout()
+}
+
+

Body reading options.

+

The defaults are function-specific.

req()

-
-
-
req() :: #{
-    method  := binary(),               %% case sensitive
-    version := cowboy:http_version() | atom(),
-    scheme  := binary(),               %% lowercase; case insensitive
-    host    := binary(),               %% lowercase; case insensitive
-    port    := inet:port_number(),
-    path    := binary(),               %% case sensitive
-    qs      := binary(),               %% case sensitive
-    headers := cowboy:http_headers(),
-    peer    := {inet:ip_address(), inet:port_number()},
-    sock    := {inet:ip_address(), inet:port_number()},
-    cert    := binary() | undefined
-}
-

The Req object.

-

Contains information about the request and response. While -some fields are publicly documented, others aren’t and shouldn’t -be used.

-

You may add custom fields if required. Make sure to namespace -them by prepending an underscore and the name of your application:

-
-
Setting a custom field
-
-
Req#{_myapp_auth_method => pubkey}.
- -
+
Req#{_myapp_auth_method => pubkey}.
+

resp_body()

-
-
-
resp_body() :: iodata()
-    | {sendfile, Offset, Length, Filename}
+
resp_body() :: iodata()
+    | {sendfile, Offset, Length, Filename}
 
-Offset   :: non_neg_integer()
-Length   :: non_neg_integer()
-Filename :: file:name_all()
-

Response body.

-

It can take two forms: the actual data to be sent or a -tuple indicating which file to send.

-

When sending data directly, the type is either a binary or -an iolist. Iolists are an efficient way to build output. -Instead of concatenating strings or binaries, you can simply -build a list containing the fragments you want to send in the -order they should be sent:

-
-
Example iolists usage
-
-
1> RespBody = ["Hello ", [<<"world">>, $!]].
-["Hello ",[<<"world">>,33]]
-2> io:format("~s~n", [RespBody]).
-Hello world!
-

Note that the length must be greater than zero for any data -to be sent. Cowboy will send an empty body when the length -is zero.

- - - -
+
1> RespBody = ["Hello ", [<<"world">>, $!]].
+["Hello ",[<<"world">>,33]]
+2> io:format("~s~n", [RespBody]).
+Hello world!
+
+

Note that the length must be greater than zero for any data to be sent. Cowboy will send an empty body when the length is zero.

See also

- - +

cowboy(7)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_rest/index.html b/docs/en/cowboy/2.3/manual/cowboy_rest/index.html index 6a8a9b34..f0fdfd09 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_rest/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_rest/index.html @@ -62,670 +62,475 @@

cowboy_rest(3)

-

Name

-
-

cowboy_rest - REST handlers

-
-
-
+

cowboy_rest - REST handlers

Description

-
-

The module cowboy_rest implements the HTTP state machine.

-

Implementing REST handlers is not enough to provide a REST -interface; this interface must also follow the REST -constraints including HATEOAS (hypermedia as the engine -of application state).

-
-
-
+

The module cowboy_rest implements the HTTP state machine.

+

Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state).

Callbacks

-
-

REST handlers implement the following interface:

-
-
-
init(Req, State)
-    -> {cowboy_rest, Req, State}
-
-Callback(Req, State)
-    -> {Result, Req, State}
-     | {stop, Req, State}
-     | {{switch_handler, Module}, Req, State}
-     | {{switch_handler, Module, Opts}, Req, State}
-
-terminate(Reason, Req, State) -> ok  %% optional
-
-Req    :: cowboy_req:req()
-State  :: any()
-Module :: module()
-Opts   :: any()
-Reason :: normal
-        | {crash, error | exit | throw, any()}
-
-Callback - see below
-Result   - see below
-Default  - see below
-

The init/2 callback is common to all handlers. To switch -to the REST handler behavior, it must return cowboy_rest -as the first element of the tuple.

-

The Callback/2 above represents all the REST-specific -callbacks. They are described in the following section -of this manual. REST-specific callbacks differ by their -name, semantics, result and default values. The default -value is the one used when the callback has not been -implemented. They otherwise all follow the same interface.

-

The stop tuple can be returned to stop REST processing. -If no response was sent before then, Cowboy will send a -204 No Content. The stop tuple can be returned from -any callback, excluding expires, generate_etag, -last_modified and variances.

-

A switch_handler tuple can be returned from these same -callbacks to stop REST processing and switch to a different -handler type. This is very useful to, for example, to stream -the response body.

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the handler. -Cowboy will terminate the process right after this. There -is no need to perform any cleanup in this callback.

-

The following terminate reasons are defined for loop handlers:

-
-
-normal -
-
-

- The handler terminated normally. -

+

REST handlers implement the following interface:

+
+
init(Req, State)
+    -> {cowboy_rest, Req, State}
+
+Callback(Req, State)
+    -> {Result, Req, State}
+     | {stop, Req, State}
+     | {{switch_handler, Module}, Req, State}
+     | {{switch_handler, Module, Opts}, Req, State}
+
+terminate(Reason, Req, State) -> ok  %% optional
+
+Req    :: cowboy_req:req()
+State  :: any()
+Module :: module()
+Opts   :: any()
+Reason :: normal
+        | {crash, error | exit | throw, any()}
+
+Callback - see below
+Result   - see below
+Default  - see below
+
+

The init/2 callback is common to all handlers. To switch to the REST handler behavior, it must return cowboy_rest as the first element of the tuple.

+

The Callback/2 above represents all the REST-specific callbacks. They are described in the following section of this manual. REST-specific callbacks differ by their name, semantics, result and default values. The default value is the one used when the callback has not been implemented. They otherwise all follow the same interface.

+

The stop tuple can be returned to stop REST processing. If no response was sent before then, Cowboy will send a 204 No Content. The stop tuple can be returned from any callback, excluding expires, generate_etag, last_modified and variances.

+

A switch_handler tuple can be returned from these same callbacks to stop REST processing and switch to a different handler type. This is very useful to, for example, to stream the response body.

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the handler. Cowboy will terminate the process right after this. There is no need to perform any cleanup in this callback.

+

The following terminate reasons are defined for loop handlers:

+
normal
+

The handler terminated normally.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
-
-
-
+

REST callbacks

-
-

AcceptCallback

-
-
-
AcceptCallback(Req, State) -> {Result, Req, State}
-
-Result  :: true | {true, URI :: iodata()} | false}
-Default  - crash
-

Process the request body.

-

This function should create or update the resource using the -request body.

-

For PUT requests, the body is a representation of the resource -that is being created or replaced.

-

For POST requests, the body is typically application-specific -instructions on how to process the request, but it may also -be a representation of the resource. When creating a new -resource with POST at a different location, return {true, URI} -with URI the new location.

-

For PATCH requests, the body is a series of instructions on -how to update the resource. Patch files or JSON Patch are -examples of such media types.

-

A response body may be sent. The appropriate media type, charset -and language for the response can be retrieved from the Req -object using the media_type, charset and language keys, -respectively. The body can be set using -cowboy_req:set_resp_body(3).

-
-
+
+
AcceptCallback(Req, State) -> {Result, Req, State}
+
+Result  :: true | {true, URI :: iodata()} | false}
+Default  - crash
+
+

Process the request body.

+

This function should create or update the resource using the request body.

+

For PUT requests, the body is a representation of the resource that is being created or replaced.

+

For POST requests, the body is typically application-specific instructions on how to process the request, but it may also be a representation of the resource. When creating a new resource with POST at a different location, return {true, URI} with URI the new location.

+

For PATCH requests, the body is a series of instructions on how to update the resource. Patch files or JSON Patch are examples of such media types.

+

A response body may be sent. The appropriate media type, charset and language for the response can be retrieved from the Req object using the media_type, charset and language keys, respectively. The body can be set using cowboy_req:set_resp_body(3).

allowed_methods

-
-
-
allowed_methods(Req, State) -> {Result, Req, State}
+
allowed_methods(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% case sensitive
-Default :: [<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]
-

Return the list of allowed methods.

-
-
+Result :: [binary()] %% case sensitive +Default :: [<<"GET">>, <<"HEAD">>, <<"OPTIONS">>] +
+

Return the list of allowed methods.

allow_missing_post

-
-
-
allow_missing_post(Req, State) -> {Result, Req, State}
+
allow_missing_post(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether POST is allowed when the resource doesn’t exist.

-

Returning true here means that a new resource will be -created. The URI for the newly created resource should be -returned from the AcceptCallback function.

-
-
+Result :: boolean() +Default :: true +
+

Return whether POST is allowed when the resource doesn't exist.

+

Returning true here means that a new resource will be created. The URI for the newly created resource should be returned from the AcceptCallback function.

charsets_provided

-
-
-
charsets_provided(Req, State) -> {Result, Req, State}
+
charsets_provided(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% lowercase; case insensitive
-Default  - skip this step
-

Return the list of charsets the resource provides in order -of preference.

-

During content negotiation Cowboy will pick the most -appropriate charset for the client. The client advertises -charsets it prefers with the accept-charset header. When -that header is missing, Cowboy picks the first charset -from the resource.

-

Cowboy will add the negotiated charset to the Req object -after this step completes:

-
-
+

Cowboy will add the negotiated charset to the Req object after this step completes:

+
-
req() :: #{
-    charset => binary()  %% lowercase; case insensitive
-}
-
-
+
req() :: #{
+    charset => binary()  %% lowercase; case insensitive
+}
+

content_types_accepted

-
-
-
content_types_accepted(Req, State) -> {Result, Req, State}
-
-Result     :: [{binary() | ParsedMime, AcceptCallback :: atom()}]
-ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-
-Default     - crash
-

Return the list of media types the resource accepts in -order of preference.

-

A media type is made of different parts. The media type -text/html;charset=utf-8 is of type text, subtype html -and has a single parameter charset with value utf-8.

-

Cowboy will match the content-type request header against -the media types the server accepts and select the appropriate -callback. When that header is missing, or when the server does not -accept this media type, the request fails and an error response -is returned. Cowboy will execute the callback immediately otherwise.

-

An empty parameters list [] means that no parameters will be -accepted. When any parameter is acceptable, the tuple form -should be used with parameters as the atom '*'.

-

Cowboy treats all parameters as case sensitive, except for the -charset parameter, which is known to be case insensitive. You -should therefore always provide the charset as a lowercase -binary string.

- -
+
+
content_types_accepted(Req, State) -> {Result, Req, State}
+
+Result     :: [{binary() | ParsedMime, AcceptCallback :: atom()}]
+ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+Default     - crash
+
+ +

Return the list of media types the resource accepts in order of preference.

+

A media type is made of different parts. The media type text/html;charset=utf-8 is of type text, subtype html and has a single parameter charset with value utf-8.

+ + + +

Cowboy will match the content-type request header against the media types the server accepts and select the appropriate callback. When that header is missing, or when the server does not accept this media type, the request fails and an error response is returned. Cowboy will execute the callback immediately otherwise.

+ +

An empty parameters list [] means that no parameters will be accepted. When any parameter is acceptable, the tuple form should be used with parameters as the atom '*'.

+

Cowboy treats all parameters as case sensitive, except for the charset parameter, which is known to be case insensitive. You should therefore always provide the charset as a lowercase binary string.

+ + + + + +

content_types_provided

-
-
-
content_types_provided(Req, State) -> {Result, Req, State}
-
-Result     :: [{binary() | ParsedMime, ProvideCallback :: atom()}]
-ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-
-Default     - [{{ <<"text">>, <<"html">>, '*'}, to_html}]
-

Return the list of media types the resource provides in -order of preference.

-

A media type is made of different parts. The media type -text/html;charset=utf-8 is of type text, subtype html -and has a single parameter charset with value utf-8.

-

During content negotiation Cowboy will pick the most appropriate -media type for the client. The client advertises media types it -prefers with the accept header. When that header is missing, -the content negotiation fails and an error response is returned.

-

The callback given for the selected media type will be called -at the end of the execution of GET and HEAD requests when a -representation must be sent to the client.

-

An empty parameters list [] means that no parameters will be -accepted. When any parameter is acceptable, the tuple form -should be used with parameters as the atom '*'.

-

Cowboy treats all parameters as case sensitive, except for the -charset parameter, which is known to be case insensitive. You -should therefore always provide the charset as a lowercase -binary string.

-

Cowboy will add the negotiated media_type to the Req object -after this step completes:

-
-
-
req() :: #{
-    media_type => ParsedMime
-}
-
-
+
+
content_types_provided(Req, State) -> {Result, Req, State}
+
+Result     :: [{binary() | ParsedMime, ProvideCallback :: atom()}]
+ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+Default     - [{{ <<"text">>, <<"html">>, '*'}, to_html}]
+
+ + +

Return the list of media types the resource provides in order of preference.

+

A media type is made of different parts. The media type text/html;charset=utf-8 is of type text, subtype html and has a single parameter charset with value utf-8.

+ + + +

During content negotiation Cowboy will pick the most appropriate media type for the client. The client advertises media types it prefers with the accept header. When that header is missing, the content negotiation fails and an error response is returned.

+

The callback given for the selected media type will be called at the end of the execution of GET and HEAD requests when a representation must be sent to the client.

+ +

An empty parameters list [] means that no parameters will be accepted. When any parameter is acceptable, the tuple form should be used with parameters as the atom '*'.

+

Cowboy treats all parameters as case sensitive, except for the charset parameter, which is known to be case insensitive. You should therefore always provide the charset as a lowercase binary string.

+

Cowboy will add the negotiated media_type to the Req object after this step completes:

+
+
req() :: #{
+    media_type => ParsedMime
+}
+
+

delete_completed

-
-
-
delete_completed(Req, State) -> {Result, Req, State}
+
delete_completed(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the resource has been fully deleted from the -system, including from any internal cache.

-

Returning false will result in a 202 Accepted response -being sent instead of a 200 OK or 204 No Content.

-
-
+Result :: boolean() +Default :: true +
+

Return whether the resource has been fully deleted from the system, including from any internal cache.

+

Returning false will result in a 202 Accepted response being sent instead of a 200 OK or 204 No Content.

delete_resource

-
-
-
delete_resource(Req, State) -> {Result, Req, State}
+
delete_resource(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Delete the resource.

-

Cowboy will send an error response when this function -returns false.

- -
+Result :: boolean() +Default :: false +
+

Delete the resource.

+

Cowboy will send an error response when this function returns false.

expires

-
-
-
expires(Req, State) -> {Result, Req, State}
+
expires(Req, State) -> {Result, Req, State}
 
-Result  :: calendar:datetime() | binary() | undefined
-Default :: undefined
-

Return the resource’s expiration date.

- -
+Result :: calendar:datetime() | binary() | undefined +Default :: undefined +
+

Return the resource's expiration date.

forbidden

-
-
-
forbidden(Req, State) -> {Result, Req, State}
+
forbidden(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether access to the resource is forbidden.

-

A 403 Forbidden response will be sent if this -function returns true. This status code means that -access is forbidden regardless of authentication, -and that the request shouldn’t be repeated.

- -
+Result :: boolean() +Default :: false +
+

Return whether access to the resource is forbidden.

+

A 403 Forbidden response will be sent if this function returns true. This status code means that access is forbidden regardless of authentication, and that the request shouldn't be repeated.

generate_etag

-
-
-
generate_etag(Req, State) -> {Result, Req, State}
+
generate_etag(Req, State) -> {Result, Req, State}
 
-Result  :: binary() | {weak | strong, binary()}
-Default  - no etag value
-

Return the entity tag of the resource.

-

When a binary is returned, the value is automatically -parsed to a tuple. The binary must be in the same -format as the etag header, including quotes.

- -
+Result :: binary() | {weak | strong, binary()} +Default - no etag value +
+

Return the entity tag of the resource.

+

When a binary is returned, the value is automatically parsed to a tuple. The binary must be in the same format as the etag header, including quotes.

is_authorized

-
-
-
is_authorized(Req, State) -> {Result, Req, State}
+
is_authorized(Req, State) -> {Result, Req, State}
 
-Result  :: true | {false, AuthHeader :: iodata()}
-Default  - true
-

Return whether the user is authorized to perform the action.

-

This function should be used to perform any necessary -authentication of the user before attempting to perform -any action on the resource.

-

When authentication fails, the AuthHeader value will -be sent in the www-authenticate header for the -401 Unauthorized response.

- -
+Result :: true | {false, AuthHeader :: iodata()} +Default - true +
+

Return whether the user is authorized to perform the action.

+

This function should be used to perform any necessary authentication of the user before attempting to perform any action on the resource.

+

When authentication fails, the AuthHeader value will be sent in the www-authenticate header for the 401 Unauthorized response.

is_conflict

-
-
-
is_conflict(Req, State) -> {Result, Req, State}
+
is_conflict(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the PUT request results in a conflict.

-

A 409 Conflict response is sent when true.

- -
+Result :: boolean() +Default :: false +
+

Return whether the PUT request results in a conflict.

+

A 409 Conflict response is sent when true.

known_methods

-
-
-
known_methods(Req, State) -> {Result, Req, State}
+
known_methods(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% case sensitive
-Default :: [<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>,
-            <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]
-

Return the list of known methods.

-

The full list of methods known by the server should be -returned, regardless of their use in the resource.

-

The default value lists the methods Cowboy knows and -implement in cowboy_rest.

- -
+Result :: [binary()] %% case sensitive +Default :: [<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, + <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>] +
+

Return the list of known methods.

+

The full list of methods known by the server should be returned, regardless of their use in the resource.

+

The default value lists the methods Cowboy knows and implement in cowboy_rest.

languages_provided

-
-
-
languages_provided(Req, State) -> {Result, Req, State}
+
languages_provided(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% lowercase; case insensitive
-Default  - skip this step
-

Return the list of languages the resource provides in order -of preference.

-

During content negotiation Cowboy will pick the most -appropriate language for the client. The client advertises -languages it prefers with the accept-language header. When -that header is missing, Cowboy picks the first language -from the resource.

-

Cowboy will add the negotiated language to the Req object -after this step completes:

-
-
+

Cowboy will add the negotiated language to the Req object after this step completes:

+
-
req() :: #{
-    language => binary()  %% lowercase; case insensitive
-}
-
-
+
req() :: #{
+    language => binary()  %% lowercase; case insensitive
+}
+

last_modified

-
-
-
last_modified(Req, State) -> {Result, Req, State}
+
last_modified(Req, State) -> {Result, Req, State}
 
-Result  :: calendar:datetime()
-Default  - no last modified value
-

Return the resource’s last modification date.

-

This date will be used to test against the if-modified-since -and if-unmodified-since headers, and sent as the last-modified -header in the response to GET and HEAD requests.

- -
+Result :: calendar:datetime() +Default - no last modified value +
+

Return the resource's last modification date.

+

This date will be used to test against the if-modified-since and if-unmodified-since headers, and sent as the last-modified header in the response to GET and HEAD requests.

malformed_request

-
-
-
malformed_request(Req, State) -> {Result, Req, State}
+
malformed_request(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the request is malformed.

-

A request is malformed when a component required by the -resource is invalid. This may include the query string -or individual headers. They should be parsed and validated -in this function. The body should not be read at this point.

- -
+Result :: boolean() +Default :: false +
+

Return whether the request is malformed.

+

A request is malformed when a component required by the resource is invalid. This may include the query string or individual headers. They should be parsed and validated in this function. The body should not be read at this point.

moved_permanently

-
-
-
moved_permanently(Req, State) -> {Result, Req, State}
+
moved_permanently(Req, State) -> {Result, Req, State}
 
-Result  :: {true, URI :: iodata()} | false
-Default :: false
-

Return whether the resource was permanently moved, and -what its new location is.

- -
+Result :: {true, URI :: iodata()} | false +Default :: false +
+

Return whether the resource was permanently moved, and what its new location is.

moved_temporarily

-
-
-
moved_temporarily(Req, State) -> {Result, Req, State}
+
moved_temporarily(Req, State) -> {Result, Req, State}
 
-Result  :: {true, URI :: iodata()} | false
-Default :: false
-

Return whether the resource was temporarily moved, and -what its new location is.

- -
+Result :: {true, URI :: iodata()} | false +Default :: false +
+

Return whether the resource was temporarily moved, and what its new location is.

multiple_choices

-
-
-
multiple_choices(Req, State) -> {Result, Req, State}
-
-Result  :: boolean()
-Default :: false
-

Return whether the client should engage in reactive -negotiation.

-

Return true when the server has multiple representations -of a resource, each with their specific identifier, but is -unable to determine which is best for the client. For -example an image might have different sizes and the server -is unable to determine the capabilities of the client.

-

When returning true the server should send a body with -links to the different representations. If the server has -a preferred representation it can send its link inside a -location header.

- -
+
+
multiple_choices(Req, State) -> {Result, Req, State}
+
+Result  :: boolean()
+Default :: false
+
+

Return whether the client should engage in reactive negotiation.

+

Return true when the server has multiple representations of a resource, each with their specific identifier, but is unable to determine which is best for the client. For example an image might have different sizes and the server is unable to determine the capabilities of the client.

+

When returning true the server should send a body with links to the different representations. If the server has a preferred representation it can send its link inside a location header.

options

-
-
-
options(Req, State) -> {ok, Req, State}
-

Respond to an OPTIONS request.

-

The response should inform the client the communication -options available for this resource. By default Cowboy -will send a 200 OK response with the allow header set.

-
-
+
options(Req, State) -> {ok, Req, State}
+
+

Respond to an OPTIONS request.

+

The response should inform the client the communication options available for this resource. By default Cowboy will send a 200 OK response with the allow header set.

previously_existed

-
-
-
previously_existed(Req, State) -> {Result, Req, State}
+
previously_existed(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the resource existed previously.

- -
+Result :: boolean() +Default :: false +
+

Return whether the resource existed previously.

ProvideCallback

-
-
-
ProvideCallback(Req, State) -> {Result, Req, State}
+
ProvideCallback(Req, State) -> {Result, Req, State}
 
-Result  :: cowboy_req:resp_body()
-Default  - crash
-

Return the response body.

-

The response body can be provided either as the actual data -to be sent or a tuple indicating which file to send.

-

This function is called for both GET and HEAD requests. For -the latter the body is not sent, however.

-

Note that there used to be a way to stream the response body. -It was temporarily removed and will be added back in a later -release.

- -
+Result :: cowboy_req:resp_body() +Default - crash +
+

Return the response body.

+

The response body can be provided either as the actual data to be sent or a tuple indicating which file to send.

+

This function is called for both GET and HEAD requests. For the latter the body is not sent, however.

+ + + +

Note that there used to be a way to stream the response body. It was temporarily removed and will be added back in a later release.

+

resource_exists

-
-
-
resource_exists(Req, State) -> {Result, Req, State}
+
resource_exists(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the resource exists.

- -
+Result :: boolean() +Default :: true +
+

Return whether the resource exists.

service_available

-
-
-
service_available(Req, State) -> {Result, Req, State}
+
service_available(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the service is available.

-

A 503 Service Unavailable response will be sent when this -function returns false.

- -
+Result :: boolean() +Default :: true +
+

Return whether the service is available.

+

A 503 Service Unavailable response will be sent when this function returns false.

uri_too_long

-
-
-
uri_too_long(Req, State) -> {Result, Req, State}
+
uri_too_long(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the requested URI is too long.

-

This function can be used to further restrict the length -of the URI for this specific resource.

- -
+Result :: boolean() +Default :: false +
+

Return whether the requested URI is too long.

+

This function can be used to further restrict the length of the URI for this specific resource.

valid_content_headers

-
-
-
valid_content_headers(Req, State) -> {Result, Req, State}
+
valid_content_headers(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the content headers are valid.

-

This callback can be used to reject requests that have -invalid content header values, for example an unsupported -content-encoding.

- -
+Result :: boolean() +Default :: true +
+

Return whether the content headers are valid.

+

This callback can be used to reject requests that have invalid content header values, for example an unsupported content-encoding.

valid_entity_length

-
-
-
valid_entity_length(Req, State) -> {Result, Req, State}
+
valid_entity_length(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the request body length is within acceptable boundaries.

-

A 413 Request Entity Too Large response will be sent if this -function returns false.

- -
+Result :: boolean() +Default :: true +
+

Return whether the request body length is within acceptable boundaries.

+

A 413 Request Entity Too Large response will be sent if this function returns false.

variances

-
-
-
variances(Req, State) -> {Result, Req, State}
+
variances(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% case insensitive
-Default :: []
-

Return the list of request headers that affect the -representation of the resource.

-

Cowboy automatically adds the accept, accept-charset and -accept-language headers when necessary. It’s also useful -to note that some standard headers also do not need to be -listed here, like the authorization header.

- - - -
+Result :: [binary()] %% case insensitive +Default :: [] +
+

Return the list of request headers that affect the representation of the resource.

+

Cowboy automatically adds the accept, accept-charset and accept-language headers when necessary. It's also useful to note that some standard headers also do not need to be listed here, like the authorization header.

Changelog

-
-
    -
  • -

    -2.1: The switch_handler return value was added. -

    +
    • 2.1: The switch_handler return value was added.
    • -
    • -

      -1.0: Behavior introduced. -

      +
    • 1.0: Behavior introduced.
    • -
-
- -
+

See also

- -
+

cowboy(7), cowboy_handler(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_router.compile/index.html b/docs/en/cowboy/2.3/manual/cowboy_router.compile/index.html index 1904d026..eb6bb8c8 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_router.compile/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_router.compile/index.html @@ -62,87 +62,48 @@

cowboy_router:compile(3)

-

Name

-
-

cowboy_router:compile - Compile routes to the resources

-
-
-
+

cowboy_router:compile - Compile routes to the resources

Description

-
-
-
-
compile(cowboy_router:routes()) -> cowboy_router:dispatch_rules()
-

Compile routes to the resources.

-

Takes a human readable list of routes and transforms it -into a form more efficient to process.

-
-
-
+
compile(cowboy_router:routes()) -> cowboy_router:dispatch_rules()
+
+

Compile routes to the resources.

+

Takes a human readable list of routes and transforms it into a form more efficient to process.

Arguments

-
-
-
-Routes -
-
-

-Human readable list of routes. -

+
Routes
+

Human readable list of routes.

-
-
- -
+

Return value

-
-

An opaque dispatch rules value is returned. This value -must be given to Cowboy as a middleware environment value.

-
-
-
+

An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Compile routes and start a listener
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []},
-        {"/[...], cowboy_static, {priv_dir, my_example_app, ""}}
-    ]}
-]),
-
-{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{
-    env => #{dispatch => Dispatch}
-}).
-
-
-
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []},
+        {"/[...], cowboy_static, {priv_dir, my_example_app, ""}}
+    ]}
+]),
+
+{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{
+    env => #{dispatch => Dispatch}
+}).
+

See also

- - +

cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_router/index.html b/docs/en/cowboy/2.3/manual/cowboy_router/index.html index dae2a362..a5895995 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_router/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_router/index.html @@ -62,110 +62,65 @@

cowboy_router(3)

-

Name

-
-

cowboy_router - Router middleware

-
-
-
+

cowboy_router - Router middleware

Description

-
-

The cowboy_router middleware maps the requested host and -path to the handler to be used for processing the request.

-

The router takes the dispatch rules as input from the -middleware environment. Dispatch rules are generated by -calling the -cowboy_router:compile(3) -function.

-

When a route matches, the router sets the handler and -handler_opts middleware environment values containing -the handler module and initial state, respectively.

-

The router will stop execution when no route matches. -It will send a 400 response if no host was found, and -a 404 response otherwise.

-
-
-
+

The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request.

+

The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function.

+

When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively.

+

The router will stop execution when no route matches. It will send a 400 response if no host was found, and a 404 response otherwise.

Exports

-
-
-
-
-
+

Types

-
-

bindings()

-
-
-
bindings() :: #{atom() => any()}
-

Bindings found during routing.

-
-
+
bindings() :: #{atom() => any()}
+
+

Bindings found during routing.

dispatch_rules()

-

Opaque type containing the compiled routes.

-
-
+

Opaque type containing the compiled routes.

routes()

-
-
-
routes() = [
-    {Host, PathList} |
-    {Host, Fields, PathList}
+
routes() = [
+    {Host, PathList} |
+    {Host, Fields, PathList}
 ]
 
-PathList :: [
-    {Path, Handler, InitialState} |
-    {Path, Fields, Handler, InitialState}
+PathList :: [
+    {Path, Handler, InitialState} |
+    {Path, Fields, Handler, InitialState}
 ]
 
-Host         :: '_' | iodata()
-Path         :: '_' | iodata()
-Fields       :: cowboy:fields()
-Handler      :: module()
-InitialState :: any()
-

Human readable list of routes to handlers.

-

Cowboy uses this list to map hosts and paths, optionally -augmented with constraints applied to the bindings, to -handler modules.

-

The syntax for routes is currently defined in the user guide.

-
-
+Host :: '_' | iodata() +Path :: '_' | iodata() +Fields :: cowboy:fields() +Handler :: module() +InitialState :: any() +
+

Human readable list of routes to handlers.

+

Cowboy uses this list to map hosts and paths, optionally augmented with constraints applied to the bindings, to handler modules.

+

The syntax for routes is currently defined in the user guide.

+ +

tokens()

-
-
-
tokens() :: [binary()]
-

List of host_info and path_info tokens that were found -using the ... syntax.

- - - -
+
tokens() :: [binary()]
+
+

List of host_info and path_info tokens that were found using the ... syntax.

See also

- - +

cowboy(7), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:host_info(3), cowboy_req:path_info(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_static/index.html b/docs/en/cowboy/2.3/manual/cowboy_static/index.html index 9cb78a3d..b00701d7 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_static/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_static/index.html @@ -62,175 +62,110 @@

cowboy_static(3)

-

Name

-
-

cowboy_static - Static file handler

-
-
-
+

cowboy_static - Static file handler

Description

-
-

The module cowboy_static implements file serving capabilities -using the REST semantics provided by cowboy_rest.

-

The static file handler is a pre-written handler coming with -Cowboy. To serve files, use it in your routes.

-
-
-
+

The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest.

+

The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes.

Options

-
-
-
-
opts() :: {priv_file, App, Path}
-        | {priv_file, App, Path, Extra}
-        | {file, Path}
-        | {file, Path, Extra}
-        | {priv_dir, App, Path}
-        | {priv_dir, App, Path, Extra}
-        | {dir, Path}
-        | {dir, Path, Extra}
-
-App        :: atom()
-Path       :: binary() | string()
-Extra      :: [Etag | Mimetypes]
-
-Etag       :: {etag, module(), function()}
-            | {etag, false}
-
-Mimetypes  :: {mimetypes, module(), function()}
-            | {mimetypes, binary() | ParsedMime}
-
-ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-

Static handler configuration.

-
-
-priv_file -
-
-

-Send a file. -

-

The path is relative to the given application’s private -directory.

+
opts() :: {priv_file, App, Path}
+        | {priv_file, App, Path, Extra}
+        | {file, Path}
+        | {file, Path, Extra}
+        | {priv_dir, App, Path}
+        | {priv_dir, App, Path, Extra}
+        | {dir, Path}
+        | {dir, Path, Extra}
+
+App        :: atom()
+Path       :: binary() | string()
+Extra      :: [Etag | Mimetypes]
+
+Etag       :: {etag, module(), function()}
+            | {etag, false}
+
+Mimetypes  :: {mimetypes, module(), function()}
+            | {mimetypes, binary() | ParsedMime}
+
+ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+

Static handler configuration.

+
priv_file
+

Send a file.

+

The path is relative to the given application's private directory.

-
-file -
-
-

-Send a file. -

-

The path is either absolute or relative to the Erlang node’s -current directory.

+
file
+

Send a file.

+

The path is either absolute or relative to the Erlang node's current directory.

-
-priv_dir -
-
-

-Recursively serve files from a directory. -

-

The path is relative to the given application’s private -directory.

+
priv_dir
+

Recursively serve files from a directory.

+

The path is relative to the given application's private directory.

-
-dir -
-
-

-Recursively serve files from a directory. -

-

The path is either absolute or relative to the Erlang node’s -current directory.

+
dir
+

Recursively serve files from a directory.

+

The path is either absolute or relative to the Erlang node's current directory.

-
-

The extra options allow you to define how the etag should be -calculated and how the MIME type of files should be detected.

-

By default the static handler will generate an etag based -on the size and modification time of the file. You may disable -the etag entirely with {etag, false} or provide a module -and function that will be called when needed:

-
-
-
generate_etag(Path, Size, Mtime) -> {strong | weak, binary()}
-
-Path  :: binary()
-Size  :: non_neg_integer()
-Mtime :: file:date_time()
-

By default the static handler will detect Web-related MIME types -by looking at the file extension. You can provide a specific -MIME type that will always be used, or a module and function that -will be called when needed:

-
-
-
detect_mimetype(Path) -> ParsedMime
-
-Path       :: binary()
-ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-

Cowboy comes with two such functions; the default function -cow_mimetypes:web/1, and a second function generated from -the Apache mime.types file, cow_mimetypes:all/1.

-

The MIME type function should return -{<<"application">>, <<"octet-stream">>, []} -when it fails to detect a file’s MIME type.

- - -
+
detect_mimetype(Path) -> ParsedMime
+
+Path       :: binary()
+ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+ +

Cowboy comes with two such functions; the default function cow_mimetypes:web/1, and a second function generated from the Apache mime.types file, cow_mimetypes:all/1.

+

The MIME type function should return {<<"application">>, <<"octet-stream">>, []} when it fails to detect a file's MIME type.

Changelog

-
-
    -
  • -

    -1.0: Handler introduced. -

    +
    • 1.0: Handler introduced.
    • -
-
- -
+

Examples

-
-
-
Custom etag function
-
-
generate_etag(Path, Size, Mtime) ->
-    {strong, integer_to_binary(
-        erlang:phash2({Path, Size, Mtime}, 16#ffffffff))}.
-
-
Custom MIME type function
-
-
always_octet_stream(_Path) ->
-    case filename:extension(Path) of
-        <<".erl">> -> {<<"text">>, <<"plain">>, []};
-        _ -> {<<"application">>, <<"octet-stream">>, []}
-    end.
-
-
-
+
always_octet_stream(_Path) ->
+    case filename:extension(Path) of
+        <<".erl">> -> {<<"text">>, <<"plain">>, []};
+        _ -> {<<"application">>, <<"octet-stream">>, []}
+    end.
+

See also

- - +

cowboy(7), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_stream/index.html b/docs/en/cowboy/2.3/manual/cowboy_stream/index.html index 3755a025..298fc18e 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_stream/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_stream/index.html @@ -62,452 +62,307 @@

cowboy_stream(3)

-

Name

-
-

cowboy_handler - Stream handlers

-
-
-
+

cowboy_handler - Stream handlers

Description

-
-

The module cowboy_stream defines a callback interface -and a protocol for handling HTTP streams.

-

An HTTP request and its associated response is called -a stream. A connection may have many streams. In HTTP/1.1 -they are executed sequentially, while in HTTP/2 they are -executed concurrently.

-

Cowboy calls the stream handler for nearly all events -related to a stream. Exceptions vary depending on the -protocol.

-

Extra care must be taken when implementing stream handlers -to ensure compatibility. While some modification of the -events and commands is allowed, it is generally not a good -idea to completely omit them.

-
-
-
+

The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams.

+

An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently.

+

Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol.

+

Extra care must be taken when implementing stream handlers to ensure compatibility. While some modification of the events and commands is allowed, it is generally not a good idea to completely omit them.

Callbacks

-
-

Stream handlers must implement the following interface:

-
-
-
init(StreamID, Req, Opts) -> {Commands, State}
-data(StreamID, IsFin, Data, State) -> {Commands, State}
-info(StreamID, Info, State) -> {Commands, State}
-terminate(StreamID, Reason, State) -> any()
-early_error(StreamID, Reason, PartialReq, Resp, Opts) -> Resp
-
-StreamID   :: cowboy_stream:streamid()
-Req        :: cowboy_req:req()
-Opts       :: cowboy:opts()
-Commands   :: cowboy_stream:commands()
-State      :: any()
-IsFin      :: cowboy_stream:fin()
-Data       :: binary()
-Info       :: any()
-Reason     :: cowboy_stream:reason()
-PartialReq  - cowboy_req:req(), except all fields are optional
-Resp       :: cowboy_stream:resp_command()
-

HTTP/1.1 will initialize a stream only when the request-line -and all headers have been received. When errors occur before -that point Cowboy will call the callback early_error/5 -with a partial request, the error reason and the response -Cowboy intends to send. All other events go throuh the -stream handler using the normal callbacks.

-

HTTP/2 will initialize the stream when the HEADERS block has -been fully received and decoded. Any protocol error occuring -before that will not result in a response being sent and -will therefore not go through the stream handler. In addition -Cowboy may terminate streams without sending an HTTP response -back.

-

The stream is initialized by calling init/3. All streams -that are initialized will eventually be terminated by calling -terminate/3.

-

When Cowboy receives data for the stream it will call data/4. -The data given is the request body after any transfer decoding -has been applied.

-

When Cowboy receives a message addressed to a stream, or when -Cowboy needs to inform the stream handler that an internal -event has occurred, it will call info/3.

-
-
-
+
init(StreamID, Req, Opts) -> {Commands, State}
+data(StreamID, IsFin, Data, State) -> {Commands, State}
+info(StreamID, Info, State) -> {Commands, State}
+terminate(StreamID, Reason, State) -> any()
+early_error(StreamID, Reason, PartialReq, Resp, Opts) -> Resp
+
+StreamID   :: cowboy_stream:streamid()
+Req        :: cowboy_req:req()
+Opts       :: cowboy:opts()
+Commands   :: cowboy_stream:commands()
+State      :: any()
+IsFin      :: cowboy_stream:fin()
+Data       :: binary()
+Info       :: any()
+Reason     :: cowboy_stream:reason()
+PartialReq  - cowboy_req:req(), except all fields are optional
+Resp       :: cowboy_stream:resp_command()
+
+

HTTP/1.1 will initialize a stream only when the request-line and all headers have been received. When errors occur before that point Cowboy will call the callback early_error/5 with a partial request, the error reason and the response Cowboy intends to send. All other events go throuh the stream handler using the normal callbacks.

+

HTTP/2 will initialize the stream when the HEADERS block has been fully received and decoded. Any protocol error occuring before that will not result in a response being sent and will therefore not go through the stream handler. In addition Cowboy may terminate streams without sending an HTTP response back.

+

The stream is initialized by calling init/3. All streams that are initialized will eventually be terminated by calling terminate/3.

+

When Cowboy receives data for the stream it will call data/4. The data given is the request body after any transfer decoding has been applied.

+

When Cowboy receives a message addressed to a stream, or when Cowboy needs to inform the stream handler that an internal event has occurred, it will call info/3.

Commands

-
-

Stream handlers can return a list of commands to be executed -from the init/3, data/4 and info/3 callbacks. In addition, -the early_error/5 callback must return a response command.

-

The following commands are defined:

-
+

Stream handlers can return a list of commands to be executed from the init/3, data/4 and info/3 callbacks. In addition, the early_error/5 callback must return a response command.

+ + + + + +

The following commands are defined:

inform

-

Send an informational response to the client.

-
-
-
{inform, cowboy:http_status(), cowboy:http_headers()}
-

Any number of informational responses may be sent, -but only until the final response is sent.

-
-
+
{inform, cowboy:http_status(), cowboy:http_headers()}
+
+

Any number of informational responses may be sent, but only until the final response is sent.

response

-

Send a response to the client.

-
-
-
{response, cowboy:http_status(), cowboy:http_headers(),
-    cowboy_req:resp_body()}
-

No more data can be sent after this command.

- -
+
{response, cowboy:http_status(), cowboy:http_headers(),
+    cowboy_req:resp_body()}
+
+

No more data can be sent after this command.

headers

-

Initiate a response to the client.

-
-
-
{headers, cowboy:http_status(), cowboy:http_headers()}
-

This initiates a response to the client. The stream -will end when a data command with the fin flag or -a trailer command is returned.

- -
+
{headers, cowboy:http_status(), cowboy:http_headers()}
+
+

This initiates a response to the client. The stream will end when a data command with the fin flag or a trailer command is returned.

data

-

Send data to the client.

-
-
-
{data, fin(), iodata()}
- -
+
{data, fin(), iodata()}
+

trailers

-

Send response trailers to the client.

-
-
-
{trailers, cowboy:http_headers()}
- -
+
{trailers, cowboy:http_headers()}
+

push

-

Push a resource to the client.

-
-
-
{push, Method, Scheme, Host, inet:port_number(),
-    Path, Qs, cowboy:http_headers()}
+
{push, Method, Scheme, Host, inet:port_number(),
+    Path, Qs, cowboy:http_headers()}
 
-Method = Scheme = Host = Path = Qs = binary()
-

The command will be ignored if the protocol does not provide -any server push mechanism.

- -
+Method = Scheme = Host = Path = Qs = binary() +
+

The command will be ignored if the protocol does not provide any server push mechanism.

flow

-
-
-
{flow, pos_integer()}
-

Request more data to be read from the request body. The -exact behavior depends on the protocol.

- -
+
{flow, pos_integer()}
+
+

Request more data to be read from the request body. The exact behavior depends on the protocol.

spawn

-

Inform Cowboy that a process was spawned and should be -supervised.

-
-
-
{spawn, pid(), timeout()}
- -
+
{spawn, pid(), timeout()}
+

error_response

-

Send an error response if no response was sent previously.

-
-
-
{error_response, cowboy:http_status(), cowboy:http_headers(), iodata()}
- -
+
{error_response, cowboy:http_status(), cowboy:http_headers(), iodata()}
+

switch_protocol

-

Switch to a different protocol.

-
-
-
{switch_protocol, cowboy:http_headers(), module(), state()}
-

Contains the headers that will be sent in the 101 response, -along with the module implementing the protocol we are -switching to and its initial state.

- -
+
{switch_protocol, cowboy:http_headers(), module(), state()}
+
+

Contains the headers that will be sent in the 101 response, along with the module implementing the protocol we are switching to and its initial state.

stop

-

Stop the stream.

-
-
-
stop
-

While no more data can be sent after the fin flag was set, -the stream is still tracked by Cowboy until it is stopped by -the handler.

-

The behavior when stopping a stream for which no response -has been sent will vary depending on the protocol. The stream -will end successfully as far as the client is concerned.

-

To indicate that an error occurred, either use error_response -before stopping, or use internal_error.

- -
+
stop
+
+

While no more data can be sent after the fin flag was set, the stream is still tracked by Cowboy until it is stopped by the handler.

+

The behavior when stopping a stream for which no response has been sent will vary depending on the protocol. The stream will end successfully as far as the client is concerned.

+

To indicate that an error occurred, either use error_response before stopping, or use internal_error.

internal_error

-

Stop the stream with an error.

-
-
-
{internal_error, Reason, HumanReadable}
-
-Reason        = any()
-HumanReadable = atom()
-

This command should be used when the stream cannot continue -because of an internal error. An error_response command -may be sent before that to advertise to the client why the -stream is dropped.

- - - -
+
{internal_error, Reason, HumanReadable}
+
+Reason        = any()
+HumanReadable = atom()
+
+

This command should be used when the stream cannot continue because of an internal error. An error_response command may be sent before that to advertise to the client why the stream is dropped.

Predefined events

-
-

Cowboy will forward all messages sent to the stream to -the info/3 callback. To send a message to a stream, -send a message to the connection process with the form -{{Pid, StreamID}, Msg}. The connection process will -then forward Msg to the stream handlers.

-

Cowboy will also forward the exit signals for the -processes that the stream spawned.

-
+

Cowboy will forward all messages sent to the stream to the info/3 callback. To send a message to a stream, send a message to the connection process with the form {{Pid, StreamID}, Msg}. The connection process will then forward Msg to the stream handlers.

+

Cowboy will also forward the exit signals for the processes that the stream spawned.

EXIT

-

A process spawned by this stream has exited.

-
-
+ + +

A process spawned by this stream has exited.

+
-
{'EXIT', pid(), any()}
-

This is the raw exit message without any modification.

-
-
+
{'EXIT', pid(), any()}
+
+

This is the raw exit message without any modification.

+ + + + + + + + + + + + + + + + +

inform

-

Same as the inform command.

-

Sent when the request process reads the body and an -expect: 100-continue header was present in the request, -or when the request process sends an informational -response on its own.

-
-
+

Same as the inform command.

+

Sent when the request process reads the body and an expect: 100-continue header was present in the request, or when the request process sends an informational response on its own.

response

-

Same as the response command.

-

Usually sent when the request process replies to the client. -May also be sent by Cowboy internally.

-
-
+

Same as the response command.

+

Usually sent when the request process replies to the client. May also be sent by Cowboy internally.

headers

-

Same as the headers command.

-

Sent when the request process starts replying to the client.

-
-
+

Same as the headers command.

+

Sent when the request process starts replying to the client.

data

-

Same as the data command.

-

Sent when the request process streams data to the client.

-
-
+

Same as the data command.

+

Sent when the request process streams data to the client.

trailers

-

Same as the trailers command.

-

Sent when the request process sends the trailer field values -to the client.

-
-
+

Same as the trailers command.

+

Sent when the request process sends the trailer field values to the client.

push

-

Same as the push command.

-

Sent when the request process pushes a resource to the client.

-
-
+

Same as the push command.

+

Sent when the request process pushes a resource to the client.

switch_protocol

- -

Sent when switching to the HTTP/2 or Websocket protocol.

-
-
- -
+

Same as the switch_protocol command.

+ +

Sent when switching to the HTTP/2 or Websocket protocol.

Exports

-
-

The following function should be called by modules implementing -stream handlers to execute the next stream handler in the list:

-
-
-
-
+

Types

-
-

commands()

-
-
-
commands() :: [Command]
-

See the list of commands for details.

-
-
+
commands() :: [Command]
+
+

See the list of commands for details.

fin()

-
-
-
fin() :: fin | nofin
-

Used in commands and events to indicate that this is -the end of the stream.

-
-
+
fin() :: fin | nofin
+
+

Used in commands and events to indicate that this is the end of the stream.

partial_req()

-
-
-
req() :: #{
-    method  => binary(),               %% case sensitive
-    version => cowboy:http_version() | atom(),
-    scheme  => binary(),               %% lowercase; case insensitive
-    host    => binary(),               %% lowercase; case insensitive
-    port    => inet:port_number(),
-    path    => binary(),               %% case sensitive
-    qs      => binary(),               %% case sensitive
-    headers => cowboy:http_headers(),
-    peer    => {inet:ip_address(), inet:port_number()}
-}
-

Partial request information received when an early error is -detected.

- -
+
req() :: #{
+    method  => binary(),               %% case sensitive
+    version => cowboy:http_version() | atom(),
+    scheme  => binary(),               %% lowercase; case insensitive
+    host    => binary(),               %% lowercase; case insensitive
+    port    => inet:port_number(),
+    path    => binary(),               %% case sensitive
+    qs      => binary(),               %% case sensitive
+    headers => cowboy:http_headers(),
+    peer    => {inet:ip_address(), inet:port_number()}
+}
+
+

Partial request information received when an early error is detected.

reason()

-
-
-
reason() :: normal | switch_protocol
-    | {internal_error, timeout | {error | exit | throw, any()}, HumanReadable}
-    | {socket_error, closed | atom(), HumanReadable}
-    | {stream_error, Error, HumanReadable}
-    | {connection_error, Error, HumanReadable}
-    | {stop, cow_http2:frame(), HumanReadable}
-
-Error         = atom()
-HumanReadable = atom()
-

Reason for the stream termination.

- -
+
reason() :: normal | switch_protocol
+    | {internal_error, timeout | {error | exit | throw, any()}, HumanReadable}
+    | {socket_error, closed | atom(), HumanReadable}
+    | {stream_error, Error, HumanReadable}
+    | {connection_error, Error, HumanReadable}
+    | {stop, cow_http2:frame(), HumanReadable}
+
+Error         = atom()
+HumanReadable = atom()
+
+

Reason for the stream termination.

resp_command()

-
-
-
resp_command() :: {response, cowboy:http_status(),
-    cowboy:http_headers(), cowboy_req:resp_body()}
-

See the response command for details.

- -
+
resp_command() :: {response, cowboy:http_status(),
+    cowboy:http_headers(), cowboy_req:resp_body()}
+
+

See the response command for details.

streamid()

-
-
-
streamid() :: any()
-

The identifier for this stream.

-

The identifier is unique over the connection process. -It is possible to form a unique identifier node-wide and -cluster-wide by wrapping it in a {self(), StreamID} -tuple.

- - - -
+
streamid() :: any()
+
+

The identifier for this stream.

+

The identifier is unique over the connection process. It is possible to form a unique identifier node-wide and cluster-wide by wrapping it in a {self(), StreamID} tuple.

Changelog

-
-
    -
  • -

    -2.2: The trailers command was introduced. -

    +
    • 2.2: The trailers command was introduced.
    • -
    • -

      -2.0: Module introduced. -

      +
    • 2.0: Module introduced.
    • -
-
- - +

cowboy(7), cowboy_http(3), cowboy_http2(3)

+ diff --git a/docs/en/cowboy/2.3/manual/cowboy_websocket/index.html b/docs/en/cowboy/2.3/manual/cowboy_websocket/index.html index 697423aa..7cd153bd 100644 --- a/docs/en/cowboy/2.3/manual/cowboy_websocket/index.html +++ b/docs/en/cowboy/2.3/manual/cowboy_websocket/index.html @@ -62,308 +62,148 @@

cowboy_websocket(3)

-

Name

-
-

cowboy_websocket - Websocket

-
-
-
+

cowboy_websocket - Websocket

Description

-
-

The module cowboy_websocket implements Websocket -as a Ranch protocol. It also defines a callback interface -for handling Websocket connections.

-
-
-
+

The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections.

Callbacks

-
-

Websocket handlers must implement the following callback -interface:

-
-
-
init(Req, State)
-    -> {cowboy_websocket, Req, State}
-     | {cowboy_websocket, Req, State, Opts}
-
-websocket_init(State)            -> CallResult  %% optional
-websocket_handle(InFrame, State) -> CallResult
-websocket_info(Info, State)      -> CallResult
-
-terminate(Reason, PartialReq, State) -> ok      %% optional
-
-Req        :: cowboy_req:req()
-PartialReq :: map()
-State      :: any()
-Opts       :: cowboy_websocket:opts()
-InFrame    :: {text | binary | ping | pong, binary()}
-OutFrame   :: cow_ws:frame()                    %% see types below
-Info       :: any()
-
-CallResult :: {ok, State}
-            | {ok, State, hibernate}
-            | {reply, OutFrame | [OutFrame], State}
-            | {reply, OutFrame | [OutFrame], State, hibernate}
-            | {stop, State}
-
-Reason     :: normal | stop | timeout
-            | remote | {remote, cow_ws:close_code(), binary()}
-            | {error, badencoding | badframe | closed | atom()}
-            | {crash, error | exit | throw, any()}
-

The init/2 callback is common to all handlers. To upgrade -the connection to Websocket, it must return cowboy_websocket -as the first element of the tuple.

-

Any operation requiring the HTTP request must be done in the -init/2 function, as the Req object will not be available -after it returns. Websocket sub-protocol selection should -therefore be done in this function.

-

The optional websocket_init/1 callback will be called once -the connection has been upgraded to Websocket. It can be used -to perform any required initialization of the handler.

-

Note that the init/2 function does not run in the same -process as the Websocket callbacks. Any Websocket-specific -initialization must be done in websocket_init/1.

-

The websocket_handle/2 callback will be called for every -frame received. The websocket_info/2 callback will be -called for every Erlang message received.

-

All three Websocket callbacks may send one or more frames -back to the client (by returning a reply tuple) or terminate -the connection (by sending a close frame or returning a stop -tuple).

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the connection. This -callback is common to all handlers. Note that Websocket will -not provide the full Req object by default, to save memory.

-

Cowboy will terminate the process right after closing the -Websocket connection. This means that there is no need to -perform any cleanup in the terminate/3 callback.

-

The following terminate reasons are defined for Websocket -connections:

-
-
-normal -
-
-

- The connection was closed normally before establishing a Websocket - connection. This typically happens if an ok tuple is returned - from the init/2 callback. -

+
init(Req, State)
+    -> {cowboy_websocket, Req, State}
+     | {cowboy_websocket, Req, State, Opts}
+
+websocket_init(State)            -> CallResult  %% optional
+websocket_handle(InFrame, State) -> CallResult
+websocket_info(Info, State)      -> CallResult
+
+terminate(Reason, PartialReq, State) -> ok      %% optional
+
+Req        :: cowboy_req:req()
+PartialReq :: map()
+State      :: any()
+Opts       :: cowboy_websocket:opts()
+InFrame    :: {text | binary | ping | pong, binary()}
+OutFrame   :: cow_ws:frame()                    %% see types below
+Info       :: any()
+
+CallResult :: {ok, State}
+            | {ok, State, hibernate}
+            | {reply, OutFrame | [OutFrame], State}
+            | {reply, OutFrame | [OutFrame], State, hibernate}
+            | {stop, State}
+
+Reason     :: normal | stop | timeout
+            | remote | {remote, cow_ws:close_code(), binary()}
+            | {error, badencoding | badframe | closed | atom()}
+            | {crash, error | exit | throw, any()}
+
+

The init/2 callback is common to all handlers. To upgrade the connection to Websocket, it must return cowboy_websocket as the first element of the tuple.

+

Any operation requiring the HTTP request must be done in the init/2 function, as the Req object will not be available after it returns. Websocket sub-protocol selection should therefore be done in this function.

+

The optional websocket_init/1 callback will be called once the connection has been upgraded to Websocket. It can be used to perform any required initialization of the handler.

+

Note that the init/2 function does not run in the same process as the Websocket callbacks. Any Websocket-specific initialization must be done in websocket_init/1.

+

The websocket_handle/2 callback will be called for every frame received. The websocket_info/2 callback will be called for every Erlang message received.

+

All three Websocket callbacks may send one or more frames back to the client (by returning a reply tuple) or terminate the connection (by sending a close frame or returning a stop tuple).

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the connection. This callback is common to all handlers. Note that Websocket will not provide the full Req object by default, to save memory.

+

Cowboy will terminate the process right after closing the Websocket connection. This means that there is no need to perform any cleanup in the terminate/3 callback.

+

The following terminate reasons are defined for Websocket connections:

+
normal
+

The connection was closed normally before establishing a Websocket connection. This typically happens if an ok tuple is returned from the init/2 callback.

-
-remote -
-
-

- The remote endpoint closed the connection without giving any - further details. -

+
remote
+

The remote endpoint closed the connection without giving any further details.

-
-{remote, Code, Payload} -
-
-

- The remote endpoint closed the connection with the given - Code and Payload as the reason. -

+
{remote, Code, Payload}
+

The remote endpoint closed the connection with the given Code and Payload as the reason.

-
-stop -
-
-

- The handler requested to close the connection, either by returning - a stop tuple or by sending a close frame. -

+
stop
+

The handler requested to close the connection, either by returning a stop tuple or by sending a close frame.

-
-timeout -
-
-

- The connection has been closed due to inactivity. The timeout - value can be configured from init/2. -

+
timeout
+

The connection has been closed due to inactivity. The timeout value can be configured from init/2.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
-{error, badencoding} -
-
-

- A text frame was sent by the client with invalid encoding. All - text frames must be valid UTF-8. -

+
{error, badencoding}
+

A text frame was sent by the client with invalid encoding. All text frames must be valid UTF-8.

-
-{error, badframe} -
-
-

- A protocol error has been detected. -

+
{error, badframe}
+

A protocol error has been detected.

-
-{error, closed} -
-
-

- The socket has been closed brutally without a close frame being - received first. -

+
{error, closed}
+

The socket has been closed brutally without a close frame being received first.

-
-{error, Reason} -
-
-

- A socket error ocurred. -

+
{error, Reason}
+

A socket error ocurred.

-
- - -
+

Types

-
-

cow_ws:frame()

-
-
-
frame() :: {text, iodata()}
-    | {binary, iodata()}
-    | ping | {ping, iodata()}
-    | pong | {pong, iodata()}
-    | close | {close, iodata()} | {close, close_code(), iodata()}
-
-close_code() :: 1000..1003 | 1006..1011 | 3000..4999
-

Websocket frames that can be sent as a response.

-

Note that there is no need to send pong frames back as -Cowboy does it automatically for you.

-
-
+
frame() :: {text, iodata()}
+    | {binary, iodata()}
+    | ping | {ping, iodata()}
+    | pong | {pong, iodata()}
+    | close | {close, iodata()} | {close, close_code(), iodata()}
+
+close_code() :: 1000..1003 | 1006..1011 | 3000..4999
+
+

Websocket frames that can be sent as a response.

+

Note that there is no need to send pong frames back as Cowboy does it automatically for you.

opts()

-
-
-
opts() :: #{
-    compress => boolean(),
-    idle_timeout => timeout(),
-    max_frame_size => non_neg_integer() | infinity,
-    req_filter => fun((cowboy_req:req()) -> map())
-}
-

Websocket handler options.

-

This configuration is passed to Cowboy from the init/2 -function:

-
-
-
init(Req, State) ->
-    Opts = #{compress => true},
-    {cowboy_websocket, Req, State, Opts}.
-

The default value is given next to the option name:

-
-
-compress (false) -
-
-

- Whether to enable the Websocket frame compression - extension. Frames will only be compressed for the - clients that support this extension. -

+
init(Req, State) ->
+    Opts = #{compress => true},
+    {cowboy_websocket, Req, State, Opts}.
+
+

The default value is given next to the option name:

+
compress (false)
+

Whether to enable the Websocket frame compression extension. Frames will only be compressed for the clients that support this extension.

-
-idle_timeout (60000) -
-
-

- Time in milliseconds that Cowboy will keep the - connection open without receiving anything from - the client. -

+
idle_timeout (60000)
+

Time in milliseconds that Cowboy will keep the connection open without receiving anything from the client.

-
-max_frame_size (infinity) -
-
-

- Maximum frame size allowed by this Websocket - handler. Cowboy will close the connection when - a client attempts to send a frame that goes over - this limit. For fragmented frames this applies - to the size of the reconstituted frame. -

+
max_frame_size (infinity)
+

Maximum frame size allowed by this Websocket handler. Cowboy will close the connection when a client attempts to send a frame that goes over this limit. For fragmented frames this applies to the size of the reconstituted frame.

-
-req_filter -
-
-

- A function applied to the Req to compact it and - only keep required information. The Req is only - given back in the terminate/3 callback. By default - it keeps the method, version, URI components and peer - information. -

+
req_filter
+

A function applied to the Req to compact it and only keep required information. The Req is only given back in the terminate/3 callback. By default it keeps the method, version, URI components and peer information.

-
- - - -
+

Changelog

-
-
    -
  • -

    -2.0: The Req object is no longer passed to Websocket callbacks. -

    +
    • 2.0: The Req object is no longer passed to Websocket callbacks.
    • -
    • -

      -2.0: The callback websocket_terminate/3 was removed in favor of terminate/3. -

      +
    • 2.0: The callback websocket_terminate/3 was removed in favor of terminate/3.
    • -
    • -

      -1.0: Protocol introduced. -

      +
    • 1.0: Protocol introduced.
    • -
-
-
- +

cowboy(7), cowboy_handler(3), cowboy_http(3), cowboy_http2(3)

+ diff --git a/docs/en/cowboy/2.3/manual/http_status_codes/index.html b/docs/en/cowboy/2.3/manual/http_status_codes/index.html index 29aeb53f..77a7be98 100644 --- a/docs/en/cowboy/2.3/manual/http_status_codes/index.html +++ b/docs/en/cowboy/2.3/manual/http_status_codes/index.html @@ -62,271 +62,92 @@

HTTP status codes(7)

-

Name

-
-

HTTP status codes - status codes used by Cowboy

-
-
-
+

HTTP status codes - status codes used by Cowboy

Description

-
-

This chapter aims to list all HTTP status codes that Cowboy -may return, with details on the reasons why. The list given -here only includes the replies that Cowboy sends, not user -replies.

-
-
-
+

This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies.

100 Continue

-
-

When the client sends an expect: 100-continue header, -Cowboy automatically sends a this status code before -trying to read the request body. This behavior can be -disabled using the appropriate body option.

-
-
-
+

When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. This behavior can be disabled using the appropriate body option.

101 Switching Protocols

-
-

This is the status code sent when switching to the -Websocket protocol.

-
-
-
+

This is the status code sent when switching to the Websocket protocol.

200 OK

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

201 Created

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

202 Accepted

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

204 No Content

-
-

This status code is sent when the processing of a request -ends without any reply having been sent. It may also be -sent by cowboy_rest under normal conditions.

-
-
-
+

This status code is sent when the processing of a request ends without any reply having been sent. It may also be sent by cowboy_rest under normal conditions.

300 Multiple Choices

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

301 Moved Permanently

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

303 See Other

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

304 Not Modified

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

307 Temporary Redirect

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

400 Bad Request

-
-

Cowboy will send this status code for any of the -following reasons:

-
    -
  • -

    -Too many empty lines were sent before the request. -

    +

    Cowboy will send this status code for any of the following reasons:

    +
    • Too many empty lines were sent before the request.
    • -
    • -

      -The request-line could not be parsed. -

      +
    • The request-line could not be parsed.
    • -
    • -

      -Too many headers were sent. -

      +
    • Too many headers were sent.
    • -
    • -

      -A header name was too long. -

      +
    • A header name was too long.
    • -
    • -

      -A header value was too long. -

      +
    • A header value was too long.
    • -
    • -

      -The host header was missing from an HTTP/1.1 request. -

      +
    • The host header was missing from an HTTP/1.1 request.
    • -
    • -

      -The host header could not be parsed. -

      +
    • The host header could not be parsed.
    • -
    • -

      -The requested host was not found. -

      +
    • The requested host was not found.
    • -
    • -

      -The requested path could not be parsed. -

      +
    • The requested path could not be parsed.
    • -
    • -

      -The accept header could not be parsed when using REST. -

      +
    • The accept header could not be parsed when using REST.
    • -
    • -

      -REST under normal conditions. -

      +
    • REST under normal conditions.
    • -
    • -

      -A Websocket upgrade failed. -

      +
    • A Websocket upgrade failed.
    • -
-
-
-
+

401 Unauthorized

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

403 Forbidden

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

404 Not Found

-
-

This status code is sent when the router successfully -resolved the host but didn’t find a matching path for -the request. It may also be sent by cowboy_rest under -normal conditions.

-
-
-
+

This status code is sent when the router successfully resolved the host but didn't find a matching path for the request. It may also be sent by cowboy_rest under normal conditions.

405 Method Not Allowed

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

406 Not Acceptable

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

408 Request Timeout

-
-

Cowboy will send this status code to the client if the -client started to send a request, indicated by the -request-line being received fully, but failed to send -all headers in a reasonable time.

-
-
-
+

Cowboy will send this status code to the client if the client started to send a request, indicated by the request-line being received fully, but failed to send all headers in a reasonable time.

409 Conflict

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

410 Gone

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

412 Precondition Failed

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

413 Request Entity Too Large

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

414 Request-URI Too Long

-
-

Cowboy will send this status code to the client if the -request-line is too long. It may also be sent by -cowboy_rest under normal conditions.

-
-
-
+

Cowboy will send this status code to the client if the request-line is too long. It may also be sent by cowboy_rest under normal conditions.

415 Unsupported Media Type

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

500 Internal Server Error

-
-

This status code is sent when a crash occurs in HTTP, loop -or REST handlers, or when an invalid return value is -returned. It may also be sent by cowboy_rest under -normal conditions.

-
-
-
+

This status code is sent when a crash occurs in HTTP, loop or REST handlers, or when an invalid return value is returned. It may also be sent by cowboy_rest under normal conditions.

501 Not Implemented

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

503 Service Unavailable

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

505 HTTP Version Not Supported

-
-

Cowboy only supports the versions 1.0 and 1.1 of HTTP. -In all other cases this status code is sent back to the -client and the connection is closed.

-
-
+

Cowboy only supports the versions 1.0 and 1.1 of HTTP. In all other cases this status code is sent back to the client and the connection is closed.

+ diff --git a/docs/en/cowboy/2.3/manual/index.html b/docs/en/cowboy/2.3/manual/index.html index bdd44991..29259ec0 100644 --- a/docs/en/cowboy/2.3/manual/index.html +++ b/docs/en/cowboy/2.3/manual/index.html @@ -62,171 +62,77 @@

Cowboy Function Reference

-

Name

-
-

cowboy - Small, fast, modern HTTP server for Erlang/OTP

-
-
-
+

cowboy - Small, fast, modern HTTP server for Erlang/OTP

Description

-
-

Cowboy is an HTTP server for Erlang/OTP with support for the -HTTP/1.1, HTTP/2 and Websocket protocols.

-

Cowboy aims to provide a complete HTTP stack. This includes -the implementation of the HTTP RFCs but also any directly -related standards, like Websocket or Server-Sent Events.

-
-
-
+

Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols.

+

Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events.

Modules

-
-

Functions:

-
-

Protocols:

-
+

Protocols:

+
-

Handlers:

-
+

Handlers:

+
-

Behaviors:

-
+

Behaviors:

+
-

Middlewares:

-
+

Middlewares:

+
-
-
-
+ +

Dependencies

-
-
    -
  • -

    -ranch(7) - Socket acceptor pool for TCP protocols -

    +
    • ranch(7) - Socket acceptor pool for TCP protocols
    • -
    • -

      -cowlib(7) - Support library for manipulating Web protocols -

      +
    • cowlib(7) - Support library for manipulating Web protocols
    • -
    • -

      -ssl - Secure communication over sockets -

      +
    • ssl - Secure communication over sockets
    • -
    • -

      -crypto - Crypto functions -

      +
    • crypto - Crypto functions
    • -
-

All these applications must be started before the cowboy -application. To start Cowboy and all dependencies at once:

-
-
-
{ok, _} = application:ensure_all_started(cowboy).
-
-
-
+
{ok, _} = application:ensure_all_started(cowboy).
+

Environment

-
-

The cowboy application does not define any application -environment configuration parameters.

-
- -
+

The cowboy application does not define any application environment configuration parameters.

See also

- -
+

ranch(7), cowlib(7)

+ diff --git a/docs/en/cowboy/2.4/guide/constraints/index.html b/docs/en/cowboy/2.4/guide/constraints/index.html index 619e99d9..de8b94f9 100644 --- a/docs/en/cowboy/2.4/guide/constraints/index.html +++ b/docs/en/cowboy/2.4/guide/constraints/index.html @@ -62,141 +62,86 @@

Constraints

-

Constraints are validation and conversion functions applied -to user input.

-

They are used in various places in Cowboy, including the -router and the cowboy_req match functions.

-
+

Constraints are validation and conversion functions applied to user input.

+

They are used in various places in Cowboy, including the router and the cowboy_req match functions.

Syntax

-
-

Constraints are provided as a list of fields. For each field -in the list, specific constraints can be applied, as well as -a default value if the field is missing.

-

A field can take the form of an atom field, a tuple with -constraints {field, Constraints} or a tuple with constraints -and a default value {field, Constraints, Default}. -The field form indicates the field is mandatory.

-

Note that when used with the router, only the second form -makes sense, as it does not use the default and the field -is always defined.

-

Constraints for each field are provided as an ordered list -of atoms or funs to apply. Built-in constraints are provided -as atoms, while custom constraints are provided as funs.

-

When multiple constraints are provided, they are applied in -the order given. If the value has been modified by a constraint -then the next one receives the new value.

-

For example, the following constraints will first validate -and convert the field my_value to an integer, and then -check that the integer is positive:

-
-
-
PositiveFun = fun
-    (_, V) when V > 0 ->
-        {ok, V};
-    (_, _) ->
-        {error, not_positive}
-end,
-{my_value, [int, PositiveFun]}.
-

We ignore the first fun argument in this snippet. We shouldn’t. -We will simply learn what it is later in this chapter.

-

When there’s only one constraint, it can be provided directly -without wrapping it into a list:

-
-
-
{my_value, int}
-
-
-
+
{my_value, int}
+

Built-in constraints

-
-

Built-in constraints are specified as an atom:

-
- --- - - - - - - - - - +

Built-in constraints are specified as an atom:

+
Constraint Description

int

Converts binary value to integer.

+ + + + - - - + + - -
ConstraintDescription
intConverts binary value to integer.

nonempty

Ensures the binary value is non-empty.

nonemptyEnsures the binary value is non-empty.
-
-
- -
+

Custom constraints

-
-

Custom constraints are specified as a fun. This fun takes -two arguments. The first argument indicates the operation -to be performed, and the second is the value. What the -value is and what must be returned depends on the operation.

-

Cowboy currently defines three operations. The operation -used for validating and converting user input is the forward -operation.

-
-
-
int(forward, Value) ->
-    try
-        {ok, binary_to_integer(Value)}
-    catch _:_ ->
-        {error, not_an_integer}
-    end;
-

The value must be returned even if it is not converted -by the constraint.

-

The reverse operation does the opposite: it -takes a converted value and changes it back to what the -user input would have been.

-
-
-
int(reverse, Value) ->
-        try
-                {ok, integer_to_binary(Value)}
-        catch _:_ ->
-                {error, not_an_integer}
-        end;
-

Finally, the format_error operation takes an error -returned by any other operation and returns a formatted -human-readable error message.

-
-
-
int(format_error, {not_an_integer, Value}) ->
-        io_lib:format("The value ~p is not an integer.", [Value]).
-

Notice that for this case you get both the error and -the value that was given to the constraint that produced -this error.

-

Cowboy will not catch exceptions coming from constraint -functions. They should be written to not emit any exceptions.

-
-
+
int(format_error, {not_an_integer, Value}) ->
+	io_lib:format("The value ~p is not an integer.", [Value]).
+ +

Notice that for this case you get both the error and the value that was given to the constraint that produced this error.

+

Cowboy will not catch exceptions coming from constraint functions. They should be written to not emit any exceptions.

+ diff --git a/docs/en/cowboy/2.4/guide/cookies/index.html b/docs/en/cowboy/2.4/guide/cookies/index.html index d9df673a..3ef48485 100644 --- a/docs/en/cowboy/2.4/guide/cookies/index.html +++ b/docs/en/cowboy/2.4/guide/cookies/index.html @@ -62,144 +62,103 @@

Using cookies

-

Cookies are a mechanism allowing applications to maintain -state on top of the stateless HTTP protocol.

-

Cookies are a name/value store where the names and values are -stored in plain text. They expire either after a delay -or when the browser closes. They can be configured on a -specific domain name or path, and restricted to secure -resources (sent or downloaded over HTTPS), or restricted -to the server (disallowing access from client-side scripts).

-

Cookie names are de facto case sensitive.

-

Cookies are stored client-side and sent with every subsequent -request that matches the domain and path for which they were -stored, until they expire. This can create a non-negligible -cost.

-

Cookies should not be considered secure. They are stored on -the user’s computer in plain text, and can be read by any -program. They can also be read by proxies when using clear -connections. Always validate the value before using it, -and never store any sensitive information inside it.

-

Cookies set by the server are only available in requests -following the client reception of the response containing -them.

-

Cookies may be sent repeatedly. This is often useful to -update the expiration time and avoid losing a cookie.

-
+

Cookies are a mechanism allowing applications to maintain state on top of the stateless HTTP protocol.

+

Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts).

+

Cookie names are de facto case sensitive.

+

Cookies are stored client-side and sent with every subsequent request that matches the domain and path for which they were stored, until they expire. This can create a non-negligible cost.

+

Cookies should not be considered secure. They are stored on the user's computer in plain text, and can be read by any program. They can also be read by proxies when using clear connections. Always validate the value before using it, and never store any sensitive information inside it.

+

Cookies set by the server are only available in requests following the client reception of the response containing them.

+

Cookies may be sent repeatedly. This is often useful to update the expiration time and avoid losing a cookie.

Setting cookies

-
-

By default cookies are defined for the duration of the session:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0).
-

They can also be set for a duration in seconds:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{max_age => 3600}).
-

To delete cookies, set max_age to 0:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{max_age => 0}).
-

To restrict cookies to a specific domain and path, the options -of the same name can be used:

-
-
-
Req = cowboy_req:set_resp_cookie(<<"inaccount">>, <<"1">>, Req0,
-    #{domain => "my.example.org", path => "/account"}).
-

Cookies will be sent with requests to this domain and all -its subdomains, and to resources on this path or deeper -in the path hierarchy.

-

To restrict cookies to secure channels (typically resources -available over HTTPS):

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{secure => true}).
-

To prevent client-side scripts from accessing a cookie:

-
-
-
SessionID = generate_session_id(),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
-    #{http_only => true}).
-

Cookies may also be set client-side, for example using -Javascript.

-
-
-
+
SessionID = generate_session_id(),
+Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0,
+    #{http_only => true}).
+
+

Cookies may also be set client-side, for example using Javascript.

Reading cookies

-
-

The client only ever sends back the cookie name and value. -All other options that can be set are never sent back.

-

Cowboy provides two functions for reading cookies. Both -involve parsing the cookie header(s) and so should not -be called repeatedly.

-

You can get all cookies as a key/value list:

-
-
-
Cookies = cowboy_req:parse_cookies(Req),
-{_, Lang} = lists:keyfind(<<"lang">>, 1, Cookies).
-

Or you can perform a match against cookies and retrieve -only the ones you need, while at the same time doing -any required post processing using constraints. -This function returns a map:

-
-
-
#{id := ID, lang := Lang} = cowboy_req:match_cookies([id, lang], Req).
-

You can use constraints to validate the values while matching -them. The following snippet will crash if the id cookie is -not an integer number or if the lang cookie is empty. Additionally -the id cookie value will be converted to an integer term:

-
-
-
CookiesMap = cowboy_req:match_cookies([{id, int}, {lang, nonempty}], Req).
-

Note that if two cookies share the same name, then the map value -will be a list of the two cookie values.

-

A default value can be provided. The default will be used -if the lang cookie is not found. It will not be used if -the cookie is found but has an empty value:

-
-
-
#{lang := Lang} = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
-

If no default is provided and the value is missing, an -exception is thrown.

-
- +
#{lang := Lang} = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
+ +

If no default is provided and the value is missing, an exception is thrown.

+ diff --git a/docs/en/cowboy/2.4/guide/erlang_web/index.html b/docs/en/cowboy/2.4/guide/erlang_web/index.html index a4d5b81a..ef054417 100644 --- a/docs/en/cowboy/2.4/guide/erlang_web/index.html +++ b/docs/en/cowboy/2.4/guide/erlang_web/index.html @@ -62,194 +62,52 @@

Erlang and the Web

-

Erlang is the ideal platform for writing Web applications. -Its features are a perfect match for the requirements of -modern Web applications.

-
+

Erlang is the ideal platform for writing Web applications. Its features are a perfect match for the requirements of modern Web applications.

The Web is concurrent

-
-

When you access a website there is little concurrency -involved. A few connections are opened and requests -are sent through these connections. Then the web page -is displayed on your screen. Your browser will only -open up to 4 or 8 connections to the server, depending -on your settings. This isn’t much.

-

But think about it. You are not the only one accessing -the server at the same time. There can be hundreds, if -not thousands, if not millions of connections to the -same server at the same time.

-

Even today a lot of systems used in production haven’t -solved the C10K problem (ten thousand concurrent connections). -And the ones who did are trying hard to get to the next -step, C100K, and are pretty far from it.

-

Erlang meanwhile has no problem handling millions of -connections. At the time of writing there are application -servers written in Erlang that can handle more than two -million connections on a single server in a real production -application, with spare memory and CPU!

-

The Web is concurrent, and Erlang is a language designed -for concurrency, so it is a perfect match.

-

Of course, various platforms need to scale beyond a few -million connections. This is where Erlang’s built-in -distribution mechanisms come in. If one server isn’t -enough, add more! Erlang allows you to use the same code -for talking to local processes or to processes in other -parts of your cluster, which means you can scale very -quickly if the need arises.

-

The Web has large userbases, and the Erlang platform was -designed to work in a distributed setting, so it is a -perfect match.

-

Or is it? Surely you can find solutions to handle that many -concurrent connections with your favorite language… But all -these solutions will break down in the next few years. Why? -Firstly because servers don’t get any more powerful, they -instead get a lot more cores and memory. This is only useful -if your application can use them properly, and Erlang is -light-years away from anything else in that area. Secondly, -today your computer and your phone are online, tomorrow your -watch, goggles, bike, car, fridge and tons of other devices -will also connect to various applications on the Internet.

-

Only Erlang is prepared to deal with what’s coming.

-
-
-
+

When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. This isn't much.

+

But think about it. You are not the only one accessing the server at the same time. There can be hundreds, if not thousands, if not millions of connections to the same server at the same time.

+

Even today a lot of systems used in production haven't solved the C10K problem (ten thousand concurrent connections). And the ones who did are trying hard to get to the next step, C100K, and are pretty far from it.

+

Erlang meanwhile has no problem handling millions of connections. At the time of writing there are application servers written in Erlang that can handle more than two million connections on a single server in a real production application, with spare memory and CPU!

+

The Web is concurrent, and Erlang is a language designed for concurrency, so it is a perfect match.

+

Of course, various platforms need to scale beyond a few million connections. This is where Erlang's built-in distribution mechanisms come in. If one server isn't enough, add more! Erlang allows you to use the same code for talking to local processes or to processes in other parts of your cluster, which means you can scale very quickly if the need arises.

+

The Web has large userbases, and the Erlang platform was designed to work in a distributed setting, so it is a perfect match.

+

Or is it? Surely you can find solutions to handle that many concurrent connections with your favorite language... But all these solutions will break down in the next few years. Why? Firstly because servers don't get any more powerful, they instead get a lot more cores and memory. This is only useful if your application can use them properly, and Erlang is light-years away from anything else in that area. Secondly, today your computer and your phone are online, tomorrow your watch, goggles, bike, car, fridge and tons of other devices will also connect to various applications on the Internet.

+

Only Erlang is prepared to deal with what's coming.

The Web is soft real time

-
-

What does soft real time mean, you ask? It means we want the -operations done as quickly as possible, and in the case of -web applications, it means we want the data propagated fast.

-

In comparison, hard real time has a similar meaning, but also -has a hard time constraint, for example an operation needs to -be done in under N milliseconds otherwise the system fails -entirely.

-

Users aren’t that needy yet, they just want to get access -to their content in a reasonable delay, and they want the -actions they make to register at most a few seconds after -they submitted them, otherwise they’ll start worrying about -whether it successfully went through.

-

The Web is soft real time because taking longer to perform an -operation would be seen as bad quality of service.

-

Erlang is a soft real time system. It will always run -processes fairly, a little at a time, switching to another -process after a while and preventing a single process to -steal resources from all others. This means that Erlang -can guarantee stable low latency of operations.

-

Erlang provides the guarantees that the soft real time Web -requires.

-
-
-
+

What does soft real time mean, you ask? It means we want the operations done as quickly as possible, and in the case of web applications, it means we want the data propagated fast.

+

In comparison, hard real time has a similar meaning, but also has a hard time constraint, for example an operation needs to be done in under N milliseconds otherwise the system fails entirely.

+

Users aren't that needy yet, they just want to get access to their content in a reasonable delay, and they want the actions they make to register at most a few seconds after they submitted them, otherwise they'll start worrying about whether it successfully went through.

+

The Web is soft real time because taking longer to perform an operation would be seen as bad quality of service.

+

Erlang is a soft real time system. It will always run processes fairly, a little at a time, switching to another process after a while and preventing a single process to steal resources from all others. This means that Erlang can guarantee stable low latency of operations.

+

Erlang provides the guarantees that the soft real time Web requires.

The Web is asynchronous

-
-

Long ago, the Web was synchronous because HTTP was synchronous. -You fired a request, and then waited for a response. Not anymore. -It all began when XmlHttpRequest started being used. It allowed -the client to perform asynchronous calls to the server.

-

Then Websocket appeared and allowed both the server and the client -to send data to the other endpoint completely asynchronously. The -data is contained within frames and no response is necessary.

-

Erlang processes work the same. They send each other data contained -within messages and then continue running without needing a response. -They tend to spend most of their time inactive, waiting for a new -message, and the Erlang VM happily activate them when one is received.

-

It is therefore quite easy to imagine Erlang being good at receiving -Websocket frames, which may come in at unpredictable times, pass the -data to the responsible processes which are always ready waiting for -new messages, and perform the operations required by only activating -the required parts of the system.

-

The more recent Web technologies, like Websocket of course, but also -HTTP/2.0, are all fully asynchronous protocols. The concept -of requests and responses is retained of course, but anything could -be sent in between, by both the client or the browser, and the -responses could also be received in a completely different order.

-

Erlang is by nature asynchronous and really good at it thanks to the -great engineering that has been done in the VM over the years. It’s -only natural that it’s so good at dealing with the asynchronous Web.

-
-
-
+

Long ago, the Web was synchronous because HTTP was synchronous. You fired a request, and then waited for a response. Not anymore. It all began when XmlHttpRequest started being used. It allowed the client to perform asynchronous calls to the server.

+

Then Websocket appeared and allowed both the server and the client to send data to the other endpoint completely asynchronously. The data is contained within frames and no response is necessary.

+

Erlang processes work the same. They send each other data contained within messages and then continue running without needing a response. They tend to spend most of their time inactive, waiting for a new message, and the Erlang VM happily activate them when one is received.

+

It is therefore quite easy to imagine Erlang being good at receiving Websocket frames, which may come in at unpredictable times, pass the data to the responsible processes which are always ready waiting for new messages, and perform the operations required by only activating the required parts of the system.

+

The more recent Web technologies, like Websocket of course, but also HTTP/2.0, are all fully asynchronous protocols. The concept of requests and responses is retained of course, but anything could be sent in between, by both the client or the browser, and the responses could also be received in a completely different order.

+

Erlang is by nature asynchronous and really good at it thanks to the great engineering that has been done in the VM over the years. It's only natural that it's so good at dealing with the asynchronous Web.

The Web is omnipresent

-
-

The Web has taken a very important part of our lives. We’re -connected at all times, when we’re on our phone, using our computer, -passing time using a tablet while in the bathroom… And this -isn’t going to slow down, every single device at home or on us -will be connected.

-

All these devices are always connected. And with the number of -alternatives to give you access to the content you seek, users -tend to not stick around when problems arise. Users today want -their applications to be always available and if it’s having -too many issues they just move on.

-

Despite this, when developers choose a product to use for building -web applications, their only concern seems to be "Is it fast?", -and they look around for synthetic benchmarks showing which one -is the fastest at sending "Hello world" with only a handful -concurrent connections. Web benchmarks haven’t been representative -of reality in a long time, and are drifting further away as -time goes on.

-

What developers should really ask themselves is "Can I service -all my users with no interruption?" and they’d find that they have -two choices. They can either hope for the best, or they can use -Erlang.

-

Erlang is built for fault tolerance. When writing code in any other -language, you have to check all the return values and act accordingly -to avoid any unforeseen issues. If you’re lucky, you won’t miss -anything important. When writing Erlang code, you can just check -the success condition and ignore all errors. If an error happens, -the Erlang process crashes and is then restarted by a special -process called a supervisor.

-

Erlang developers thus have no need to fear unhandled -errors, and can focus on handling only the errors that should -give some feedback to the user and let the system take care of -the rest. This also has the advantage of allowing them to write -a lot less code, and let them sleep at night.

-

Erlang’s fault tolerance oriented design is the first piece of -what makes it the best choice for the omnipresent, always available -Web.

-

The second piece is Erlang’s built-in distribution. Distribution -is a key part of building a fault tolerant system, because it -allows you to handle bigger failures, like a whole server going -down, or even a data center entirely.

-

Fault tolerance and distribution are important today, and will be -vital in the future of the Web. Erlang is ready.

-
-
-
+

The Web has taken a very important part of our lives. We're connected at all times, when we're on our phone, using our computer, passing time using a tablet while in the bathroom... And this isn't going to slow down, every single device at home or on us will be connected.

+

All these devices are always connected. And with the number of alternatives to give you access to the content you seek, users tend to not stick around when problems arise. Users today want their applications to be always available and if it's having too many issues they just move on.

+

Despite this, when developers choose a product to use for building web applications, their only concern seems to be "Is it fast?", and they look around for synthetic benchmarks showing which one is the fastest at sending "Hello world" with only a handful concurrent connections. Web benchmarks haven't been representative of reality in a long time, and are drifting further away as time goes on.

+

What developers should really ask themselves is "Can I service all my users with no interruption?" and they'd find that they have two choices. They can either hope for the best, or they can use Erlang.

+

Erlang is built for fault tolerance. When writing code in any other language, you have to check all the return values and act accordingly to avoid any unforeseen issues. If you're lucky, you won't miss anything important. When writing Erlang code, you can just check the success condition and ignore all errors. If an error happens, the Erlang process crashes and is then restarted by a special process called a supervisor.

+

Erlang developers thus have no need to fear unhandled errors, and can focus on handling only the errors that should give some feedback to the user and let the system take care of the rest. This also has the advantage of allowing them to write a lot less code, and let them sleep at night.

+

Erlang's fault tolerance oriented design is the first piece of what makes it the best choice for the omnipresent, always available Web.

+

The second piece is Erlang's built-in distribution. Distribution is a key part of building a fault tolerant system, because it allows you to handle bigger failures, like a whole server going down, or even a data center entirely.

+

Fault tolerance and distribution are important today, and will be vital in the future of the Web. Erlang is ready.

Learn Erlang

-
-

If you are new to Erlang, you may want to grab a book or -two to get started. Those are my recommendations as the -author of Cowboy.

-
+

If you are new to Erlang, you may want to grab a book or two to get started. Those are my recommendations as the author of Cowboy.

The Erlanger Playbook

-

The Erlanger Playbook is an ebook I am currently writing, -which covers a number of different topics from code to -documentation to testing Erlang applications. It also has -an Erlang section where it covers directly the building -blocks and patterns, rather than details like the syntax.

-

You can most likely read it as a complete beginner, but -you will need a companion book to make the most of it. -Buy it from the Nine Nines website.

-
-
+

The Erlanger Playbook is an ebook I am currently writing, which covers a number of different topics from code to documentation to testing Erlang applications. It also has an Erlang section where it covers directly the building blocks and patterns, rather than details like the syntax.

+

You can most likely read it as a complete beginner, but you will need a companion book to make the most of it. Buy it from the Nine Nines website.

Programming Erlang

-

This book is from one of the creator of Erlang, Joe -Armstrong. It provides a very good explanation of what -Erlang is and why it is so. It serves as a very good -introduction to the language and platform.

-

The book is Programming Erlang, -and it also features a chapter on Cowboy.

-
-
+

This book is from one of the creator of Erlang, Joe Armstrong. It provides a very good explanation of what Erlang is and why it is so. It serves as a very good introduction to the language and platform.

+

The book is Programming Erlang, and it also features a chapter on Cowboy.

Learn You Some Erlang for Great Good!

-

LYSE is a much more complete -book covering many aspects of Erlang, while also providing -stories and humor. Be warned: it’s pretty verbose. It comes -with a free online version and a more refined paper and -ebook version.

-
-
-
+

LYSE is a much more complete book covering many aspects of Erlang, while also providing stories and humor. Be warned: it's pretty verbose. It comes with a free online version and a more refined paper and ebook version.

+ diff --git a/docs/en/cowboy/2.4/guide/flow_diagram/index.html b/docs/en/cowboy/2.4/guide/flow_diagram/index.html index 1f014904..e76d4b7f 100644 --- a/docs/en/cowboy/2.4/guide/flow_diagram/index.html +++ b/docs/en/cowboy/2.4/guide/flow_diagram/index.html @@ -62,113 +62,30 @@

Flow diagram

-

Cowboy is a lightweight HTTP server with support for HTTP/1.1, -HTTP/2 and Websocket.

-

It is built on top of Ranch. Please see the Ranch guide for more -information about how the network connections are handled.

-
+

Cowboy is a lightweight HTTP server with support for HTTP/1.1, HTTP/2 and Websocket.

+

It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled.

Overview

-
-
-
-HTTP request/response flowchart -
-
-

As you can see on the diagram, the client -begins by connecting to the server. This step is handled -by a Ranch acceptor, which is a process dedicated to -accepting new connections.

-

After Ranch accepts a new connection, whether it is an -HTTP/1.1 or HTTP/2 connection, Cowboy starts receiving -requests and handling them.

-

In HTTP/1.1 all requests come sequentially. In HTTP/2 -the requests may arrive and be processed concurrently.

-

When a request comes in, Cowboy creates a stream, which -is a set of request/response and all the events associated -with them. The protocol code in Cowboy defers the handling -of these streams to stream handler modules. When you -configure Cowboy you may define one or more module that -will receive all events associated with a stream, including -the request, response, bodies, Erlang messages and more.

-

By default Cowboy comes configured with a stream handler -called cowboy_stream_h. This stream handler will create -a new process for every request coming in, and then -communicate with this process to read the body or send -a response back. The request process executes middlewares -which, by default, including the router and then the -execution of handlers. Like stream handlers, middlewares -may also be customized.

-

A response may be sent at almost any point in this -diagram. If the response must be sent before the stream -is initialized (because an error occurred early, for -example) then stream handlers receive a special event -indicating this error.

-
-
-
+HTTP request/response flowchart

As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections.

+

After Ranch accepts a new connection, whether it is an HTTP/1.1 or HTTP/2 connection, Cowboy starts receiving requests and handling them.

+

In HTTP/1.1 all requests come sequentially. In HTTP/2 the requests may arrive and be processed concurrently.

+

When a request comes in, Cowboy creates a stream, which is a set of request/response and all the events associated with them. The protocol code in Cowboy defers the handling of these streams to stream handler modules. When you configure Cowboy you may define one or more module that will receive all events associated with a stream, including the request, response, bodies, Erlang messages and more.

+

By default Cowboy comes configured with a stream handler called cowboy_stream_h. This stream handler will create a new process for every request coming in, and then communicate with this process to read the body or send a response back. The request process executes middlewares which, by default, including the router and then the execution of handlers. Like stream handlers, middlewares may also be customized.

+

A response may be sent at almost any point in this diagram. If the response must be sent before the stream is initialized (because an error occurred early, for example) then stream handlers receive a special event indicating this error.

Protocol-specific headers

-
-

Cowboy takes care of protocol-specific headers and prevents -you from sending them manually. For HTTP/1.1 this includes -the transfer-encoding and connection headers. For HTTP/2 -this includes the colon headers like :status.

-

Cowboy will also remove protocol-specific headers from -requests before passing them to stream handlers. Cowboy -tries to hide the implementation details of all protocols -as well as possible.

-
-
-
+

Cowboy takes care of protocol-specific headers and prevents you from sending them manually. For HTTP/1.1 this includes the transfer-encoding and connection headers. For HTTP/2 this includes the colon headers like :status.

+

Cowboy will also remove protocol-specific headers from requests before passing them to stream handlers. Cowboy tries to hide the implementation details of all protocols as well as possible.

Number of processes per connection

-
-

By default, Cowboy will use one process per connection, -plus one process per set of request/response (called a -stream, internally).

-

The reason it creates a new process for every request is due -to the requirements of HTTP/2 where requests are executed -concurrently and independently from the connection. The -frames from the different requests end up interleaved on -the single TCP connection.

-

The request processes are never reused. There is therefore -no need to perform any cleanup after the response has been -sent. The process will terminate and Erlang/OTP will reclaim -all memory at once.

-

Cowboy ultimately does not require more than one process -per connection. It is possible to interact with the connection -directly from a stream handler, a low level interface to Cowboy. -They are executed from within the connection process, and can -handle the incoming requests and send responses. This is however -not recommended in normal circumstances, as a stream handler -taking too long to execute could have a negative impact on -concurrent requests or the state of the connection itself.

-
-
-
+

By default, Cowboy will use one process per connection, plus one process per set of request/response (called a stream, internally).

+

The reason it creates a new process for every request is due to the requirements of HTTP/2 where requests are executed concurrently and independently from the connection. The frames from the different requests end up interleaved on the single TCP connection.

+

The request processes are never reused. There is therefore no need to perform any cleanup after the response has been sent. The process will terminate and Erlang/OTP will reclaim all memory at once.

+

Cowboy ultimately does not require more than one process per connection. It is possible to interact with the connection directly from a stream handler, a low level interface to Cowboy. They are executed from within the connection process, and can handle the incoming requests and send responses. This is however not recommended in normal circumstances, as a stream handler taking too long to execute could have a negative impact on concurrent requests or the state of the connection itself.

Date header

-
-

Because querying for the current date and time can be expensive, -Cowboy generates one Date header value every second, shares it -to all other processes, which then simply copy it in the response. -This allows compliance with HTTP/1.1 with no actual performance loss.

-
-
-
+

Because querying for the current date and time can be expensive, Cowboy generates one Date header value every second, shares it to all other processes, which then simply copy it in the response. This allows compliance with HTTP/1.1 with no actual performance loss.

Binaries

-
-

Cowboy makes extensive use of binaries.

-

Binaries are more efficient than lists for representing -strings because they take less memory space. Processing -performance can vary depending on the operation. Binaries -are known for generally getting a great boost if the code -is compiled natively. Please see the HiPE documentation -for more details.

-

Binaries may end up being shared between processes. This -can lead to some large memory usage when one process keeps -the binary data around forever without freeing it. If you -see some weird memory usage in your application, this might -be the cause.

-
-
+

Cowboy makes extensive use of binaries.

+

Binaries are more efficient than lists for representing strings because they take less memory space. Processing performance can vary depending on the operation. Binaries are known for generally getting a great boost if the code is compiled natively. Please see the HiPE documentation for more details.

+

Binaries may end up being shared between processes. This can lead to some large memory usage when one process keeps the binary data around forever without freeing it. If you see some weird memory usage in your application, this might be the cause.

+ diff --git a/docs/en/cowboy/2.4/guide/getting_started/index.html b/docs/en/cowboy/2.4/guide/getting_started/index.html index b2302211..fe40a86a 100644 --- a/docs/en/cowboy/2.4/guide/getting_started/index.html +++ b/docs/en/cowboy/2.4/guide/getting_started/index.html @@ -62,161 +62,104 @@

Getting started

-

Erlang is more than a language, it is also an operating system -for your applications. Erlang developers rarely write standalone -modules, they write libraries or applications, and then bundle -those into what is called a release. A release contains the -Erlang VM plus all applications required to run the node, so -it can be pushed to production directly.

-

This chapter walks you through all the steps of setting up -Cowboy, writing your first application and generating your first -release. At the end of this chapter you should know everything -you need to push your first Cowboy application to production.

-
+

Erlang is more than a language, it is also an operating system for your applications. Erlang developers rarely write standalone modules, they write libraries or applications, and then bundle those into what is called a release. A release contains the Erlang VM plus all applications required to run the node, so it can be pushed to production directly.

+

This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. At the end of this chapter you should know everything you need to push your first Cowboy application to production.

Prerequisites

-
-

We are going to use the Erlang.mk -build system. If you are using Windows, please check the -Installation instructions -to get your environment setup before you continue.

-
-
-
+

We are going to use the Erlang.mk build system. If you are using Windows, please check the Installation instructions to get your environment setup before you continue.

Bootstrap

-
-

First, let’s create the directory for our application.

-
-
$ mkdir hello_erlang
-$ cd hello_erlang
-

Then we need to download Erlang.mk. Either use the following -command or download it manually.

-
-
-
$ wget https://erlang.mk/erlang.mk
-

We can now bootstrap our application. Since we are going to generate -a release, we will also bootstrap it at the same time.

-
-
-
$ make -f erlang.mk bootstrap bootstrap-rel
-

This creates a Makefile, a base application, and the release files -necessary for creating the release. We can already build and start -this release.

-
-
$ make run
-...
-(hello_erlang@127.0.0.1)1>
-

Entering the command i(). will show the running processes, including -one called hello_erlang_sup. This is the supervisor for our -application.

-

The release currently does nothing. In the rest of this chapter we -will add Cowboy as a dependency and write a simple "Hello world!" -handler.

-
-
-
+... +(hello_erlang@127.0.0.1)1> +
+

Entering the command i(). will show the running processes, including one called hello_erlang_sup. This is the supervisor for our application.

+

The release currently does nothing. In the rest of this chapter we will add Cowboy as a dependency and write a simple "Hello world!" handler.

Cowboy setup

-
-

We will modify the Makefile to tell the build system it needs to -fetch and compile Cowboy:

-
-
-
PROJECT = hello_erlang
+
PROJECT = hello_erlang
 
-DEPS = cowboy
-dep_cowboy_commit = 2.4.0
+DEPS = cowboy
+dep_cowboy_commit = 2.4.0
 
-DEP_PLUGINS = cowboy
+DEP_PLUGINS = cowboy
 
-include erlang.mk
-

We also tell the build system to load the plugins Cowboy provides. -These include predefined templates that we will use soon.

-

If you do make run now, Cowboy will be included in the release -and started automatically. This is not enough however, as Cowboy -doesn’t do anything by default. We still need to tell Cowboy to -listen for connections.

-
- -
+include erlang.mk +
+

We also tell the build system to load the plugins Cowboy provides. These include predefined templates that we will use soon.

+

If you do make run now, Cowboy will be included in the release and started automatically. This is not enough however, as Cowboy doesn't do anything by default. We still need to tell Cowboy to listen for connections.

Listening for connections

-
-

First we define the routes that Cowboy will use to map requests -to handler modules, and then we start the listener. This is best -done at application startup.

-

Open the src/hello_erlang_app.erl file and add the necessary -code to the start/2 function to make it look like this:

-
-
-
start(_Type, _Args) ->
-    Dispatch = cowboy_router:compile([
-        {'_', [{"/", hello_handler, []}]}
+
start(_Type, _Args) ->
+    Dispatch = cowboy_router:compile([
+        {'_', [{"/", hello_handler, []}]}
     ]),
-    {ok, _} = cowboy:start_clear(my_http_listener,
-        [{port, 8080}],
-        #{env => #{dispatch => Dispatch}}
+    {ok, _} = cowboy:start_clear(my_http_listener,
+        [{port, 8080}],
+        #{env => #{dispatch => Dispatch}}
     ),
-    hello_erlang_sup:start_link().
-

Routes are explained in details in the Routing -chapter. For this tutorial we map the path / to the handler -module hello_handler. This module doesn’t exist yet.

-

Build and start the release, then open http://localhost:8080 -in your browser. You will get a 500 error because the module is missing. -Any other URL, like http://localhost:8080/test, will result in a -404 error.

-
- -
+ hello_erlang_sup:start_link(). +
+

Routes are explained in details in the Routing chapter. For this tutorial we map the path / to the handler module hello_handler. This module doesn't exist yet.

+

Build and start the release, then open http://localhost:8080 in your browser. You will get a 500 error because the module is missing. Any other URL, like http://localhost:8080/test, will result in a 404 error.

Handling requests

-
-

Cowboy features different kinds of handlers, including REST -and Websocket handlers. For this tutorial we will use a plain -HTTP handler.

-

Generate a handler from a template:

-
-
-
$ make new t=cowboy.http n=hello_handler
-

Then, open the src/hello_handler.erl file and modify -the init/2 function like this to send a reply.

-
-
-
init(Req0, State) ->
-    Req = cowboy_req:reply(200,
-        #{<<"content-type">> => <<"text/plain">>},
-        <<"Hello Erlang!">>,
-        Req0),
-    {ok, Req, State}.
-

What the above code does is send a 200 OK reply, with the -Content-type header set to text/plain and the response -body set to Hello Erlang!.

-

If you run the release and open http://localhost:8080 -in your browser, you should get a nice Hello Erlang! displayed!

-
- +
init(Req0, State) ->
+    Req = cowboy_req:reply(200,
+        #{<<"content-type">> => <<"text/plain">>},
+        <<"Hello Erlang!">>,
+        Req0),
+    {ok, Req, State}.
+ +

What the above code does is send a 200 OK reply, with the Content-type header set to text/plain and the response body set to Hello Erlang!.

+

If you run the release and open http://localhost:8080 in your browser, you should get a nice Hello Erlang! displayed!

+ diff --git a/docs/en/cowboy/2.4/guide/handlers/index.html b/docs/en/cowboy/2.4/guide/handlers/index.html index 255cc546..78f64505 100644 --- a/docs/en/cowboy/2.4/guide/handlers/index.html +++ b/docs/en/cowboy/2.4/guide/handlers/index.html @@ -62,91 +62,57 @@

Handlers

-

Handlers are Erlang modules that handle HTTP requests.

-
+

Handlers are Erlang modules that handle HTTP requests.

Plain HTTP handlers

-
-

The most basic handler in Cowboy implements the mandatory -init/2 callback, manipulates the request, optionally -sends a response and then returns.

-

This callback receives the Req object and the initial -state defined in the router configuration.

-

A handler that does nothing would look like this:

-
-
-
init(Req, State) ->
-    {ok, Req, State}.
-

Despite sending no reply, a 204 No Content response will be -sent to the client, as Cowboy makes sure that a response is -sent for every request.

-

We need to use the Req object to reply.

-
-
-
init(Req0, State) ->
-    Req = cowboy_req:reply(200, #{
-        <<"content-type">> => <<"text/plain">>
-    }, <<"Hello World!">>, Req0),
-    {ok, Req, State}.
-

Cowboy will immediately send a response when cowboy:reply/4 -is called.

-

We then return a 3-tuple. ok means that the handler ran -successfully. We also give the modified Req back to Cowboy.

-

The last value of the tuple is a state that will be used -in every subsequent callbacks to this handler. Plain HTTP -handlers only have one additional callback, the optional -and rarely used terminate/3.

-
-
-
+
init(Req0, State) ->
+    Req = cowboy_req:reply(200, #{
+        <<"content-type">> => <<"text/plain">>
+    }, <<"Hello World!">>, Req0),
+    {ok, Req, State}.
+
+

Cowboy will immediately send a response when cowboy:reply/4 is called.

+

We then return a 3-tuple. ok means that the handler ran successfully. We also give the modified Req back to Cowboy.

+

The last value of the tuple is a state that will be used in every subsequent callbacks to this handler. Plain HTTP handlers only have one additional callback, the optional and rarely used terminate/3.

Other handlers

-
-

The init/2 callback can also be used to inform Cowboy -that this is a different kind of handler and that Cowboy -should switch to it. To do this you simply need to return -the module name of the handler type you want to switch to.

-

Cowboy comes with three handler types you can switch to: -cowboy_rest, cowboy_websocket -and cowboy_loop. In addition to those you -can define your own handler types.

-

Switching is simple. Instead of returning ok, you simply -return the name of the handler type you want to use. The -following snippet switches to a Websocket handler:

-
-
-
init(Req, State) ->
-    {cowboy_websocket, Req, State}.
-
- -
+
init(Req, State) ->
+    {cowboy_websocket, Req, State}.
+

Cleaning up

-
-

All handler types provide the optional terminate/3 callback.

-
-
-
terminate(_Reason, _Req, _State) ->
-    ok.
-

This callback is strictly reserved for any required cleanup. -You cannot send a response from this function. There is no -other return value.

-

This callback is optional because it is rarely necessary. -Cleanup should be done in separate processes directly (by -monitoring the handler process to detect when it exits).

-

Cowboy does not reuse processes for different requests. The -process will terminate soon after this call returns.

-
- +
terminate(_Reason, _Req, _State) ->
+    ok.
+ +

This callback is strictly reserved for any required cleanup. You cannot send a response from this function. There is no other return value.

+

This callback is optional because it is rarely necessary. Cleanup should be done in separate processes directly (by monitoring the handler process to detect when it exits).

+

Cowboy does not reuse processes for different requests. The process will terminate soon after this call returns.

+ diff --git a/docs/en/cowboy/2.4/guide/index.html b/docs/en/cowboy/2.4/guide/index.html index 06d3b7fa..9a7ac2e9 100644 --- a/docs/en/cowboy/2.4/guide/index.html +++ b/docs/en/cowboy/2.4/guide/index.html @@ -62,219 +62,87 @@

Cowboy User Guide

-
+ +

Rationale

- -
-
+

Introduction

- -
-
+

Configuration

-
- -
-
-
+

Handlers

- -
- - - -
+

Advanced

-
- -
-
- + + diff --git a/docs/en/cowboy/2.4/guide/introduction/index.html b/docs/en/cowboy/2.4/guide/introduction/index.html index ecdfa50e..4eae9298 100644 --- a/docs/en/cowboy/2.4/guide/introduction/index.html +++ b/docs/en/cowboy/2.4/guide/introduction/index.html @@ -62,79 +62,40 @@

Introduction

-

Cowboy is a small, fast and modern HTTP server for Erlang/OTP.

-

Cowboy aims to provide a complete modern Web stack. -This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and -Webmachine-based REST.

-

Cowboy comes with functions for introspection and tracing, enabling -developers to know precisely what is happening at any time. Its modular -design also easily enable developers to add instrumentation.

-

Cowboy is a high quality project. It has a small code base, is very -efficient (both in latency and memory use) and can easily be embedded -in another application.

-

Cowboy is clean Erlang code. It includes hundreds of tests and its code -is fully compliant with the Dialyzer. It is also well documented and -features a Function Reference, a User Guide and numerous Tutorials.

-
+

Cowboy is a small, fast and modern HTTP server for Erlang/OTP.

+

Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST.

+

Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation.

+

Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application.

+

Cowboy is clean Erlang code. It includes hundreds of tests and its code is fully compliant with the Dialyzer. It is also well documented and features a Function Reference, a User Guide and numerous Tutorials.

Prerequisites

-
-

Beginner Erlang knowledge is recommended for reading this guide.

-

Knowledge of the HTTP protocol is recommended but not required, as it -will be detailed throughout the guide.

-
-
-
+

Beginner Erlang knowledge is recommended for reading this guide.

+

Knowledge of the HTTP protocol is recommended but not required, as it will be detailed throughout the guide.

Supported platforms

-
-

Cowboy is tested and supported on Linux, FreeBSD, Windows and OSX.

-

Cowboy has been reported to work on other platforms, but we make no -guarantee that the experience will be safe and smooth. You are advised -to perform the necessary testing and security audits prior to deploying -on other platforms.

-

Cowboy is developed for Erlang/OTP 19.0 and newer.

-
-
-
+

Cowboy is tested and supported on Linux, FreeBSD, Windows and OSX.

+

Cowboy has been reported to work on other platforms, but we make no guarantee that the experience will be safe and smooth. You are advised to perform the necessary testing and security audits prior to deploying on other platforms.

+

Cowboy is developed for Erlang/OTP 19.0 and newer.

License

-
-

Cowboy uses the ISC License.

-
-
-
Copyright (c) 2011-2017, Loïc Hoguin <essen@ninenines.eu>
+

Cowboy uses the ISC License.

+
Copyright (c) 2011-2017, Loïc Hoguin <essen@ninenines.eu>
 
 Permission to use, copy, modify, and/or distribute this software for any
 purpose with or without fee is hereby granted, provided that the above
 copyright notice and this permission notice appear in all copies.
 
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-
-
-
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Versioning

-
- -
-
-
+

Cowboy uses Semantic Versioning 2.0.0.

Conventions

-
-

In the HTTP protocol, the method name is case sensitive. All standard -method names are uppercase.

-

Header names are case insensitive. When using HTTP/1.1, Cowboy converts -all the request header names to lowercase. HTTP/2 requires clients to -send them as lowercase. Any other header name is expected to be provided -lowercased, including when querying information about the request or -when sending responses.

-

The same applies to any other case insensitive value.

-
-
+

In the HTTP protocol, the method name is case sensitive. All standard method names are uppercase.

+

Header names are case insensitive. When using HTTP/1.1, Cowboy converts all the request header names to lowercase. HTTP/2 requires clients to send them as lowercase. Any other header name is expected to be provided lowercased, including when querying information about the request or when sending responses.

+

The same applies to any other case insensitive value.

+ diff --git a/docs/en/cowboy/2.4/guide/listeners/index.html b/docs/en/cowboy/2.4/guide/listeners/index.html index 925b4c0f..f6a82645 100644 --- a/docs/en/cowboy/2.4/guide/listeners/index.html +++ b/docs/en/cowboy/2.4/guide/listeners/index.html @@ -62,109 +62,61 @@

Listeners

-

A listener is a set of processes that listens on a port for -new connections. Incoming connections get handled by Cowboy. -Depending on the connection handshake, one or another protocol -may be used.

-

This chapter is specific to Cowboy. Please refer to the -Ranch User Guide -for more information about listeners.

-

Cowboy provides two types of listeners: one listening for -clear TCP connections, and one listening for secure TLS -connections. Both of them support the HTTP/1.1 and HTTP/2 -protocols.

-
+

A listener is a set of processes that listens on a port for new connections. Incoming connections get handled by Cowboy. Depending on the connection handshake, one or another protocol may be used.

+

This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners.

+

Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. Both of them support the HTTP/1.1 and HTTP/2 protocols.

Clear TCP listener

-
-

The clear TCP listener will accept connections on the -given port. A typical HTTP server would listen on port 80. -Port 80 requires special permissions on most platforms -however so a common alternative is port 8080.

-

The following snippet starts listening for connections -on port 8080:

-
-
-
start(_Type, _Args) ->
-    Dispatch = cowboy_router:compile([
-        {'_', [{"/", hello_handler, []}]}
+
start(_Type, _Args) ->
+    Dispatch = cowboy_router:compile([
+        {'_', [{"/", hello_handler, []}]}
     ]),
-    {ok, _} = cowboy:start_clear(my_http_listener,
-        [{port, 8080}],
-        #{env => #{dispatch => Dispatch}}
+    {ok, _} = cowboy:start_clear(my_http_listener,
+        [{port, 8080}],
+        #{env => #{dispatch => Dispatch}}
     ),
-    hello_erlang_sup:start_link().
-

The Getting Started chapter uses a -clear TCP listener.

-

Clients connecting to Cowboy on the clear listener port are -expected to use either HTTP/1.1 or HTTP/2.

-

Cowboy supports both methods of initiating a clear -HTTP/2 connection: through the Upgrade mechanism -(RFC 7540 3.2) -or by sending the preface directly -(RFC 7540 3.4).

-

Compatibility with HTTP/1.0 is provided by Cowboy’s HTTP/1.1 -implementation.

-
-
-
+ hello_erlang_sup:start_link(). +
+

The Getting Started chapter uses a clear TCP listener.

+

Clients connecting to Cowboy on the clear listener port are expected to use either HTTP/1.1 or HTTP/2.

+

Cowboy supports both methods of initiating a clear HTTP/2 connection: through the Upgrade mechanism (RFC 7540 3.2) or by sending the preface directly (RFC 7540 3.4).

+

Compatibility with HTTP/1.0 is provided by Cowboy's HTTP/1.1 implementation.

Secure TLS listener

-
-

The secure TLS listener will accept connections on the -given port. A typical HTTPS server would listen on port 443. -Port 443 requires special permissions on most platforms -however so a common alternative is port 8443.

-

The function provided by Cowboy will ensure that the TLS -options given are following the HTTP/2 RFC with regards -to security. For example some TLS extensions or ciphers -may be disabled. This also applies to HTTP/1.1 connections -on this listener. If this is not desirable, Ranch can be -used directly to setup a custom listener.

-
-
+

The function provided by Cowboy will ensure that the TLS options given are following the HTTP/2 RFC with regards to security. For example some TLS extensions or ciphers may be disabled. This also applies to HTTP/1.1 connections on this listener. If this is not desirable, Ranch can be used directly to setup a custom listener.

+
-
start(_Type, _Args) ->
-    Dispatch = cowboy_router:compile([
-        {'_', [{"/", hello_handler, []}]}
+
start(_Type, _Args) ->
+    Dispatch = cowboy_router:compile([
+        {'_', [{"/", hello_handler, []}]}
     ]),
-    {ok, _} = cowboy:start_tls(my_http_listener,
+    {ok, _} = cowboy:start_tls(my_http_listener,
         [
-            {port, 8443},
-            {certfile, "/path/to/certfile"},
-            {keyfile, "/path/to/keyfile"}
+            {port, 8443},
+            {certfile, "/path/to/certfile"},
+            {keyfile, "/path/to/keyfile"}
         ],
-        #{env => #{dispatch => Dispatch}}
+        #{env => #{dispatch => Dispatch}}
     ),
-    hello_erlang_sup:start_link().
-

Clients connecting to Cowboy on the secure listener are -expected to use the ALPN TLS extension to indicate what -protocols they understand. Cowboy always prefers HTTP/2 -over HTTP/1.1 when both are supported. When neither are -supported by the client, or when the ALPN extension was -missing, Cowboy expects HTTP/1.1 to be used.

-

Cowboy also advertises HTTP/2 support through the older -NPN TLS extension for compatibility. Note however that -this support will likely not be enabled by default when -Cowboy 2.0 gets released.

-

Compatibility with HTTP/1.0 is provided by Cowboy’s HTTP/1.1 -implementation.

-
-
-
+ hello_erlang_sup:start_link(). +
+

Clients connecting to Cowboy on the secure listener are expected to use the ALPN TLS extension to indicate what protocols they understand. Cowboy always prefers HTTP/2 over HTTP/1.1 when both are supported. When neither are supported by the client, or when the ALPN extension was missing, Cowboy expects HTTP/1.1 to be used.

+

Cowboy also advertises HTTP/2 support through the older NPN TLS extension for compatibility. Note however that this support will likely not be enabled by default when Cowboy 2.0 gets released.

+

Compatibility with HTTP/1.0 is provided by Cowboy's HTTP/1.1 implementation.

Protocol configuration

-
-

The HTTP/1.1 and HTTP/2 protocols share the same semantics; -only their framing differs. The first is a text protocol and -the second a binary protocol.

-

Cowboy doesn’t separate the configuration for HTTP/1.1 and -HTTP/2. Everything goes into the same map. Many options are -shared.

-
- +

The HTTP/1.1 and HTTP/2 protocols share the same semantics; only their framing differs. The first is a text protocol and the second a binary protocol.

+

Cowboy doesn't separate the configuration for HTTP/1.1 and HTTP/2. Everything goes into the same map. Many options are shared.

+ + + diff --git a/docs/en/cowboy/2.4/guide/loop_handlers/index.html b/docs/en/cowboy/2.4/guide/loop_handlers/index.html index 3285fae4..e66ebf77 100644 --- a/docs/en/cowboy/2.4/guide/loop_handlers/index.html +++ b/docs/en/cowboy/2.4/guide/loop_handlers/index.html @@ -62,131 +62,72 @@

Loop handlers

-

Loop handlers are a special kind of HTTP handlers used when the -response can not be sent right away. The handler enters instead -a receive loop waiting for the right message before it can send -a response.

-

Loop handlers are used for requests where a response might not -be immediately available, but where you would like to keep the -connection open for a while in case the response arrives. The -most known example of such practice is known as long polling.

-

Loop handlers can also be used for requests where a response is -partially available and you need to stream the response body -while the connection is open. The most known example of such -practice is server-sent events.

-

While the same can be accomplished using plain HTTP handlers, -it is recommended to use loop handlers because they are well-tested -and allow using built-in features like hibernation and timeouts.

-

Loop handlers essentially wait for one or more Erlang messages -and feed these messages to the info/3 callback. It also features -the init/2 and terminate/3 callbacks which work the same as -for plain HTTP handlers.

-
+

Loop handlers are a special kind of HTTP handlers used when the response can not be sent right away. The handler enters instead a receive loop waiting for the right message before it can send a response.

+

Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling.

+

Loop handlers can also be used for requests where a response is partially available and you need to stream the response body while the connection is open. The most known example of such practice is server-sent events.

+

While the same can be accomplished using plain HTTP handlers, it is recommended to use loop handlers because they are well-tested and allow using built-in features like hibernation and timeouts.

+

Loop handlers essentially wait for one or more Erlang messages and feed these messages to the info/3 callback. It also features the init/2 and terminate/3 callbacks which work the same as for plain HTTP handlers.

Initialization

-
-

The init/2 function must return a cowboy_loop tuple to enable -loop handler behavior. This tuple may optionally contain -a timeout value and/or the atom hibernate to make the -process enter hibernation until a message is received.

-

This snippet enables the loop handler:

-
-
-
init(Req, State) ->
-    {cowboy_loop, Req, State}.
-

This also makes the process hibernate:

-
-
-
init(Req, State) ->
-    {cowboy_loop, Req, State, hibernate}.
-
-
-
+
init(Req, State) ->
+    {cowboy_loop, Req, State, hibernate}.
+

Receive loop

-
-

Once initialized, Cowboy will wait for messages to arrive -in the process' mailbox. When a message arrives, Cowboy -calls the info/3 function with the message, the Req object -and the handler’s state.

-

The following snippet sends a reply when it receives a -reply message from another process, or waits for another -message otherwise.

-
-
-
info({reply, Body}, Req, State) ->
-    cowboy_req:reply(200, #{}, Body, Req),
-    {stop, Req, State};
-info(_Msg, Req, State) ->
-    {ok, Req, State, hibernate}.
-

Do note that the reply tuple here may be any message -and is simply an example.

-

This callback may perform any necessary operation including -sending all or parts of a reply, and will subsequently -return a tuple indicating if more messages are to be expected.

-

The callback may also choose to do nothing at all and just -skip the message received.

-

If a reply is sent, then the stop tuple should be returned. -This will instruct Cowboy to end the request.

-

Otherwise an ok tuple should be returned.

-
- -
+
info({reply, Body}, Req, State) ->
+    cowboy_req:reply(200, #{}, Body, Req),
+    {stop, Req, State};
+info(_Msg, Req, State) ->
+    {ok, Req, State, hibernate}.
+
+

Do note that the reply tuple here may be any message and is simply an example.

+

This callback may perform any necessary operation including sending all or parts of a reply, and will subsequently return a tuple indicating if more messages are to be expected.

+

The callback may also choose to do nothing at all and just skip the message received.

+

If a reply is sent, then the stop tuple should be returned. This will instruct Cowboy to end the request.

+

Otherwise an ok tuple should be returned.

Streaming loop

-
-

Another common case well suited for loop handlers is -streaming data received in the form of Erlang messages. -This can be done by initiating a chunked reply in the -init/2 callback and then using cowboy_req:chunk/2 -every time a message is received.

-

The following snippet does exactly that. As you can see -a chunk is sent every time an event message is received, -and the loop is stopped by sending an eof message.

-
-
-
init(Req, State) ->
-    Req2 = cowboy_req:stream_reply(200, Req),
-    {cowboy_loop, Req2, State}.
-
-info(eof, Req, State) ->
-    {stop, Req, State};
-info({event, Data}, Req, State) ->
-    cowboy_req:stream_body(Data, nofin, Req),
-    {ok, Req, State};
-info(_Msg, Req, State) ->
-    {ok, Req, State}.
-
- -
+
init(Req, State) ->
+    Req2 = cowboy_req:stream_reply(200, Req),
+    {cowboy_loop, Req2, State}.
+
+info(eof, Req, State) ->
+    {stop, Req, State};
+info({event, Data}, Req, State) ->
+    cowboy_req:stream_body(Data, nofin, Req),
+    {ok, Req, State};
+info(_Msg, Req, State) ->
+    {ok, Req, State}.
+

Cleaning up

-
-

It is recommended that you set the connection header to -close when replying, as this process may be reused for -a subsequent request.

-

Please refer to the Handlers chapter -for general instructions about cleaning up.

-
- -
+

It is recommended that you set the connection header to close when replying, as this process may be reused for a subsequent request.

+

Please refer to the Handlers chapter for general instructions about cleaning up.

Hibernate

-
-

To save memory, you may hibernate the process in between -messages received. This is done by returning the atom -hibernate as part of the loop tuple callbacks normally -return. Just add the atom at the end and Cowboy will hibernate -accordingly.

-
-
+

To save memory, you may hibernate the process in between messages received. This is done by returning the atom hibernate as part of the loop tuple callbacks normally return. Just add the atom at the end and Cowboy will hibernate accordingly.

+ diff --git a/docs/en/cowboy/2.4/guide/middlewares/index.html b/docs/en/cowboy/2.4/guide/middlewares/index.html index 094b0a66..4c1c2cd1 100644 --- a/docs/en/cowboy/2.4/guide/middlewares/index.html +++ b/docs/en/cowboy/2.4/guide/middlewares/index.html @@ -62,92 +62,38 @@

Middlewares

-

Cowboy delegates the request processing to middleware components. -By default, two middlewares are defined, for the routing and handling -of the request, as is detailed in most of this guide.

-

Middlewares give you complete control over how requests are to be -processed. You can add your own middlewares to the mix or completely -change the chain of middlewares as needed.

-

Cowboy will execute all middlewares in the given order, unless one -of them decides to stop processing.

-
+

Cowboy delegates the request processing to middleware components. By default, two middlewares are defined, for the routing and handling of the request, as is detailed in most of this guide.

+

Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed.

+

Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing.

Usage

-
-

Middlewares only need to implement a single callback: execute/2. -It is defined in the cowboy_middleware behavior.

-

This callback has two arguments. The first is the Req object. -The second is the environment.

-

Middlewares can return one of three different values:

-
    -
  • -

    -{ok, Req, Env} to continue the request processing -

    +

    Middlewares only need to implement a single callback: execute/2. It is defined in the cowboy_middleware behavior.

    +

    This callback has two arguments. The first is the Req object. The second is the environment.

    +

    Middlewares can return one of three different values:

    +
    • {ok, Req, Env} to continue the request processing
    • -
    • -

      -{suspend, Module, Function, Args} to hibernate -

      +
    • {suspend, Module, Function, Args} to hibernate
    • -
    • -

      -{stop, Req} to stop processing and move on to the next request -

      +
    • {stop, Req} to stop processing and move on to the next request
    • -
-

Of note is that when hibernating, processing will resume on the given -MFA, discarding all previous stacktrace. Make sure you keep the Req -and Env in the arguments of this MFA for later use.

-

If an error happens during middleware processing, Cowboy will not try -to send an error back to the socket, the process will just crash. It -is up to the middleware to make sure that a reply is sent if something -goes wrong.

-
-
-
+ +

Of note is that when hibernating, processing will resume on the given MFA, discarding all previous stacktrace. Make sure you keep the Req and Env in the arguments of this MFA for later use.

+

If an error happens during middleware processing, Cowboy will not try to send an error back to the socket, the process will just crash. It is up to the middleware to make sure that a reply is sent if something goes wrong.

Configuration

-
-

The middleware environment is defined as the env protocol option. -In the previous chapters we saw it briefly when we needed to pass -the routing information. It is a list of tuples with the first -element being an atom and the second any Erlang term.

-

Two values in the environment are reserved:

-
    -
  • -

    -listener contains the name of the listener -

    +

    The middleware environment is defined as the env protocol option. In the previous chapters we saw it briefly when we needed to pass the routing information. It is a list of tuples with the first element being an atom and the second any Erlang term.

    +

    Two values in the environment are reserved:

    +
    • listener contains the name of the listener
    • -
    • -

      -result contains the result of the processing -

      +
    • result contains the result of the processing
    • -
-

The listener value is always defined. The result value can be -set by any middleware. If set to anything other than ok, Cowboy -will not process any subsequent requests on this connection.

-

The middlewares that come with Cowboy may define or require other -environment values to perform.

-

You can update the environment by calling the cowboy:set_env/3 -convenience function, adding or replacing a value in the environment.

-
-
-
+ +

The listener value is always defined. The result value can be set by any middleware. If set to anything other than ok, Cowboy will not process any subsequent requests on this connection.

+

The middlewares that come with Cowboy may define or require other environment values to perform.

+

You can update the environment by calling the cowboy:set_env/3 convenience function, adding or replacing a value in the environment.

Routing middleware

-
-

The routing middleware requires the dispatch value. If routing -succeeds, it will put the handler name and options in the handler -and handler_opts values of the environment, respectively.

-
-
-
+

The routing middleware requires the dispatch value. If routing succeeds, it will put the handler name and options in the handler and handler_opts values of the environment, respectively.

Handler middleware

-
-

The handler middleware requires the handler and handler_opts -values. It puts the result of the request handling into result.

-
-
+

The handler middleware requires the handler and handler_opts values. It puts the result of the request handling into result.

+ diff --git a/docs/en/cowboy/2.4/guide/migrating_from_1.0/index.html b/docs/en/cowboy/2.4/guide/migrating_from_1.0/index.html index 275ca51c..8acb1595 100644 --- a/docs/en/cowboy/2.4/guide/migrating_from_1.0/index.html +++ b/docs/en/cowboy/2.4/guide/migrating_from_1.0/index.html @@ -62,388 +62,120 @@

Migrating from Cowboy 1.0 to 2.0

-

A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req -interface in particular has seen a massive revamp. Hooks are -gone, their functionality can now be achieved via stream -handlers.

-

The documentation has seen great work, in particular the -manual. Each module and each function now has its own dedicated -manual page with full details and examples.

-
+

A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req interface in particular has seen a massive revamp. Hooks are gone, their functionality can now be achieved via stream handlers.

+

The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples.

Compatibility

-
-

Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. -Erlang/OTP 19.0 or above is required. It is non-trivial to -make Cowboy 2.0 work with older Erlang/OTP versions.

-

Cowboy 2.0 is not compatible with Cowlib versions older than -2.0. It should be compatible with Ranch 1.0 or above, however -it has not been tested with Ranch versions older than 1.4.

-

Cowboy 2.0 is tested on Arch Linux, Ubuntu, FreeBSD, Windows -and OSX. It is tested with every point release (latest patch -release) and also with HiPE on the most recent release.

-

Cowboy 2.0 now comes with Erlang.mk templates.

-
-
-
+

Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. Erlang/OTP 19.0 or above is required. It is non-trivial to make Cowboy 2.0 work with older Erlang/OTP versions.

+

Cowboy 2.0 is not compatible with Cowlib versions older than 2.0. It should be compatible with Ranch 1.0 or above, however it has not been tested with Ranch versions older than 1.4.

+

Cowboy 2.0 is tested on Arch Linux, Ubuntu, FreeBSD, Windows and OSX. It is tested with every point release (latest patch release) and also with HiPE on the most recent release.

+

Cowboy 2.0 now comes with Erlang.mk templates.

Features added

-
-
    -
  • -

    -The HTTP/2 protocol is now supported. -

    -
  • -
  • -

    -Cowboy no longer uses only one process per connection. - It now uses one process per connection plus one process - per request by default. This is necessary for HTTP/2. - There might be a slight drop in performance for HTTP/1.1 - connections due to this change. -

    -
  • -
  • -

    -Cowboy internals have largely been reworked in order to - support HTTP/2. This opened the way to stream handlers, - which are a chain of modules that are called whenever - something happens relating to a request/response. -

    -
  • -
  • -

    -The cowboy_stream_h stream handler has been added. - It provides most of Cowboy’s default behavior. -

    -
  • -
  • -

    -The cowboy_compress_h stream handler has been added. - It compresses responses when possible. It’s worth noting - that it compresses in more cases than Cowboy 1.0 ever did. -

    -
  • -
  • -

    -Because of the many changes in the internals of Cowboy, - many options have been added or modified. Of note is that - the Websocket options are now given per handler rather - than for the entire listener. -

    -
  • -
  • -

    -Websocket permessage-deflate compression is now supported - via the compress option. -

    -
  • -
  • -

    -Static file handlers will now correctly find files found - in .ez archives. -

    -
  • -
  • -

    -Constraints have been generalized and are now used not only - in the router but also in some cowboy_req functions. Their - interface has also been modified to allow for reverse - operations and formatting of errors. -

    -
  • -
-
-
-
+
  • The HTTP/2 protocol is now supported. +
  • +
  • Cowboy no longer uses only one process per connection. It now uses one process per connection plus one process per request by default. This is necessary for HTTP/2. There might be a slight drop in performance for HTTP/1.1 connections due to this change. +
  • +
  • Cowboy internals have largely been reworked in order to support HTTP/2. This opened the way to stream handlers, which are a chain of modules that are called whenever something happens relating to a request/response. +
  • +
  • The cowboy_stream_h stream handler has been added. It provides most of Cowboy's default behavior. +
  • +
  • The cowboy_compress_h stream handler has been added. It compresses responses when possible. It's worth noting that it compresses in more cases than Cowboy 1.0 ever did. +
  • +
  • Because of the many changes in the internals of Cowboy, many options have been added or modified. Of note is that the Websocket options are now given per handler rather than for the entire listener. +
  • +
  • Websocket permessage-deflate compression is now supported via the compress option. +
  • +
  • Static file handlers will now correctly find files found in .ez archives. +
  • +
  • Constraints have been generalized and are now used not only in the router but also in some cowboy_req functions. Their interface has also been modified to allow for reverse operations and formatting of errors. +
  • +

Features removed

-
-
    -
  • -

    -SPDY support has been removed. Use HTTP/2 instead. -

    -
  • -
  • -

    -Hooks have been removed. Use stream handlers instead. -

    -
  • -
  • -

    -The undocumented waiting_stream hack has been removed. - It allowed disabling chunked transfer-encoding for HTTP/1.1. - It has no equivalent in Cowboy 2.0. Open a ticket if necessary. -

    -
  • -
  • -

    -Sub protocols still exist, but their interface has largely changed - and they are no longer documented for the time being. -

    -
  • -
-
-
-
+
  • SPDY support has been removed. Use HTTP/2 instead. +
  • +
  • Hooks have been removed. Use stream handlers instead. +
  • +
  • The undocumented waiting_stream hack has been removed. It allowed disabling chunked transfer-encoding for HTTP/1.1. It has no equivalent in Cowboy 2.0. Open a ticket if necessary. +
  • +
  • Sub protocols still exist, but their interface has largely changed and they are no longer documented for the time being. +
  • +

Changed behaviors

-
-
    -
  • -

    -The handler behaviors have been renamed and are now cowboy_handler, - cowboy_loop, cowboy_rest and cowboy_websocket. -

    -
  • -
  • -

    -Plain HTTP, loop, REST and Websocket handlers have had their - init and terminate callbacks unified. They now all use the - init/2 and terminate/3 callbacks. The latter is now optional. - The terminate reason has now been documented for all handlers. -

    -
  • -
  • -

    -The tuple returned to switch to a different handler type has - changed. It now takes the form {Module, Req, State} or - {Module, Req, State, Opts}, where Opts is a map of options - to configure the handler. The timeout and hibernate options - must now be specified using this map, where applicable. -

    -
  • -
  • -

    -All behaviors that used to accept halt or shutdown tuples - as a return value no longer do so. The return value is now - a stop tuple, consistent across Cowboy. -

    -
  • -
  • -

    -Middlewares can no longer return an error tuple. They have - to send the response and return a stop tuple instead. -

    -
  • -
  • -

    -The known_content_type REST handler callback has been removed - as it was found unnecessary. -

    -
  • -
  • -

    -Websocket handlers have both the normal init/2 and - an optional websocket_init/1 function. The reason for - that exception is that the websocket_* callbacks execute - in a separate process from the init/2 callback, and it - was therefore not obvious how timers or monitors should - be setup properly. They are effectively initializing the - handler before and after the HTTP/1.1 upgrade. -

    -
  • -
  • -

    -Websocket handlers can now send frames directly from - websocket_init/1. The frames will be sent immediately - after the handshake. -

    -
  • -
  • -

    -Websocket handler callbacks no longer receive the Req - argument. The init/2 callback still receives it and - can be used to extract relevant information. The terminate/3 - callback, if implemented, may still receive the Req - (see next bullet point). -

    -
  • -
  • -

    -Websocket handlers have a new req_filter option that - can be used to customize how much information should be - discarded from the Req object after the handshake. Note - that the Req object is only available in terminate/3 - past that point. -

    -
  • -
  • -

    -Websocket handlers have their timeout default changed - from infinity to 60 seconds. -

    -
  • -
-
-
-
+
  • The handler behaviors have been renamed and are now cowboy_handler, cowboy_loop, cowboy_rest and cowboy_websocket. +
  • +
  • Plain HTTP, loop, REST and Websocket handlers have had their init and terminate callbacks unified. They now all use the init/2 and terminate/3 callbacks. The latter is now optional. The terminate reason has now been documented for all handlers. +
  • +
  • The tuple returned to switch to a different handler type has changed. It now takes the form {Module, Req, State} or {Module, Req, State, Opts}, where Opts is a map of options to configure the handler. The timeout and hibernate options must now be specified using this map, where applicable. +
  • +
  • All behaviors that used to accept halt or shutdown tuples as a return value no longer do so. The return value is now a stop tuple, consistent across Cowboy. +
  • +
  • Middlewares can no longer return an error tuple. They have to send the response and return a stop tuple instead. +
  • +
  • The known_content_type REST handler callback has been removed as it was found unnecessary. +
  • +
  • Websocket handlers have both the normal init/2 and an optional websocket_init/1 function. The reason for that exception is that the websocket_* callbacks execute in a separate process from the init/2 callback, and it was therefore not obvious how timers or monitors should be setup properly. They are effectively initializing the handler before and after the HTTP/1.1 upgrade. +
  • +
  • Websocket handlers can now send frames directly from websocket_init/1. The frames will be sent immediately after the handshake. +
  • +
  • Websocket handler callbacks no longer receive the Req argument. The init/2 callback still receives it and can be used to extract relevant information. The terminate/3 callback, if implemented, may still receive the Req (see next bullet point). +
  • +
  • Websocket handlers have a new req_filter option that can be used to customize how much information should be discarded from the Req object after the handshake. Note that the Req object is only available in terminate/3 past that point. +
  • +
  • Websocket handlers have their timeout default changed from infinity to 60 seconds. +
  • +

New functions

-
-
    -
  • -

    -The cowboy_req:scheme/1 function has been added. -

    -
  • -
  • -

    -The cowboy_req:uri/1,2 function has been added, replacing the - less powerful functions cowboy_req:url/1 and cowboy_req:host_url/1. -

    -
  • -
  • -

    -The functions cowboy_req:match_qs/2 and cowboy_req:match_cookies/2 - allow matching query string and cookies against constraints. -

    -
  • -
  • -

    -The function cowboy_req:set_resp_cookie/3 has been added to - complement cowboy_req:set_resp_cookie/4. -

    -
  • -
  • -

    -The functions cowboy_req:resp_header/2,3 and cowboy_req:resp_headers/1 - have been added. They can be used to retrieve response headers - that were previously set. -

    -
  • -
  • -

    -The function cowboy_req:set_resp_headers/2 has been added. It - allows setting many response headers at once. -

    -
  • -
  • -

    -The functions cowboy_req:push/3,4 can be used to push resources - for protocols that support it (by default only HTTP/2). -

    -
  • -
-
-
-
+
  • The cowboy_req:scheme/1 function has been added. +
  • +
  • The cowboy_req:uri/1,2 function has been added, replacing the less powerful functions cowboy_req:url/1 and cowboy_req:host_url/1. +
  • +
  • The functions cowboy_req:match_qs/2 and cowboy_req:match_cookies/2 allow matching query string and cookies against constraints. +
  • +
  • The function cowboy_req:set_resp_cookie/3 has been added to complement cowboy_req:set_resp_cookie/4. +
  • +
  • The functions cowboy_req:resp_header/2,3 and cowboy_req:resp_headers/1 have been added. They can be used to retrieve response headers that were previously set. +
  • +
  • The function cowboy_req:set_resp_headers/2 has been added. It allows setting many response headers at once. +
  • +
  • The functions cowboy_req:push/3,4 can be used to push resources for protocols that support it (by default only HTTP/2). +
  • +

Changed functions

-
-
    -
  • -

    -The cowboy:start_http/4 function was renamed to cowboy:start_clear/3. -

    -
  • -
  • -

    -The cowboy:start_https/4 function was renamed to cowboy:start_tls/3. -

    -
  • -
  • -

    -Most, if not all, functions in the cowboy_req module have been modified. - Please consult the changelog of each individual functions. The changes - are mainly about simplifying and clarifying the interface. The Req is no - longer returned when not necessary, maps are used wherever possible, - and some functions have been renamed. -

    -
  • -
  • -

    -The position of the Opts argument for cowboy_req:set_resp_cookie/4 - has changed to improve consistency. It is now the last argument. -

    -
  • -
-
-
-
+
  • The cowboy:start_http/4 function was renamed to cowboy:start_clear/3. +
  • +
  • The cowboy:start_https/4 function was renamed to cowboy:start_tls/3. +
  • +
  • Most, if not all, functions in the cowboy_req module have been modified. Please consult the changelog of each individual functions. The changes are mainly about simplifying and clarifying the interface. The Req is no longer returned when not necessary, maps are used wherever possible, and some functions have been renamed. +
  • +
  • The position of the Opts argument for cowboy_req:set_resp_cookie/4 has changed to improve consistency. It is now the last argument. +
  • +

Removed functions

-
-
    -
  • -

    -The functions cowboy_req:url/1 and cowboy_req:host_url/1 have been - removed in favor of the new function cowboy_req:uri/1,2. -

    -
  • -
  • -

    -The functions cowboy_req:meta/2,3 and cowboy_req:set_meta/3 have - been removed. The Req object is now a public map, therefore they became - unnecessary. -

    -
  • -
  • -

    -The functions cowboy_req:set_resp_body_fun/2,3 have been removed. - For sending files, the function cowboy_req:set_resp_body/2 can now - take a sendfile tuple. -

    -
  • -
  • -

    -Remove many undocumented functions from cowboy_req, including the - functions cowboy_req:get/2 and cowboy_req:set/3. -

    -
  • -
-
-
-
+
  • The functions cowboy_req:url/1 and cowboy_req:host_url/1 have been removed in favor of the new function cowboy_req:uri/1,2. +
  • +
  • The functions cowboy_req:meta/2,3 and cowboy_req:set_meta/3 have been removed. The Req object is now a public map, therefore they became unnecessary. +
  • +
  • The functions cowboy_req:set_resp_body_fun/2,3 have been removed. For sending files, the function cowboy_req:set_resp_body/2 can now take a sendfile tuple. +
  • +
  • Remove many undocumented functions from cowboy_req, including the functions cowboy_req:get/2 and cowboy_req:set/3. +
  • +

Other changes

-
-
    -
  • -

    -The correct percent-decoding algorithm is now used for path elements - during routing. It will no longer decode + characters. -

    -
  • -
  • -

    -The router will now properly handle path segments . and ... -

    -
  • -
  • -

    -Routing behavior has changed for URIs containing latin1 characters. - They are no longer allowed. URIs are expected to be in UTF-8 once - they are percent-decoded. -

    -
  • -
  • -

    -Clients that send multiple headers of the same name - will have the values of those headers concatenated into a - comma-separated list. This is of special importance in the - case of the content-type header, as previously only the - first value was used in the content_types_accepted/2 step - in REST handlers. -

    -
  • -
  • -

    -Etag comparison in REST handlers has been fixed. Some requests may - now fail when they succeeded in the past. -

    -
  • -
  • -

    -The If-*-Since headers are now ignored in REST handlers if - the corresponding If*-Match header exist. The former is - largely a backward compatible header and this shouldn’t create - any issue. The new behavior follows the current RFCs more closely. -

    -
  • -
  • -

    -The static file handler has been improved to handle more special - characters on systems that accept them. -

    -
  • -
-
-
+
  • The correct percent-decoding algorithm is now used for path elements during routing. It will no longer decode + characters. +
  • +
  • The router will now properly handle path segments . and ... +
  • +
  • Routing behavior has changed for URIs containing latin1 characters. They are no longer allowed. URIs are expected to be in UTF-8 once they are percent-decoded. +
  • +
  • Clients that send multiple headers of the same name will have the values of those headers concatenated into a comma-separated list. This is of special importance in the case of the content-type header, as previously only the first value was used in the content_types_accepted/2 step in REST handlers. +
  • +
  • Etag comparison in REST handlers has been fixed. Some requests may now fail when they succeeded in the past. +
  • +
  • The If-*-Since headers are now ignored in REST handlers if the corresponding If*-Match header exist. The former is largely a backward compatible header and this shouldn't create any issue. The new behavior follows the current RFCs more closely. +
  • +
  • The static file handler has been improved to handle more special characters on systems that accept them. +
  • +
+ diff --git a/docs/en/cowboy/2.4/guide/migrating_from_2.0/index.html b/docs/en/cowboy/2.4/guide/migrating_from_2.0/index.html index 7be09358..d5a9767f 100644 --- a/docs/en/cowboy/2.4/guide/migrating_from_2.0/index.html +++ b/docs/en/cowboy/2.4/guide/migrating_from_2.0/index.html @@ -62,188 +62,55 @@

Migrating from Cowboy 2.0 to 2.1

-

Cowboy 2.1 focused on adding features that were temporarily -removed in Cowboy 2.0. A number of bugs found in the 2.0 -release were also fixed.

-
+

Cowboy 2.1 focused on adding features that were temporarily removed in Cowboy 2.0. A number of bugs found in the 2.0 release were also fixed.

Features added

-
-
    -
  • -

    -It is now possible to obtain the client TLS certificate - and the local IP/port for the connection from the Req object. -

    +
    • It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object.
    • -
    • -

      -Informational responses (1XX responses) can now be sent. - They must be sent before initiating the final response. -

      +
    • Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response.
    • -
    • -

      -The expect: 100-continue header is now handled - automatically. The 100 response will be sent on the - first cowboy_req:read_body/2,3,4 call. This only applies - when using the default cowboy_stream_h stream handler. -

      +
    • The expect: 100-continue header is now handled automatically. The 100 response will be sent on the first cowboy_req:read_body/2,3,4 call. This only applies when using the default cowboy_stream_h stream handler.
    • -
-
-
-
+

Experimental features added

-
-

Experimental features are previews of features that will be -added in a future release. They are not documented and their -interface may change at any time. You are welcome to try them -and provide feedback.

-
    -
  • -

    -The cowboy_metrics_h stream handler can be used to - extract metrics out of Cowboy. It must be used first in - the list of stream handlers, and will record all events - related to requests, responses and spawned processes. - When the stream terminates it will pass this information - to a user-defined callback. -

    +

    Experimental features are previews of features that will be added in a future release. They are not documented and their interface may change at any time. You are welcome to try them and provide feedback.

    +
    • The cowboy_metrics_h stream handler can be used to extract metrics out of Cowboy. It must be used first in the list of stream handlers, and will record all events related to requests, responses and spawned processes. When the stream terminates it will pass this information to a user-defined callback.
    • -
    • -

      -The cowboy_tracer_h stream handler can be used to setup - automatic tracing of specific requests. You can conditionally - enable tracing based on a function, header, path or any other - element from the request and the trace will apply to the - entire connection and any processes created by it. This is - meant to be used for debugging both in tests and production. -

      +
    • The cowboy_tracer_h stream handler can be used to setup automatic tracing of specific requests. You can conditionally enable tracing based on a function, header, path or any other element from the request and the trace will apply to the entire connection and any processes created by it. This is meant to be used for debugging both in tests and production.
    • -
-
-
-
+

Changed behaviors

-
-
    -
  • -

    -The cowboy_rest handler now implements a mechanism for - switching to a different type of handler from any callback - where stop is also allowed. Switch by returning - {switch_handler, Module} or {switch_handler, Module, Opts}. - This is especially useful for switching to cowboy_loop - for streaming the request or response body. -

    +
    • The cowboy_rest handler now implements a mechanism for switching to a different type of handler from any callback where stop is also allowed. Switch by returning {switch_handler, Module} or {switch_handler, Module, Opts}. This is especially useful for switching to cowboy_loop for streaming the request or response body.
    • -
    • -

      -REST callbacks that do not allow stop as a return value - are now explicitly listed in the documentation. -

      +
    • REST callbacks that do not allow stop as a return value are now explicitly listed in the documentation.
    • -
-
-
-
+

New functions

-
-
    -
  • -

    -The function cowboy_req:sock/1 returns the IP/port - of the local socket. -

    +
    • The function cowboy_req:sock/1 returns the IP/port of the local socket.
    • -
    • -

      -The function cowboy_req:cert/1 returns the client - TLS certificate or undefined if it isn’t available. -

      +
    • The function cowboy_req:cert/1 returns the client TLS certificate or undefined if it isn't available.
    • -
    • -

      -The function cowboy_req:inform/2,3 sends an - informational response. -

      +
    • The function cowboy_req:inform/2,3 sends an informational response.
    • -
-
-
-
+

Bugs fixed

-
-
    -
  • -

    -Ensure HTTP/2 connections are not closed prematurely - when the user code does not read the request body. -

    +
    • Ensure HTTP/2 connections are not closed prematurely when the user code does not read the request body.
    • -
    • -

      -Ensure HTTP/1.1 streams are not terminated too early. - Their behavior is now consistent with the HTTP/2 code - where the stream handler is only terminated when the - stop command is returned. -

      +
    • Ensure HTTP/1.1 streams are not terminated too early. Their behavior is now consistent with the HTTP/2 code where the stream handler is only terminated when the stop command is returned.
    • -
    • -

      -Sending zero-sized data from stream handlers or from - cowboy_req:stream_body/3 could lead to issues with - HTTP/1.1. This has been fixed. -

      +
    • Sending zero-sized data from stream handlers or from cowboy_req:stream_body/3 could lead to issues with HTTP/1.1. This has been fixed.
    • -
    • -

      -The final chunk sent by Cowboy when it terminates a - chunked body after the handler process exits was not - passed through stream handlers, which could lead to - issues when cowboy_compress_h was being used. This - is now corrected. -

      +
    • The final chunk sent by Cowboy when it terminates a chunked body after the handler process exits was not passed through stream handlers, which could lead to issues when cowboy_compress_h was being used. This is now corrected.
    • -
    • -

      -The stream handler state was discarded in some cases - where Cowboy had to send a response or response data - automatically when ending a stream. This has now - been corrected. -

      +
    • The stream handler state was discarded in some cases where Cowboy had to send a response or response data automatically when ending a stream. This has now been corrected.
    • -
    • -

      -The stream handler callback terminate/3 will now be - called when switching to another protocol using the - command switch_protocol. This doesn’t apply when - doing upgrades to HTTP/2 as those occur before the - stream is initialized. -

      +
    • The stream handler callback terminate/3 will now be called when switching to another protocol using the command switch_protocol. This doesn't apply when doing upgrades to HTTP/2 as those occur before the stream is initialized.
    • -
    • -

      -Cowlib has been updated to 2.0.1 to fix an issue with - Websocket compression when using Erlang/OTP 20.1. Note - that at the time of writing all 20.1 versions (from - 20.1 to 20.1.4) have issues when compression is enabled. - It is expected to work properly from 20.1.5 onward. In - the meantime it is recommended to run the plain 20.1 - release and disable Websocket compression, or use a - release before 20.1. -

      +
    • Cowlib has been updated to 2.0.1 to fix an issue with Websocket compression when using Erlang/OTP 20.1. Note that at the time of writing all 20.1 versions (from 20.1 to 20.1.4) have issues when compression is enabled. It is expected to work properly from 20.1.5 onward. In the meantime it is recommended to run the plain 20.1 release and disable Websocket compression, or use a release before 20.1.
    • -
    • -

      -Cowboy will no longer crash when the cowboy_clock - process is not running. This can happen when Cowboy - is being restarted during upgrades, for example. -

      +
    • Cowboy will no longer crash when the cowboy_clock process is not running. This can happen when Cowboy is being restarted during upgrades, for example.
    • -
-
-
+ + diff --git a/docs/en/cowboy/2.4/guide/migrating_from_2.1/index.html b/docs/en/cowboy/2.4/guide/migrating_from_2.1/index.html index f9afc1c1..5ed0a8f8 100644 --- a/docs/en/cowboy/2.4/guide/migrating_from_2.1/index.html +++ b/docs/en/cowboy/2.4/guide/migrating_from_2.1/index.html @@ -62,203 +62,66 @@

Migrating from Cowboy 2.1 to 2.2

-

Cowboy 2.2 focused on adding features required for writing -gRPC servers and on completing test suites for the core -HTTP RFCs, fixing many bugs along the way.

-
+

Cowboy 2.2 focused on adding features required for writing gRPC servers and on completing test suites for the core HTTP RFCs, fixing many bugs along the way.

Features added

-
-
    -
  • -

    -Add support for sending trailers at the end of response bodies. - Trailers are additional header fields that may be sent after the - body to add more information to the response. Their usage is - required in gRPC servers. They are optional and may be discarded - in other scenarios (for example if the request goes through an - HTTP/1.0 proxy, as HTTP/1.0 does not support trailers). -

    +
    • Add support for sending trailers at the end of response bodies. Trailers are additional header fields that may be sent after the body to add more information to the response. Their usage is required in gRPC servers. They are optional and may be discarded in other scenarios (for example if the request goes through an HTTP/1.0 proxy, as HTTP/1.0 does not support trailers).
    • -
    • -

      -The max_skip_body_length option was added to cowboy_http. - It controls how much of a request body Cowboy is willing to skip - when the handler did not touch it. If the remaining body size is - too large Cowboy instead closes the connection. It defaults to 1MB. -

      +
    • The max_skip_body_length option was added to cowboy_http. It controls how much of a request body Cowboy is willing to skip when the handler did not touch it. If the remaining body size is too large Cowboy instead closes the connection. It defaults to 1MB.
    • -
    • -

      -The CONNECT and TRACE methods are now rejected as they are - currently not implemented and must be handled differently than - other methods. They will be implemented in a future release. -

      +
    • The CONNECT and TRACE methods are now rejected as they are currently not implemented and must be handled differently than other methods. They will be implemented in a future release.
    • -
-
-
-
+

New functions

-
-
    -
  • -

    -The function stream_trailers/2 has been added. It terminates - a stream and adds trailer fields at the end of the response. A - corresponding stream handler command {trailers, Trailers} - has also been added. -

    +
    • The function stream_trailers/2 has been added. It terminates a stream and adds trailer fields at the end of the response. A corresponding stream handler command {trailers, Trailers} has also been added.
    • -
-
-
-
+

Bugs fixed

-
-
    -
  • -

    -Test suites for the core HTTP RFCs RFC7230, RFC7231 and RFC7540 - have been completed. Many of the bugs listed here were fixed as - a result of this work. -

    +
    • Test suites for the core HTTP RFCs RFC7230, RFC7231 and RFC7540 have been completed. Many of the bugs listed here were fixed as a result of this work.
    • -
    • -

      -Many HTTP/2 edge cases when clients are misbehaving have been - corrected. This includes many cases where the request is malformed - (for example when a pseudo-header is present twice). -

      +
    • Many HTTP/2 edge cases when clients are misbehaving have been corrected. This includes many cases where the request is malformed (for example when a pseudo-header is present twice).
    • -
    • -

      -When the HTTP/2 SETTINGS_INITIAL_WINDOW_SIZE value changes, - Cowboy now properly updates the flow control windows. -

      +
    • When the HTTP/2 SETTINGS_INITIAL_WINDOW_SIZE value changes, Cowboy now properly updates the flow control windows.
    • -
    • -

      -HTTP/2 could mistakenly log stray messages that actually were - expected. This is no longer the case. -

      +
    • HTTP/2 could mistakenly log stray messages that actually were expected. This is no longer the case.
    • -
    • -

      -We no longer send a GOAWAY frame when the HTTP/2 preface is invalid. -

      +
    • We no longer send a GOAWAY frame when the HTTP/2 preface is invalid.
    • -
    • -

      -Some values in the Req object of pushed requests were in the - wrong type. They are now the expected binary instead of iolist. -

      +
    • Some values in the Req object of pushed requests were in the wrong type. They are now the expected binary instead of iolist.
    • -
    • -

      -A response body was sometimes sent in response to HEAD requests - when using HTTP/2. The body is now ignored. -

      +
    • A response body was sometimes sent in response to HEAD requests when using HTTP/2. The body is now ignored.
    • -
    • -

      -The max_headers option for cowboy_http was not always respected - depending on the contents of the buffer. The limit is now strict. -

      +
    • The max_headers option for cowboy_http was not always respected depending on the contents of the buffer. The limit is now strict.
    • -
    • -

      -When an early error occurred on the HTTP/1.1 request line, the - partial Req given to stream handlers was missing the ref and - peer information. This has been corrected. -

      +
    • When an early error occurred on the HTTP/1.1 request line, the partial Req given to stream handlers was missing the ref and peer information. This has been corrected.
    • -
    • -

      -Absolute URIs with a userinfo component, or without an authority - component, are now properly rejected for HTTP/1.0 and HTTP/1.1. -

      +
    • Absolute URIs with a userinfo component, or without an authority component, are now properly rejected for HTTP/1.0 and HTTP/1.1.
    • -
    • -

      -Whitespace is no longer allowed in header lines before the colon. -

      +
    • Whitespace is no longer allowed in header lines before the colon.
    • -
    • -

      -408 responses to HTTP/1.1 requests now properly include a - connection: close header indicating that we are going to - close the connection. This header will also be sent for - other early errors resulting in the closing of the connection. -

      +
    • 408 responses to HTTP/1.1 requests now properly include a connection: close header indicating that we are going to close the connection. This header will also be sent for other early errors resulting in the closing of the connection.
    • -
    • -

      -When both the transfer-encoding and content-length headers are - sent in an HTTP/1.1 request, the transfer-encoding now takes - precedence over the content-length header and the latter is - removed from the Req object. -

      +
    • When both the transfer-encoding and content-length headers are sent in an HTTP/1.1 request, the transfer-encoding now takes precedence over the content-length header and the latter is removed from the Req object.
    • -
    • -

      -A 400 response is now returned when the transfer-encoding - header is invalid or contains any transfer-coding other - than chunked. -

      +
    • A 400 response is now returned when the transfer-encoding header is invalid or contains any transfer-coding other than chunked.
    • -
    • -

      -Invalid chunk sizes are now rejected immediately. -

      +
    • Invalid chunk sizes are now rejected immediately.
    • -
    • -

      -Chunk extensions are now limited to 129 characters. They are - not used in practice and are still ignored by Cowboy. The limit - is not configurable. -

      +
    • Chunk extensions are now limited to 129 characters. They are not used in practice and are still ignored by Cowboy. The limit is not configurable.
    • -
    • -

      -The final chunk was mistakenly sent in responses to HEAD - requests. This is now corrected. -

      +
    • The final chunk was mistakenly sent in responses to HEAD requests. This is now corrected.
    • -
    • -

      -OPTIONS * requests were broken in Cowboy 2.0. They are now - working again. Both the routing and cowboy_req:uri/1,2 have - been corrected. -

      +
    • OPTIONS * requests were broken in Cowboy 2.0. They are now working again. Both the routing and cowboy_req:uri/1,2 have been corrected.
    • -
    • -

      -204 responses no longer include a content-length header. -

      +
    • 204 responses no longer include a content-length header.
    • -
    • -

      -A packet could be lost when switching to Websocket or any - other protocol via the switch_protocol command. This is - now fixed. -

      +
    • A packet could be lost when switching to Websocket or any other protocol via the switch_protocol command. This is now fixed.
    • -
    • -

      -A 426 response will now be sent when a handler requires - the client to upgrade to Websocket and the request did not - include the required headers. -

      +
    • A 426 response will now be sent when a handler requires the client to upgrade to Websocket and the request did not include the required headers.
    • -
    • -

      -Both experimental stream handlers cowboy_metrics_h and - cowboy_tracer_h received a number of fixes and improvements. -

      +
    • Both experimental stream handlers cowboy_metrics_h and cowboy_tracer_h received a number of fixes and improvements.
    • -
-
-
+ + diff --git a/docs/en/cowboy/2.4/guide/migrating_from_2.2/index.html b/docs/en/cowboy/2.4/guide/migrating_from_2.2/index.html index 5bc480c7..e21d669b 100644 --- a/docs/en/cowboy/2.4/guide/migrating_from_2.2/index.html +++ b/docs/en/cowboy/2.4/guide/migrating_from_2.2/index.html @@ -62,108 +62,38 @@

Migrating from Cowboy 2.2 to 2.3

-

Cowboy 2.3 focused on making the Cowboy processes behave -properly according to OTP principles. This version is a -very good milestone toward that goal and most of everything -should now work. Release upgrades and a few details will -be improved in future versions.

-
+

Cowboy 2.3 focused on making the Cowboy processes behave properly according to OTP principles. This version is a very good milestone toward that goal and most of everything should now work. Release upgrades and a few details will be improved in future versions.

Features added

-
-
    -
  • -

    -Add support for all functions from the module sys. Note - that Cowboy currently does not implement the sys debugging - mechanisms as tracing is recommended instead. -

    +
    • Add support for all functions from the module sys. Note that Cowboy currently does not implement the sys debugging mechanisms as tracing is recommended instead.
    • -
    • -

      -Add a max_frame_size option for Websocket handlers - to close the connection when the client attempts to - send a frame that’s too large. It currently defaults - to infinity to avoid breaking existing code but will - be changed in a future version. -

      +
    • Add a max_frame_size option for Websocket handlers to close the connection when the client attempts to send a frame that's too large. It currently defaults to infinity to avoid breaking existing code but will be changed in a future version.
    • -
    • -

      -Update Cowlib to 2.2.1. -

      +
    • Update Cowlib to 2.2.1.
    • -
    • -

      -Add support for the 308 status code and a test suite - for RFC7538 where it is defined. -

      +
    • Add support for the 308 status code and a test suite for RFC7538 where it is defined.
    • -
-
-
-
+

Bugs fixed

-
-
    -
  • -

    -Ensure timeout options accept the value infinity as - documented. -

    +
    • Ensure timeout options accept the value infinity as documented.
    • -
    • -

      -Properly reject HTTP/2 requests with an invalid content-length - header instead of simply crashing. -

      +
    • Properly reject HTTP/2 requests with an invalid content-length header instead of simply crashing.
    • -
    • -

      -When switching from HTTP/1.1 to Websocket or user protocols - all the messages in the mailbox were flushed. Only messages - specific to cowboy_http should now be flushed. -

      +
    • When switching from HTTP/1.1 to Websocket or user protocols all the messages in the mailbox were flushed. Only messages specific to cowboy_http should now be flushed.
    • -
    • -

      -Parsing of the x-forwarded-for header has been corrected. - It now supports IPv6 addresses both with and without port. -

      +
    • Parsing of the x-forwarded-for header has been corrected. It now supports IPv6 addresses both with and without port.
    • -
    • -

      -Websocket subprotocol tokens are now parsed in a case - insensitive manner, according to the spec. -

      +
    • Websocket subprotocol tokens are now parsed in a case insensitive manner, according to the spec.
    • -
    • -

      -Cookies without values are now allowed. For example Cookie: foo. -

      +
    • Cookies without values are now allowed. For example Cookie: foo.
    • -
    • -

      -Colons are now allowed within path segments in routes provided - to cowboy_router:compile/1 as long as they are not the first - character of the path segment. -

      +
    • Colons are now allowed within path segments in routes provided to cowboy_router:compile/1 as long as they are not the first character of the path segment.
    • -
    • -

      -The cowboy_req:delete_resp_header/2 function will no longer - crash when no response header was set before calling it. -

      +
    • The cowboy_req:delete_resp_header/2 function will no longer crash when no response header was set before calling it.
    • -
    • -

      -A miscount of the output HTTP/2 flow control window has been - fixed. It prevented sending the response body fully to some - clients. The issue only affected response bodies sent as iolists. -

      +
    • A miscount of the output HTTP/2 flow control window has been fixed. It prevented sending the response body fully to some clients. The issue only affected response bodies sent as iolists.
    • -
-
-
+ + diff --git a/docs/en/cowboy/2.4/guide/migrating_from_2.3/index.html b/docs/en/cowboy/2.4/guide/migrating_from_2.3/index.html index f9f5dd2b..a0437915 100644 --- a/docs/en/cowboy/2.4/guide/migrating_from_2.3/index.html +++ b/docs/en/cowboy/2.4/guide/migrating_from_2.3/index.html @@ -62,121 +62,40 @@

Migrating from Cowboy 2.3 to 2.4

-

Cowboy 2.4 focused on improving the HTTP/2 implementation. -All existing tests from RFC7540 and the h2spec test suite -now all pass. Numerous options have been added to control -SETTINGS and related behavior. In addition experimental -support for Websocket over HTTP/2 was added.

-
+

Cowboy 2.4 focused on improving the HTTP/2 implementation. All existing tests from RFC7540 and the h2spec test suite now all pass. Numerous options have been added to control SETTINGS and related behavior. In addition experimental support for Websocket over HTTP/2 was added.

Features added

-
-
    -
  • -

    -Add experimental support for Websocket over HTTP/2. - You can use the enable_connect_protocol option to - enable. It implements the following draft: - https://tools.ietf.org/html/draft-ietf-httpbis-h2-websockets-01 -

    +
    • Add experimental support for Websocket over HTTP/2. You can use the enable_connect_protocol option to enable. It implements the following draft: https://tools.ietf.org/html/draft-ietf-httpbis-h2-websockets-01
    • -
    • -

      -Add options max_decode_table_size and - max_encode_table_size to restrict the size of the - HPACK compression dictionary. -

      +
    • Add options max_decode_table_size and max_encode_table_size to restrict the size of the HPACK compression dictionary.
    • -
    • -

      -Add option max_concurrent_streams to restrict the - number of HTTP/2 streams that can be opened concurrently. -

      +
    • Add option max_concurrent_streams to restrict the number of HTTP/2 streams that can be opened concurrently.
    • -
    • -

      -Add options initial_connection_window_size and - initial_stream_window_size to restrict the size of - the HTTP/2 request body buffers for the whole connection - and per stream, respectively. -

      +
    • Add options initial_connection_window_size and initial_stream_window_size to restrict the size of the HTTP/2 request body buffers for the whole connection and per stream, respectively.
    • -
    • -

      -Add options max_frame_size_received and - max_frame_size_sent to restrict the size of - HTTP/2 frames. -

      +
    • Add options max_frame_size_received and max_frame_size_sent to restrict the size of HTTP/2 frames.
    • -
    • -

      -Add option settings_timeout to reject clients that - did not send a SETTINGS ack. Note that this currently - may only occur at the beginning of the connection. -

      +
    • Add option settings_timeout to reject clients that did not send a SETTINGS ack. Note that this currently may only occur at the beginning of the connection.
    • -
    • -

      -Update Ranch to 1.5.0 -

      +
    • Update Ranch to 1.5.0
    • -
    • -

      -Update Cowlib to 2.3.0 -

      +
    • Update Cowlib to 2.3.0
    • -
-
-
-
+

Bugs fixed

-
-
    -
  • -

    -Fix the END_STREAM flag for informational responses - when using HTTP/2. -

    +
    • Fix the END_STREAM flag for informational responses when using HTTP/2.
    • -
    • -

      -Receive and ignore HTTP/2 request trailers if any - for HTTP/2 requests. Request trailer information will - be propagated to the user code in a future release. -

      +
    • Receive and ignore HTTP/2 request trailers if any for HTTP/2 requests. Request trailer information will be propagated to the user code in a future release.
    • -
    • -

      -Reject WINDOW_UPDATE frames that are sent after the - client sent an RST_STREAM. Note that Cowboy will not - keep state information about terminated streams - forever and so the behavior might differ depending - on when the stream was reset. -

      +
    • Reject WINDOW_UPDATE frames that are sent after the client sent an RST_STREAM. Note that Cowboy will not keep state information about terminated streams forever and so the behavior might differ depending on when the stream was reset.
    • -
    • -

      -Reject streams that depend on themselves. Note that - Cowboy currently does not implement HTTP/2’s priority - mechanisms so this issue was harmless. -

      +
    • Reject streams that depend on themselves. Note that Cowboy currently does not implement HTTP/2's priority mechanisms so this issue was harmless.
    • -
    • -

      -Reject HTTP/2 requests where the body size is different - than the content-length value. Note that due to how Cowboy - works some requests might go through regardless, for - example when the user code does not read the request body. -

      +
    • Reject HTTP/2 requests where the body size is different than the content-length value. Note that due to how Cowboy works some requests might go through regardless, for example when the user code does not read the request body.
    • -
    • -

      -Fix all existing test failures from RFC7540. This was - mostly incorrect test cases or intermittent failures. -

      +
    • Fix all existing test failures from RFC7540. This was mostly incorrect test cases or intermittent failures.
    • -
-
-
+ + diff --git a/docs/en/cowboy/2.4/guide/modern_web/index.html b/docs/en/cowboy/2.4/guide/modern_web/index.html index 0a335686..00328997 100644 --- a/docs/en/cowboy/2.4/guide/modern_web/index.html +++ b/docs/en/cowboy/2.4/guide/modern_web/index.html @@ -62,115 +62,38 @@

The modern Web

-

Cowboy is a server for the modern Web. This chapter explains -what it means and details all the standards involved.

-

Cowboy supports all the standards listed in this document.

-
+

Cowboy is a server for the modern Web. This chapter explains what it means and details all the standards involved.

+

Cowboy supports all the standards listed in this document.

HTTP/2

-
-

HTTP/2 is the most efficient protocol for consuming Web -services. It enables clients to keep a connection open -for long periods of time; to send requests concurrently; -to reduce the size of requests through HTTP headers -compression; and more. The protocol is binary, greatly -reducing the resources needed to parse it.

-

HTTP/2 also enables the server to push messages to the -client. This can be used for various purposes, including -the sending of related resources before the client requests -them, in an effort to reduce latency. This can also be used -to enable bidirectional communication.

-

Cowboy provides transparent support for HTTP/2. Clients -that know it can use it; others fall back to HTTP/1.1 -automatically.

-

HTTP/2 is compatible with the HTTP/1.1 semantics.

-

HTTP/2 is defined by RFC 7540 and RFC 7541.

-
-
-
+

HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. The protocol is binary, greatly reducing the resources needed to parse it.

+

HTTP/2 also enables the server to push messages to the client. This can be used for various purposes, including the sending of related resources before the client requests them, in an effort to reduce latency. This can also be used to enable bidirectional communication.

+

Cowboy provides transparent support for HTTP/2. Clients that know it can use it; others fall back to HTTP/1.1 automatically.

+

HTTP/2 is compatible with the HTTP/1.1 semantics.

+

HTTP/2 is defined by RFC 7540 and RFC 7541.

HTTP/1.1

-
-

HTTP/1.1 is the previous version of the HTTP protocol. -The protocol itself is text-based and suffers from numerous -issues and limitations. In particular it is not possible -to execute requests concurrently (though pipelining is -sometimes possible), and it’s also sometimes difficult -to detect that a client disconnected.

-

HTTP/1.1 does provide very good semantics for interacting -with Web services. It defines the standard methods, headers -and status codes used by HTTP/1.1 and HTTP/2 clients and -servers.

-

HTTP/1.1 also defines compatibility with an older version -of the protocol, HTTP/1.0, which was never really standardized -across implementations.

-

The core of HTTP/1.1 is defined by RFC 7230, RFC 7231, -RFC 7232, RFC 7233, RFC 7234 and RFC 7235. Numerous RFCs -and other specifications exist defining additional HTTP -methods, status codes, headers or semantics.

-
-
-
+

HTTP/1.1 is the previous version of the HTTP protocol. The protocol itself is text-based and suffers from numerous issues and limitations. In particular it is not possible to execute requests concurrently (though pipelining is sometimes possible), and it's also sometimes difficult to detect that a client disconnected.

+

HTTP/1.1 does provide very good semantics for interacting with Web services. It defines the standard methods, headers and status codes used by HTTP/1.1 and HTTP/2 clients and servers.

+

HTTP/1.1 also defines compatibility with an older version of the protocol, HTTP/1.0, which was never really standardized across implementations.

+

The core of HTTP/1.1 is defined by RFC 7230, RFC 7231, RFC 7232, RFC 7233, RFC 7234 and RFC 7235. Numerous RFCs and other specifications exist defining additional HTTP methods, status codes, headers or semantics.

Websocket

-
-

Websocket is a protocol built on top of HTTP/1.1 -that provides a two-ways communication channel between the client and -the server. Communication is asynchronous and can occur concurrently.

-

It consists of a Javascript object allowing setting up a -Websocket connection to the server, and a binary based -protocol for sending data to the server or the client.

-

Websocket connections can transfer either UTF-8 encoded text -data or binary data. The protocol also includes support for -implementing a ping/pong mechanism, allowing the server and -the client to have more confidence that the connection is still -alive.

-

A Websocket connection can be used to transfer any kind of data, -small or big, text or binary. Because of this Websocket is -sometimes used for communication between systems.

-

Websocket messages have no semantics on their own. Websocket -is closer to TCP in that aspect, and requires you to design -and implement your own protocol on top of it; or adapt an -existing protocol to Websocket.

-

Cowboy provides an interface known as Websocket handlers -that gives complete control over a Websocket connection.

-

The Websocket protocol is defined by RFC 6455.

-
-
-
+

Websocket is a protocol built on top of HTTP/1.1 that provides a two-ways communication channel between the client and the server. Communication is asynchronous and can occur concurrently.

+

It consists of a Javascript object allowing setting up a Websocket connection to the server, and a binary based protocol for sending data to the server or the client.

+

Websocket connections can transfer either UTF-8 encoded text data or binary data. The protocol also includes support for implementing a ping/pong mechanism, allowing the server and the client to have more confidence that the connection is still alive.

+

A Websocket connection can be used to transfer any kind of data, small or big, text or binary. Because of this Websocket is sometimes used for communication between systems.

+

Websocket messages have no semantics on their own. Websocket is closer to TCP in that aspect, and requires you to design and implement your own protocol on top of it; or adapt an existing protocol to Websocket.

+

Cowboy provides an interface known as Websocket handlers that gives complete control over a Websocket connection.

+

The Websocket protocol is defined by RFC 6455.

Long-lived requests

-
-

Cowboy provides an interface that can be used to support -long-polling or to stream large amounts of data reliably, -including using Server-Sent Events.

-

Long-polling is a mechanism in which the client performs -a request which may not be immediately answered by the -server. It allows clients to request resources that may -not currently exist, but are expected to be created soon, -and which will be returned as soon as they are.

-

Long-polling is essentially a hack, but it is widely used -to overcome limitations on older clients and servers.

-

Server-Sent Events is a small protocol defined as a media -type, text/event-stream, along with a new HTTP header, -Last-Event-ID. It is defined in the EventSource W3C -specification.

-

Cowboy provides an interface known as loop handlers -that facilitates the implementation of long-polling or stream -mechanisms. It works regardless of the underlying protocol.

-
-
-
+

Cowboy provides an interface that can be used to support long-polling or to stream large amounts of data reliably, including using Server-Sent Events.

+

Long-polling is a mechanism in which the client performs a request which may not be immediately answered by the server. It allows clients to request resources that may not currently exist, but are expected to be created soon, and which will be returned as soon as they are.

+

Long-polling is essentially a hack, but it is widely used to overcome limitations on older clients and servers.

+

Server-Sent Events is a small protocol defined as a media type, text/event-stream, along with a new HTTP header, Last-Event-ID. It is defined in the EventSource W3C specification.

+

Cowboy provides an interface known as loop handlers that facilitates the implementation of long-polling or stream mechanisms. It works regardless of the underlying protocol.

REST

-
-

REST, or REpresentational State Transfer, -is a style of architecture for loosely connected distributed -systems. It can easily be implemented on top of HTTP.

-

REST is essentially a set of constraints to be followed. -Many of these constraints are purely architectural and -solved by simply using HTTP. Some constraints must be -explicitly followed by the developer.

-

Cowboy provides an interface known as REST handlers -that simplifies the implementation of a REST API on top of -the HTTP protocol.

-
-
+

REST, or REpresentational State Transfer, is a style of architecture for loosely connected distributed systems. It can easily be implemented on top of HTTP.

+

REST is essentially a set of constraints to be followed. Many of these constraints are purely architectural and solved by simply using HTTP. Some constraints must be explicitly followed by the developer.

+

Cowboy provides an interface known as REST handlers that simplifies the implementation of a REST API on top of the HTTP protocol.

+ diff --git a/docs/en/cowboy/2.4/guide/multipart/index.html b/docs/en/cowboy/2.4/guide/multipart/index.html index 2cec2e85..e6a5b0b7 100644 --- a/docs/en/cowboy/2.4/guide/multipart/index.html +++ b/docs/en/cowboy/2.4/guide/multipart/index.html @@ -62,169 +62,107 @@

Multipart requests

-

Multipart originates from MIME, an Internet standard that -extends the format of emails.

-

A multipart message is a list of parts. A part contains -headers and a body. The body of the parts may be -of any media type, and contain text or binary data. -It is possible for parts to contain a multipart media -type.

-

In the context of HTTP, multipart is most often used -with the multipart/form-data media type. It is what -browsers use to upload files through HTML forms.

-

The multipart/byteranges is also common. It is the -media type used to send arbitrary bytes from a resource, -enabling clients to resume downloads.

-
+

Multipart originates from MIME, an Internet standard that extends the format of emails.

+

A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type.

+

In the context of HTTP, multipart is most often used with the multipart/form-data media type. It is what browsers use to upload files through HTML forms.

+

The multipart/byteranges is also common. It is the media type used to send arbitrary bytes from a resource, enabling clients to resume downloads.

Form-data

-
-

In the normal case, when a form is submitted, the -browser will use the application/x-www-form-urlencoded -content-type. This type is just a list of keys and -values and is therefore not fit for uploading files.

-

That’s where the multipart/form-data content-type -comes in. When the form is configured to use this -content-type, the browser will create a multipart -message where each part corresponds to a field on -the form. For files, it also adds some metadata in -the part headers, like the file name.

-

A form with a text input, a file input and a select -choice box will result in a multipart message with -three parts, one for each field.

-

The browser does its best to determine the media type -of the files it sends this way, but you should not -rely on it for determining the contents of the file. -Proper investigation of the contents is recommended.

-
-
-
+

In the normal case, when a form is submitted, the browser will use the application/x-www-form-urlencoded content-type. This type is just a list of keys and values and is therefore not fit for uploading files.

+

That's where the multipart/form-data content-type comes in. When the form is configured to use this content-type, the browser will create a multipart message where each part corresponds to a field on the form. For files, it also adds some metadata in the part headers, like the file name.

+

A form with a text input, a file input and a select choice box will result in a multipart message with three parts, one for each field.

+

The browser does its best to determine the media type of the files it sends this way, but you should not rely on it for determining the contents of the file. Proper investigation of the contents is recommended.

Checking for multipart messages

-
-

The content-type header indicates the presence of -a multipart message:

-
-
-
{<<"multipart">>, <<"form-data">>, _}
-    = cowboy_req:parse_header(<<"content-type">>, Req).
-
-
-
+
{<<"multipart">>, <<"form-data">>, _}
+    = cowboy_req:parse_header(<<"content-type">>, Req).
+

Reading a multipart message

-
-

Cowboy provides two sets of functions for reading -request bodies as multipart messages.

-

The cowboy_req:read_part/1,2 functions return the -next part’s headers, if any.

-

The cowboy_req:read_part_body/1,2 functions return -the current part’s body. For large bodies you may -need to call the function multiple times.

-

To read a multipart message you need to iterate over -all its parts:

-
-
-
multipart(Req0) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, _Headers, Req1} ->
-            {ok, _Body, Req} = cowboy_req:read_part_body(Req1),
-            multipart(Req);
-        {done, Req} ->
-            Req
-    end.
-

When part bodies are too large, Cowboy will return -a more tuple, and allow you to loop until the part -body has been fully read.

-

The function cow_multipart:form_data/1 can be used -to quickly obtain information about a part from a -multipart/form-data message. The function returns -a data or a file tuple depending on whether this -is a normal field or a file being uploaded.

-

The following snippet will use this function and -use different strategies depending on whether the -part is a file:

-
-
-
multipart(Req0) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, Headers, Req1} ->
-            Req = case cow_multipart:form_data(Headers) of
-                {data, _FieldName} ->
-                    {ok, _Body, Req2} = cowboy_req:read_part_body(Req1),
-                    Req2;
-                {file, _FieldName, _Filename, _CType} ->
-                    stream_file(Req1)
-            end,
-            multipart(Req);
-        {done, Req} ->
-            Req
-    end.
-
-stream_file(Req0) ->
-    case cowboy_req:read_part_body(Req0) of
-        {ok, _LastBodyChunk, Req} ->
-            Req;
-        {more, _BodyChunk, Req} ->
-            stream_file(Req)
-    end.
-

Both the part header and body reading functions can take -options that will be given to the request body reading -functions. By default, cowboy_req:read_part/1 reads -up to 64KB for up to 5 seconds. cowboy_req:read_part_body/1 -has the same defaults as cowboy_req:read_body/1.

-

To change the defaults for part headers:

-
-
-
cowboy_req:read_part(Req, #{length => 128000}).
-

And for part bodies:

-
-
-
cowboy_req:read_part_body(Req, #{length => 1000000, period => 7000}).
-
- -
+
cowboy_req:read_part_body(Req, #{length => 1000000, period => 7000}).
+

Skipping unwanted parts

-
-

Part bodies do not have to be read. Cowboy will automatically -skip it when you request the next part’s body.

-

The following snippet reads all part headers and skips -all bodies:

-
-
-
multipart(Req0) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, _Headers, Req} ->
-            multipart(Req);
-        {done, Req} ->
-            Req
-    end.
-

Similarly, if you start reading the body and it ends up -being too big, you can simply continue with the next part. -Cowboy will automatically skip what remains.

-

While Cowboy can skip part bodies automatically, the read -rate is not configurable. Depending on your application -you may want to skip manually, in particular if you observe -poor performance while skipping.

-

You do not have to read all parts either. You can stop -reading as soon as you find the data you need.

-
- +
multipart(Req0) ->
+    case cowboy_req:read_part(Req0) of
+        {ok, _Headers, Req} ->
+            multipart(Req);
+        {done, Req} ->
+            Req
+    end.
+ +

Similarly, if you start reading the body and it ends up being too big, you can simply continue with the next part. Cowboy will automatically skip what remains.

+

While Cowboy can skip part bodies automatically, the read rate is not configurable. Depending on your application you may want to skip manually, in particular if you observe poor performance while skipping.

+

You do not have to read all parts either. You can stop reading as soon as you find the data you need.

+ + diff --git a/docs/en/cowboy/2.4/guide/req/index.html b/docs/en/cowboy/2.4/guide/req/index.html index 4c03cb6f..f23bf6c8 100644 --- a/docs/en/cowboy/2.4/guide/req/index.html +++ b/docs/en/cowboy/2.4/guide/req/index.html @@ -62,407 +62,282 @@

The Req object

-

The Req object is a variable used for obtaining information -about a request, read its body or send a response.

-

It is not really an object in the object-oriented sense. -It is a simple map that can be directly accessed or -used when calling functions from the cowboy_req module.

-

The Req object is the subject of a few different chapters. -In this chapter we will learn about the Req object and -look at how to retrieve information about the request.

-
+

The Req object is a variable used for obtaining information about a request, read its body or send a response.

+

It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module.

+

The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request.

Direct access

-
-

The Req map contains a number of fields which are documented -and can be accessed directly. They are the fields that have -a direct mapping to HTTP: the request method; the HTTP -version used; the effective URI components scheme, -host, port, path and qs; the request headers; -and the connection peer address and port.

-

Note that the version field can be used to determine -whether a connection is using HTTP/2.

-

To access a field, you can simply match in the function -head. The following example sends a simple "Hello world!" -response when the method is GET, and a 405 error -otherwise.

-
-
-
init(Req0=#{method := <<"GET">>}, State) ->
-    Req = cowboy_req:reply(200, #{
-        <<"content-type">> => <<"text/plain">>
-    }, <<"Hello world!">>, Req0),
-    {ok, Req, State};
-init(Req0, State) ->
-    Req = cowboy_req:reply(405, #{
-        <<"allow">> => <<"GET">>
-    }, Req0),
-    {ok, Req, State}.
-

Any other field is internal and should not be accessed. -They may change in future releases, including maintenance -releases, without notice.

-

Modifying the Req object, while allowed, is not recommended -unless strictly necessary. If adding new fields, make sure -to namespace the field names so that no conflict can occur -with future Cowboy updates or third party projects.

-
-
-
+
init(Req0=#{method := <<"GET">>}, State) ->
+    Req = cowboy_req:reply(200, #{
+        <<"content-type">> => <<"text/plain">>
+    }, <<"Hello world!">>, Req0),
+    {ok, Req, State};
+init(Req0, State) ->
+    Req = cowboy_req:reply(405, #{
+        <<"allow">> => <<"GET">>
+    }, Req0),
+    {ok, Req, State}.
+
+

Any other field is internal and should not be accessed. They may change in future releases, including maintenance releases, without notice.

+

Modifying the Req object, while allowed, is not recommended unless strictly necessary. If adding new fields, make sure to namespace the field names so that no conflict can occur with future Cowboy updates or third party projects.

Introduction to the cowboy_req interface

-
-

Functions in the cowboy_req module provide access to -the request information but also various operations that -are common when dealing with HTTP requests.

-

All the functions that begin with a verb indicate an action. -Other functions simply return the corresponding value -(sometimes that value does need to be built, but the -cost of the operation is equivalent to retrieving a value).

-

Some of the cowboy_req functions return an updated Req -object. They are the read, reply, set and delete functions. -While ignoring the returned Req will not cause incorrect -behavior for some of them, it is highly recommended to -always keep and use the last returned Req object. The -manual for cowboy_req details these functions and what -modifications are done to the Req object.

-

Some of the calls to cowboy_req have side effects. This -is the case of the read and reply functions. Cowboy reads -the request body or replies immediately when the function -is called.

-

All functions will crash if something goes wrong. There -is usually no need to catch these errors, Cowboy will -send the appropriate 4xx or 5xx response depending on -where the crash occurred.

-
- -
+ +

Functions in the cowboy_req module provide access to the request information but also various operations that are common when dealing with HTTP requests.

+

All the functions that begin with a verb indicate an action. Other functions simply return the corresponding value (sometimes that value does need to be built, but the cost of the operation is equivalent to retrieving a value).

+

Some of the cowboy_req functions return an updated Req object. They are the read, reply, set and delete functions. While ignoring the returned Req will not cause incorrect behavior for some of them, it is highly recommended to always keep and use the last returned Req object. The manual for cowboy_req details these functions and what modifications are done to the Req object.

+

Some of the calls to cowboy_req have side effects. This is the case of the read and reply functions. Cowboy reads the request body or replies immediately when the function is called.

+

All functions will crash if something goes wrong. There is usually no need to catch these errors, Cowboy will send the appropriate 4xx or 5xx response depending on where the crash occurred.

Request method

-
-

The request method can be retrieved directly:

-
-
-
#{method := Method} = Req.
-

Or using a function:

-
-
-
Method = cowboy_req:method(Req).
-

The method is a case sensitive binary string. Standard -methods include GET, HEAD, OPTIONS, PATCH, POST, PUT -or DELETE.

-
-
-
+
Method = cowboy_req:method(Req).
+
+

The method is a case sensitive binary string. Standard methods include GET, HEAD, OPTIONS, PATCH, POST, PUT or DELETE.

HTTP version

-
-

The HTTP version is informational. It does not indicate that -the client implements the protocol well or fully.

-

There is typically no need to change behavior based on the -HTTP version: Cowboy already does it for you.

-

It can be useful in some cases, though. For example, one may -want to redirect HTTP/1.1 clients to use Websocket, while HTTP/2 -clients keep using HTTP/2.

-

The HTTP version can be retrieved directly:

-
-
-
#{version := Version} = Req.
-

Or using a function:

-
-
-
Version = cowboy_req:version(Req).
-

Cowboy defines the 'HTTP/1.0', 'HTTP/1.1' and 'HTTP/2' -versions. Custom protocols can define their own values as -atoms.

-
- -
+
Version = cowboy_req:version(Req).
+
+

Cowboy defines the 'HTTP/1.0', 'HTTP/1.1' and 'HTTP/2' versions. Custom protocols can define their own values as atoms.

Effective request URI

-
-

The scheme, host, port, path and query string components -of the effective request URI can all be retrieved directly:

-
-
#{
-    scheme := Scheme,
-    host := Host,
-    port := Port,
-    path := Path,
-    qs := Qs
-} = Req.
-

Or using the related functions:

-
-
-
Scheme = cowboy_req:scheme(Req),
-Host = cowboy_req:host(Req),
-Port = cowboy_req:port(Req),
-Path = cowboy_req:path(Req).
-Qs = cowboy_req:qs(Req).
-

The scheme and host are lowercased case insensitive binary -strings. The port is an integer representing the port number. -The path and query string are case sensitive binary strings.

-

Cowboy defines only the <<"http">> and <<"https">> schemes. -They are chosen so that the scheme will only be <<"https">> -for requests on secure HTTP/1.1 or HTTP/2 connections.

-

The effective request URI itself can be reconstructed with -the cowboy_req:uri/1,2 function. By default, an absolute -URI is returned:

-
-
+

The effective request URI itself can be reconstructed with the cowboy_req:uri/1,2 function. By default, an absolute URI is returned:

+
-
%% scheme://host[:port]/path[?qs]
-URI = cowboy_req:uri(Req).
-

Options are available to either disable or replace some -or all of the components. Various URIs or URI formats can -be generated this way, including the origin form:

-
-
-
%% /path[?qs]
-URI = cowboy_req:uri(Req, #{host => undefined}).
-

The protocol relative form:

-
-
-
%% //host[:port]/path[?qs]
-URI = cowboy_req:uri(Req, #{scheme => undefined}).
-

The absolute URI without a query string:

-
-
-
URI = cowboy_req:uri(Req, #{qs => undefined}).
-

A different host:

-
-
-
URI = cowboy_req:uri(Req, #{host => <<"example.org">>}).
-

And any other combination.

-
-
-
+
URI = cowboy_req:uri(Req, #{host => <<"example.org">>}).
+
+

And any other combination.

Bindings

-
-

Bindings are the host and path components that you chose -to extract when defining the routes of your application. -They are only available after the routing.

-

Cowboy provides functions to retrieve one or all bindings.

-

To retrieve a single value:

-
-
-
Value = cowboy_req:binding(userid, Req).
-

When attempting to retrieve a value that was not bound, -undefined will be returned. A different default value -can be provided:

-
-
-
Value = cowboy_req:binding(userid, Req, 42).
-

To retrieve everything that was bound:

-
-
-
Bindings = cowboy_req:bindings(Req).
-

They are returned as a map, with keys being atoms.

-

The Cowboy router also allows you to capture many host -or path segments at once using the ... qualifier.

-

To retrieve the segments captured from the host name:

-
-
-
HostInfo = cowboy_req:host_info(Req).
-

And the path segments:

-
-
-
PathInfo = cowboy_req:path_info(Req).
-

Cowboy will return undefined if ... was not used -in the route.

-
- -
+
PathInfo = cowboy_req:path_info(Req).
+
+

Cowboy will return undefined if ... was not used in the route.

Query parameters

-
-

Cowboy provides two functions to access query parameters. -You can use the first to get the entire list of parameters.

-
-
-
QsVals = cowboy_req:parse_qs(Req),
-{_, Lang} = lists:keyfind(<<"lang">>, 1, QsVals).
-

Cowboy will only parse the query string, and not do any -transformation. This function may therefore return duplicates, -or parameter names without an associated value. The order of -the list returned is undefined.

-

When a query string is key=1&key=2, the list returned will -contain two parameters of name key.

-

The same is true when trying to use the PHP-style suffix []. -When a query string is key[]=1&key[]=2, the list returned will -contain two parameters of name key[].

-

When a query string is simply key, Cowboy will return the -list [{<<"key">>, true}], using true to indicate that the -parameter key was defined, but with no value.

-

The second function Cowboy provides allows you to match out -only the parameters you are interested in, and at the same -time do any post processing you require using constraints. -This function returns a map.

-
-
-
#{id := ID, lang := Lang} = cowboy_req:match_qs([id, lang], Req).
-

Constraints can be applied automatically. The following -snippet will crash when the id parameter is not an integer, -or when the lang parameter is empty. At the same time, the -value for id will be converted to an integer term:

-
-
-
QsMap = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req).
-

A default value may also be provided. The default will be used -if the lang key is not found. It will not be used if -the key is found but has an empty value.

-
-
-
#{lang := Lang} = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
-

If no default is provided and the value is missing, the -query string is deemed invalid and the process will crash.

-

When the query string is key=1&key=2, the value for key -will be the list [1, 2]. Parameter names do not need to -include the PHP-style suffix. Constraints may be used to -ensure that only one value was passed through.

-
- -
+
#{lang := Lang} = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
+
+

If no default is provided and the value is missing, the query string is deemed invalid and the process will crash.

+

When the query string is key=1&key=2, the value for key will be the list [1, 2]. Parameter names do not need to include the PHP-style suffix. Constraints may be used to ensure that only one value was passed through.

Headers

-
-

Header values can be retrieved either as a binary string -or parsed into a more meaningful representation.

-

The get the raw value:

-
-
-
HeaderVal = cowboy_req:header(<<"content-type">>, Req).
-

Cowboy expects all header names to be provided as lowercase -binary strings. This is true for both requests and responses, -regardless of the underlying protocol.

-

When the header is missing from the request, undefined -will be returned. A different default can be provided:

-
-
-
HeaderVal = cowboy_req:header(<<"content-type">>, Req, <<"text/plain">>).
-

All headers can be retrieved at once, either directly:

-
-
-
#{headers := AllHeaders} = Req.
-

Or using a function:

-
-
-
AllHeaders = cowboy_req:headers(Req).
-

Cowboy provides equivalent functions to parse individual -headers. There is no function to parse all headers at once.

-

To parse a specific header:

-
-
-
ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req).
-

An exception will be thrown if it doesn’t know how to parse the -given header, or if the value is invalid. The list of known headers -and default values can be found in the manual.

-

When the header is missing, undefined is returned. You can -change the default value. Note that it should be the parsed value -directly:

-
-
-
ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req,
-    {<<"text">>, <<"plain">>, []}).
-
- -
+
ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req,
+    {<<"text">>, <<"plain">>, []}).
+

Peer

-
-

The peer address and port number for the connection can be -retrieved either directly or using a function.

-

To retrieve the peer directly:

-
-
-
#{peer := {IP, Port}} = Req.
-

And using a function:

-
-
-
{IP, Port} = cowboy_req:peer(Req).
-

Note that the peer corresponds to the remote end of the -connection to the server, which may or may not be the -client itself. It may also be a proxy or a gateway.

-
- +
{IP, Port} = cowboy_req:peer(Req).
+ +

Note that the peer corresponds to the remote end of the connection to the server, which may or may not be the client itself. It may also be a proxy or a gateway.

+ diff --git a/docs/en/cowboy/2.4/guide/req_body/index.html b/docs/en/cowboy/2.4/guide/req_body/index.html index 3ced946f..1f642ae1 100644 --- a/docs/en/cowboy/2.4/guide/req_body/index.html +++ b/docs/en/cowboy/2.4/guide/req_body/index.html @@ -62,144 +62,93 @@

Reading the request body

-

The request body can be read using the Req object.

-

Cowboy will not attempt to read the body until requested. -You need to call the body reading functions in order to -retrieve it.

-

Cowboy will not cache the body, it is therefore only -possible to read it once.

-

You are not required to read it, however. If a body is -present and was not read, Cowboy will either cancel or -skip its download, depending on the protocol.

-

Cowboy provides functions for reading the body raw, -and read and parse form urlencoded or multipart bodies. -The latter is covered in its own chapter.

-
+

The request body can be read using the Req object.

+

Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it.

+

Cowboy will not cache the body, it is therefore only possible to read it once.

+

You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol.

+

Cowboy provides functions for reading the body raw, and read and parse form urlencoded or multipart bodies. The latter is covered in its own chapter.

Request body presence

-
-

Not all requests come with a body. You can check for -the presence of a request body with this function:

-
-
-
cowboy_req:has_body(Req).
-

It returns true if there is a body; false otherwise.

-

In practice, this function is rarely used. When the -method is POST, PUT or PATCH, the request body -is often required by the application, which should -just attempt to read it directly.

-
-
-
+
cowboy_req:has_body(Req).
+
+

It returns true if there is a body; false otherwise.

+

In practice, this function is rarely used. When the method is POST, PUT or PATCH, the request body is often required by the application, which should just attempt to read it directly.

Request body length

-
-

You can obtain the length of the body:

-
-
-
Length = cowboy_req:body_length(Req).
-

Note that the length may not be known in advance. In -that case undefined will be returned. This can happen -with HTTP/1.1’s chunked transfer-encoding, or HTTP/2 -when no content-length was provided.

-

Cowboy will update the body length in the Req object -once the body has been read completely. A length will -always be returned when attempting to call this function -after reading the body completely.

-
- -
+
Length = cowboy_req:body_length(Req).
+
+

Note that the length may not be known in advance. In that case undefined will be returned. This can happen with HTTP/1.1's chunked transfer-encoding, or HTTP/2 when no content-length was provided.

+

Cowboy will update the body length in the Req object once the body has been read completely. A length will always be returned when attempting to call this function after reading the body completely.

Reading the body

-
-

You can read the entire body with one function call:

-
-
-
{ok, Data, Req} = cowboy_req:read_body(Req0).
-

Cowboy returns an ok tuple when the body has been -read fully.

-

By default, Cowboy will attempt to read up to 8MB -of data, for up to 15 seconds. The call will return -once Cowboy has read at least 8MB of data, or at -the end of the 15 seconds period.

-

These values can be customized. For example, to read -only up to 1MB for up to 5 seconds:

-
-
-
{ok, Data, Req} = cowboy_req:read_body(Req0,
-    #{length => 1000000, period => 5000}).
-

You may also disable the length limit:

-
-
-
{ok, Data, Req} = cowboy_req:read_body(Req0, #{length => infinity}).
-

This makes the function wait 15 seconds and return with -whatever arrived during that period. This is not -recommended for public facing applications.

-

These two options can effectively be used to control -the rate of transmission of the request body.

-
- -
+
{ok, Data, Req} = cowboy_req:read_body(Req0, #{length => infinity}).
+
+

This makes the function wait 15 seconds and return with whatever arrived during that period. This is not recommended for public facing applications.

+

These two options can effectively be used to control the rate of transmission of the request body.

Streaming the body

-
-

When the body is too large, the first call will return -a more tuple instead of ok. You can call the -function again to read more of the body, reading -it one chunk at a time.

-
-
-
read_body_to_console(Req0) ->
-    case cowboy_req:read_body(Req0) of
-        {ok, Data, Req} ->
-            io:format("~s", [Data]),
-            Req;
-        {more, Data, Req} ->
-            io:format("~s", [Data]),
-            read_body_to_console(Req)
-    end.
-

The length and period options can also be used. -They need to be passed for every call.

-
- -
+
read_body_to_console(Req0) ->
+    case cowboy_req:read_body(Req0) of
+        {ok, Data, Req} ->
+            io:format("~s", [Data]),
+            Req;
+        {more, Data, Req} ->
+            io:format("~s", [Data]),
+            read_body_to_console(Req)
+    end.
+
+

The length and period options can also be used. They need to be passed for every call.

Reading a form urlencoded body

-
-

Cowboy provides a convenient function for reading and -parsing bodies sent as application/x-www-form-urlencoded.

-
-
-
{ok, KeyValues, Req} = cowboy_req:read_urlencoded_body(Req0).
-

This function returns a list of key/values, exactly like -the function cowboy_req:parse_qs/1.

-

The defaults for this function are different. Cowboy will -read for up to 64KB and up to 5 seconds. They can be modified:

-
-
-
{ok, KeyValues, Req} = cowboy_req:read_urlencoded_body(Req0,
-    #{length => 4096, period => 3000}).
-
- +
{ok, KeyValues, Req} = cowboy_req:read_urlencoded_body(Req0,
+    #{length => 4096, period => 3000}).
+ + diff --git a/docs/en/cowboy/2.4/guide/resource_design/index.html b/docs/en/cowboy/2.4/guide/resource_design/index.html index c0b9fc1d..ca63c33d 100644 --- a/docs/en/cowboy/2.4/guide/resource_design/index.html +++ b/docs/en/cowboy/2.4/guide/resource_design/index.html @@ -62,213 +62,66 @@

Designing a resource handler

-

This chapter aims to provide you with a list of questions -you must answer in order to write a good resource handler. -It is meant to be usable as a step by step guide.

-
+

This chapter aims to provide you with a list of questions you must answer in order to write a good resource handler. It is meant to be usable as a step by step guide.

The service

-
-

Can the service become unavailable, and when it does, can -we detect it? For example, database connectivity problems -may be detected early. We may also have planned outages -of all or parts of the system. Implement the -service_available callback.

-

What HTTP methods does the service implement? Do we need -more than the standard OPTIONS, HEAD, GET, PUT, POST, -PATCH and DELETE? Are we not using one of those at all? -Implement the known_methods callback.

-
-
-
+

Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. Implement the service_available callback.

+

What HTTP methods does the service implement? Do we need more than the standard OPTIONS, HEAD, GET, PUT, POST, PATCH and DELETE? Are we not using one of those at all? Implement the known_methods callback.

Type of resource handler

-
-

Am I writing a handler for a collection of resources, -or for a single resource?

-

The semantics for each of these are quite different. -You should not mix collection and single resource in -the same handler.

-
-
-
+

Am I writing a handler for a collection of resources, or for a single resource?

+

The semantics for each of these are quite different. You should not mix collection and single resource in the same handler.

Collection handler

-
-

Skip this section if you are not doing a collection.

-

Is the collection hardcoded or dynamic? For example, -if you use the route /users for the collection of -users then the collection is hardcoded; if you use -/forums/:category for the collection of threads -then it isn’t. When the collection is hardcoded you -can safely assume the resource always exists.

-

What methods should I implement?

-

OPTIONS is used to get some information about the -collection. It is recommended to allow it even if you -do not implement it, as Cowboy has a default -implementation built-in.

-

HEAD and GET are used to retrieve the collection. -If you allow GET, also allow HEAD as there’s no extra -work required to make it work.

-

POST is used to create a new resource inside the -collection. Creating a resource by using POST on -the collection is useful when resources may be -created before knowing their URI, usually because -parts of it are generated dynamically. A common -case is some kind of auto incremented integer -identifier.

-

The next methods are more rarely allowed.

-

PUT is used to create a new collection (when -the collection isn’t hardcoded), or replace -the entire collection.

-

DELETE is used to delete the entire collection.

-

PATCH is used to modify the collection using -instructions given in the request body. A PATCH -operation is atomic. The PATCH operation may -be used for such things as reordering; adding, -modifying or deleting parts of the collection.

-
-
-
+

Skip this section if you are not doing a collection.

+

Is the collection hardcoded or dynamic? For example, if you use the route /users for the collection of users then the collection is hardcoded; if you use /forums/:category for the collection of threads then it isn't. When the collection is hardcoded you can safely assume the resource always exists.

+

What methods should I implement?

+

OPTIONS is used to get some information about the collection. It is recommended to allow it even if you do not implement it, as Cowboy has a default implementation built-in.

+

HEAD and GET are used to retrieve the collection. If you allow GET, also allow HEAD as there's no extra work required to make it work.

+

POST is used to create a new resource inside the collection. Creating a resource by using POST on the collection is useful when resources may be created before knowing their URI, usually because parts of it are generated dynamically. A common case is some kind of auto incremented integer identifier.

+

The next methods are more rarely allowed.

+

PUT is used to create a new collection (when the collection isn't hardcoded), or replace the entire collection.

+

DELETE is used to delete the entire collection.

+

PATCH is used to modify the collection using instructions given in the request body. A PATCH operation is atomic. The PATCH operation may be used for such things as reordering; adding, modifying or deleting parts of the collection.

Single resource handler

-
-

Skip this section if you are doing a collection.

-

What methods should I implement?

-

OPTIONS is used to get some information about the -resource. It is recommended to allow it even if you -do not implement it, as Cowboy has a default -implementation built-in.

-

HEAD and GET are used to retrieve the resource. -If you allow GET, also allow HEAD as there’s no extra -work required to make it work.

-

POST is used to update the resource.

-

PUT is used to create a new resource (when it doesn’t -already exist) or replace the resource.

-

DELETE is used to delete the resource.

-

PATCH is used to modify the resource using -instructions given in the request body. A PATCH -operation is atomic. The PATCH operation may -be used for adding, removing or modifying specific -values in the resource.

-
-
-
+

Skip this section if you are doing a collection.

+

What methods should I implement?

+

OPTIONS is used to get some information about the resource. It is recommended to allow it even if you do not implement it, as Cowboy has a default implementation built-in.

+

HEAD and GET are used to retrieve the resource. If you allow GET, also allow HEAD as there's no extra work required to make it work.

+

POST is used to update the resource.

+

PUT is used to create a new resource (when it doesn't already exist) or replace the resource.

+

DELETE is used to delete the resource.

+

PATCH is used to modify the resource using instructions given in the request body. A PATCH operation is atomic. The PATCH operation may be used for adding, removing or modifying specific values in the resource.

The resource

-
-

Following the above discussion, implement the -allowed_methods callback.

-

Does the resource always exist? If it may not, implement -the resource_exists callback.

-

Do I need to authenticate the client before they can -access the resource? What authentication mechanisms -should I provide? This may include form-based, token-based -(in the URL or a cookie), HTTP basic, HTTP digest, -SSL certificate or any other form of authentication. -Implement the is_authorized callback.

-

Do I need fine-grained access control? How do I determine -that they are authorized access? Handle that in your -is_authorized callback.

-

Can access to a resource be forbidden regardless of access -being authorized? A simple example of that is censorship -of a resource. Implement the forbidden callback.

-

Are there any constraints on the length of the resource URI? -For example, the URI may be used as a key in storage and may -have a limit in length. Implement uri_too_long.

-
-
-
+

Following the above discussion, implement the allowed_methods callback.

+

Does the resource always exist? If it may not, implement the resource_exists callback.

+

Do I need to authenticate the client before they can access the resource? What authentication mechanisms should I provide? This may include form-based, token-based (in the URL or a cookie), HTTP basic, HTTP digest, SSL certificate or any other form of authentication. Implement the is_authorized callback.

+

Do I need fine-grained access control? How do I determine that they are authorized access? Handle that in your is_authorized callback.

+

Can access to a resource be forbidden regardless of access being authorized? A simple example of that is censorship of a resource. Implement the forbidden callback.

+

Are there any constraints on the length of the resource URI? For example, the URI may be used as a key in storage and may have a limit in length. Implement uri_too_long.

Representations

-
-

What media types do I provide? If text based, what charsets -are provided? What languages do I provide?

-

Implement the mandatory content_types_provided. Prefix -the callbacks with to_ for clarity. For example, to_html -or to_text.

-

Implement the languages_provided or charsets_provided -callbacks if applicable.

-

Is there any other header that may make the representation -of the resource vary? Implement the variances callback.

-

Depending on your choices for caching content, you may -want to implement one or more of the generate_etag, -last_modified and expires callbacks.

-

Do I want the user or user agent to actively choose a -representation available? Send a list of available -representations in the response body and implement -the multiple_choices callback.

-
-
-
+

What media types do I provide? If text based, what charsets are provided? What languages do I provide?

+

Implement the mandatory content_types_provided. Prefix the callbacks with to_ for clarity. For example, to_html or to_text.

+

Implement the languages_provided or charsets_provided callbacks if applicable.

+

Is there any other header that may make the representation of the resource vary? Implement the variances callback.

+

Depending on your choices for caching content, you may want to implement one or more of the generate_etag, last_modified and expires callbacks.

+

Do I want the user or user agent to actively choose a representation available? Send a list of available representations in the response body and implement the multiple_choices callback.

Redirections

-
-

Do I need to keep track of what resources were deleted? -For example, you may have a mechanism where moving a -resource leaves a redirect link to its new location. -Implement the previously_existed callback.

-

Was the resource moved, and is the move temporary? If -it is explicitly temporary, for example due to maintenance, -implement the moved_temporarily callback. Otherwise, -implement the moved_permanently callback.

-
-
-
+

Do I need to keep track of what resources were deleted? For example, you may have a mechanism where moving a resource leaves a redirect link to its new location. Implement the previously_existed callback.

+

Was the resource moved, and is the move temporary? If it is explicitly temporary, for example due to maintenance, implement the moved_temporarily callback. Otherwise, implement the moved_permanently callback.

The request

-
-

Do you need to read the query string? Individual headers? -Implement malformed_request and do all the parsing and -validation in this function. Note that the body should not -be read at this point.

-

May there be a request body? Will I know its size? -What’s the maximum size of the request body I’m willing -to accept? Implement valid_entity_length.

-

Finally, take a look at the sections corresponding to the -methods you are implementing.

-
-
-
+

Do you need to read the query string? Individual headers? Implement malformed_request and do all the parsing and validation in this function. Note that the body should not be read at this point.

+

May there be a request body? Will I know its size? What's the maximum size of the request body I'm willing to accept? Implement valid_entity_length.

+

Finally, take a look at the sections corresponding to the methods you are implementing.

OPTIONS method

-
-

Cowboy by default will send back a list of allowed methods. -Do I need to add more information to the response? Implement -the options method.

-
-
-
+

Cowboy by default will send back a list of allowed methods. Do I need to add more information to the response? Implement the options method.

GET and HEAD methods

-
-

If you implement the methods GET and/or HEAD, you must -implement one ProvideResource callback for each -content-type returned by the content_types_provided -callback.

-
-
-
-

PUT, POST and PATCH methods

-
-

If you implement the methods PUT, POST and/or PATCH, -you must implement the content_types_accepted callback, -and one AcceptCallback callback for each content-type -it returns. Prefix the AcceptCallback callback names -with from_ for clarity. For example, from_html or -from_json.

-

Do we want to allow the POST method to create individual -resources directly through their URI (like PUT)? Implement -the allow_missing_post callback. It is recommended to -explicitly use PUT in these cases instead.

-

May there be conflicts when using PUT to create or replace -a resource? Do we want to make sure that two updates around -the same time are not cancelling one another? Implement the -is_conflict callback.

-
-
-
+

If you implement the methods GET and/or HEAD, you must implement one ProvideResource callback for each content-type returned by the content_types_provided callback.

+

PUT, POST and PATCH methods

+

If you implement the methods PUT, POST and/or PATCH, you must implement the content_types_accepted callback, and one AcceptCallback callback for each content-type it returns. Prefix the AcceptCallback callback names with from_ for clarity. For example, from_html or from_json.

+

Do we want to allow the POST method to create individual resources directly through their URI (like PUT)? Implement the allow_missing_post callback. It is recommended to explicitly use PUT in these cases instead.

+

May there be conflicts when using PUT to create or replace a resource? Do we want to make sure that two updates around the same time are not cancelling one another? Implement the is_conflict callback.

DELETE methods

-
-

If you implement the method DELETE, you must implement -the delete_resource callback.

-

When delete_resource returns, is the resource completely -removed from the server, including from any caching service? -If not, and/or if the deletion is asynchronous and we have -no way of knowing it has been completed yet, implement the -delete_completed callback.

-
-
+

If you implement the method DELETE, you must implement the delete_resource callback.

+

When delete_resource returns, is the resource completely removed from the server, including from any caching service? If not, and/or if the deletion is asynchronous and we have no way of knowing it has been completed yet, implement the delete_completed callback.

+ diff --git a/docs/en/cowboy/2.4/guide/resp/index.html b/docs/en/cowboy/2.4/guide/resp/index.html index 4d8a6a52..43106dff 100644 --- a/docs/en/cowboy/2.4/guide/resp/index.html +++ b/docs/en/cowboy/2.4/guide/resp/index.html @@ -62,373 +62,249 @@

Sending a response

-

The response must be sent using the Req object.

-

Cowboy provides two different ways of sending responses: -either directly or by streaming the body. Response headers -and body may be set in advance. The response is sent as -soon as one of the reply or stream reply function is -called.

-

Cowboy also provides a simplified interface for sending -files. It can also send only specific parts of a file.

-

While only one response is allowed for every request, -HTTP/2 introduced a mechanism that allows the server -to push additional resources related to the response. -This chapter also describes how this feature works in -Cowboy.

-
+

The response must be sent using the Req object.

+

Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called.

+

Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file.

+

While only one response is allowed for every request, HTTP/2 introduced a mechanism that allows the server to push additional resources related to the response. This chapter also describes how this feature works in Cowboy.

Reply

-
-

Cowboy provides three functions for sending the entire reply, -depending on whether you need to set headers and body. In all -cases, Cowboy will add any headers required by the protocol -(for example the date header will always be sent).

-

When you need to set only the status code, -use cowboy_req:reply/2:

-
-
-
Req = cowboy_req:reply(200, Req0).
-

When you need to set response headers at the same time, -use cowboy_req:reply/3:

-
-
-
Req = cowboy_req:reply(303, #{
-    <<"location">> => <<"https://ninenines.eu">>
-}, Req0).
-

Note that the header name must always be a lowercase -binary.

-

When you also need to set the response body, -use cowboy_req:reply/4:

-
-
-
Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, "Hello world!", Req0).
-

You should always set the content-type header when the -response has a body. There is however no need to set -the content-length header; Cowboy does it automatically.

-

The response body and the header values must be either -a binary or an iolist. An iolist is a list containing -binaries, characters, strings or other iolists. This -allows you to build a response from different parts -without having to do any concatenation:

-
-
-
Title = "Hello world!",
-Body = <<"Hats off!">>,
-Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/html">>
-}, ["<html><head><title>", Title, "</title></head>",
-    "<body><p>", Body, "</p></body></html>"], Req0).
-

This method of building responses is more efficient than -concatenating. Behind the scenes, each element of the list -is simply a pointer, and those pointers are used directly -when writing to the socket.

-
-
-
+
Title = "Hello world!",
+Body = <<"Hats off!">>,
+Req = cowboy_req:reply(200, #{
+    <<"content-type">> => <<"text/html">>
+}, ["<html><head><title>", Title, "</title></head>",
+    "<body><p>", Body, "</p></body></html>"], Req0).
+
+

This method of building responses is more efficient than concatenating. Behind the scenes, each element of the list is simply a pointer, and those pointers are used directly when writing to the socket.

Stream reply

-
-

Cowboy provides two functions for initiating a response, -and an additional function for streaming the response body. -Cowboy will add any required headers to the response.

-

When you need to set only the status code, -use cowboy_req:stream_reply/2:

-
-
+

When you need to set only the status code, use cowboy_req:stream_reply/2:

+
-
Req = cowboy_req:stream_reply(200, Req0),
-
-cowboy_req:stream_body("Hello...", nofin, Req),
-cowboy_req:stream_body("chunked...", nofin, Req),
-cowboy_req:stream_body("world!!", fin, Req).
-

The second argument to cowboy_req:stream_body/3 indicates -whether this data terminates the body. Use fin for the -final flag, and nofin otherwise.

-

This snippet does not set a content-type header. This is -not recommended. All responses with a body should have -a content-type. The header can be set beforehand, or -using the cowboy_req:stream_reply/3:

-
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/html">>
-}, Req0),
-
-cowboy_req:stream_body("<html><head>Hello world!</head>", nofin, Req),
-cowboy_req:stream_body("<body><p>Hats off!</p></body></html>", fin, Req).
-

HTTP provides a few different ways to stream response bodies. -Cowboy will select the most appropriate one based on the HTTP -version and the request and response headers.

-

While not required by any means, it is recommended that you -set the content-length header in the response if you know it -in advance. This will ensure that the best response method -is selected and help clients understand when the response -is fully received.

-

Cowboy also provides a function to send response trailers. -Response trailers are semantically equivalent to the headers -you send in the response, only they are sent at the end. -This is especially useful to attach information to the -response that could not be generated until the response -body was fully generated.

-

Trailer fields must be listed in the trailer header. Any -field not listed might be dropped by the client or an intermediary.

-
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/html">>,
-    <<"trailer">> => <<"expires, content-md5">>
-}, Req0),
-
-cowboy_req:stream_body("<html><head>Hello world!</head>", nofin, Req),
-cowboy_req:stream_body("<body><p>Hats off!</p></body></html>", nofin, Req),
-
-cowboy_req:stream_trailers(#{
-    <<"expires">> => <<"Sun, 10 Dec 2017 19:13:47 GMT">>,
-    <<"content-md5">> => <<"c6081d20ff41a42ce17048ed1c0345e2">>
-}, Req).
-

The stream ends with trailers. It is no longer possible to -send data after sending trailers. You cannot send trailers -after setting the fin flag when streaming the body.

-
-
-
+
Req = cowboy_req:stream_reply(200, #{
+    <<"content-type">> => <<"text/html">>,
+    <<"trailer">> => <<"expires, content-md5">>
+}, Req0),
+
+cowboy_req:stream_body("<html><head>Hello world!</head>", nofin, Req),
+cowboy_req:stream_body("<body><p>Hats off!</p></body></html>", nofin, Req),
+
+cowboy_req:stream_trailers(#{
+    <<"expires">> => <<"Sun, 10 Dec 2017 19:13:47 GMT">>,
+    <<"content-md5">> => <<"c6081d20ff41a42ce17048ed1c0345e2">>
+}, Req).
+
+

The stream ends with trailers. It is no longer possible to send data after sending trailers. You cannot send trailers after setting the fin flag when streaming the body.

Preset response headers

-
-

Cowboy provides functions to set response headers without -immediately sending them. They are stored in the Req object -and sent as part of the response when a reply function is -called.

-

To set response headers:

-
-
-
Req = cowboy_req:set_resp_header(<<"allow">>, "GET", Req0).
-

Header names must be a lowercase binary.

-

Do not use this function for setting cookies. Refer to -the Cookies chapter for more information.

-

To check if a response header has already been set:

-
-
-
cowboy_req:has_resp_header(<<"allow">>, Req).
-

It returns true if the header was set, false otherwise.

-

To delete a response header that was set previously:

-
-
-
Req = cowboy_req:delete_resp_header(<<"allow">>, Req0).
-
- -
+
Req = cowboy_req:delete_resp_header(<<"allow">>, Req0).
+

Overriding headers

-
-

As Cowboy provides different ways of setting response -headers and body, clashes may occur, so it’s important -to understand what happens when a header is set twice.

-

Headers come from five different origins:

-
    -
  • -

    -Protocol-specific headers (for example HTTP/1.1’s connection header) -

    +

    As Cowboy provides different ways of setting response headers and body, clashes may occur, so it's important to understand what happens when a header is set twice.

    +

    Headers come from five different origins:

    +
    • Protocol-specific headers (for example HTTP/1.1's connection header)
    • -
    • -

      -Other required headers (for example the date header) -

      +
    • Other required headers (for example the date header)
    • -
    • -

      -Preset headers -

      +
    • Preset headers
    • -
    • -

      -Headers given to the reply function -

      +
    • Headers given to the reply function
    • -
    • -

      -Set-cookie headers -

      +
    • Set-cookie headers
    • -
-

Cowboy does not allow overriding protocol-specific headers.

-

Set-cookie headers will always be appended at the end of -the list of headers before sending the response.

-

Headers given to the reply function will always override -preset headers and required headers. If a header is found -in two or three of these, then the one in the reply function -is picked and the others are dropped.

-

Similarly, preset headers will always override required -headers.

-

To illustrate, look at the following snippet. Cowboy by -default sends the server header with the value "Cowboy". -We can override it:

-
-
-
Req = cowboy_req:reply(200, #{
-    <<"server">> => <<"yaws">>
-}, Req0).
-
- -
+
Req = cowboy_req:reply(200, #{
+    <<"server">> => <<"yaws">>
+}, Req0).
+

Preset response body

-
-

Cowboy provides functions to set the response body without -immediately sending it. It is stored in the Req object and -sent when the reply function is called.

-

To set the response body:

-
-
-
Req = cowboy_req:set_resp_body("Hello world!", Req0).
-

To check if a response body has already been set:

-
-
+ +

To check if a response body has already been set:

+
-
cowboy_req:has_resp_body(Req).
-

It returns true if the body was set and is non-empty, -false otherwise.

-

The preset response body is only sent if the reply function -used is cowboy_req:reply/2 or cowboy_req:reply/3.

-
-
-
+
cowboy_req:has_resp_body(Req).
+
+

It returns true if the body was set and is non-empty, false otherwise.

+ + + +

The preset response body is only sent if the reply function used is cowboy_req:reply/2 or cowboy_req:reply/3.

Sending files

-
-

Cowboy provides a shortcut for sending files. When -using cowboy_req:reply/4, or when presetting the -response header, you can give a sendfile tuple to -Cowboy:

-
-
-
{sendfile, Offset, Length, Filename}
-

Depending on the values for Offset or Length, the -entire file may be sent, or just a part of it.

-

The length is required even for sending the entire file. -Cowboy sends it in the content-length header.

-

To send a file while replying:

-
-
-
Req = cowboy_req:reply(200, #{
-    <<"content-type">> => "image/png"
-}, {sendfile, 0, 12345, "path/to/logo.png"}, Req0).
-
- -
+
Req = cowboy_req:reply(200, #{
+    <<"content-type">> => "image/png"
+}, {sendfile, 0, 12345, "path/to/logo.png"}, Req0).
+
+ + + + + + + + +

Informational responses

-
-

Cowboy allows you to send informational responses.

-

Informational responses are responses that have a status -code between 100 and 199. Any number can be sent before -the proper response. Sending an informational response -does not change the behavior of the proper response, and -clients are expected to ignore any informational response -they do not understand.

-

The following snippet sends a 103 informational response -with some headers that are expected to be in the final -response.

-
-
-
Req = cowboy_req:inform(103, #{
-    <<"link">> => <<"</style.css>; rel=preload; as=style, </script.js>; rel=preload; as=script">>
-}, Req0).
-
- -
+
Req = cowboy_req:inform(103, #{
+    <<"link">> => <<"</style.css>; rel=preload; as=style, </script.js>; rel=preload; as=script">>
+}, Req0).
+

Push

-
-

The HTTP/2 protocol introduced the ability to push resources -related to the one sent in the response. Cowboy provides two -functions for that purpose: cowboy_req:push/3,4.

-

Push is only available for HTTP/2. Cowboy will automatically -ignore push requests if the protocol doesn’t support it.

-

The push function must be called before any of the reply -functions. Doing otherwise will result in a crash.

-

To push a resource, you need to provide the same information -as a client performing a request would. This includes the -HTTP method, the URI and any necessary request headers.

-

Cowboy by default only requires you to give the path to -the resource and the request headers. The rest of the URI -is taken from the current request (excluding the query -string, set to empty) and the method is GET by default.

-

The following snippet pushes a CSS file that is linked to -in the response:

-
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, Req0),
-Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/html">>
-}, ["<html><head><title>My web page</title>",
-    "<link rel='stylesheet' type='text/css' href='/static/style.css'>",
-    "<body><p>Welcome to Erlang!</p></body></html>"], Req0).
-

To override the method, scheme, host, port or query string, -simply pass in a fourth argument. The following snippet -uses a different host name:

-
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, #{host => <<"cdn.example.org">>}, Req),
-

Pushed resources don’t have to be files. As long as the push -request is cacheable, safe and does not include a body, the -resource can be pushed.

-

Under the hood, Cowboy handles pushed requests the same as -normal requests: a different process is created which will -ultimately send a response to the client.

-
- +
cowboy_req:push("/static/style.css", #{
+    <<"accept">> => <<"text/css">>
+}, #{host => <<"cdn.example.org">>}, Req),
+ +

Pushed resources don't have to be files. As long as the push request is cacheable, safe and does not include a body, the resource can be pushed.

+

Under the hood, Cowboy handles pushed requests the same as normal requests: a different process is created which will ultimately send a response to the client.

+ diff --git a/docs/en/cowboy/2.4/guide/rest_flowcharts/index.html b/docs/en/cowboy/2.4/guide/rest_flowcharts/index.html index 3347d7dd..c5662db1 100644 --- a/docs/en/cowboy/2.4/guide/rest_flowcharts/index.html +++ b/docs/en/cowboy/2.4/guide/rest_flowcharts/index.html @@ -62,244 +62,64 @@

REST flowcharts

-

This chapter will explain the REST handler state machine through -a number of different diagrams.

-

There are four main paths that requests may follow. One for the -method OPTIONS; one for the methods GET and HEAD; one for the -methods PUT, POST and PATCH; and one for the method DELETE.

-

All paths start with the "Start" diagram, and all paths excluding -the OPTIONS path go through the "Content negotiation" diagram -and optionally the "Conditional requests" diagram if the resource -exists.

-

The red squares refer to another diagram. The light green squares -indicate a response. Other squares may be either a callback or a -question answered by Cowboy itself. Green arrows tend to indicate -the default behavior if the callback is undefined.

-
+

This chapter will explain the REST handler state machine through a number of different diagrams.

+

There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE.

+

All paths start with the "Start" diagram, and all paths excluding the OPTIONS path go through the "Content negotiation" diagram and optionally the "Conditional requests" diagram if the resource exists.

+

The red squares refer to another diagram. The light green squares indicate a response. Other squares may be either a callback or a question answered by Cowboy itself. Green arrows tend to indicate the default behavior if the callback is undefined.

Start

-
-

All requests start from here.

-
-
-REST starting flowchart -
-
-

A series of callbacks are called in succession to perform -a general checkup of the service, the request line and -request headers.

-

The request body, if any, is not expected to have been -received for any of these steps. It is only processed -at the end of the "PUT, POST and PATCH methods" diagram, -when all conditions have been met.

-

The known_methods and allowed_methods callbacks -return a list of methods. Cowboy then checks if the request -method is in the list, and stops otherwise.

-

The is_authorized callback may be used to check that -access to the resource is authorized. Authentication -may also be performed as needed. When authorization is -denied, the return value from the callback must include -a challenge applicable to the requested resource, which -will be sent back to the client in the www-authenticate -header.

-

This diagram is immediately followed by either the -"OPTIONS method" diagram when the request method is -OPTIONS, or the "Content negotiation" diagram otherwise.

-
-
-
+

All requests start from here.

+REST starting flowchart

A series of callbacks are called in succession to perform a general checkup of the service, the request line and request headers.

+

The request body, if any, is not expected to have been received for any of these steps. It is only processed at the end of the "PUT, POST and PATCH methods" diagram, when all conditions have been met.

+

The known_methods and allowed_methods callbacks return a list of methods. Cowboy then checks if the request method is in the list, and stops otherwise.

+

The is_authorized callback may be used to check that access to the resource is authorized. Authentication may also be performed as needed. When authorization is denied, the return value from the callback must include a challenge applicable to the requested resource, which will be sent back to the client in the www-authenticate header.

+

This diagram is immediately followed by either the "OPTIONS method" diagram when the request method is OPTIONS, or the "Content negotiation" diagram otherwise.

OPTIONS method

-
-

This diagram only applies to OPTIONS requests.

-
-
-REST OPTIONS method flowchart -
-
-

The options callback may be used to add information -about the resource, such as media types or languages -provided; allowed methods; any extra information. A -response body may also be set, although clients should -not be expected to read it.

-

If the options callback is not defined, Cowboy will -send a response containing the list of allowed methods -by default.

-
-
-
+

This diagram only applies to OPTIONS requests.

+REST OPTIONS method flowchart

The options callback may be used to add information about the resource, such as media types or languages provided; allowed methods; any extra information. A response body may also be set, although clients should not be expected to read it.

+

If the options callback is not defined, Cowboy will send a response containing the list of allowed methods by default.

Content negotiation

-
-

This diagram applies to all request methods other than -OPTIONS. It is executed right after the "Start" diagram -is completed.

-
-
-REST content negotiation flowchart -
-
-

The purpose of these steps is to determine an appropriate -representation to be sent back to the client.

-

The request may contain any of the accept header; the -accept-language header; or the accept-charset header. -When present, Cowboy will parse the headers and then -call the corresponding callback to obtain the list -of provided content-type, language or charset for this -resource. It then automatically select the best match -based on the request.

-

If a callback is not defined, Cowboy will select the -content-type, language or charset that the client -prefers.

-

The content_types_provided also returns the name of -a callback for every content-type it accepts. This -callback will only be called at the end of the -"GET and HEAD methods" diagram, when all conditions -have been met.

-

The selected content-type, language and charset are -saved as meta values in the Req object. You should -use the appropriate representation if you set a -response body manually (alongside an error code, -for example).

-

This diagram is immediately followed by -the "GET and HEAD methods" diagram, -the "PUT, POST and PATCH methods" diagram, -or the "DELETE method" diagram, depending on the -method.

-
-
-
+

This diagram applies to all request methods other than OPTIONS. It is executed right after the "Start" diagram is completed.

+REST content negotiation flowchart

The purpose of these steps is to determine an appropriate representation to be sent back to the client.

+

The request may contain any of the accept header; the accept-language header; or the accept-charset header. When present, Cowboy will parse the headers and then call the corresponding callback to obtain the list of provided content-type, language or charset for this resource. It then automatically select the best match based on the request.

+

If a callback is not defined, Cowboy will select the content-type, language or charset that the client prefers.

+

The content_types_provided also returns the name of a callback for every content-type it accepts. This callback will only be called at the end of the "GET and HEAD methods" diagram, when all conditions have been met.

+

The selected content-type, language and charset are saved as meta values in the Req object. You should use the appropriate representation if you set a response body manually (alongside an error code, for example).

+

This diagram is immediately followed by the "GET and HEAD methods" diagram, the "PUT, POST and PATCH methods" diagram, or the "DELETE method" diagram, depending on the method.

GET and HEAD methods

-
-

This diagram only applies to GET and HEAD requests.

-

For a description of the cond step, please see -the "Conditional requests" diagram.

-
-
-REST GET/HEAD methods flowchart -
-
-

When the resource exists, and the conditional steps -succeed, the resource can be retrieved.

-

Cowboy prepares the response by first retrieving -metadata about the representation, then by calling -the ProvideResource callback. This is the callback -you defined for each content-types you returned from -content_types_provided. This callback returns the body -that will be sent back to the client, or a fun if the -body must be streamed.

-

When the resource does not exist, Cowboy will figure out -whether the resource existed previously, and if so whether -it was moved elsewhere in order to redirect the client to -the new URI.

-

The moved_permanently and moved_temporarily callbacks -must return the new location of the resource if it was in -fact moved.

-
-
-
-

PUT, POST and PATCH methods

-
-

This diagram only applies to PUT, POST and PATCH requests.

-

For a description of the cond step, please see -the "Conditional requests" diagram.

-
-
-REST PUT/POST/PATCH methods flowchart -
-
-

When the resource exists, first the conditional steps -are executed. When that succeeds, and the method is PUT, -Cowboy will call the is_conflict callback. This function -can be used to prevent potential race conditions, by locking -the resource for example.

-

Then all three methods reach the content_types_accepted -step that we will describe in a few paragraphs.

-

When the resource does not exist, and the method is PUT, -Cowboy will check for conflicts and then move on to the -content_types_accepted step. For other methods, Cowboy -will figure out whether the resource existed previously, -and if so whether it was moved elsewhere. If the resource -is truly non-existent, the method is POST and the call -for allow_missing_post returns true, then Cowboy will -move on to the content_types_accepted step. Otherwise -the request processing ends there.

-

The moved_permanently and moved_temporarily callbacks -must return the new location of the resource if it was in -fact moved.

-

The content_types_accepted returns a list of -content-types it accepts, but also the name of a callback -for each of them. Cowboy will select the appropriate -callback for processing the request body and call it.

-

This callback may return one of three different return -values.

-

If an error occurred while processing the request body, -it must return false and Cowboy will send an -appropriate error response.

-

If the method is POST, then you may return true with -an URI of where the resource has been created. This is -especially useful for writing handlers for collections.

-

Otherwise, return true to indicate success. Cowboy -will select the appropriate response to be sent depending -on whether a resource has been created, rather than -modified, and on the availability of a location header -or a body in the response.

-
-
-
+

This diagram only applies to GET and HEAD requests.

+

For a description of the cond step, please see the "Conditional requests" diagram.

+REST GET/HEAD methods flowchart

When the resource exists, and the conditional steps succeed, the resource can be retrieved.

+

Cowboy prepares the response by first retrieving metadata about the representation, then by calling the ProvideResource callback. This is the callback you defined for each content-types you returned from content_types_provided. This callback returns the body that will be sent back to the client, or a fun if the body must be streamed.

+

When the resource does not exist, Cowboy will figure out whether the resource existed previously, and if so whether it was moved elsewhere in order to redirect the client to the new URI.

+

The moved_permanently and moved_temporarily callbacks must return the new location of the resource if it was in fact moved.

+

PUT, POST and PATCH methods

+

This diagram only applies to PUT, POST and PATCH requests.

+

For a description of the cond step, please see the "Conditional requests" diagram.

+REST PUT/POST/PATCH methods flowchart

When the resource exists, first the conditional steps are executed. When that succeeds, and the method is PUT, Cowboy will call the is_conflict callback. This function can be used to prevent potential race conditions, by locking the resource for example.

+

Then all three methods reach the content_types_accepted step that we will describe in a few paragraphs.

+

When the resource does not exist, and the method is PUT, Cowboy will check for conflicts and then move on to the content_types_accepted step. For other methods, Cowboy will figure out whether the resource existed previously, and if so whether it was moved elsewhere. If the resource is truly non-existent, the method is POST and the call for allow_missing_post returns true, then Cowboy will move on to the content_types_accepted step. Otherwise the request processing ends there.

+

The moved_permanently and moved_temporarily callbacks must return the new location of the resource if it was in fact moved.

+

The content_types_accepted returns a list of content-types it accepts, but also the name of a callback for each of them. Cowboy will select the appropriate callback for processing the request body and call it.

+

This callback may return one of three different return values.

+

If an error occurred while processing the request body, it must return false and Cowboy will send an appropriate error response.

+

If the method is POST, then you may return true with an URI of where the resource has been created. This is especially useful for writing handlers for collections.

+

Otherwise, return true to indicate success. Cowboy will select the appropriate response to be sent depending on whether a resource has been created, rather than modified, and on the availability of a location header or a body in the response.

DELETE method

-
-

This diagram only applies to DELETE requests.

-

For a description of the cond step, please see -the "Conditional requests" diagram.

-
-
-REST DELETE method flowchart -
-
-

When the resource exists, and the conditional steps -succeed, the resource can be deleted.

-

Deleting the resource is a two steps process. First -the callback delete_resource is executed. Use this -callback to delete the resource.

-

Because the resource may be cached, you must also -delete all cached representations of this resource -in the system. This operation may take a while though, -so you may return before it finished.

-

Cowboy will then call the delete_completed callback. -If you know that the resource has been completely -deleted from your system, including from caches, then -you can return true. If any doubts persist, return -false. Cowboy will assume true by default.

-

To finish, Cowboy checks if you set a response body, -and depending on that, sends the appropriate response.

-

When the resource does not exist, Cowboy will figure out -whether the resource existed previously, and if so whether -it was moved elsewhere in order to redirect the client to -the new URI.

-

The moved_permanently and moved_temporarily callbacks -must return the new location of the resource if it was in -fact moved.

-
-
-
+

This diagram only applies to DELETE requests.

+

For a description of the cond step, please see the "Conditional requests" diagram.

+REST DELETE method flowchart

When the resource exists, and the conditional steps succeed, the resource can be deleted.

+

Deleting the resource is a two steps process. First the callback delete_resource is executed. Use this callback to delete the resource.

+

Because the resource may be cached, you must also delete all cached representations of this resource in the system. This operation may take a while though, so you may return before it finished.

+

Cowboy will then call the delete_completed callback. If you know that the resource has been completely deleted from your system, including from caches, then you can return true. If any doubts persist, return false. Cowboy will assume true by default.

+

To finish, Cowboy checks if you set a response body, and depending on that, sends the appropriate response.

+

When the resource does not exist, Cowboy will figure out whether the resource existed previously, and if so whether it was moved elsewhere in order to redirect the client to the new URI.

+

The moved_permanently and moved_temporarily callbacks must return the new location of the resource if it was in fact moved.

Conditional requests

-
-

This diagram applies to all request methods other than -OPTIONS. It is executed right after the resource_exists -callback, when the resource exists.

-
-
-REST conditional requests flowchart -
-
-

A request becomes conditional when it includes either of -the if-match header; the if-unmodified-since header; the -if-none-match header; or the if-modified-since header.

-

If the condition fails, the request ends immediately -without any retrieval or modification of the resource.

-

The generate_etag and last_modified are called as -needed. Cowboy will only call them once and then cache -the results for subsequent use.

-
-
+

This diagram applies to all request methods other than OPTIONS. It is executed right after the resource_exists callback, when the resource exists.

+REST conditional requests flowchart

A request becomes conditional when it includes either of the if-match header; the if-unmodified-since header; the if-none-match header; or the if-modified-since header.

+

If the condition fails, the request ends immediately without any retrieval or modification of the resource.

+

The generate_etag and last_modified are called as needed. Cowboy will only call them once and then cache the results for subsequent use.

+ diff --git a/docs/en/cowboy/2.4/guide/rest_handlers/index.html b/docs/en/cowboy/2.4/guide/rest_handlers/index.html index 74a31e9e..5423d553 100644 --- a/docs/en/cowboy/2.4/guide/rest_handlers/index.html +++ b/docs/en/cowboy/2.4/guide/rest_handlers/index.html @@ -62,287 +62,162 @@

REST handlers

-

REST is implemented in Cowboy as a sub protocol. The request -is handled as a state machine with many optional callbacks -describing the resource and modifying the machine’s behavior.

-

The REST handler is the recommended way to handle HTTP requests.

-
+

REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine's behavior.

+

The REST handler is the recommended way to handle HTTP requests.

Initialization

-
-

First, the init/2 callback is called. This callback is common -to all handlers. To use REST for the current request, this function -must return a cowboy_rest tuple.

-
-
-
init(Req, State) ->
-    {cowboy_rest, Req, State}.
-

Cowboy will then switch to the REST protocol and start executing -the state machine.

-

After reaching the end of the flowchart, the terminate/3 callback -will be called if it is defined.

-
-
-
+
init(Req, State) ->
+    {cowboy_rest, Req, State}.
+
+

Cowboy will then switch to the REST protocol and start executing the state machine.

+

After reaching the end of the flowchart, the terminate/3 callback will be called if it is defined.

Methods

-
-

The REST component has code for handling the following HTTP methods: -HEAD, GET, POST, PATCH, PUT, DELETE and OPTIONS.

-

Other methods can be accepted, however they have no specific callback -defined for them at this time.

-
- -
+

The REST component has code for handling the following HTTP methods: HEAD, GET, POST, PATCH, PUT, DELETE and OPTIONS.

+

Other methods can be accepted, however they have no specific callback defined for them at this time.

Callbacks

-
-

All callbacks are optional. Some may become mandatory depending -on what other defined callbacks return. The various flowcharts -in the next chapter should be a useful to determine which callbacks -you need.

-

All callbacks take two arguments, the Req object and the State, -and return a three-element tuple of the form {Value, Req, State}.

-

Nearly all callbacks can also return {stop, Req, State} to -stop execution of the request, and -{{switch_handler, Module}, Req, State} or -{{switch_handler, Module, Opts}, Req, State} to switch to -a different handler type. The exceptions are expires -generate_etag, last_modified and variances.

-

The following table summarizes the callbacks and their default values. -If the callback isn’t defined, then the default value will be used. -Please look at the flowcharts to find out the result of each return -value.

-

In the following table, "skip" means the callback is entirely skipped -if it is undefined, moving directly to the next step. Similarly, -"none" means there is no default value for this callback.

-
- --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +

All callbacks are optional. Some may become mandatory depending on what other defined callbacks return. The various flowcharts in the next chapter should be a useful to determine which callbacks you need.

+

All callbacks take two arguments, the Req object and the State, and return a three-element tuple of the form {Value, Req, State}.

+

Nearly all callbacks can also return {stop, Req, State} to stop execution of the request, and {{switch_handler, Module}, Req, State} or {{switch_handler, Module, Opts}, Req, State} to switch to a different handler type. The exceptions are expires generate_etag, last_modified and variances.

+

The following table summarizes the callbacks and their default values. If the callback isn't defined, then the default value will be used. Please look at the flowcharts to find out the result of each return value.

+

In the following table, "skip" means the callback is entirely skipped if it is undefined, moving directly to the next step. Similarly, "none" means there is no default value for this callback.

+
Callback name Default value

allowed_methods

[<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]

allow_missing_post

true

charsets_provided

skip

content_types_accepted

none

content_types_provided

[{{ <<"text">>, <<"html">>, '*'}, to_html}]

delete_completed

true

delete_resource

false

expires

undefined

forbidden

false

generate_etag

undefined

is_authorized

true

is_conflict

false

known_methods

[<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]

languages_provided

skip

last_modified

undefined

malformed_request

false

moved_permanently

false

moved_temporarily

false

multiple_choices

false

options

ok

previously_existed

false

resource_exists

true

service_available

true

uri_too_long

false

+ + + + - - - + + - - - + + - - - + + - -
Callback nameDefault value
allowed_methods[<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]

valid_content_headers

true

allow_missing_posttrue

valid_entity_length

true

charsets_providedskip

variances

[]

content_types_acceptednone
-
-

As you can see, Cowboy tries to move on with the request whenever -possible by using well thought out default values.

-

In addition to these, there can be any number of user-defined -callbacks that are specified through content_types_accepted/2 -and content_types_provided/2. They can take any name, however -it is recommended to use a separate prefix for the callbacks of -each function. For example, from_html and to_html indicate -in the first case that we’re accepting a resource given as HTML, -and in the second case that we send one as HTML.

-
-
-
+content_types_provided +[{{ <<"text">>, <<"html">>, '*'}, to_html}] + +delete_completed +true + +delete_resource +false + +expires +undefined + +forbidden +false + +generate_etag +undefined + +is_authorized +true + +is_conflict +false + +known_methods +[<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>] + +languages_provided +skip + +last_modified +undefined + +malformed_request +false + +moved_permanently +false + +moved_temporarily +false + +multiple_choices +false + +options +ok + +previously_existed +false + +resource_exists +true + +service_available +true + +uri_too_long +false + +valid_content_headers +true + +valid_entity_length +true + +variances +[] + + +

As you can see, Cowboy tries to move on with the request whenever possible by using well thought out default values.

+

In addition to these, there can be any number of user-defined callbacks that are specified through content_types_accepted/2 and content_types_provided/2. They can take any name, however it is recommended to use a separate prefix for the callbacks of each function. For example, from_html and to_html indicate in the first case that we're accepting a resource given as HTML, and in the second case that we send one as HTML.

Meta data

-
-

Cowboy will set informative values to the Req object at various -points of the execution. You can retrieve them by matching the -Req object directly. The values are defined in the following table:

-
- --- - - - - - - - - - - - - - - - - - - - -
Key Details

media_type

The content-type negotiated for the response entity.

language

The language negotiated for the response entity.

charset

The charset negotiated for the response entity.

-
-

They can be used to send a proper body with the response to a -request that used a method other than HEAD or GET.

-
-
-
+

Cowboy will set informative values to the Req object at various points of the execution. You can retrieve them by matching the Req object directly. The values are defined in the following table:

+ + + + + + + + + + + + +
KeyDetails
media_typeThe content-type negotiated for the response entity.
languageThe language negotiated for the response entity.
charsetThe charset negotiated for the response entity.
+

They can be used to send a proper body with the response to a request that used a method other than HEAD or GET.

Response headers

-
-

Cowboy will set response headers automatically over the execution -of the REST code. They are listed in the following table.

-
- --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Header name Details

content-language

Language used in the response body

content-type

Media type and charset of the response body

etag

Etag of the resource

expires

Expiration date of the resource

last-modified

Last modification date for the resource

location

Relative or absolute URI to the requested resource

vary

List of headers that may change the representation of the resource

-
-
-
+

Cowboy will set response headers automatically over the execution of the REST code. They are listed in the following table.

+ + + + + + + + + + + + + + + + + + + + + + + + +
Header nameDetails
content-languageLanguage used in the response body
content-typeMedia type and charset of the response body
etagEtag of the resource
expiresExpiration date of the resource
last-modifiedLast modification date for the resource
locationRelative or absolute URI to the requested resource
varyList of headers that may change the representation of the resource
+ diff --git a/docs/en/cowboy/2.4/guide/rest_principles/index.html b/docs/en/cowboy/2.4/guide/rest_principles/index.html index f8b6b874..7d2e3862 100644 --- a/docs/en/cowboy/2.4/guide/rest_principles/index.html +++ b/docs/en/cowboy/2.4/guide/rest_principles/index.html @@ -62,153 +62,38 @@

REST principles

-

This chapter will attempt to define the concepts behind REST -and explain what makes a service RESTful.

-

REST is often confused with performing a distinct operation -depending on the HTTP method, while using more than the GET -and POST methods. That’s highly misguided at best.

-

We will first attempt to define REST and will look at what -it means in the context of HTTP and the Web. -For a more in-depth explanation of REST, you can read -Roy T. Fielding’s dissertation -as it does a great job explaining where it comes from and -what it achieves.

-
+

This chapter will attempt to define the concepts behind REST and explain what makes a service RESTful.

+

REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That's highly misguided at best.

+

We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. Fielding's dissertation as it does a great job explaining where it comes from and what it achieves.

REST architecture

-
-

REST is a client-server architecture. The client and the server -both have a different set of concerns. The server stores and/or -manipulates information and makes it available to the user in -an efficient manner. The client takes that information and -displays it to the user and/or uses it to perform subsequent -requests for information. This separation of concerns allows both -the client and the server to evolve independently as it only -requires that the interface stays the same.

-

REST is stateless. That means the communication between the -client and the server always contains all the information needed -to perform the request. There is no session state in the server, -it is kept entirely on the client’s side. If access to a resource -requires authentication, then the client needs to authenticate -itself with every request.

-

REST is cacheable. The client, the server and any intermediary -components can all cache resources in order to improve performance.

-

REST provides a uniform interface between components. This -simplifies the architecture, as all components follow the same -rules to speak to one another. It also makes it easier to understand -the interactions between the different components of the system. -A number of constraints are required to achieve this. They are -covered in the rest of the chapter.

-

REST is a layered system. Individual components cannot see -beyond the immediate layer with which they are interacting. This -means that a client connecting to an intermediate component, like -a proxy, has no knowledge of what lies beyond. This allows -components to be independent and thus easily replaceable or -extendable.

-

REST optionally provides code on demand. Code may be downloaded -to extend client functionality. This is optional however because -the client may not be able to download or run this code, and so -a REST component cannot rely on it being executed.

-
-
-
+

REST is a client-server architecture. The client and the server both have a different set of concerns. The server stores and/or manipulates information and makes it available to the user in an efficient manner. The client takes that information and displays it to the user and/or uses it to perform subsequent requests for information. This separation of concerns allows both the client and the server to evolve independently as it only requires that the interface stays the same.

+

REST is stateless. That means the communication between the client and the server always contains all the information needed to perform the request. There is no session state in the server, it is kept entirely on the client's side. If access to a resource requires authentication, then the client needs to authenticate itself with every request.

+

REST is cacheable. The client, the server and any intermediary components can all cache resources in order to improve performance.

+

REST provides a uniform interface between components. This simplifies the architecture, as all components follow the same rules to speak to one another. It also makes it easier to understand the interactions between the different components of the system. A number of constraints are required to achieve this. They are covered in the rest of the chapter.

+

REST is a layered system. Individual components cannot see beyond the immediate layer with which they are interacting. This means that a client connecting to an intermediate component, like a proxy, has no knowledge of what lies beyond. This allows components to be independent and thus easily replaceable or extendable.

+

REST optionally provides code on demand. Code may be downloaded to extend client functionality. This is optional however because the client may not be able to download or run this code, and so a REST component cannot rely on it being executed.

Resources and resource identifiers

-
-

A resource is an abstract concept. In a REST system, any information -that can be named may be a resource. This includes documents, images, -a collection of resources and any other information. Any information -that can be the target of an hypertext link can be a resource.

-

A resource is a conceptual mapping to a set of entities. The set of -entities evolves over time; a resource doesn’t. For example, a resource -can map to "users who have logged in this past month" and another -to "all users". At some point in time they may map to the same set of -entities, because all users logged in this past month. But they are -still different resources. Similarly, if nobody logged in recently, -then the first resource may map to the empty set. This resource exists -regardless of the information it maps to.

-

Resources are identified by uniform resource identifiers, also known -as URIs. Sometimes internationalized resource identifiers, or IRIs, -may also be used, but these can be directly translated into a URI.

-

In practice we will identify two kinds of resources. Individual -resources map to a set of one element, for example "user Joe". -Collection of resources map to a set of 0 to N elements, -for example "all users".

-
-
-
+

A resource is an abstract concept. In a REST system, any information that can be named may be a resource. This includes documents, images, a collection of resources and any other information. Any information that can be the target of an hypertext link can be a resource.

+

A resource is a conceptual mapping to a set of entities. The set of entities evolves over time; a resource doesn't. For example, a resource can map to "users who have logged in this past month" and another to "all users". At some point in time they may map to the same set of entities, because all users logged in this past month. But they are still different resources. Similarly, if nobody logged in recently, then the first resource may map to the empty set. This resource exists regardless of the information it maps to.

+

Resources are identified by uniform resource identifiers, also known as URIs. Sometimes internationalized resource identifiers, or IRIs, may also be used, but these can be directly translated into a URI.

+

In practice we will identify two kinds of resources. Individual resources map to a set of one element, for example "user Joe". Collection of resources map to a set of 0 to N elements, for example "all users".

Resource representations

-
-

The representation of a resource is a sequence of bytes associated -with metadata.

-

The metadata comes as a list of key-value pairs, where the name -corresponds to a standard that defines the value’s structure and -semantics. With HTTP, the metadata comes in the form of request -or response headers. The headers' structure and semantics are well -defined in the HTTP standard. Metadata includes representation -metadata, resource metadata and control data.

-

The representation metadata gives information about the -representation, such as its media type, the date of last -modification, or even a checksum.

-

Resource metadata could be link to related resources or -information about additional representations of the resource.

-

Control data allows parameterizing the request or response. -For example, we may only want the representation returned if -it is more recent than the one we have in cache. Similarly, -we may want to instruct the client about how it should cache -the representation. This isn’t restricted to caching. We may, -for example, want to store a new representation of a resource -only if it wasn’t modified since we first retrieved it.

-

The data format of a representation is also known as the media -type. Some media types are intended for direct rendering to the -user, while others are intended for automated processing. The -media type is a key component of the REST architecture.

-
-
-
+

The representation of a resource is a sequence of bytes associated with metadata.

+

The metadata comes as a list of key-value pairs, where the name corresponds to a standard that defines the value's structure and semantics. With HTTP, the metadata comes in the form of request or response headers. The headers' structure and semantics are well defined in the HTTP standard. Metadata includes representation metadata, resource metadata and control data.

+

The representation metadata gives information about the representation, such as its media type, the date of last modification, or even a checksum.

+

Resource metadata could be link to related resources or information about additional representations of the resource.

+

Control data allows parameterizing the request or response. For example, we may only want the representation returned if it is more recent than the one we have in cache. Similarly, we may want to instruct the client about how it should cache the representation. This isn't restricted to caching. We may, for example, want to store a new representation of a resource only if it wasn't modified since we first retrieved it.

+

The data format of a representation is also known as the media type. Some media types are intended for direct rendering to the user, while others are intended for automated processing. The media type is a key component of the REST architecture.

Self-descriptive messages

-
-

Messages must be self-descriptive. That means that the data -format of a representation must always come with its media -type (and similarly requesting a resource involves choosing -the media type of the representation returned). If you are -sending HTML, then you must say it is HTML by sending the -media type with the representation. In HTTP this is done -using the content-type header.

-

The media type is often an IANA registered media type, like -text/html or image/png, but does not need to be. Exactly -two things are important for respecting this constraint: that -the media type is well specified, and that the sender and -recipient agree about what the media type refers to.

-

This means that you can create your own media types, like -application/x-mine, and that as long as you write the -specifications for it and that both endpoints agree about -it then the constraint is respected.

-
-
-
+

Messages must be self-descriptive. That means that the data format of a representation must always come with its media type (and similarly requesting a resource involves choosing the media type of the representation returned). If you are sending HTML, then you must say it is HTML by sending the media type with the representation. In HTTP this is done using the content-type header.

+

The media type is often an IANA registered media type, like text/html or image/png, but does not need to be. Exactly two things are important for respecting this constraint: that the media type is well specified, and that the sender and recipient agree about what the media type refers to.

+

This means that you can create your own media types, like application/x-mine, and that as long as you write the specifications for it and that both endpoints agree about it then the constraint is respected.

Hypermedia as the engine of application state

-
-

The last constraint is generally where services that claim -to be RESTful fail. Interactions with a server must be -entirely driven by hypermedia. The client does not need -any prior knowledge of the service in order to use it, -other than an entry point and of course basic understanding -of the media type of the representations, at the very least -enough to find and identify hyperlinks and link relations.

-

To give a simple example, if your service only works with -the application/json media type then this constraint -cannot be respected (as there are no concept of links in -JSON) and thus your service isn’t RESTful. This is the case -for the majority of self-proclaimed REST services.

-

On the other hand if you create a JSON based media type -that has a concept of links and link relations, then -your service might be RESTful.

-

Respecting this constraint means that the entirety of the -service becomes self-discoverable, not only the resources -in it, but also the operations you can perform on it. This -makes clients very thin as there is no need to implement -anything specific to the service to operate on it.

-
-
+

The last constraint is generally where services that claim to be RESTful fail. Interactions with a server must be entirely driven by hypermedia. The client does not need any prior knowledge of the service in order to use it, other than an entry point and of course basic understanding of the media type of the representations, at the very least enough to find and identify hyperlinks and link relations.

+

To give a simple example, if your service only works with the application/json media type then this constraint cannot be respected (as there are no concept of links in JSON) and thus your service isn't RESTful. This is the case for the majority of self-proclaimed REST services.

+

On the other hand if you create a JSON based media type that has a concept of links and link relations, then your service might be RESTful.

+

Respecting this constraint means that the entirety of the service becomes self-discoverable, not only the resources in it, but also the operations you can perform on it. This makes clients very thin as there is no need to implement anything specific to the service to operate on it.

+ diff --git a/docs/en/cowboy/2.4/guide/routing/index.html b/docs/en/cowboy/2.4/guide/routing/index.html index bd8d5e12..e61a970d 100644 --- a/docs/en/cowboy/2.4/guide/routing/index.html +++ b/docs/en/cowboy/2.4/guide/routing/index.html @@ -62,261 +62,181 @@

Routing

-

Cowboy does nothing by default.

-

To make Cowboy useful, you need to map URIs to Erlang modules that will -handle the requests. This is called routing.

-

When Cowboy receives a request, it tries to match the requested host and -path to the configured routes. When there’s a match, the route’s -associated handler is executed.

-

Routes need to be compiled before they can be used by Cowboy. -The result of the compilation is the dispatch rules.

-
+

Cowboy does nothing by default.

+

To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing.

+

When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there's a match, the route's associated handler is executed.

+

Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules.

Syntax

-
-

The general structure for the routes is defined as follow.

-
-
-
Routes = [Host1, Host2, ... HostN].
-

Each host contains matching rules for the host along with optional -constraints, and a list of routes for the path component.

-
-
-
Host1 = {HostMatch, PathsList}.
-Host2 = {HostMatch, Constraints, PathsList}.
-

The list of routes for the path component is defined similar to the -list of hosts.

-
-
-
PathsList = [Path1, Path2, ... PathN].
-

Finally, each path contains matching rules for the path along with -optional constraints, and gives us the handler module to be used -along with its initial state.

-
-
-
Path1 = {PathMatch, Handler, InitialState}.
-Path2 = {PathMatch, Constraints, Handler, InitialState}.
-

Continue reading to learn more about the match syntax and the optional -constraints.

-
-
-
+
Path1 = {PathMatch, Handler, InitialState}.
+Path2 = {PathMatch, Constraints, Handler, InitialState}.
+
+

Continue reading to learn more about the match syntax and the optional constraints.

Match syntax

-
-

The match syntax is used to associate host names and paths with their -respective handlers.

-

The match syntax is the same for host and path with a few subtleties. -Indeed, the segments separator is different, and the host is matched -starting from the last segment going to the first. All examples will -feature both host and path match rules and explain the differences -when encountered.

-

Excluding special values that we will explain at the end of this section, -the simplest match value is a host or a path. It can be given as either -a string() or a binary().

-
-
-
PathMatch1 = "/".
-PathMatch2 = "/path/to/resource".
-
-HostMatch1 = "cowboy.example.org".
-

As you can see, all paths defined this way must start with a slash -character. Note that these two paths are identical as far as routing -is concerned.

-
-
-
PathMatch2 = "/path/to/resource".
-PathMatch3 = "/path/to/resource/".
-

Hosts with and without a trailing dot are equivalent for routing. -Similarly, hosts with and without a leading dot are also equivalent.

-
-
-
HostMatch1 = "cowboy.example.org".
-HostMatch2 = "cowboy.example.org.".
-HostMatch3 = ".cowboy.example.org".
-

It is possible to extract segments of the host and path and to store -the values in the Req object for later use. We call these kind of -values bindings.

-

The syntax for bindings is very simple. A segment that begins with -the : character means that what follows until the end of the segment -is the name of the binding in which the segment value will be stored.

-
-
-
PathMatch = "/hats/:name/prices".
-HostMatch = ":subdomain.example.org".
-

If these two end up matching when routing, you will end up with two -bindings defined, subdomain and name, each containing the -segment value where they were defined. For example, the URL -http://test.example.org/hats/wild_cowboy_legendary/prices will -result in having the value test bound to the name subdomain -and the value wild_cowboy_legendary bound to the name name. -They can later be retrieved using cowboy_req:binding/{2,3}. The -binding name must be given as an atom.

-

There is a special binding name you can use to mimic the underscore -variable in Erlang. Any match against the _ binding will succeed -but the data will be discarded. This is especially useful for -matching against many domain names in one go.

-
-
-
HostMatch = "ninenines.:_".
-

Similarly, it is possible to have optional segments. Anything -between brackets is optional.

-
-
-
PathMatch = "/hats/[page/:number]".
-HostMatch = "[www.]ninenines.eu".
-

You can also have imbricated optional segments.

-
-
-
PathMatch = "/hats/[page/[:number]]".
-

You can retrieve the rest of the host or path using [...]. -In the case of hosts it will match anything before, in the case -of paths anything after the previously matched segments. It is -a special case of optional segments, in that it can have -zero, one or many segments. You can then find the segments using -cowboy_req:host_info/1 and cowboy_req:path_info/1 respectively. -They will be represented as a list of segments.

-
-
-
PathMatch = "/hats/[...]".
-HostMatch = "[...]ninenines.eu".
-

If a binding appears twice in the routing rules, then the match -will succeed only if they share the same value. This copies the -Erlang pattern matching behavior.

-
-
-
PathMatch = "/hats/:name/:name".
-

This is also true when an optional segment is present. In this -case the two values must be identical only if the segment is -available.

-
-
-
PathMatch = "/hats/:name/[:name]".
-

If a binding is defined in both the host and path, then they must -also share the same value.

-
-
-
PathMatch = "/:user/[...]".
-HostMatch = ":user.github.com".
-

Finally, there are two special match values that can be used. The -first is the atom '_' which will match any host or path.

-
-
-
PathMatch = '_'.
-HostMatch = '_'.
-

The second is the special host match "*" which will match the -wildcard path, generally used alongside the OPTIONS method.

-
-
-
HostMatch = "*".
-
- -
+
HostMatch = "*".
+

Constraints

-
-

After the matching has completed, the resulting bindings can be tested -against a set of constraints. Constraints are only tested when the -binding is defined. They run in the order you defined them. The match -will succeed only if they all succeed. If the match fails, then Cowboy -tries the next route in the list.

-

The format used for constraints is the same as match functions in -cowboy_req: they are provided as a list of fields which may have -one or more constraints. While the router accepts the same format, -it will skip fields with no constraints and will also ignore default -values, if any.

-

Read more about constraints.

-
- -
+

After the matching has completed, the resulting bindings can be tested against a set of constraints. Constraints are only tested when the binding is defined. They run in the order you defined them. The match will succeed only if they all succeed. If the match fails, then Cowboy tries the next route in the list.

+

The format used for constraints is the same as match functions in cowboy_req: they are provided as a list of fields which may have one or more constraints. While the router accepts the same format, it will skip fields with no constraints and will also ignore default values, if any.

+

Read more about constraints.

Compilation

-
-

The routes must be compiled before Cowboy can use them. The compilation -step normalizes the routes to simplify the code and speed up the -execution, but the routes are still looked up one by one in the end. -Faster compilation strategies could be to compile the routes directly -to Erlang code, but would require heavier dependencies.

-

To compile routes, just call the appropriate function:

-
-
-
Dispatch = cowboy_router:compile([
-    %% {HostMatch, list({PathMatch, Handler, InitialState})}
-    {'_', [{'_', my_handler, #{}}]}
+
Dispatch = cowboy_router:compile([
+    %% {HostMatch, list({PathMatch, Handler, InitialState})}
+    {'_', [{'_', my_handler, #{}}]}
 ]),
-%% Name, NbAcceptors, TransOpts, ProtoOpts
-cowboy:start_clear(my_http_listener,
-    [{port, 8080}],
-    #{env => #{dispatch => Dispatch}}
-).
-
-
-
+%% Name, NbAcceptors, TransOpts, ProtoOpts +cowboy:start_clear(my_http_listener, + [{port, 8080}], + #{env => #{dispatch => Dispatch}} +). +

Live update

-
-

You can use the cowboy:set_env/3 function for updating the dispatch -list used by routing. This will apply to all new connections accepted -by the listener:

-
-
-
Dispatch = cowboy_router:compile(Routes),
-cowboy:set_env(my_http_listener, dispatch, Dispatch).
-

Note that you need to compile the routes again before updating.

-
- +
Dispatch = cowboy_router:compile(Routes),
+cowboy:set_env(my_http_listener, dispatch, Dispatch).
+ +

Note that you need to compile the routes again before updating.

+ diff --git a/docs/en/cowboy/2.4/guide/specs/index.html b/docs/en/cowboy/2.4/guide/specs/index.html index 9f34951a..bbee8377 100644 --- a/docs/en/cowboy/2.4/guide/specs/index.html +++ b/docs/en/cowboy/2.4/guide/specs/index.html @@ -62,859 +62,345 @@

HTTP and other specifications

-

This chapter intends to list all the specification documents -for or related to HTTP.

-
+

This chapter intends to list all the specification documents for or related to HTTP.

HTTP

-
- -
+

Current

-
    -
  • -

    -CORS: Cross-Origin Resource Sharing -

    -
  • -
  • -

    -CSP2: Content Security Policy Level 2 -

    -
  • -
  • -

    -DNT: Tracking Preference Expression (DNT) -

    -
  • -
  • -

    -eventsource: Server-Sent Events -

    -
  • -
  • -

    -Form content types: Form content types -

    -
  • -
  • -

    -Preload: Preload -

    -
  • -
  • -

    -PROXY: The PROXY protocol -

    -
  • -
  • -

    -REST: Fielding’s Dissertation -

    -
  • -
  • -

    -RFC 1945: HTTP/1.0 -

    -
  • -
  • -

    -RFC 1951: DEFLATE Compressed Data Format Specification version 1.3 -

    -
  • -
  • -

    -RFC 1952: GZIP file format specification version 4.3 -

    -
  • -
  • -

    -RFC 2046: Multipart media type (in MIME Part Two: Media Types) -

    -
  • -
  • -

    -RFC 2295: Transparent Content Negotiation in HTTP -

    -
  • -
  • -

    -RFC 2296: HTTP Remote Variant Selection Algorithm: RVSA/1.0 -

    -
  • -
  • -

    -RFC 2817: Upgrading to TLS Within HTTP/1.1 -

    -
  • -
  • -

    -RFC 2818: HTTP Over TLS -

    -
  • -
  • -

    -RFC 3230: Instance Digests in HTTP -

    -
  • -
  • -

    -RFC 4559: SPNEGO-based Kerberos and NTLM HTTP Authentication in Microsoft Windows -

    -
  • -
  • -

    -RFC 5789: PATCH Method for HTTP -

    -
  • -
  • -

    -RFC 5843: Additional Hash Algorithms for HTTP Instance Digests -

    -
  • -
  • -

    -RFC 5861: HTTP Cache-Control Extensions for Stale Content -

    -
  • -
  • -

    -RFC 5988: Web Linking -

    -
  • -
  • -

    -RFC 6265: HTTP State Management Mechanism -

    -
  • -
  • -

    -RFC 6266: Use of the Content-Disposition Header Field -

    -
  • -
  • -

    -RFC 6454: The Web Origin Concept -

    -
  • -
  • -

    -RFC 6455: The WebSocket Protocol -

    -
  • -
  • -

    -RFC 6585: Additional HTTP Status Codes -

    -
  • -
  • -

    -RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage -

    -
  • -
  • -

    -RFC 6797: HTTP Strict Transport Security (HSTS) -

    -
  • -
  • -

    -RFC 6903: Additional Link Relation Types -

    -
  • -
  • -

    -RFC 7034: HTTP Header Field X-Frame-Options -

    -
  • -
  • -

    -RFC 7089: Time-Based Access to Resource States: Memento -

    -
  • -
  • -

    -RFC 7230: HTTP/1.1 Message Syntax and Routing -

    -
  • -
  • -

    -RFC 7231: HTTP/1.1 Semantics and Content -

    -
  • -
  • -

    -RFC 7232: HTTP/1.1 Conditional Requests -

    -
  • -
  • -

    -RFC 7233: HTTP/1.1 Range Requests -

    -
  • -
  • -

    -RFC 7234: HTTP/1.1 Caching -

    -
  • -
  • -

    -RFC 7235: HTTP/1.1 Authentication -

    -
  • -
  • -

    -RFC 7239: Forwarded HTTP Extension -

    -
  • -
  • -

    -RFC 7240: Prefer Header for HTTP -

    -
  • -
  • -

    -RFC 7469: Public Key Pinning Extension for HTTP -

    -
  • -
  • -

    -RFC 7486: HTTP Origin-Bound Authentication (HOBA) -

    -
  • -
  • -

    -RFC 7538: HTTP Status Code 308 (Permanent Redirect) -

    -
  • -
  • -

    -RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2) -

    -
  • -
  • -

    -RFC 7541: HPACK: Header Compression for HTTP/2 -

    -
  • -
  • -

    -RFC 7578: Returning Values from Forms: multipart/form-data -

    -
  • -
  • -

    -RFC 7615: HTTP Authentication-Info and Proxy-Authentication-Info Response Header Fields -

    -
  • -
  • -

    -RFC 7616: HTTP Digest Access Authentication -

    -
  • -
  • -

    -RFC 7617: The Basic HTTP Authentication Scheme -

    -
  • -
  • -

    -RFC 7639: The ALPN HTTP Header Field -

    -
  • -
  • -

    -RFC 7692: Compression Extensions for WebSocket -

    -
  • -
  • -

    -RFC 7694: HTTP Client-Initiated Content-Encoding -

    -
  • -
  • -

    -RFC 7725: An HTTP Status Code to Report Legal Obstacles -

    -
  • -
  • -

    -RFC 7804: Salted Challenge Response HTTP Authentication Mechanism -

    -
  • -
  • -

    -RFC 7838: HTTP Alternative Services -

    -
  • -
  • -

    -RFC 7932: Brotli Compressed Data Format -

    -
  • -
  • -

    -RFC 7936: Clarifying Registry Procedures for the WebSocket Subprotocol Name Registry -

    -
  • -
  • -

    -RFC 8053: HTTP Authentication Extensions for Interactive Clients -

    -
  • -
  • -

    -RFC 8164: Opportunistic Security for HTTP/2 -

    -
  • -
  • -

    -RFC 8187: Indicating Character Encoding and Language for HTTP Header Field Parameters -

    -
  • -
  • -

    -RFC 8188: Encrypted Content-Encoding for HTTP -

    -
  • -
  • -

    -RFC 8246: HTTP Immutable Responses -

    -
  • -
  • -

    -RFC 8297: An HTTP Status Code for Indicating Hints -

    -
  • -
  • -

    -RFC 8336: The ORIGIN HTTP/2 Frame -

    -
  • -
  • -

    -Webmention: Webmention -

    -
  • -
-
-
+
  • CORS: Cross-Origin Resource Sharing +
  • +
  • CSP2: Content Security Policy Level 2 +
  • +
  • DNT: Tracking Preference Expression (DNT) +
  • +
  • eventsource: Server-Sent Events +
  • +
  • Form content types: Form content types +
  • +
  • Preload: Preload +
  • +
  • PROXY: The PROXY protocol +
  • +
  • REST: Fielding's Dissertation +
  • +
  • RFC 1945: HTTP/1.0 +
  • +
  • RFC 1951: DEFLATE Compressed Data Format Specification version 1.3 +
  • +
  • RFC 1952: GZIP file format specification version 4.3 +
  • +
  • RFC 2046: Multipart media type (in MIME Part Two: Media Types) +
  • +
  • RFC 2295: Transparent Content Negotiation in HTTP +
  • +
  • RFC 2296: HTTP Remote Variant Selection Algorithm: RVSA/1.0 +
  • +
  • RFC 2817: Upgrading to TLS Within HTTP/1.1 +
  • +
  • RFC 2818: HTTP Over TLS +
  • +
  • RFC 3230: Instance Digests in HTTP +
  • +
  • RFC 4559: SPNEGO-based Kerberos and NTLM HTTP Authentication in Microsoft Windows +
  • +
  • RFC 5789: PATCH Method for HTTP +
  • +
  • RFC 5843: Additional Hash Algorithms for HTTP Instance Digests +
  • +
  • RFC 5861: HTTP Cache-Control Extensions for Stale Content +
  • +
  • RFC 5988: Web Linking +
  • +
  • RFC 6265: HTTP State Management Mechanism +
  • +
  • RFC 6266: Use of the Content-Disposition Header Field +
  • +
  • RFC 6454: The Web Origin Concept +
  • +
  • RFC 6455: The WebSocket Protocol +
  • +
  • RFC 6585: Additional HTTP Status Codes +
  • +
  • RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage +
  • +
  • RFC 6797: HTTP Strict Transport Security (HSTS) +
  • +
  • RFC 6903: Additional Link Relation Types +
  • +
  • RFC 7034: HTTP Header Field X-Frame-Options +
  • +
  • RFC 7089: Time-Based Access to Resource States: Memento +
  • +
  • RFC 7230: HTTP/1.1 Message Syntax and Routing +
  • +
  • RFC 7231: HTTP/1.1 Semantics and Content +
  • +
  • RFC 7232: HTTP/1.1 Conditional Requests +
  • +
  • RFC 7233: HTTP/1.1 Range Requests +
  • +
  • RFC 7234: HTTP/1.1 Caching +
  • +
  • RFC 7235: HTTP/1.1 Authentication +
  • +
  • RFC 7239: Forwarded HTTP Extension +
  • +
  • RFC 7240: Prefer Header for HTTP +
  • +
  • RFC 7469: Public Key Pinning Extension for HTTP +
  • +
  • RFC 7486: HTTP Origin-Bound Authentication (HOBA) +
  • +
  • RFC 7538: HTTP Status Code 308 (Permanent Redirect) +
  • +
  • RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2) +
  • +
  • RFC 7541: HPACK: Header Compression for HTTP/2 +
  • +
  • RFC 7578: Returning Values from Forms: multipart/form-data +
  • +
  • RFC 7615: HTTP Authentication-Info and Proxy-Authentication-Info Response Header Fields +
  • +
  • RFC 7616: HTTP Digest Access Authentication +
  • +
  • RFC 7617: The Basic HTTP Authentication Scheme +
  • +
  • RFC 7639: The ALPN HTTP Header Field +
  • +
  • RFC 7692: Compression Extensions for WebSocket +
  • +
  • RFC 7694: HTTP Client-Initiated Content-Encoding +
  • +
  • RFC 7725: An HTTP Status Code to Report Legal Obstacles +
  • +
  • RFC 7804: Salted Challenge Response HTTP Authentication Mechanism +
  • +
  • RFC 7838: HTTP Alternative Services +
  • +
  • RFC 7932: Brotli Compressed Data Format +
  • +
  • RFC 7936: Clarifying Registry Procedures for the WebSocket Subprotocol Name Registry +
  • +
  • RFC 8053: HTTP Authentication Extensions for Interactive Clients +
  • +
  • RFC 8164: Opportunistic Security for HTTP/2 +
  • +
  • RFC 8187: Indicating Character Encoding and Language for HTTP Header Field Parameters +
  • +
  • RFC 8188: Encrypted Content-Encoding for HTTP +
  • +
  • RFC 8246: HTTP Immutable Responses +
  • +
  • RFC 8297: An HTTP Status Code for Indicating Hints +
  • +
  • RFC 8336: The ORIGIN HTTP/2 Frame +
  • +
  • Webmention: Webmention +
  • +

Upcoming

- -
-
+

Informative

-
    -
  • -

    -Architecture of the World Wide Web -

    -
  • -
  • -

    -RFC 2936: HTTP MIME Type Handler Detection -

    -
  • -
  • -

    -RFC 2964: Use of HTTP State Management -

    -
  • -
  • -

    -RFC 3143: Known HTTP Proxy/Caching Problems -

    -
  • -
  • -

    -RFC 6202: Known Issues and Best Practices for the Use of Long Polling and Streaming in Bidirectional HTTP -

    -
  • -
  • -

    -RFC 6838: Media Type Specifications and Registration Procedures -

    -
  • -
  • -

    -RFC 7478: Web Real-Time Communication Use Cases and Requirements -

    -
  • -
-
-
+
  • Architecture of the World Wide Web +
  • +
  • RFC 2936: HTTP MIME Type Handler Detection +
  • +
  • RFC 2964: Use of HTTP State Management +
  • +
  • RFC 3143: Known HTTP Proxy/Caching Problems +
  • +
  • RFC 6202: Known Issues and Best Practices for the Use of Long Polling and Streaming in Bidirectional HTTP +
  • +
  • RFC 6838: Media Type Specifications and Registration Procedures +
  • +
  • RFC 7478: Web Real-Time Communication Use Cases and Requirements +
  • +
-
-
-
+

Seemingly obsolete

-
    -
  • -

    -RFC 2227: Simple Hit-Metering and Usage-Limiting for HTTP -

    -
  • -
  • -

    -RFC 2310: The Safe Response Header Field -

    -
  • -
  • -

    -RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) -

    -
  • -
  • -

    -RFC 2660: The Secure HyperText Transfer Protocol -

    -
  • -
  • -

    -RFC 2774: An HTTP Extension Framework -

    -
  • -
  • -

    -RFC 2965: HTTP State Management Mechanism (Cookie2) -

    -
  • -
  • -

    -RFC 3229: Delta encoding in HTTP -

    -
  • -
  • -

    -RFC 7168: The Hyper Text Coffee Pot Control Protocol for Tea Efflux Appliances (HTCPCP-TEA) -

    -
  • -
  • -

    -SPDY: SPDY Protocol -

    -
  • -
  • -

    -x-webkit-deflate-frame: Deprecated Websocket compression -

    -
  • -
-
-
-
-
+
  • RFC 2227: Simple Hit-Metering and Usage-Limiting for HTTP +
  • +
  • RFC 2310: The Safe Response Header Field +
  • +
  • RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) +
  • +
  • RFC 2660: The Secure HyperText Transfer Protocol +
  • +
  • RFC 2774: An HTTP Extension Framework +
  • +
  • RFC 2965: HTTP State Management Mechanism (Cookie2) +
  • +
  • RFC 3229: Delta encoding in HTTP +
  • +
  • RFC 7168: The Hyper Text Coffee Pot Control Protocol for Tea Efflux Appliances (HTCPCP-TEA) +
  • +
  • SPDY: SPDY Protocol +
  • +
  • x-webkit-deflate-frame: Deprecated Websocket compression +
  • +

URL

-
-
-
-
-
+

WebDAV

-
-
    -
  • -

    -RFC 3253: Versioning Extensions to WebDAV -

    -
  • -
  • -

    -RFC 3648: WebDAV Ordered Collections Protocol -

    -
  • -
  • -

    -RFC 3744: WebDAV Access Control Protocol -

    -
  • -
  • -

    -RFC 4316: Datatypes for WebDAV Properties -

    -
  • -
  • -

    -RFC 4331: Quota and Size Properties for DAV Collections -

    -
  • -
  • -

    -RFC 4437: WebDAV Redirect Reference Resources -

    -
  • -
  • -

    -RFC 4709: Mounting WebDAV Servers -

    -
  • -
  • -

    -RFC 4791: Calendaring Extensions to WebDAV (CalDAV) -

    -
  • -
  • -

    -RFC 4918: HTTP Extensions for WebDAV -

    -
  • -
  • -

    -RFC 5323: WebDAV SEARCH -

    -
  • -
  • -

    -RFC 5397: WebDAV Current Principal Extension -

    -
  • -
  • -

    -RFC 5689: Extended MKCOL for WebDAV -

    -
  • -
  • -

    -RFC 5842: Binding Extensions to WebDAV -

    -
  • -
  • -

    -RFC 5995: Using POST to Add Members to WebDAV Collections -

    -
  • -
  • -

    -RFC 6352: CardDAV: vCard Extensions to WebDAV -

    -
  • -
  • -

    -RFC 6578: Collection Synchronization for WebDAV -

    -
  • -
  • -

    -RFC 6638: Scheduling Extensions to CalDAV -

    -
  • -
  • -

    -RFC 6764: Locating Services for Calendaring Extensions to WebDAV (CalDAV) and vCard Extensions to WebDAV (CardDAV) -

    -
  • -
  • -

    -RFC 7809: Calendaring Extensions to WebDAV (CalDAV): Time Zones by Reference -

    -
  • -
  • -

    -RFC 7953: Calendar Availability -

    -
  • -
  • -

    -RFC 8144: Use of the Prefer Header Field in WebDAV -

    -
  • -
-
-
-
+
  • RFC 3253: Versioning Extensions to WebDAV +
  • +
  • RFC 3648: WebDAV Ordered Collections Protocol +
  • +
  • RFC 3744: WebDAV Access Control Protocol +
  • +
  • RFC 4316: Datatypes for WebDAV Properties +
  • +
  • RFC 4331: Quota and Size Properties for DAV Collections +
  • +
  • RFC 4437: WebDAV Redirect Reference Resources +
  • +
  • RFC 4709: Mounting WebDAV Servers +
  • +
  • RFC 4791: Calendaring Extensions to WebDAV (CalDAV) +
  • +
  • RFC 4918: HTTP Extensions for WebDAV +
  • +
  • RFC 5323: WebDAV SEARCH +
  • +
  • RFC 5397: WebDAV Current Principal Extension +
  • +
  • RFC 5689: Extended MKCOL for WebDAV +
  • +
  • RFC 5842: Binding Extensions to WebDAV +
  • +
  • RFC 5995: Using POST to Add Members to WebDAV Collections +
  • +
  • RFC 6352: CardDAV: vCard Extensions to WebDAV +
  • +
  • RFC 6578: Collection Synchronization for WebDAV +
  • +
  • RFC 6638: Scheduling Extensions to CalDAV +
  • +
  • RFC 6764: Locating Services for Calendaring Extensions to WebDAV (CalDAV) and vCard Extensions to WebDAV (CardDAV) +
  • +
  • RFC 7809: Calendaring Extensions to WebDAV (CalDAV): Time Zones by Reference +
  • +
  • RFC 7953: Calendar Availability +
  • +
  • RFC 8144: Use of the Prefer Header Field in WebDAV +
  • +

CoAP

-
-
    -
  • -

    -RFC 7252: The Constrained Application Protocol (CoAP) -

    -
  • -
  • -

    -RFC 7390: Group Communication for CoAP -

    -
  • -
  • -

    -RFC 7641: Observing Resources in CoAP -

    -
  • -
  • -

    -RFC 7650: A CoAP Usage for REsource LOcation And Discovery (RELOAD) -

    -
  • -
  • -

    -RFC 7959: Block-Wise Transfers in CoAP -

    -
  • -
  • -

    -RFC 7967: CoAP Option for No Server Response -

    -
  • -
  • -

    -RFC 8075: Guidelines for Mapping Implementations: HTTP to CoAP -

    -
  • -
  • -

    -RFC 8132: PATCH and FETCH Methods for CoAP -

    -
  • -
  • -

    -RFC 8323: CoAP over TCP, TLS, and WebSockets -

    -
  • -
-
-
+
  • RFC 7252: The Constrained Application Protocol (CoAP) +
  • +
  • RFC 7390: Group Communication for CoAP +
  • +
  • RFC 7641: Observing Resources in CoAP +
  • +
  • RFC 7650: A CoAP Usage for REsource LOcation And Discovery (RELOAD) +
  • +
  • RFC 7959: Block-Wise Transfers in CoAP +
  • +
  • RFC 7967: CoAP Option for No Server Response +
  • +
  • RFC 8075: Guidelines for Mapping Implementations: HTTP to CoAP +
  • +
  • RFC 8132: PATCH and FETCH Methods for CoAP +
  • +
  • RFC 8323: CoAP over TCP, TLS, and WebSockets +
  • +
+ diff --git a/docs/en/cowboy/2.4/guide/static_files/index.html b/docs/en/cowboy/2.4/guide/static_files/index.html index 4baf89f1..a6d5c7bb 100644 --- a/docs/en/cowboy/2.4/guide/static_files/index.html +++ b/docs/en/cowboy/2.4/guide/static_files/index.html @@ -62,173 +62,101 @@

Static files

-

Cowboy comes with a ready to use handler for serving static -files. It is provided as a convenience for serving files -during development.

-

For systems in production, consider using one of the many -Content Distribution Network (CDN) available on the market, -as they are the best solution for serving files.

-

The static handler can serve either one file or all files -from a given directory. The etag generation and mime types -can be configured.

-
+

Cowboy comes with a ready to use handler for serving static files. It is provided as a convenience for serving files during development.

+

For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files.

+

The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured.

Serve one file

-
-

You can use the static handler to serve one specific file -from an application’s private directory. This is particularly -useful to serve an index.html file when the client requests -the / path, for example. The path configured is relative -to the given application’s private directory.

-

The following rule will serve the file static/index.html -from the application my_app's priv directory whenever the -path / is accessed:

-
-
-
{"/", cowboy_static, {priv_file, my_app, "static/index.html"}}
-

You can also specify the absolute path to a file, or the -path to the file relative to the current directory:

-
-
-
{"/", cowboy_static, {file, "/var/www/index.html"}}
-
-
-
+
{"/", cowboy_static, {file, "/var/www/index.html"}}
+

Serve all files from a directory

-
-

You can also use the static handler to serve all files that -can be found in the configured directory. The handler will -use the path_info information to resolve the file location, -which means that your route must end with a [...] pattern -for it to work. All files are served, including the ones that -may be found in subfolders.

-

You can specify the directory relative to an application’s -private directory.

-

The following rule will serve any file found in the application -my_app's priv directory inside the static/assets folder -whenever the requested path begins with /assets/:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets"}}
-

You can also specify the absolute path to the directory or -set it relative to the current directory:

-
-
-
{"/assets/[...]", cowboy_static, {dir, "/var/www/assets"}}
-
- -
+
{"/assets/[...]", cowboy_static, {dir, "/var/www/assets"}}
+

Customize the mimetype detection

-
-

By default, Cowboy will attempt to recognize the mimetype -of your static files by looking at the extension.

-

You can override the function that figures out the mimetype -of the static files. It can be useful when Cowboy is missing -a mimetype you need to handle, or when you want to reduce -the list to make lookups faster. You can also give a -hard-coded mimetype that will be used unconditionally.

-

Cowboy comes with two functions built-in. The default -function only handles common file types used when building -Web applications. The other function is an extensive list -of hundreds of mimetypes that should cover almost any need -you may have. You can of course create your own function.

-

To use the default function, you should not have to configure -anything, as it is the default. If you insist, though, the -following will do the job:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{mimetypes, cow_mimetypes, web}]}}
-

As you can see, there is an optional field that may contain -a list of less used options, like mimetypes or etag. All option -types have this optional field.

-

To use the function that will detect almost any mimetype, -the following configuration will do:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{mimetypes, cow_mimetypes, all}]}}
-

You probably noticed the pattern by now. The configuration -expects a module and a function name, so you can use any -of your own functions instead:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{mimetypes, Module, Function}]}}
-

The function that performs the mimetype detection receives -a single argument that is the path to the file on disk. It -is recommended to return the mimetype in tuple form, although -a binary string is also allowed (but will require extra -processing). If the function can’t figure out the mimetype, -then it should return {<<"application">>, <<"octet-stream">>, []}.

-

When the static handler fails to find the extension, -it will send the file as application/octet-stream. -A browser receiving such file will attempt to download it -directly to disk.

-

Finally, the mimetype can be hard-coded for all files. -This is especially useful in combination with the file -and priv_file options as it avoids needless computation:

-
-
-
{"/", cowboy_static, {priv_file, my_app, "static/index.html",
-    [{mimetypes, {<<"text">>, <<"html">>, []}}]}}
-
- -
+
{"/", cowboy_static, {priv_file, my_app, "static/index.html",
+    [{mimetypes, {<<"text">>, <<"html">>, []}}]}}
+

Generate an etag

-
-

By default, the static handler will generate an etag header -value based on the size and modified time. This solution -can not be applied to all systems though. It would perform -rather poorly over a cluster of nodes, for example, as the -file metadata will vary from server to server, giving a -different etag on each server.

-

You can however change the way the etag is calculated:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{etag, Module, Function}]}}
-

This function will receive three arguments: the path to the -file on disk, the size of the file and the last modification -time. In a distributed setup, you would typically use the -file path to retrieve an etag value that is identical across -all your servers.

-

You can also completely disable etag handling:

-
-
-
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
-    [{etag, false}]}}
-
- +
{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets",
+    [{etag, false}]}}
+ + diff --git a/docs/en/cowboy/2.4/guide/streams/index.html b/docs/en/cowboy/2.4/guide/streams/index.html index 2a185fb0..6917f902 100644 --- a/docs/en/cowboy/2.4/guide/streams/index.html +++ b/docs/en/cowboy/2.4/guide/streams/index.html @@ -62,61 +62,23 @@

Streams

-

A stream is the set of messages that form an HTTP -request/response pair.

-

The term stream comes from HTTP/2. In Cowboy, it is -also used when talking about HTTP/1.1 or HTTP/1.0. -It should not be confused with streaming the request -or response body.

-

All versions of HTTP allow clients to initiate -streams. HTTP/2 is the only one also allowing servers, -through its server push feature. Both client and -server-initiated streams go through the same process -in Cowboy.

-
+

A stream is the set of messages that form an HTTP request/response pair.

+

The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body.

+

All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy.

Stream handlers

-
-

Stream handlers must implement five different callbacks. -Four of them are directly related; one is special.

-

All callbacks receives the stream ID as first argument.

-

Most of them can return a list of commands to be executed -by Cowboy. When callbacks are chained, it is possible to -intercept and modify these commands. This can be useful -for modifying responses for example.

-

The init/3 callback is invoked when a new request -comes in. It receives the Req object and the protocol options -for this listener.

-

The data/4 callback is invoked when data from the request -body is received. It receives both this data and a flag -indicating whether more is to be expected.

-

The info/3 callback is invoked when an Erlang message is -received for this stream. They will typically be messages -sent by the request process.

-

Finally the terminate/3 callback is invoked with the -terminate reason for the stream. The return value is ignored. -Note that as with all terminate callbacks in Erlang, there -is no strong guarantee that it will be called.

-

The special callback early_error/5 is called when an error -occurs before the request headers were fully received and -Cowboy is sending a response. It receives the partial Req -object, the error reason, the protocol options and the response -Cowboy will send. This response must be returned, possibly -modified.

-
-
-
+

Stream handlers must implement five different callbacks. Four of them are directly related; one is special.

+

All callbacks receives the stream ID as first argument.

+

Most of them can return a list of commands to be executed by Cowboy. When callbacks are chained, it is possible to intercept and modify these commands. This can be useful for modifying responses for example.

+

The init/3 callback is invoked when a new request comes in. It receives the Req object and the protocol options for this listener.

+

The data/4 callback is invoked when data from the request body is received. It receives both this data and a flag indicating whether more is to be expected.

+

The info/3 callback is invoked when an Erlang message is received for this stream. They will typically be messages sent by the request process.

+

Finally the terminate/3 callback is invoked with the terminate reason for the stream. The return value is ignored. Note that as with all terminate callbacks in Erlang, there is no strong guarantee that it will be called.

+

The special callback early_error/5 is called when an error occurs before the request headers were fully received and Cowboy is sending a response. It receives the partial Req object, the error reason, the protocol options and the response Cowboy will send. This response must be returned, possibly modified.

Built-in handlers

-
-

Cowboy comes with two handlers.

-

cowboy_stream_h is the default stream handler. -It is the core of much of the functionality of Cowboy. -All chains of stream handlers should call it last.

-

cowboy_compress_h will automatically compress -responses when possible. It is not enabled by default. -It is a good example for writing your own handlers -that will modify responses.

-
-
+

Cowboy comes with two handlers.

+

cowboy_stream_h is the default stream handler. It is the core of much of the functionality of Cowboy. All chains of stream handlers should call it last.

+

cowboy_compress_h will automatically compress responses when possible. It is not enabled by default. It is a good example for writing your own handlers that will modify responses.

+ diff --git a/docs/en/cowboy/2.4/guide/ws_handlers/index.html b/docs/en/cowboy/2.4/guide/ws_handlers/index.html index a7783d07..94bf2f9e 100644 --- a/docs/en/cowboy/2.4/guide/ws_handlers/index.html +++ b/docs/en/cowboy/2.4/guide/ws_handlers/index.html @@ -62,297 +62,190 @@

Websocket handlers

-

Websocket handlers provide an interface for upgrading HTTP/1.1 -connections to Websocket and sending or receiving frames on -the Websocket connection.

-

As Websocket connections are established through the HTTP/1.1 -upgrade mechanism, Websocket handlers need to be able to first -receive the HTTP request for the upgrade, before switching to -Websocket and taking over the connection. They can then receive -or send Websocket frames, handle incoming Erlang messages or -close the connection.

-
+

Websocket handlers provide an interface for upgrading HTTP/1.1 connections to Websocket and sending or receiving frames on the Websocket connection.

+

As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection.

Upgrade

-
-

The init/2 callback is called when the request is received. -To establish a Websocket connection, you must switch to the -cowboy_websocket module:

-
-
-
init(Req, State) ->
-    {cowboy_websocket, Req, State}.
-

Cowboy will perform the Websocket handshake immediately. Note -that the handshake will fail if the client did not request an -upgrade to Websocket.

-

The Req object becomes unavailable after this function returns. -Any information required for proper execution of the Websocket -handler must be saved in the state.

-
-
-
-

Subprotocol

-
-

The client may provide a list of Websocket subprotocols it -supports in the sec-websocket-protocol header. The server must -select one of them and send it back to the client or the -handshake will fail.

-

For example, a client could understand both STOMP and MQTT over -Websocket, and provide the header:

-
-
-
sec-websocket-protocol: v12.stomp, mqtt
+
init(Req, State) ->
+    {cowboy_websocket, Req, State}.
-

If the server only understands MQTT it can return:

-
-
-
sec-websocket-protocol: mqtt
-
-

This selection must be done in init/2. An example usage could -be:

-
-
-
init(Req0, State) ->
-    case cowboy_req:parse_header(<<"sec-websocket-protocol">>, Req0) of
-        undefined ->
-            {cowboy_websocket, Req0, State};
-        Subprotocols ->
-            case lists:keymember(<<"mqtt">>, 1, Subprotocols) of
-                true ->
-                    Req = cowboy_req:set_resp_header(<<"sec-websocket-protocol">>,
-                        <<"mqtt">>, Req0),
-                    {cowboy_websocket, Req, State};
-                false ->
-                    Req = cowboy_req:reply(400, Req0),
-                    {ok, Req, State}
-            end
-    end.
-
-
-
+
init(Req0, State) ->
+    case cowboy_req:parse_header(<<"sec-websocket-protocol">>, Req0) of
+        undefined ->
+            {cowboy_websocket, Req0, State};
+        Subprotocols ->
+            case lists:keymember(<<"mqtt">>, 1, Subprotocols) of
+                true ->
+                    Req = cowboy_req:set_resp_header(<<"sec-websocket-protocol">>,
+                        <<"mqtt">>, Req0),
+                    {cowboy_websocket, Req, State};
+                false ->
+                    Req = cowboy_req:reply(400, Req0),
+                    {ok, Req, State}
+            end
+    end.
+

Post-upgrade initialization

-
-

Cowboy has separate processes for handling the connection -and requests. Because Websocket takes over the connection, -the Websocket protocol handling occurs in a different -process than the request handling.

-

This is reflected in the different callbacks Websocket -handlers have. The init/2 callback is called from the -temporary request process and the websocket_ callbacks -from the connection process.

-

This means that some initialization cannot be done from -init/2. Anything that would require the current pid, -or be tied to the current pid, will not work as intended. -The optional websocket_init/1 can be used instead:

-
-
-
websocket_init(State) ->
-    erlang:start_timer(1000, self(), <<"Hello!">>),
-    {ok, State}.
-

All Websocket callbacks share the same return values. This -means that we can send frames to the client right after -the upgrade:

-
-
-
websocket_init(State) ->
-    {reply, {text, <<"Hello!">>}, State}.
-
- -
+
websocket_init(State) ->
+    {reply, {text, <<"Hello!">>}, State}.
+

Receiving frames

-
-

Cowboy will call websocket_handle/2 whenever a text, binary, -ping or pong frame arrives from the client.

-

The handler can handle or ignore the frames. It can also -send frames back to the client or stop the connection.

-

The following snippet echoes back any text frame received and -ignores all others:

-
-
-
websocket_handle(Frame = {text, _}, State) ->
-    {reply, Frame, State};
-websocket_handle(_Frame, State) ->
-    {ok, State}.
-

Note that ping and pong frames require no action from the -handler as Cowboy will automatically reply to ping frames. -They are provided for informative purposes only.

-
- -
+
websocket_handle(Frame = {text, _}, State) ->
+    {reply, Frame, State};
+websocket_handle(_Frame, State) ->
+    {ok, State}.
+
+

Note that ping and pong frames require no action from the handler as Cowboy will automatically reply to ping frames. They are provided for informative purposes only.

Receiving Erlang messages

-
-

Cowboy will call websocket_info/2 whenever an Erlang message -arrives.

-

The handler can handle or ignore the messages. It can also -send frames to the client or stop the connection.

-

The following snippet forwards log messages to the client -and ignores all others:

-
-
-
websocket_info({log, Text}, State) ->
-    {reply, {text, Text}, State};
-websocket_info(_Info, State) ->
-    {ok, State}.
-
- -
+
websocket_info({log, Text}, State) ->
+    {reply, {text, Text}, State};
+websocket_info(_Info, State) ->
+    {ok, State}.
+

Sending frames

-
-

All websocket_ callbacks share return values. They may -send zero, one or many frames to the client.

-

To send nothing, just return an ok tuple:

-
-
+ + +

All websocket_ callbacks share return values. They may send zero, one or many frames to the client.

+

To send nothing, just return an ok tuple:

+
-
websocket_info(_Info, State) ->
-    {ok, State}.
-

To send one frame, return a reply tuple with the frame to send:

-
-
-
websocket_info(_Info, State) ->
-    {reply, {text, <<"Hello!">>}, State}.
-

You can send frames of any type: text, binary, ping, pong -or close frames.

-

To send many frames at once, return a reply tuple with the -list of frames to send:

-
-
-
websocket_info(_Info, State) ->
-    {reply, [
-        {text, "Hello"},
-        {text, <<"world!">>},
-        {binary, <<0:8000>>}
-    ], State}.
-

They are sent in the given order.

-
-
-
+
websocket_info(_Info, State) ->
+    {reply, [
+        {text, "Hello"},
+        {text, <<"world!">>},
+        {binary, <<0:8000>>}
+    ], State}.
+
+

They are sent in the given order.

Keeping the connection alive

-
-

Cowboy will automatically respond to ping frames sent by -the client. They are still forwarded to the handler for -informative purposes, but no further action is required.

-

Cowboy does not send ping frames itself. The handler can -do it if required. A better solution in most cases is to -let the client handle pings. Doing it from the handler -would imply having an additional timer per connection and -this can be a considerable cost for servers that need to -handle large numbers of connections.

-

Cowboy can be configured to close idle connections -automatically. It is highly recommended to configure -a timeout here, to avoid having processes linger longer -than needed.

-

The init/2 callback can set the timeout to be used -for the connection. For example, this would make Cowboy -close connections idle for more than 30 seconds:

-
-
-
init(Req, State) ->
-    {cowboy_websocket, Req, State, #{
-        idle_timeout => 30000}}.
-

This value cannot be changed once it is set. It defaults to -60000.

-
- -
+
init(Req, State) ->
+    {cowboy_websocket, Req, State, #{
+        idle_timeout => 30000}}.
+
+

This value cannot be changed once it is set. It defaults to 60000.

Limiting frame sizes

-
-

Cowboy accepts frames of any size by default. You should -limit the size depending on what your handler may handle. -You can do this via the init/2 callback:

-
-
-
init(Req, State) ->
-    {cowboy_websocket, Req, State, #{
-        max_frame_size => 8000000}}.
-

The lack of limit is historical. A future version of -Cowboy will have a more reasonable default.

-
- -
+
init(Req, State) ->
+    {cowboy_websocket, Req, State, #{
+        max_frame_size => 8000000}}.
+
+

The lack of limit is historical. A future version of Cowboy will have a more reasonable default.

Saving memory

-
-

The Websocket connection process can be set to hibernate -after the callback returns.

-

Simply add an hibernate field to the ok or reply tuples:

-
-
-
websocket_init(State) ->
-    {ok, State, hibernate}.
-
-websocket_handle(_Frame, State) ->
-    {ok, State, hibernate}.
-
-websocket_info(_Info, State) ->
-    {reply, {text, <<"Hello!">>}, State, hibernate}.
-

It is highly recommended to write your handlers with -hibernate enabled, as this allows to greatly reduce the -memory usage. Do note however that an increase in the -CPU usage or latency can be observed instead, in particular -for the more busy connections.

-
- -
+
websocket_init(State) ->
+    {ok, State, hibernate}.
+
+websocket_handle(_Frame, State) ->
+    {ok, State, hibernate}.
+
+websocket_info(_Info, State) ->
+    {reply, {text, <<"Hello!">>}, State, hibernate}.
+
+

It is highly recommended to write your handlers with hibernate enabled, as this allows to greatly reduce the memory usage. Do note however that an increase in the CPU usage or latency can be observed instead, in particular for the more busy connections.

Closing the connection

-
-

The connection can be closed at any time, either by telling -Cowboy to stop it or by sending a close frame.

-

To tell Cowboy to close the connection, use a stop tuple:

-
-
-
websocket_info(_Info, State) ->
-    {stop, State}.
-

Sending a close frame will immediately initiate the closing -of the Websocket connection. Note that when sending a list of -frames that include a close frame, any frame found after the -close frame will not be sent.

-

The following example sends a close frame with a reason message:

-
-
-
websocket_info(_Info, State) ->
-    {reply, {close, 1000, <<"some-reason">>}, State}.
-
- +
websocket_info(_Info, State) ->
+    {reply, {close, 1000, <<"some-reason">>}, State}.
+ + diff --git a/docs/en/cowboy/2.4/guide/ws_protocol/index.html b/docs/en/cowboy/2.4/guide/ws_protocol/index.html index 1bc3bf89..a5766799 100644 --- a/docs/en/cowboy/2.4/guide/ws_protocol/index.html +++ b/docs/en/cowboy/2.4/guide/ws_protocol/index.html @@ -62,70 +62,22 @@

The Websocket protocol

-

This chapter explains what Websocket is and why it is -a vital component of soft realtime Web applications.

-
+

This chapter explains what Websocket is and why it is a vital component of soft realtime Web applications.

Description

-
-

Websocket is an extension to HTTP that emulates plain TCP -connections between the client, typically a Web browser, -and the server. It uses the HTTP Upgrade mechanism to -establish the connection.

-

Websocket connections are fully asynchronous, unlike -HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the -server can only initiate streams in response to requests). -With Websocket, the client and the server can both send -frames at any time without any restriction. It is closer -to TCP than any of the HTTP protocols.

-

Websocket is an IETF standard. Cowboy supports the standard -and all drafts that were previously implemented by browsers, -excluding the initial flawed draft sometimes known as -"version 0".

-
-
-
+

Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection.

+

Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). With Websocket, the client and the server can both send frames at any time without any restriction. It is closer to TCP than any of the HTTP protocols.

+

Websocket is an IETF standard. Cowboy supports the standard and all drafts that were previously implemented by browsers, excluding the initial flawed draft sometimes known as "version 0".

Websocket vs HTTP/2

-
-

For a few years Websocket was the only way to have a -bidirectional asynchronous connection with the server. -This changed when HTTP/2 was introduced. While HTTP/2 -requires the client to first perform a request before -the server can push data, this is only a minor restriction -as the client can do so just as it connects.

-

Websocket was designed as a kind-of-TCP channel to a -server. It only defines the framing and connection -management and lets the developer implement a protocol -on top of it. For example you could implement IRC over -Websocket and use a Javascript IRC client to speak to -the server.

-

HTTP/2 on the other hand is just an improvement over -the HTTP/1.1 connection and request/response mechanism. -It has the same semantics as HTTP/1.1.

-

If all you need is to access an HTTP API, then HTTP/2 -should be your first choice. On the other hand, if what -you need is a different protocol, then you can use -Websocket to implement it.

-
-
-
+

For a few years Websocket was the only way to have a bidirectional asynchronous connection with the server. This changed when HTTP/2 was introduced. While HTTP/2 requires the client to first perform a request before the server can push data, this is only a minor restriction as the client can do so just as it connects.

+

Websocket was designed as a kind-of-TCP channel to a server. It only defines the framing and connection management and lets the developer implement a protocol on top of it. For example you could implement IRC over Websocket and use a Javascript IRC client to speak to the server.

+

HTTP/2 on the other hand is just an improvement over the HTTP/1.1 connection and request/response mechanism. It has the same semantics as HTTP/1.1.

+

If all you need is to access an HTTP API, then HTTP/2 should be your first choice. On the other hand, if what you need is a different protocol, then you can use Websocket to implement it.

Implementation

-
-

Cowboy implements Websocket as a protocol upgrade. Once the -upgrade is performed from the init/2 callback, Cowboy -switches to Websocket. Please consult the next chapter for -more information on initiating and handling Websocket -connections.

-

The implementation of Websocket in Cowboy is validated using -the Autobahn test suite, which is an extensive suite of tests -covering all aspects of the protocol. Cowboy passes the -suite with 100% success, including all optional tests.

-

Cowboy’s Websocket implementation also includes the -permessage-deflate and x-webkit-deflate-frame compression -extensions.

-

Cowboy will automatically use compression when the -compress option is returned from the init/2 function.

-
-
+

Cowboy implements Websocket as a protocol upgrade. Once the upgrade is performed from the init/2 callback, Cowboy switches to Websocket. Please consult the next chapter for more information on initiating and handling Websocket connections.

+

The implementation of Websocket in Cowboy is validated using the Autobahn test suite, which is an extensive suite of tests covering all aspects of the protocol. Cowboy passes the suite with 100% success, including all optional tests.

+

Cowboy's Websocket implementation also includes the permessage-deflate and x-webkit-deflate-frame compression extensions.

+

Cowboy will automatically use compression when the compress option is returned from the init/2 function.

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy.set_env/index.html b/docs/en/cowboy/2.4/manual/cowboy.set_env/index.html index 89ae117c..5ac0bdb2 100644 --- a/docs/en/cowboy/2.4/manual/cowboy.set_env/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy.set_env/index.html @@ -62,117 +62,59 @@

cowboy:set_env(3)

-

Name

-
-

cowboy:set_env - Update a listener’s environment value

-
-
-
+

cowboy:set_env - Update a listener's environment value

Description

-
-
-
-
set_env(Name  :: ranch:ref(),
-        Key   :: atom(),
-        Value :: any())
-    -> ok
-

Set or update an environment value for a previously started -listener.

-

This is most useful for updating the routes dynamically, -without having to restart the listener.

-

The new value will only be available to new connections. -Pre-existing connections will still use the old value.

-
-
-
+
set_env(Name  :: ranch:ref(),
+        Key   :: atom(),
+        Value :: any())
+    -> ok
+
+

Set or update an environment value for a previously started listener.

+

This is most useful for updating the routes dynamically, without having to restart the listener.

+

The new value will only be available to new connections. Pre-existing connections will still use the old value.

Arguments

-
-
-
-Name -
-
-

-The name of the listener to update. -

-

The name of the listener is the first argument given to the -cowboy:start_clear(3), -cowboy:start_tls(3) or -ranch:start_listener(3) function.

+
Name
+

The name of the listener to update.

+

The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function.

-
-Key -
-
-

-The key in the environment map. Common keys include dispatch -and middlewares. -

+
Key
+

The key in the environment map. Common keys include dispatch and middlewares.

-
-Value -
-
-

-The new value. -

-

The type of the value differs depending on the key.

+
Value
+

The new value.

+

The type of the value differs depending on the key.

-
-
- -
+

Return value

-
-

The atom ok is returned on success.

-

An exit:badarg exception is thrown when the listener does -not exist.

-
-
-
+

The atom ok is returned on success.

+

An exit:badarg exception is thrown when the listener does not exist.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Update a listener’s routes
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []},
-        {"/ws", websocket_h, []}
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []},
+        {"/ws", websocket_h, []}
     ]}
 ]),
 
-cowboy:set_env(example, dispatch, Dispatch).
-
-
-
+cowboy:set_env(example, dispatch, Dispatch). +

See also

- - +

cowboy(3), cowboy:start_clear(3), cowboy:start_tls(3), ranch:set_protocol_options(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy.start_clear/index.html b/docs/en/cowboy/2.4/manual/cowboy.start_clear/index.html index 04d9f310..f932cb38 100644 --- a/docs/en/cowboy/2.4/manual/cowboy.start_clear/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy.start_clear/index.html @@ -62,148 +62,77 @@

cowboy:start_clear(3)

-

Name

-
-

cowboy:start_clear - Listen for connections using plain TCP

-
-
-
+

cowboy:start_clear - Listen for connections using plain TCP

Description

-
-
-
-
start_clear(Name          :: ranch:ref(),
-            TransportOpts :: ranch_tcp:opts(),
-            ProtocolOpts  :: opts())
-    -> {ok, ListenerPid :: pid()}
-     | {error, any()}
-

Start listening for connections over a clear TCP channel.

-

Both HTTP/1.1 and HTTP/2 are supported on this listener. -HTTP/2 has two methods of establishing a connection over -a clear TCP channel. Both the upgrade and the prior knowledge -methods are supported.

-
-
-
+
start_clear(Name          :: ranch:ref(),
+            TransportOpts :: ranch_tcp:opts(),
+            ProtocolOpts  :: opts())
+    -> {ok, ListenerPid :: pid()}
+     | {error, any()}
+
+

Start listening for connections over a clear TCP channel.

+

Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported.

Arguments

-
-
-
-Name -
-
-

-The listener name is used to refer to this listener in -future calls, for example when stopping it or when -updating the routes defined. -

-

It can be any Erlang term. An atom is generally good enough, -for example api, my_app_clear or my_app_tls.

+
Name
+

The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined.

+

It can be any Erlang term. An atom is generally good enough, for example api, my_app_clear or my_app_tls.

-
-TransportOpts -
-
-

-The transport options are where the TCP options, including -the listener’s port number, are defined. Transport options -are provided as a list of keys and values, for example -[{port, 8080}]. -

-

The available options are documented in the -ranch_tcp(3) manual.

+
TransportOpts
+

The transport options are where the TCP options, including the listener's port number, are defined. Transport options are provided as a list of keys and values, for example [{port, 8080}].

+

The available options are documented in the ranch_tcp(3) manual.

-
-ProtocolOpts -
-
-

-The protocol options are in a map containing all the options for -the different protocols that may be involved when connecting -to the listener, including HTTP/1.1 and HTTP/2. -

-

The HTTP/1.1 options are documented in the -cowboy_http(3) manual; -and the HTTP/2 options in -cowboy_http2(3).

+
ProtocolOpts
+

The protocol options are in a map containing all the options for the different protocols that may be involved when connecting to the listener, including HTTP/1.1 and HTTP/2.

+

The HTTP/1.1 options are documented in the cowboy_http(3) manual; and the HTTP/2 options in cowboy_http2(3).

-
-
- -
+

Return value

-
-

An ok tuple is returned on success. It contains the pid of -the top-level supervisor for the listener.

-

An error tuple is returned on error. The error reason may -be any Erlang term.

-

A common error is eaddrinuse. It indicates that the port -configured for Cowboy is already in use.

-
-
-
+

An ok tuple is returned on success. It contains the pid of the top-level supervisor for the listener.

+

An error tuple is returned on error. The error reason may be any Erlang term.

+

A common error is eaddrinuse. It indicates that the port configured for Cowboy is already in use.

Changelog

-
-
    -
  • -

    -2.0: HTTP/2 support added. -

    +
    • 2.0: HTTP/2 support added.
    • -
    • -

      -2.0: Function introduced. Replaces cowboy:start_http/4. -

      +
    • 2.0: Function introduced. Replaces cowboy:start_http/4.
    • -
-
-
-
+

Examples

-
-
-
Start a listener
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []}
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []}
     ]}
 ]),
 
-{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{
-    env => #{dispatch => Dispatch}
-}).
-
-
Start a listener on a random port
-
-
Name = example,
+
Name = example,
 
-{ok, _} = cowboy:start_clear(Name, [], #{
-    env => #{dispatch => Dispatch}
+{ok, _} = cowboy:start_clear(Name, [], #{
+    env => #{dispatch => Dispatch}
 }),
 
-Port = ranch:get_port(Name).
-
-
-
+Port = ranch:get_port(Name). +

See also

- - +

cowboy(3), cowboy:start_tls(3), cowboy:stop_listener(3), ranch(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy.start_tls/index.html b/docs/en/cowboy/2.4/manual/cowboy.start_tls/index.html index 009a39a5..27f8e409 100644 --- a/docs/en/cowboy/2.4/manual/cowboy.start_tls/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy.start_tls/index.html @@ -62,153 +62,82 @@

cowboy:start_tls(3)

-

Name

-
-

cowboy:start_tls - Listen for connections using TLS

-
-
-
+

cowboy:start_tls - Listen for connections using TLS

Description

-
-
-
-
start_tls(Name          :: ranch:ref(),
-          TransportOpts :: ranch_ssl:opts(),
-          ProtocolOpts  :: opts())
-    -> {ok, ListenerPid :: pid()}
-     | {error, any()}
-

Start listening for connections over a secure TLS channel.

-

Both HTTP/1.1 and HTTP/2 are supported on this listener. -The ALPN TLS extension must be used to initiate an HTTP/2 -connection.

-
-
-
+
start_tls(Name          :: ranch:ref(),
+          TransportOpts :: ranch_ssl:opts(),
+          ProtocolOpts  :: opts())
+    -> {ok, ListenerPid :: pid()}
+     | {error, any()}
+
+

Start listening for connections over a secure TLS channel.

+

Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection.

Arguments

-
-
-
-Name -
-
-

-The listener name is used to refer to this listener in -future calls, for example when stopping it or when -updating the routes defined. -

-

It can be any Erlang term. An atom is generally good enough, -for example api, my_app_clear or my_app_tls.

+
Name
+

The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined.

+

It can be any Erlang term. An atom is generally good enough, for example api, my_app_clear or my_app_tls.

-
-TransportOpts -
-
-

-The transport options are where the TCP options, including -the listener’s port number, are defined. They also contain -the TLS options, like the server’s certificate. Transport options -are provided as a list of keys and values, for example -[{port, 8443}, {certfile, "path/to/cert.pem"}]. -

-

The available options are documented in the -ranch_ssl(3) manual.

+
TransportOpts
+

The transport options are where the TCP options, including the listener's port number, are defined. They also contain the TLS options, like the server's certificate. Transport options are provided as a list of keys and values, for example [{port, 8443}, {certfile, "path/to/cert.pem"}].

+

The available options are documented in the ranch_ssl(3) manual.

-
-ProtocolOpts -
-
-

-The protocol options are in a map containing all the options for -the different protocols that may be involved when connecting -to the listener, including HTTP/1.1 and HTTP/2. -

-

The HTTP/1.1 options are documented in the -cowboy_http(3) manual; -and the HTTP/2 options in -cowboy_http2(3).

+
ProtocolOpts
+

The protocol options are in a map containing all the options for the different protocols that may be involved when connecting to the listener, including HTTP/1.1 and HTTP/2.

+

The HTTP/1.1 options are documented in the cowboy_http(3) manual; and the HTTP/2 options in cowboy_http2(3).

-
-
- -
+

Return value

-
-

An ok tuple is returned on success. It contains the pid of -the top-level supervisor for the listener.

-

An error tuple is returned on error. The error reason may -be any Erlang term.

-

A common error is eaddrinuse. It indicates that the port -configured for Cowboy is already in use.

-
-
-
+

An ok tuple is returned on success. It contains the pid of the top-level supervisor for the listener.

+

An error tuple is returned on error. The error reason may be any Erlang term.

+

A common error is eaddrinuse. It indicates that the port configured for Cowboy is already in use.

Changelog

-
-
    -
  • -

    -2.0: HTTP/2 support added. -

    +
    • 2.0: HTTP/2 support added.
    • -
    • -

      -2.0: Function introduced. Replaces cowboy:start_https/4. -

      +
    • 2.0: Function introduced. Replaces cowboy:start_https/4.
    • -
-
-
-
+

Examples

-
-
-
Start a listener
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []}
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []}
     ]}
 ]),
 
-{ok, _} = cowboy:start_tls(example, [
-    {port, 8443},
-    {cert, "path/to/cert.pem"}
+{ok, _} = cowboy:start_tls(example, [
+    {port, 8443},
+    {cert, "path/to/cert.pem"}
 ], #{
-    env => #{dispatch => Dispatch}
-}).
-
-
Start a listener on a random port
-
-
Name = example,
+
Name = example,
 
-{ok, _} = cowboy:start_tls(Name, [
-    {cert, "path/to/cert.pem"}
+{ok, _} = cowboy:start_tls(Name, [
+    {cert, "path/to/cert.pem"}
 ], #{
-    env => #{dispatch => Dispatch}
+    env => #{dispatch => Dispatch}
 }),
 
-Port = ranch:get_port(Name).
-
-
-
+Port = ranch:get_port(Name). +

See also

- - +

cowboy(3), cowboy:start_clear(3), cowboy:stop_listener(3), ranch(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy.stop_listener/index.html b/docs/en/cowboy/2.4/manual/cowboy.stop_listener/index.html index 06b88e2d..59e0c6eb 100644 --- a/docs/en/cowboy/2.4/manual/cowboy.stop_listener/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy.stop_listener/index.html @@ -62,87 +62,42 @@

cowboy:stop_listener(3)

-

Name

-
-

cowboy:stop_listener - Stop the given listener

-
-
-
+

cowboy:stop_listener - Stop the given listener

Description

-
-
-
-
stop_listener(Name :: ranch:ref())
-    -> ok | {error, not_found}.
-

Stop a previously started listener.

- -
-
-
+
stop_listener(Name :: ranch:ref())
+    -> ok | {error, not_found}.
+
+

Stop a previously started listener.

+

Alias of ranch:stop_listener(3).

Arguments

-
-
-
-Name -
-
-

-The name of the listener to be stopped. -

-

The name of the listener is the first argument given to the -cowboy:start_clear(3), -cowboy:start_tls(3) or -ranch:start_listener(3) function.

+
Name
+

The name of the listener to be stopped.

+

The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function.

-
-
- -
+

Return value

-
-

The atom ok is returned on success.

-

The {error, not_found} tuple is returned when the listener -does not exist.

-
-
-
+

The atom ok is returned on success.

+

The {error, not_found} tuple is returned when the listener does not exist.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Stop a listener
-
-
ok = cowboy:stop_listener(example).
-
-
-
+
ok = cowboy:stop_listener(example).
+

See also

- - +

cowboy(3), cowboy:start_clear(3), cowboy:start_tls(3), ranch(3), ranch:start_listener(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy/index.html b/docs/en/cowboy/2.4/manual/cowboy/index.html index f9e9e279..fb723a60 100644 --- a/docs/en/cowboy/2.4/manual/cowboy/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy/index.html @@ -62,129 +62,76 @@

cowboy(3)

-

Name

-
-

cowboy - HTTP server

-
-
-
+

cowboy - HTTP server

Description

-
-

The module cowboy provides convenience functions for -manipulating Ranch listeners.

-
-
-
+

The module cowboy provides convenience functions for manipulating Ranch listeners.

Exports

-
-
-
-
-
+

Types

-
-

fields()

-
-
-
fields() :: [Name
-           | {Name, Constraints}
-           | {Name, Constraints, Default}]
-
-Name        :: atom()
-Constraints :: Constraint | [Constraint]
-Constraint  :: cowboy_constraints:constraint()
-Default     :: any()
-

Fields description for match operations.

-

This type is used in cowboy_router(3) -for matching bindings and in the match functions found in -cowboy_req(3).

-
-
+
fields() :: [Name
+           | {Name, Constraints}
+           | {Name, Constraints, Default}]
+
+Name        :: atom()
+Constraints :: Constraint | [Constraint]
+Constraint  :: cowboy_constraints:constraint()
+Default     :: any()
+
+

Fields description for match operations.

+

This type is used in cowboy_router(3) for matching bindings and in the match functions found in cowboy_req(3).

http_headers()

-
-
-
http_headers() :: #{binary() => iodata()}
-

HTTP headers.

-
-
+
http_headers() :: #{binary() => iodata()}
+
+

HTTP headers.

http_status()

-
-
-
http_status() :: non_neg_integer() | binary()
-

HTTP response status.

-

A binary status can be used to set a reason phrase. Note -however that HTTP/2 only sends the status code and drops -the reason phrase entirely.

- -
+
http_status() :: non_neg_integer() | binary()
+
+

HTTP response status.

+

A binary status can be used to set a reason phrase. Note however that HTTP/2 only sends the status code and drops the reason phrase entirely.

http_version()

-
-
-
http_version() :: 'HTTP/2' | 'HTTP/1.1' | 'HTTP/1.0'
-

HTTP version.

-

Note that semantically, HTTP/1.1 and HTTP/2 are equivalent.

- -
+
http_version() :: 'HTTP/2' | 'HTTP/1.1' | 'HTTP/1.0'
+
+

HTTP version.

+

Note that semantically, HTTP/1.1 and HTTP/2 are equivalent.

opts()

-
-
-
opts() :: map()
-

Options for the HTTP/1.1, HTTP/2 and Websocket protocols.

-

The protocol options are in a map containing all the options for -the different protocols that may be involved when connecting -to the listener, including HTTP/1.1 and HTTP/2.

-

The HTTP/1.1 options are documented in the -cowboy_http(3) manual -and the HTTP/2 options in -cowboy_http2(3).

- - - -
+
opts() :: map()
+
+

Options for the HTTP/1.1, HTTP/2 and Websocket protocols.

+

The protocol options are in a map containing all the options for the different protocols that may be involved when connecting to the listener, including HTTP/1.1 and HTTP/2.

+

The HTTP/1.1 options are documented in the cowboy_http(3) manual and the HTTP/2 options in cowboy_http2(3).

See also

- - +

cowboy(7), ranch(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_app/index.html b/docs/en/cowboy/2.4/manual/cowboy_app/index.html index ab3eecf9..11819440 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_app/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_app/index.html @@ -62,171 +62,77 @@

cowboy(7)

-

Name

-
-

cowboy - Small, fast, modern HTTP server for Erlang/OTP

-
-
-
+

cowboy - Small, fast, modern HTTP server for Erlang/OTP

Description

-
-

Cowboy is an HTTP server for Erlang/OTP with support for the -HTTP/1.1, HTTP/2 and Websocket protocols.

-

Cowboy aims to provide a complete HTTP stack. This includes -the implementation of the HTTP RFCs but also any directly -related standards, like Websocket or Server-Sent Events.

-
-
-
+

Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols.

+

Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events.

Modules

-
-

Functions:

-
-

Protocols:

-
+

Protocols:

+
-

Handlers:

-
+

Handlers:

+
-

Behaviors:

-
+

Behaviors:

+
-

Middlewares:

-
+

Middlewares:

+
-
-
-
+ +

Dependencies

-
-
    -
  • -

    -ranch(7) - Socket acceptor pool for TCP protocols -

    +
    • ranch(7) - Socket acceptor pool for TCP protocols
    • -
    • -

      -cowlib(7) - Support library for manipulating Web protocols -

      +
    • cowlib(7) - Support library for manipulating Web protocols
    • -
    • -

      -ssl - Secure communication over sockets -

      +
    • ssl - Secure communication over sockets
    • -
    • -

      -crypto - Crypto functions -

      +
    • crypto - Crypto functions
    • -
-

All these applications must be started before the cowboy -application. To start Cowboy and all dependencies at once:

-
-
-
{ok, _} = application:ensure_all_started(cowboy).
-
-
-
+
{ok, _} = application:ensure_all_started(cowboy).
+

Environment

-
-

The cowboy application does not define any application -environment configuration parameters.

-
- -
+

The cowboy application does not define any application environment configuration parameters.

See also

- -
+

ranch(7), cowlib(7)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_constraints.int/index.html b/docs/en/cowboy/2.4/manual/cowboy_constraints.int/index.html index aa888d30..38536c3f 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_constraints.int/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_constraints.int/index.html @@ -62,92 +62,52 @@

cowboy_constraints:int(3)

-

Name

-
-

cowboy_constraints:int - Integer constraint

-
-
-
+

cowboy_constraints:int - Integer constraint

Description

-
-

Constraint functions implement a number of different operations.

-
-
-
int(forward, Bin) -> {ok, Int} | {error, not_an_integer}
+
int(forward, Bin) -> {ok, Int} | {error, not_an_integer}
 
-Bin :: binary()
-Int :: integer()
-

Validate and convert the text representation of an integer.

-
-
-
int(reverse, Int) -> {ok, Bin} | {error, not_an_integer}
-

Convert an integer back to its text representation.

-
-
-
int(format_error, Error) -> HumanReadable
+
int(format_error, Error) -> HumanReadable
 
-Error         :: {not_an_integer, Bin | Int}
-HumanReadable :: iolist()
-

Generate a human-readable error message.

-
-
-
+Error :: {not_an_integer, Bin | Int} +HumanReadable :: iolist() +
+

Generate a human-readable error message.

Arguments

-
-

Arguments vary depending on the operation. Constraint -functions always take the operation type as first argument, -and the value as second argument.

-
- -
+

Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument.

Return value

-
-

The return value varies depending on the operation.

-
-
-
+

The return value varies depending on the operation.

Changelog

-
-
    -
  • -

    -2.0: Interface modified to allow for a variety of operations. -

    +
    • 2.0: Interface modified to allow for a variety of operations.
    • -
    • -

      -1.0: Constraint introduced. -

      +
    • 1.0: Constraint introduced.
    • -
-
-
-
+

Examples

-
-

This function is not meant to be called directly.

-
-
-
+

This function is not meant to be called directly.

See also

- -
+

cowboy_constraints(3), cowboy_constraints:nonempty(3), cowboy_router(3), cowboy_req:match_cookies(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_constraints.nonempty/index.html b/docs/en/cowboy/2.4/manual/cowboy_constraints.nonempty/index.html index 25112067..e0369700 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_constraints.nonempty/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_constraints.nonempty/index.html @@ -62,91 +62,51 @@

cowboy_constraints:nonempty(3)

-

Name

-
-

cowboy_constraints:nonempty - Non-empty constraint

-
-
-
+

cowboy_constraints:nonempty - Non-empty constraint

Description

-
-

Constraint functions implement a number of different operations.

-
-
-
nonempty(forward | reverse, <<>>) -> {error, empty}
-

Reject empty values.

-
-
-
nonempty(forward | reverse, Bin) -> {ok, Bin}
+
nonempty(forward | reverse, Bin) -> {ok, Bin}
 
-Bin :: binary()
-

Accept any other binary values.

-
-
-
nonempty(format_error, Error) -> HumanReadable
+
nonempty(format_error, Error) -> HumanReadable
 
-Error         :: {empty, Bin}
-HumanReadable :: iolist()
-

Generate a human-readable error message.

-
-
-
+Error :: {empty, Bin} +HumanReadable :: iolist() +
+

Generate a human-readable error message.

Arguments

-
-

Arguments vary depending on the operation. Constraint -functions always take the operation type as first argument, -and the value as second argument.

-
- -
+

Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument.

Return value

-
-

The return value varies depending on the operation.

-
-
-
+

The return value varies depending on the operation.

Changelog

-
-
    -
  • -

    -2.0: Interface modified to allow for a variety of operations. -

    +
    • 2.0: Interface modified to allow for a variety of operations.
    • -
    • -

      -1.0: Constraint introduced. -

      +
    • 1.0: Constraint introduced.
    • -
-
-
-
+

Examples

-
-

This function is not meant to be called directly.

-
-
-
+

This function is not meant to be called directly.

See also

- -
+

cowboy_constraints(3), cowboy_constraints:int(3), cowboy_router(3), cowboy_req:match_cookies(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_constraints/index.html b/docs/en/cowboy/2.4/manual/cowboy_constraints/index.html index 09db9803..82c7f1a2 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_constraints/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_constraints/index.html @@ -62,84 +62,43 @@

cowboy_constraints(3)

-

Name

-
-

cowboy_constraints - Constraints

-
-
-
+

cowboy_constraints - Constraints

Description

-
-

The module cowboy_constraints defines the built-in -constraints in Cowboy and provides an interface for -manipulating these constraints.

-

Constraints are functions that define what type of -input is allowed. They are used throughout Cowboy, -from the router to query strings to cookies.

-
-
-
+

The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints.

+

Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies.

Exports

-
-

Built-in constraints:

-
-
-
-
+

Types

-
-

constraint()

-
-
-
constraint() :: int | nonempty | fun()
-

A constraint function.

-

The atom constraints are built-in, see the corresponding -function in the exports list above.

-
-
+
constraint() :: int | nonempty | fun()
+
+

A constraint function.

+

The atom constraints are built-in, see the corresponding function in the exports list above.

reason()

-
-
-
reason() :: {constraint(), Reason, Value}
-
-Reason :: any()
-Value  :: any()
-

Reason for the constraint failure.

-

It includes the constraint function in question, -a machine-readable error reason and the value that -made the constraint fail.

-
- - -
+
reason() :: {constraint(), Reason, Value}
+
+Reason :: any()
+Value  :: any()
+
+

Reason for the constraint failure.

+

It includes the constraint function in question, a machine-readable error reason and the value that made the constraint fail.

See also

- - +

cowboy(7), cowboy(3), cowboy_router(3), cowboy_req:match_cookies(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_handler.terminate/index.html b/docs/en/cowboy/2.4/manual/cowboy_handler.terminate/index.html index 2c010b6a..f677bbab 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_handler.terminate/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_handler.terminate/index.html @@ -62,109 +62,54 @@

cowboy_handler:terminate(3)

-

Name

-
-

cowboy_handler:terminate - Terminate the handler

-
-
-
+

cowboy_handler:terminate - Terminate the handler

Description

-
-
-
-
terminate(Reason, PartialReq, State, Handler) -> ok
-
-Reason     :: any()
-PartialReq :: map()
-State      :: any()
-Handler    :: module()
-

Call the optional terminate callback if it is defined.

-

Make sure to use this function at the end of the execution -of modules that implement custom handler behaviors.

-
-
-
+
terminate(Reason, PartialReq, State, Handler) -> ok
+
+Reason     :: any()
+PartialReq :: map()
+State      :: any()
+Handler    :: module()
+
+

Call the optional terminate callback if it is defined.

+

Make sure to use this function at the end of the execution of modules that implement custom handler behaviors.

Arguments

-
-
-
-Reason -
-
-

-Reason for termination. -

+
Reason
+

Reason for termination.

-
-PartialReq -
-
-

-The Req object. -

-

It is possible to remove fields from the Req object to save memory -when the handler has no concept of requests/responses. The only -requirement is that a map is provided.

+
PartialReq
+

The Req object.

+

It is possible to remove fields from the Req object to save memory when the handler has no concept of requests/responses. The only requirement is that a map is provided.

-
-State -
-
-

-Handler state. -

+
State
+

Handler state.

-
-Handler -
-
-

-Handler module. -

+
Handler
+

Handler module.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Terminate a handler normally
-
-
cowboy_handler:terminate(normal, Req, State, Handler).
-
-
-
+
cowboy_handler:terminate(normal, Req, State, Handler).
+

See also

- - +

cowboy_handler(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_handler/index.html b/docs/en/cowboy/2.4/manual/cowboy_handler/index.html index 5414b066..e6a0c3f4 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_handler/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_handler/index.html @@ -62,96 +62,46 @@

cowboy_handler(3)

-

Name

-
-

cowboy_handler - Plain HTTP handlers

-
-
-
+

cowboy_handler - Plain HTTP handlers

Description

-
-

The cowboy_handler middleware executes the handler selected -by the router or any other preceding middleware.

-

This middleware takes the handler module and initial state -from the handler and handler_opts environment values, -respectively. On completion, it adds a result value to -the middleware environment, containing the return value -of the terminate/3 callback (if defined) and ok otherwise.

-

This module also defines a callback interface for handling -HTTP requests.

-
-
-
+

The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware.

+

This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise.

+

This module also defines a callback interface for handling HTTP requests.

Callbacks

-
-

Plain HTTP handlers implement the following interface:

-
-
-
init(Req, State) -> {ok, Req, State}
-
-terminate(Reason, Req, State) -> ok  %% optional
-
-Req    :: cowboy_req:req()
-State  :: any()
-Reason :: normal
-        | {crash, error | exit | throw, any()}
-

These two callbacks are common to all handlers.

-

Plain HTTP handlers do all their work in the init/2 -callback. Returning ok terminates the handler. If no -response is sent, Cowboy will send a 204 No Content.

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the handler. -Cowboy will terminate the process right after this. There -is no need to perform any cleanup in this callback.

-

The following terminate reasons are defined for plain HTTP -handlers:

-
-
-normal -
-
-

- The connection was closed normally. -

+
init(Req, State) -> {ok, Req, State}
+
+terminate(Reason, Req, State) -> ok  %% optional
+
+Req    :: cowboy_req:req()
+State  :: any()
+Reason :: normal
+        | {crash, error | exit | throw, any()}
+
+

These two callbacks are common to all handlers.

+

Plain HTTP handlers do all their work in the init/2 callback. Returning ok terminates the handler. If no response is sent, Cowboy will send a 204 No Content.

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the handler. Cowboy will terminate the process right after this. There is no need to perform any cleanup in this callback.

+

The following terminate reasons are defined for plain HTTP handlers:

+
normal
+

The connection was closed normally.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
- - -
+

Exports

-
-

The following function should be called by modules implementing -custom handlers to execute the optional terminate callback:

-
-
-
-
+

See also

- -
+

cowboy(7)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_http/index.html b/docs/en/cowboy/2.4/manual/cowboy_http/index.html index d7304e5a..467563e1 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_http/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_http/index.html @@ -62,255 +62,116 @@

cowboy_http(3)

-

Name

-
-

cowboy_http - HTTP/1.1

-
-
-
+

cowboy_http - HTTP/1.1

Description

-
-

The module cowboy_http implements HTTP/1.1 and HTTP/1.0 -as a Ranch protocol.

-
-
-
+

The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol.

Options

-
-
-
+ +
-
opts() :: #{
-    connection_type         => worker | supervisor,
-    env                     => cowboy_middleware:env(),
-    idle_timeout            => timeout(),
-    inactivity_timeout      => timeout(),
-    max_empty_lines         => non_neg_integer(),
-    max_header_name_length  => non_neg_integer(),
-    max_header_value_length => non_neg_integer(),
-    max_headers             => non_neg_integer(),
-    max_keepalive           => non_neg_integer(),
-    max_method_length       => non_neg_integer(),
-    max_request_line_length => non_neg_integer(),
-    max_skip_body_length    => non_neg_integer(),
-    middlewares             => [module()],
-    request_timeout         => timeout(),
-    shutdown_timeout        => timeout(),
-    stream_handlers         => [module()]
-}
-

Configuration for the HTTP/1.1 protocol.

-

This configuration is passed to Cowboy when starting listeners -using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

-

It can be updated without restarting listeners using the -Ranch functions ranch:get_protocol_options/1 and -ranch:set_protocol_options/2.

-

The default value is given next to the option name:

-
-
-connection_type (supervisor) -
-
-

- Whether the connection process also acts as a supervisor. -

-
-
-env (#{}) -
-
-

- Middleware environment. -

-
-
-idle_timeout (60000) -
-
-

- Time in ms with no data received before Cowboy closes the connection. -

-
-
-inactivity_timeout (300000) -
-
-

- Time in ms with nothing received at all before Cowboy closes the connection. -

-
-
-max_empty_lines (5) -
-
-

- Maximum number of empty lines before a request. -

-
-
-max_header_name_length (64) -
-
-

- Maximum length of header names. -

-
-
-max_header_value_length (4096) -
-
-

- Maximum length of header values. -

-
-
-max_headers (100) -
-
-

- Maximum number of headers allowed per request. -

-
-
-max_keepalive (100) -
-
-

- Maximum number of requests allowed per connection. -

-
-
-max_method_length (32) -
-
-

- Maximum length of the method. -

-
-
-max_request_line_length (8000) -
-
-

- Maximum length of the request line. -

-
-
-max_skip_body_length (1000000) -
-
-

- Maximum length Cowboy is willing to skip when the user code did not read the body fully. - When the remaining length is too large or unknown Cowboy will close the connection. -

-
-
-middlewares ([cowboy_router, cowboy_handler]) -
-
-

- Middlewares to run for every request. -

-
-
-request_timeout (5000) -
-
-

- Time in ms with no requests before Cowboy closes the connection. -

-
-
-shutdown_timeout (5000) -
-
-

- Time in ms Cowboy will wait for child processes to shut down before killing them. -

-
-
-stream_handlers ([cowboy_stream_h]) -
-
-

- Ordered list of stream handlers that will handle all stream events. -

-
-
-
-
-
+
opts() :: #{
+    connection_type         => worker | supervisor,
+    env                     => cowboy_middleware:env(),
+    idle_timeout            => timeout(),
+    inactivity_timeout      => timeout(),
+    max_empty_lines         => non_neg_integer(),
+    max_header_name_length  => non_neg_integer(),
+    max_header_value_length => non_neg_integer(),
+    max_headers             => non_neg_integer(),
+    max_keepalive           => non_neg_integer(),
+    max_method_length       => non_neg_integer(),
+    max_request_line_length => non_neg_integer(),
+    max_skip_body_length    => non_neg_integer(),
+    middlewares             => [module()],
+    request_timeout         => timeout(),
+    shutdown_timeout        => timeout(),
+    stream_handlers         => [module()]
+}
+
+

Configuration for the HTTP/1.1 protocol.

+

This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

+

It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2.

+

The default value is given next to the option name:

+
connection_type (supervisor)
+

Whether the connection process also acts as a supervisor.

+
+
env (#{})
+

Middleware environment.

+
+
idle_timeout (60000)
+

Time in ms with no data received before Cowboy closes the connection.

+
+
inactivity_timeout (300000)
+

Time in ms with nothing received at all before Cowboy closes the connection.

+
+
max_empty_lines (5)
+

Maximum number of empty lines before a request.

+
+
max_header_name_length (64)
+

Maximum length of header names.

+
+
max_header_value_length (4096)
+

Maximum length of header values.

+
+
max_headers (100)
+

Maximum number of headers allowed per request.

+
+
max_keepalive (100)
+

Maximum number of requests allowed per connection.

+
+
max_method_length (32)
+

Maximum length of the method.

+
+
max_request_line_length (8000)
+

Maximum length of the request line.

+
+
max_skip_body_length (1000000)
+

Maximum length Cowboy is willing to skip when the user code did not read the body fully. When the remaining length is too large or unknown Cowboy will close the connection.

+
+
middlewares ([cowboy_router, cowboy_handler])
+

Middlewares to run for every request.

+
+
request_timeout (5000)
+

Time in ms with no requests before Cowboy closes the connection.

+
+
shutdown_timeout (5000)
+

Time in ms Cowboy will wait for child processes to shut down before killing them.

+
+
stream_handlers ([cowboy_stream_h])
+

Ordered list of stream handlers that will handle all stream events.

+
+

Changelog

-
-
    -
  • -

    -2.2: The max_skip_body_length option was added. -

    +
    • 2.2: The max_skip_body_length option was added.
    • -
    • -

      -2.0: The timeout option was renamed request_timeout. -

      +
    • 2.0: The timeout option was renamed request_timeout.
    • -
    • -

      -2.0: The idle_timeout, inactivity_timeout and shutdown_timeout options were added. -

      +
    • 2.0: The idle_timeout, inactivity_timeout and shutdown_timeout options were added.
    • -
    • -

      -2.0: The max_method_length option was added. -

      +
    • 2.0: The max_method_length option was added.
    • -
    • -

      -2.0: The max_request_line_length default was increased from 4096 to 8000. -

      +
    • 2.0: The max_request_line_length default was increased from 4096 to 8000.
    • -
    • -

      -2.0: The connection_type option was added. -

      +
    • 2.0: The connection_type option was added.
    • -
    • -

      -2.0: The env option is now a map instead of a proplist. -

      +
    • 2.0: The env option is now a map instead of a proplist.
    • -
    • -

      -2.0: The stream_handlers option was added. -

      +
    • 2.0: The stream_handlers option was added.
    • -
    • -

      -2.0: The compress option was removed in favor of the cowboy_compress_h stream handler. -

      +
    • 2.0: The compress option was removed in favor of the cowboy_compress_h stream handler.
    • -
    • -

      -2.0: Options are now a map instead of a proplist. -

      +
    • 2.0: Options are now a map instead of a proplist.
    • -
    • -

      -2.0: Protocol introduced. Replaces cowboy_protocol. -

      +
    • 2.0: Protocol introduced. Replaces cowboy_protocol.
    • -
-
-
- +

cowboy(7), cowboy_http2(3), cowboy_websocket(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_http2/index.html b/docs/en/cowboy/2.4/manual/cowboy_http2/index.html index ec1b8d28..9b915b91 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_http2/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_http2/index.html @@ -62,243 +62,102 @@

cowboy_http2(3)

-

Name

-
-

cowboy_http2 - HTTP/2

-
-
-
+

cowboy_http2 - HTTP/2

Description

-
-

The module cowboy_http2 implements HTTP/2 -as a Ranch protocol.

-
-
-
+

The module cowboy_http2 implements HTTP/2 as a Ranch protocol.

Options

-
-
-
+ +
-
opts() :: #{
-    connection_type                => worker | supervisor,
-    enable_connect_protocol        => boolean(),
-    env                            => cowboy_middleware:env(),
-    inactivity_timeout             => timeout(),
-    initial_connection_window_size => 65535..16#7fffffff,
-    initial_stream_window_size     => 0..16#7fffffff,
-    max_concurrent_streams         => non_neg_integer() | infinity,
-    max_decode_table_size          => non_neg_integer(),
-    max_encode_table_size          => non_neg_integer(),
-    max_frame_size_received        => 16384..16777215,
-    max_frame_size_sent            => 16384..16777215 | infinity,
-    middlewares                    => [module()],
-    preface_timeout                => timeout(),
-    settings_timeout               => timeout(),
-    shutdown_timeout               => timeout(),
-    stream_handlers                => [module()]
-}
-

Configuration for the HTTP/2 protocol.

-

This configuration is passed to Cowboy when starting listeners -using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

-

It can be updated without restarting listeners using the -Ranch functions ranch:get_protocol_options/1 and -ranch:set_protocol_options/2.

-

The default value is given next to the option name:

-
-
-connection_type (supervisor) -
-
-

- Whether the connection process also acts as a supervisor. -

+
opts() :: #{
+    connection_type                => worker | supervisor,
+    enable_connect_protocol        => boolean(),
+    env                            => cowboy_middleware:env(),
+    inactivity_timeout             => timeout(),
+    initial_connection_window_size => 65535..16#7fffffff,
+    initial_stream_window_size     => 0..16#7fffffff,
+    max_concurrent_streams         => non_neg_integer() | infinity,
+    max_decode_table_size          => non_neg_integer(),
+    max_encode_table_size          => non_neg_integer(),
+    max_frame_size_received        => 16384..16777215,
+    max_frame_size_sent            => 16384..16777215 | infinity,
+    middlewares                    => [module()],
+    preface_timeout                => timeout(),
+    settings_timeout               => timeout(),
+    shutdown_timeout               => timeout(),
+    stream_handlers                => [module()]
+}
+
+

Configuration for the HTTP/2 protocol.

+

This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions.

+

It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2.

+

The default value is given next to the option name:

+
connection_type (supervisor)
+

Whether the connection process also acts as a supervisor.

-
-enable_connect_protocol (false) -
-
-

- Whether to enable the extended CONNECT method to allow - protocols like Websocket to be used over an HTTP/2 stream. - This option is experimental and disabled by default. -

+
enable_connect_protocol (false)
+

Whether to enable the extended CONNECT method to allow protocols like Websocket to be used over an HTTP/2 stream. This option is experimental and disabled by default.

-
-env (#{}) -
-
-

- Middleware environment. -

+
env (#{})
+

Middleware environment.

-
-inactivity_timeout (300000) -
-
-

- Time in ms with nothing received at all before Cowboy closes the connection. -

+
inactivity_timeout (300000)
+

Time in ms with nothing received at all before Cowboy closes the connection.

-
-initial_connection_window_size (65535) -
-
-

- Initial window size for the connection. This is the total amount - of data (from request bodies for example) that may be buffered - by the connection across all streams before the user code - explicitly requests it. -

-
-
-
Note that this value cannot be lower than the default.
-
+
initial_connection_window_size (65535)
+

Initial window size for the connection. This is the total amount of data (from request bodies for example) that may be buffered by the connection across all streams before the user code explicitly requests it.

+

Note that this value cannot be lower than the default.

-
-initial_stream_window_size (65535) -
-
-

- Initial window size for new streams. This is the total amount - of data (from request bodies for example) that may be buffered - by a single stream before the user code explicitly requests it. -

+
initial_stream_window_size (65535)
+

Initial window size for new streams. This is the total amount of data (from request bodies for example) that may be buffered by a single stream before the user code explicitly requests it.

-
-max_concurrent_streams (infinity) -
-
-

- Maximum number of concurrent streams allowed on the connection. -

+
max_concurrent_streams (infinity)
+

Maximum number of concurrent streams allowed on the connection.

-
-max_decode_table_size (4096) -
-
-

- Maximum header table size used by the decoder. This is the value advertised - to the client. The client can then choose a header table size equal or lower - to the advertised value. -

+
max_decode_table_size (4096)
+

Maximum header table size used by the decoder. This is the value advertised to the client. The client can then choose a header table size equal or lower to the advertised value.

-
-max_encode_table_size (4096) -
-
-

- Maximum header table size used by the encoder. The server will compare this - value to what the client advertises and choose the smallest one as the - encoder’s header table size. -

+
max_encode_table_size (4096)
+

Maximum header table size used by the encoder. The server will compare this value to what the client advertises and choose the smallest one as the encoder's header table size.

-
-max_frame_size_received (16384) -
-
-

- Maximum size of the frames received by the server. This value is - advertised to the remote endpoint which can then decide to use - any value lower or equal for its frame sizes. -

+
max_frame_size_received (16384)
+

Maximum size of the frames received by the server. This value is advertised to the remote endpoint which can then decide to use any value lower or equal for its frame sizes.

-
-max_frame_size_sent (infinity) -
-
-

- Maximum size of the frames sent by the server. This option allows - setting an upper limit to the frame sizes instead of blindly - following the client’s advertised maximum. -

-
-
-
Note that actual frame sizes may be lower than the limit when
-there is not enough space left in the flow control window.
-
+
max_frame_size_sent (infinity)
+

Maximum size of the frames sent by the server. This option allows setting an upper limit to the frame sizes instead of blindly following the client's advertised maximum.

+

Note that actual frame sizes may be lower than the limit when there is not enough space left in the flow control window.

-
-middlewares ([cowboy_router, cowboy_handler]) -
-
-

- Middlewares to run for every request. -

+
middlewares ([cowboy_router, cowboy_handler])
+

Middlewares to run for every request.

-
-preface_timeout (5000) -
-
-

- Time in ms Cowboy is willing to wait for the connection preface. -

+
preface_timeout (5000)
+

Time in ms Cowboy is willing to wait for the connection preface.

-
-settings_timeout (5000) -
-
-

- Time in ms Cowboy is willing to wait for a SETTINGS ack. -

+
settings_timeout (5000)
+

Time in ms Cowboy is willing to wait for a SETTINGS ack.

-
-shutdown_timeout (5000) -
-
-

- Time in ms Cowboy will wait for child processes to shut down before killing them. -

+
shutdown_timeout (5000)
+

Time in ms Cowboy will wait for child processes to shut down before killing them.

-
-stream_handlers ([cowboy_stream_h]) -
-
-

- Ordered list of stream handlers that will handle all stream events. -

+
stream_handlers ([cowboy_stream_h])
+

Ordered list of stream handlers that will handle all stream events.

-
-
-
-
+

Changelog

-
-
    -
  • -

    -2.4: Add the options initial_connection_window_size, - initial_stream_window_size, max_concurrent_streams, - max_decode_table_size, max_encode_table_size, - max_frame_size_received, max_frame_size_sent - and settings_timeout to configure HTTP/2 SETTINGS - and related behavior. -

    +
    • 2.4: Add the options initial_connection_window_size, initial_stream_window_size, max_concurrent_streams, max_decode_table_size, max_encode_table_size, max_frame_size_received, max_frame_size_sent and settings_timeout to configure HTTP/2 SETTINGS and related behavior.
    • -
    • -

      -2.4: Add the experimental option enable_connect_protocol. -

      +
    • 2.4: Add the experimental option enable_connect_protocol.
    • -
    • -

      -2.0: Protocol introduced. -

      +
    • 2.0: Protocol introduced.
    • -
-
-
- +

cowboy(7), cowboy_http(3), cowboy_websocket(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_loop/index.html b/docs/en/cowboy/2.4/manual/cowboy_loop/index.html index ea078cb9..a6348946 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_loop/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_loop/index.html @@ -62,120 +62,60 @@

cowboy_loop(3)

-

Name

-
-

cowboy_loop - Loop handlers

-
-
-
+

cowboy_loop - Loop handlers

Description

-
-

The module cowboy_loop defines a callback interface for -long running HTTP connections.

-

You should switch to this behavior for long polling, -server-sent events and similar long-running requests.

-

There are generally two usage patterns:

-
    -
  • -

    -Loop until receiving a specific message, then send - a response and stop execution (for example long polling); -

    +

    The module cowboy_loop defines a callback interface for long running HTTP connections.

    +

    You should switch to this behavior for long polling, server-sent events and similar long-running requests.

    +

    There are generally two usage patterns:

    +
    • Loop until receiving a specific message, then send a response and stop execution (for example long polling);
    • -
    • -

      -Or initiate a response in init/2 and stream the - body in info/3 as necessary (for example server-sent events). -

      +
    • Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events).
    • -
-
-
-
+

Callbacks

-
-

Loop handlers implement the following interface:

-
-
-
init(Req, State)
-    -> {cowboy_loop, Req, State}
-     | {cowboy_loop, Req, State, hibernate}
-
-info(Info, Req, State)
-    -> {ok, Req, State}
-     | {ok, Req, State, hibernate}
-     | {stop, Req, State}
-
-terminate(Reason, Req, State) -> ok  %% optional
-
-Req    :: cowboy_req:req()
-State  :: any()
-Info   :: any()
-Reason :: stop
-        | {crash, error | exit | throw, any()}
-

The init/2 callback is common to all handlers. To switch -to the loop behavior, it must return cowboy_loop as the -first element of the tuple.

-

The info/3 callback will be called for every Erlang message -received. It may choose to continue the receive loop or stop -it.

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the handler. -Cowboy will terminate the process right after this. There -is no need to perform any cleanup in this callback.

-

The following terminate reasons are defined for loop handlers:

-
-
-stop -
-
-

- The handler requested to close the connection by returning - a stop tuple. -

+
init(Req, State)
+    -> {cowboy_loop, Req, State}
+     | {cowboy_loop, Req, State, hibernate}
+
+info(Info, Req, State)
+    -> {ok, Req, State}
+     | {ok, Req, State, hibernate}
+     | {stop, Req, State}
+
+terminate(Reason, Req, State) -> ok  %% optional
+
+Req    :: cowboy_req:req()
+State  :: any()
+Info   :: any()
+Reason :: stop
+        | {crash, error | exit | throw, any()}
+
+

The init/2 callback is common to all handlers. To switch to the loop behavior, it must return cowboy_loop as the first element of the tuple.

+

The info/3 callback will be called for every Erlang message received. It may choose to continue the receive loop or stop it.

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the handler. Cowboy will terminate the process right after this. There is no need to perform any cleanup in this callback.

+

The following terminate reasons are defined for loop handlers:

+
stop
+

The handler requested to close the connection by returning a stop tuple.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
- - -
+

Changelog

-
-
    -
  • -

    -2.0: Loop handlers no longer need to handle overflow/timeouts. -

    +
    • 2.0: Loop handlers no longer need to handle overflow/timeouts.
    • -
    • -

      -1.0: Behavior introduced. -

      +
    • 1.0: Behavior introduced.
    • -
-
-
-
+

See also

- -
+

cowboy(7), cowboy_handler(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_middleware/index.html b/docs/en/cowboy/2.4/manual/cowboy_middleware/index.html index e7e7de29..8d5a30ad 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_middleware/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_middleware/index.html @@ -62,115 +62,56 @@

cowboy_middleware(3)

-

Name

-
-

cowboy_middleware - Middlewares

-
-
-
+

cowboy_middleware - Middlewares

Description

-
-

The module cowboy_middleware defines a callback interface for -Cowboy middlewares.

-

Middlewares process the request sequentially in the order they -are configured.

-
-
-
+

The module cowboy_middleware defines a callback interface for Cowboy middlewares.

+

Middlewares process the request sequentially in the order they are configured.

Callbacks

-
-

Middlewares implement the following interface:

-
-
-
execute(Req, Env)
-    -> {ok, Req, Env}
-     | {suspend, module(), atom(), [any()]}
-     | {stop, Req}
-
-Req :: cowboy_req:req()
-Env :: cowboy_middleware:env()
-

The execute/2 is the only callback that needs to be -implemented. It must execute the middleware and return -with instructions for Cowboy.

-
-
-ok -
-
-

-Cowboy should continue processing the request using the -returned Req object and environment. -

+
execute(Req, Env)
+    -> {ok, Req, Env}
+     | {suspend, module(), atom(), [any()]}
+     | {stop, Req}
+
+Req :: cowboy_req:req()
+Env :: cowboy_middleware:env()
+
+

The execute/2 is the only callback that needs to be implemented. It must execute the middleware and return with instructions for Cowboy.

+
ok
+

Cowboy should continue processing the request using the returned Req object and environment.

-
-suspend -
-
-

-Cowboy will hibernate the process. When resuming, Cowboy -will apply the returned module, function and arguments. -

+
suspend
+

Cowboy will hibernate the process. When resuming, Cowboy will apply the returned module, function and arguments.

-
-stop -
-
-

-Cowboy will stop middleware execution. No other middleware -will be executed. This effectively ends the processing of -the request. -

+
stop
+

Cowboy will stop middleware execution. No other middleware will be executed. This effectively ends the processing of the request.

-
- - -
+

Types

-
-

env()

-
-
-
env() :: #{atom() => any()}
-

Middleware environment.

-

A new environment is created for every request. The initial -environment contained the user configured environment values -(like dispatch for example) plus the listener value which -contains the name of the listener for this connection.

-

Middlewares may modify the environment as necessary.

-
-
-
-
+
env() :: #{atom() => any()}
+
+

Middleware environment.

+

A new environment is created for every request. The initial environment contained the user configured environment values (like dispatch for example) plus the listener value which contains the name of the listener for this connection.

+

Middlewares may modify the environment as necessary.

Changelog

-
-
    -
  • -

    -2.0: The env type is now a map instead of a proplist. -

    +
    • 2.0: The env type is now a map instead of a proplist.
    • -
    • -

      -1.0: Behavior introduced. -

      +
    • 1.0: Behavior introduced.
    • -
-
- -
+

See also

- -
+

cowboy(7)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.binding/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.binding/index.html index 46d46121..95666a38 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.binding/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.binding/index.html @@ -62,116 +62,60 @@

cowboy_req:binding(3)

-

Name

-
-

cowboy_req:binding - Access a value bound from the route

-
-
-
+

cowboy_req:binding - Access a value bound from the route

Description

-
-
-
-
binding(Name, Req)          -> binding(Name, Req, undefined)
-binding(Name, Req, Default) -> any() | Default
-
-Name    :: atom()
-Req     :: cowboy_req:req()
-Default :: any()
-

Return the value for the given binding.

-
-
-
+
binding(Name, Req)          -> binding(Name, Req, undefined)
+binding(Name, Req, Default) -> any() | Default
+
+Name    :: atom()
+Req     :: cowboy_req:req()
+Default :: any()
+
+

Return the value for the given binding.

Arguments

-
-
-
-Name -
-
-

-Desired binding name as an atom. -

+
Name
+

Desired binding name as an atom.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the binding is missing. -

+
Default
+

Default value returned when the binding is missing.

-
-
- -
+

Return value

-
-

By default the value is a case sensitive binary string, however -constraints may change the type of this value (for example -automatically converting numbers to integer).

-
-
-
+

By default the value is a case sensitive binary string, however constraints may change the type of this value (for example automatically converting numbers to integer).

Changelog

-
-
    -
  • -

    -2.0: Only the value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the username from the path
-
-
%% Route is "/users/:user"
-Username = cowboy_req:binding(user, Req).
-
-
Get the branch name, with a default
-
-
%% Route is "/log[/:branch]"
-Branch = cowboy_req:binding(branch, Req, <<"master">>)
-
-
-
+
%% Route is "/log[/:branch]"
+Branch = cowboy_req:binding(branch, Req, <<"master">>)
+

See also

- - +

cowboy_req(3), cowboy_req:bindings(3), cowboy_req:host_info(3), cowboy_req:path_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.bindings/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.bindings/index.html index 12415270..aa61c3ac 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.bindings/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.bindings/index.html @@ -62,86 +62,40 @@

cowboy_req:bindings(3)

-

Name

-
-

cowboy_req:bindings - Access all values bound from the route

-
-
-
+

cowboy_req:bindings - Access all values bound from the route

Description

-
-
-
-
bindings(Req :: cowboy_req:req()) -> cowboy_router:bindings()
-

Return a map containing all bindings.

-
-
-
+
bindings(Req :: cowboy_req:req()) -> cowboy_router:bindings()
+
+

Return a map containing all bindings.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

By default values are case sensitive binary strings, however -constraints may change the type of this value (for example -automatically converting numbers to integer).

-
-
-
+

By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer).

Changelog

-
-
    -
  • -

    -2.0: Only the values are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the values are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get all bindings
-
-
Bindings = cowboy_req:bindings(Req).
-
-
-
+
Bindings = cowboy_req:bindings(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:host_info(3), cowboy_req:path_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.body_length/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.body_length/index.html index de5f9045..fe1fc5bc 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.body_length/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.body_length/index.html @@ -62,89 +62,41 @@

cowboy_req:body_length(3)

-

Name

-
-

cowboy_req:body_length - Body length

-
-
-
+

cowboy_req:body_length - Body length

Description

-
-
-
-
body_length(Req :: cowboy_req:req()) -> undefined | non_neg_integer()
-

Return the length of the request body.

-

The length is not always known before reading the body. -In those cases Cowboy will return undefined. The body -length is available after the body has been fully read.

-
-
-
+
body_length(Req :: cowboy_req:req()) -> undefined | non_neg_integer()
+
+

Return the length of the request body.

+

The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The length of the request body, or undefined if it is -not known.

-
-
-
+

The length of the request body, or undefined if it is not known.

Changelog

-
-
    -
  • -

    -2.0: Only the length is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the length is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the body length
-
-
Length = cowboy_req:body_length(Req).
-
-
-
+
Length = cowboy_req:body_length(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.cert/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.cert/index.html index 5035f160..3222b2f3 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.cert/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.cert/index.html @@ -62,104 +62,60 @@

cowboy_req:cert(3)

-

Name

-
-

cowboy_req:cert - Client TLS certificate

-
-
-
+

cowboy_req:cert - Client TLS certificate

Description

-
-
-
-
cert(Req :: cowboy_req:req()) -> binary() | undefined
-

Return the peer’s TLS certificate.

-

Using the default configuration this function will always return -undefined. You need to explicitly configure Cowboy to request -the client certificate. To do this you need to set the verify -transport option to verify_peer:

-
-
-
{ok, _} = cowboy:start_tls(example, [
-    {port, 8443},
-    {cert, "path/to/cert.pem"},
-    {verify, verify_peer}
+
{ok, _} = cowboy:start_tls(example, [
+    {port, 8443},
+    {cert, "path/to/cert.pem"},
+    {verify, verify_peer}
 ], #{
-    env => #{dispatch => Dispatch}
-}).
-

You may also want to customize the verify_fun function. Please -consult the ssl application’s manual for more details.

-

TCP connections do not allow a certificate and this function -will therefore always return undefined.

-

The certificate can also be obtained using pattern matching:

-
-
-
#{cert := Cert} = Req.
-
-
-
+
#{cert := Cert} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The client TLS certificate.

-
-
-
+

The client TLS certificate.

Changelog

-
-
    -
  • -

    -2.1: Function introduced. -

    +
    • 2.1: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the client TLS certificate.
-
-
Cert = cowboy_req:cert(Req).
-
-
-
+
Cert = cowboy_req:cert(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:peer(3), cowboy_req:sock(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.delete_resp_header/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.delete_resp_header/index.html index 073d8fb9..8dfbb72d 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.delete_resp_header/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.delete_resp_header/index.html @@ -62,95 +62,45 @@

cowboy_req:delete_resp_header(3)

-

Name

-
-

cowboy_req:delete_resp_header - Delete a response header

-
-
-
+

cowboy_req:delete_resp_header - Delete a response header

Description

-
-
-
-
delete_resp_header(Name, Req :: cowboy_req:req()) -> Req
+
delete_resp_header(Name, Req :: cowboy_req:req()) -> Req
 
-Name :: binary()  %% lowercase; case insensitive
-

Delete the given response header.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+Name :: binary() %% lowercase; case insensitive +
+

Delete the given response header.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Name -
-
-

-Header name as a lowercase binary string. -

+
Name
+

Header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the header will still be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the header will still be sent in the response.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Remove the content-type header from the response
-
-
Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),
-
-
-
+
Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:has_resp_header(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.has_body/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.has_body/index.html index c093e60d..591691aa 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.has_body/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.has_body/index.html @@ -62,80 +62,38 @@

cowboy_req:has_body(3)

-

Name

-
-

cowboy_req:has_body - Is there a request body?

-
-
-
+

cowboy_req:has_body - Is there a request body?

Description

-
-
-
-
has_body(Req :: cowboy_req:req()) -> boolean()
-

Return whether the request has a body.

-
-
-
+
has_body(Req :: cowboy_req:req()) -> boolean()
+
+

Return whether the request has a body.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A boolean indicating whether the request has a body.

-
-
-
+

A boolean indicating whether the request has a body.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Ensure the request has a body
-
-
true = cowboy_req:has_body(Req).
-
-
-
+
true = cowboy_req:has_body(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.has_resp_body/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.has_resp_body/index.html index e99ff1b7..34624718 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.has_resp_body/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.has_resp_body/index.html @@ -62,82 +62,43 @@

cowboy_req:has_resp_body(3)

-

Name

-
-

cowboy_req:has_resp_body - Is there a response body?

-
-
-
+

cowboy_req:has_resp_body - Is there a response body?

Description

-
-
-
-
has_resp_body(Req :: cowboy_req:req()) -> boolean()
-

Return whether a response body has been set.

-
-
-
+
has_resp_body(Req :: cowboy_req:req()) -> boolean()
+
+

Return whether a response body has been set.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A boolean indicating whether a response body has been set.

-

This function will return false when an empty response -body has been set.

-
-
-
+

A boolean indicating whether a response body has been set.

+

This function will return false when an empty response body has been set.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Check whether a body has been set
-
-
false = cowboy_req:has_resp_body(Req0),
-Req1 = cowboy_req:set_resp_body(<<"Hello!">>, Req0),
-true = cowboy_req:has_resp_body(Req1),
-Req = cowboy_req:set_resp_body(<<>>, Req1),
-false = cowboy_req:has_resp_body(Req).
-
-
-
+
false = cowboy_req:has_resp_body(Req0),
+Req1 = cowboy_req:set_resp_body(<<"Hello!">>, Req0),
+true = cowboy_req:has_resp_body(Req1),
+Req = cowboy_req:set_resp_body(<<>>, Req1),
+false = cowboy_req:has_resp_body(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_body(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.has_resp_header/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.has_resp_header/index.html index 21eca0bc..2d613eca 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.has_resp_header/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.has_resp_header/index.html @@ -62,95 +62,46 @@

cowboy_req:has_resp_header(3)

-

Name

-
-

cowboy_req:has_resp_header - Is the given response header set?

-
-
-
+

cowboy_req:has_resp_header - Is the given response header set?

Description

-
-
-
-
has_resp_header(Name, Req :: cowboy_req:req()) -> boolean()
+
has_resp_header(Name, Req :: cowboy_req:req()) -> boolean()
 
-Name :: binary()  %% lowercase; case insensitive
-

Return whether the given response header has been set.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+Name :: binary() %% lowercase; case insensitive +
+

Return whether the given response header has been set.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Name -
-
-

-Header name as a lowercase binary string. -

+
Name
+

Header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A boolean indicating whether the given response header has been set.

-
-
-
+

A boolean indicating whether the given response header has been set.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Check whether the content-type header has been set
-
-
false = cowboy_req:has_resp_header(<<"content-type">>, Req0),
-Req = cowboy_req:set_resp_header(<<"content-type">>, <<"text/html">>, Req0),
-true = cowboy_req:has_resp_header(<<"content-type">>, Req).
-
-
-
+
false = cowboy_req:has_resp_header(<<"content-type">>, Req0),
+Req = cowboy_req:set_resp_header(<<"content-type">>, <<"text/html">>, Req0),
+true = cowboy_req:has_resp_header(<<"content-type">>, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3), cowboy_req:delete_resp_header(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.header/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.header/index.html index ed2978a7..487a76da 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.header/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.header/index.html @@ -62,122 +62,67 @@

cowboy_req:header(3)

-

Name

-
-

cowboy_req:header - HTTP header

-
-
-
+

cowboy_req:header - HTTP header

Description

-
-
-
-
header(Name, Req)          -> header(Name, Req, undefined)
-header(Name, Req, Default) -> binary() | Default
-
-Name    :: binary()          %% lowercase; case insensitive
-Req     :: cowboy_req:req()
-Default :: any()
-

Return the value for the given HTTP header.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Headers can also be obtained using pattern matching:

-
-
-
#{headers := #{Name := Value}} = Req.
-

Note that this snippet will crash if the header is missing.

-
-
-
+
#{headers := #{Name := Value}} = Req.
+
+

Note that this snippet will crash if the header is missing.

Arguments

-
-
-
-Name -
-
-

-Desired HTTP header name as a lowercase binary string. -

+
Name
+

Desired HTTP header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the header is missing. -

+
Default
+

Default value returned when the header is missing.

-
-
- -
+

Return value

-
-

The header value is returned as a binary string. When the -header is missing, the default argument is returned.

-
-
-
+

The header value is returned as a binary string. When the header is missing, the default argument is returned.

Changelog

-
-
    -
  • -

    -2.0: Only the header value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the header value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the accept header
-
-
Accept = cowboy_req:header(<<"accept">>, Req).
-
-
Get the content-length header with a default value
-
-
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).
-
-
-
+
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).
+

See also

- - +

cowboy_req(3), cowboy_req:headers(3), cowboy_req:parse_header(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.headers/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.headers/index.html index 420c594e..514d9f2a 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.headers/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.headers/index.html @@ -62,90 +62,47 @@

cowboy_req:headers(3)

-

Name

-
-

cowboy_req:headers - HTTP headers

-
-
-
+

cowboy_req:headers - HTTP headers

Description

-
-
-
-
headers(Req :: cowboy_req:req()) -> cowboy:http_headers()
-

Return all request headers.

-

Request headers can also be obtained using pattern matching:

-
-
-
#{headers := Headers} = Req.
-
-
-
+
#{headers := Headers} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Headers are returned as a map with keys being lowercase -binary strings, and values as binary strings.

-
-
-
+

Headers are returned as a map with keys being lowercase binary strings, and values as binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the headers are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the headers are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get all headers
-
-
Headers = cowboy_req:headers(Req).
-
-
-
+
Headers = cowboy_req:headers(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:header(3), cowboy_req:parse_header(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.host/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.host/index.html index f04f7c16..a8e0e313 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.host/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.host/index.html @@ -62,91 +62,47 @@

cowboy_req:host(3)

-

Name

-
-

cowboy_req:host - URI host name

-
-
-
+

cowboy_req:host - URI host name

Description

-
-
-
-
host(Req :: cowboy_req:req()) -> Host :: binary()
-

Return the host name of the effective request URI.

-

The host name can also be obtained using pattern matching:

-
-
-
#{host := Host} = Req.
-
-
-
+
#{host := Host} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The host name is returned as a lowercase binary string. -It is case insensitive.

-
-
-
+

The host name is returned as a lowercase binary string. It is case insensitive.

Changelog

-
-
    -
  • -

    -2.0: Only the host name is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the host name is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s host name
-
-
Host = cowboy_req:host(Req).
-
-
-
+
Host = cowboy_req:host(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:host_info(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.host_info/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.host_info/index.html index 16947144..bff72d35 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.host_info/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.host_info/index.html @@ -62,87 +62,41 @@

cowboy_req:host_info(3)

-

Name

-
-

cowboy_req:host_info - Access the route’s heading host segments

-
-
-
+

cowboy_req:host_info - Access the route's heading host segments

Description

-
-
-
-
host_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
-

Return the tokens for the heading host segments.

-

This is the part of the host name that was matched using -the ... notation.

-
-
-
+
host_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
+
+

Return the tokens for the heading host segments.

+

This is the part of the host name that was matched using the ... notation.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The tokens are returned as a list of case insensitive -binary strings.

-
-
-
+

The tokens are returned as a list of case insensitive binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the tokens are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the host_info tokens
-
-
HostInfo = cowboy_req:host_info(Req).
-
-
-
+
HostInfo = cowboy_req:host_info(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:path_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.inform/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.inform/index.html index b017d12d..b3c27fe1 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.inform/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.inform/index.html @@ -62,125 +62,66 @@

cowboy_req:inform(3)

-

Name

-
-

cowboy_req:inform - Send an informational response

-
-
-
+

cowboy_req:inform - Send an informational response

Description

-
-
-
-
inform(Status, Req :: cowboy_req:req())
-    -> inform(StatusCode, #{}, Req)
-
-inform(Status, Headers, Req :: cowboy_req:req())
-    -> ok
-
-Status  :: cowboy:http_status()
-Headers :: cowboy:http_headers()
-

Send an informational response.

-

Informational responses use a status code between 100 and 199. -They cannot include a body. This function will not use any -of the previously set headers. All headers to be sent must -be given directly.

-

Any number of informational responses can be sent as long as -they are sent before the proper response. Attempting to use -this function after sending a normal response will result -in an error.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+
inform(Status, Req :: cowboy_req:req())
+    -> inform(StatusCode, #{}, Req)
+
+inform(Status, Headers, Req :: cowboy_req:req())
+    -> ok
+
+Status  :: cowboy:http_status()
+Headers :: cowboy:http_headers()
+
+

Send an informational response.

+

Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly.

+

Any number of informational responses can be sent as long as they are sent before the proper response. Attempting to use this function after sending a normal response will result in an error.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Status -
-
-

-The status code for the response. -

+
Status
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Req -
-
-

-The Req object. -

+
+

Header names must be given as lowercase binary strings.

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.1: Function introduced. -

    +
    • 2.1: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Send an informational response
-
-
Req = cowboy_req:inform(102, Req0).
-
-
Send an informational response with headers
-
-
Req = cowboy_req:inform(103, #{
-    <<"link">> => <<"</style.css>; rel=preload; as=style">>,
-    <<"link">> => <<"</script.js>; rel=preload; as=script">>
-}, Req0).
-
-
-
+
Req = cowboy_req:inform(103, #{
+    <<"link">> => <<"</style.css>; rel=preload; as=style">>,
+    <<"link">> => <<"</script.js>; rel=preload; as=script">>
+}, Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:reply(3), cowboy_req:stream_reply(3), cowboy_req:push(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.match_cookies/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.match_cookies/index.html index b5ebef85..9b524b1c 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.match_cookies/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.match_cookies/index.html @@ -62,123 +62,67 @@

cowboy_req:match_cookies(3)

-

Name

-
-

cowboy_req:match_cookies - Match cookies against constraints

-
-
-
+

cowboy_req:match_cookies - Match cookies against constraints

Description

-
-
-
-
match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req())
-    -> #{atom() => any()}
-

Parse the cookies and match specific values against -constraints.

-

Cowboy will only return the cookie values specified in the -fields list, and ignore all others. Fields can be either -the name of the cookie requested; the name along with a -list of constraints; or the name, a list of constraints -and a default value in case the cookie is missing.

-

This function will crash if the cookie is missing and no -default value is provided. This function will also crash -if a constraint fails.

-

The name of the cookie must be provided as an atom. The -key of the returned map will be that atom. The value may -be converted through the use of constraints, making this -function able to extract, validate and convert values all -in one step.

-
-
-
+
match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req())
+    -> #{atom() => any()}
+
+

Parse the cookies and match specific values against constraints.

+

Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing.

+

This function will crash if the cookie is missing and no default value is provided. This function will also crash if a constraint fails.

+

The name of the cookie must be provided as an atom. The key of the returned map will be that atom. The value may be converted through the use of constraints, making this function able to extract, validate and convert values all in one step.

Arguments

-
-
-
-Fields -
-
-

-Cookies to retrieve. -

-

See cowboy(3) for a complete description.

+
Fields
+

Cookies to retrieve.

+

See cowboy(3) for a complete description.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Desired values are returned as a map. The key is the atom -that was given in the list of fields, and the value is the -optionally converted value after applying constraints.

-

The map contains the same keys that were given in the fields.

-

An exception is triggered when the match fails.

-
-
-
+

Desired values are returned as a map. The key is the atom that was given in the list of fields, and the value is the optionally converted value after applying constraints.

+

The map contains the same keys that were given in the fields.

+

An exception is triggered when the match fails.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Match fields
-
-
%% ID and Lang are binaries.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_cookies([id, lang], Req).
-
-
Match fields and apply constraints
-
-
%% ID is an integer and Lang a non-empty binary.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_cookies([{id, int}, {lang, nonempty}], Req).
-
-
Match fields with default values
-
-
#{lang := Lang}
-    = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
-
-
-
+
#{lang := Lang}
+    = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
+

See also

- - +

cowboy_req(3), cowboy_req:parse_cookies(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.match_qs/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.match_qs/index.html index 634b6723..b46745c6 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.match_qs/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.match_qs/index.html @@ -62,123 +62,67 @@

cowboy_req:match_qs(3)

-

Name

-
-

cowboy_req:match_qs - Match the query string against constraints

-
-
-
+

cowboy_req:match_qs - Match the query string against constraints

Description

-
-
-
-
match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req())
-    -> #{atom() => any()}
-

Parse the query string and match specific values against -constraints.

-

Cowboy will only return the query string values specified -in the fields list, and ignore all others. Fields can be -either the key requested; the key along with a list of -constraints; or the key, a list of constraints and a -default value in case the key is missing.

-

This function will crash if the key is missing and no -default value is provided. This function will also crash -if a constraint fails.

-

The key must be provided as an atom. The key of the -returned map will be that atom. The value may be converted -through the use of constraints, making this function able -to extract, validate and convert values all in one step.

-
-
-
+
match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req())
+    -> #{atom() => any()}
+
+

Parse the query string and match specific values against constraints.

+

Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing.

+

This function will crash if the key is missing and no default value is provided. This function will also crash if a constraint fails.

+

The key must be provided as an atom. The key of the returned map will be that atom. The value may be converted through the use of constraints, making this function able to extract, validate and convert values all in one step.

Arguments

-
-
-
-Fields -
-
-

-Fields to retrieve from the query string. -

-

See cowboy(3) for a complete description.

+
Fields
+

Fields to retrieve from the query string.

+

See cowboy(3) for a complete description.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Desired values are returned as a map. The key is the atom -that was given in the list of fields, and the value is the -optionally converted value after applying constraints.

-

The map contains the same keys that were given in the fields.

-

An exception is triggered when the match fails.

-
-
-
+

Desired values are returned as a map. The key is the atom that was given in the list of fields, and the value is the optionally converted value after applying constraints.

+

The map contains the same keys that were given in the fields.

+

An exception is triggered when the match fails.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Match fields
-
-
%% ID and Lang are binaries.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_qs([id, lang], Req).
-
-
Match fields and apply constraints
-
-
%% ID is an integer and Lang a non-empty binary.
-#{id := ID, lang := Lang}
-    = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req).
-
-
Match fields with default values
-
-
#{lang := Lang}
-    = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
-
-
-
+
#{lang := Lang}
+    = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
+

See also

- - +

cowboy_req(3), cowboy_req:qs(3), cowboy_req:parse_qs(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.method/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.method/index.html index 5619ed1f..facfa943 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.method/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.method/index.html @@ -62,100 +62,58 @@

cowboy_req:method(3)

-

Name

-
-

cowboy_req:method - HTTP method

-
-
-
+

cowboy_req:method - HTTP method

Description

-
-
-
-
method(Req :: cowboy_req:req()) -> Method :: binary()
-

Return the request’s HTTP method.

-

The method can also be obtained using pattern matching:

-
-
-
#{method := Method} = Req.
-
-
-
+
#{method := Method} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The request’s HTTP method is returned as a binary string. -While methods are case sensitive, standard methods are -always uppercase.

-
-
-
+

The request's HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase.

Changelog

-
-
    -
  • -

    -2.0: Only the method is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the method is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Ensure the request’s method is GET
-
-
<<"GET">> = cowboy_req:method(Req).
-
-
Allow methods from list
-
-
init(Req, State) ->
-    case lists:member(cowboy_req:method(Req), [<<"GET">>, <<"POST">>]) of
-        true -> handle(Req, State);
-        false -> method_not_allowed(Req, State)
-    end.
-
-
-
+
init(Req, State) ->
+    case lists:member(cowboy_req:method(Req), [<<"GET">>, <<"POST">>]) of
+        true -> handle(Req, State);
+        false -> method_not_allowed(Req, State)
+    end.
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.parse_cookies/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.parse_cookies/index.html index 932f72a3..d8188db0 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.parse_cookies/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.parse_cookies/index.html @@ -62,91 +62,47 @@

cowboy_req:parse_cookies(3)

-

Name

-
-

cowboy_req:parse_cookies - Parse cookie headers

-
-
-
+

cowboy_req:parse_cookies - Parse cookie headers

Description

-
-
-
-
parse_cookies(Req) -> [{Name, Value}]
-
-Name  :: binary() %% case sensitive
-Value :: binary() %% case sensitive
-

Parse cookie headers.

- -

When the cookie header is missing, [] is returned.

-

While an empty cookie header is not valid, some clients do -send it. Cowboy will in this case also return [].

-
-
-
+
parse_cookies(Req) -> [{Name, Value}]
+
+Name  :: binary() %% case sensitive
+Value :: binary() %% case sensitive
+
+

Parse cookie headers.

+

Alias for cowboy_req:parse_header(<<"cookie">>, Req).

+

When the cookie header is missing, [] is returned.

+

While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return [].

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The cookies are returned as a list of key/values. Keys and -values are case sensitive binary strings.

-
-
-
+

The cookies are returned as a list of key/values. Keys and values are case sensitive binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces cookie/2,3 and cookies/1. -

      +
    • 2.0: Function introduced. Replaces cookie/2,3 and cookies/1.
    • -
-
-
-
+

Examples

-
-
-
Look for a specific cookie
-
-
Cookies = cowboy_req:parse_cookies(Req),
-{_, Token} = lists:keyfind(<<"token">>, 1, Cookies).
-
-
-
+
Cookies = cowboy_req:parse_cookies(Req),
+{_, Token} = lists:keyfind(<<"token">>, 1, Cookies).
+

See also

- - +

cowboy_req(3), cowboy_req:parse_header(3), cowboy_req:match_cookies(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.parse_header/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.parse_header/index.html index a074485f..a4e0c4d7 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.parse_header/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.parse_header/index.html @@ -62,283 +62,218 @@

cowboy_req:parse_header(3)

-

Name

-
-

cowboy_req:parse_header - Parse the given HTTP header

-
-
-
+

cowboy_req:parse_header - Parse the given HTTP header

Description

-
-
-
-
parse_header(Name, Req)          -> ParsedValue | Default
-parse_header(Name, Req, Default) -> ParsedValue | Default
-
-Name        :: binary()
-Req         :: cowboy_req:req()
-ParsedValue :: any()
-Default     :: any()
-

Parse the given HTTP header.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

The type of the parsed value varies depending on -the header. Similarly, the default value when calling -cowboy_req:parse_header/2 differs depending on the -header.

-
-
-
+
parse_header(Name, Req)          -> ParsedValue | Default
+parse_header(Name, Req, Default) -> ParsedValue | Default
+
+Name        :: binary()
+Req         :: cowboy_req:req()
+ParsedValue :: any()
+Default     :: any()
+
+

Parse the given HTTP header.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

The type of the parsed value varies depending on the header. Similarly, the default value when calling cowboy_req:parse_header/2 differs depending on the header.

Arguments

-
-
-
-Name -
-
-

-Desired HTTP header name as a lowercase binary string. -

+
Name
+

Desired HTTP header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the header is missing. -

+
Default
+

Default value returned when the header is missing.

-
-
- -
+

Return value

-
-

The parsed header value varies depending on the header. -When the header is missing, the default argument is returned.

-
-
-
+

The parsed header value varies depending on the header. When the header is missing, the default argument is returned.

Headers

-
-

The following snippets detail the types returned by the -different headers. Unless mentioned otherwise, the -default value when the header is missing will be undefined:

-
-
accept
-
-
parse_header(<<"accept">>, Req)
-    -> [{{Type, SubType, Params}, Quality, AcceptExt}]
-
-Type      :: binary()               %% case insensitive
-SubType   :: binary()               %% case insensitive
-Params    :: [{Key, Value}]
-Quality   :: 0..1000
-AcceptExt :: [Key | {Key, Value}]
-Key       :: binary()               %% case insensitive
-Value     :: binary()               %% case sensitive
-
-
accept-charset, accept-encoding and accept-language
-
-
parse_header(Name, Req) -> [{Value, Quality}]
-
-Name    :: <<"accept-charset">>
-         | <<"accept-encoding">>
-         | <<"accept-language">>
-Value   :: binary()                 %% case insensitive
-Quality :: 0..1000
-
-
authorization
-
-
parse_header(<<"authorization">>, Req)
-    -> {basic, Username :: binary(), Password :: binary()}
-     | {bearer, Token :: binary()}
-     | {digest, [{Key :: binary(), Value :: binary()}]}
-
-
content-length
-
+
content-length
+
-
parse_header(<<"content-length">>, Req) -> non_neg_integer()
-

When the content-length header is missing, 0 is returned.

-
-
content-type
-
-
parse_header(<<"content-type">>, Req)
-    -> {Type, SubType, Params}
-
-Type      :: binary()               %% case insensitive
-SubType   :: binary()               %% case insensitive
-Params    :: [{Key, Value}]
-Key       :: binary()               %% case insensitive
-Value     :: binary()               %% case sensitive;
-

Note that the value for the charset parameter is case insensitive -and returned as a lowercase binary string.

-
-
cookie
-
-
parse_header(<<"cookie">>, Req) -> [{Name, Value}]
-
-Name  :: binary()                   %% case sensitive
-Value :: binary()                   %% case sensitive
-

When the cookie header is missing, [] is returned.

-

While an empty cookie header is not valid, some clients do -send it. Cowboy will in this case also return [].

-
-
expect
-
-
parse_header(<<"expect">>, Req) -> continue
-
-
if-match and if-none-match
-
-
parse_header(Name, Req)
-    -> '*' | [{weak | strong, OpaqueTag}]
-
-Name      :: <<"if-match">>
-           | <<"if-none-match">>
-OpaqueTag :: binary()               %% case sensitive
-
-
if-modified-since and if-unmodified-since
-
-
parse_header(Name, Req) -> calendar:datetime()
-
-
range
-
-
parse_header(<<"range">>, Req) -> {From, To} | Final
-
-From  :: non_neg_integer()
-To    :: non_neg_integer() | infinity
-Final :: neg_integer()
-
-
sec-websocket-extensions
-
-
parse_header(<<"sec-websocket-extensions">>, Req)
-    -> [{Extension, Params}]
-
-Extension :: binary()               %% case sensitive
-Params    :: [Key | {Key, Value}]
-Key       :: binary()               %% case sensitive
-Value     :: binary()               %% case sensitive
-
-
sec-websocket-protocol and upgrade
-
-
parse_header(Name, Req) -> [Token]
-
-Name  :: <<"sec-websocket-protocol">>
-       | <<"upgrade">>
-Token :: binary()                   %% case insensitive
-
-
x-forwarded-for
-
-
parse_header(<<"x-forwarded-for">>, Req) -> [Token]
+
parse_header(<<"x-forwarded-for">>, Req) -> [Token]
 
-Token :: binary()                   %% case sensitive
-
-
Unknown headers
-
-
parse_header(_, Req) -> {undefined, RawValue}
-
-
-
+
parse_header(_, Req) -> {undefined, RawValue}
+

Changelog

-
-
    -
  • -

    -2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Parse the accept header with a custom default value
-
-
%% Accept everything when header is missing.
-Accept = cowboy_req:parse_header(<<"accept">>, Req,
-    [{{ <<"*">>, <<"*">>, []}, 1000, []}]).
-
-
Parse the content-length header
-
-
%% Default content-length is 0.
-Length = cowboy_req:header(<<"content-length">>, Req).
-
-
-
+
%% Default content-length is 0.
+Length = cowboy_req:header(<<"content-length">>, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:header(3), cowboy_req:headers(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.parse_qs/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.parse_qs/index.html index bff11c10..1680b60e 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.parse_qs/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.parse_qs/index.html @@ -62,117 +62,55 @@

cowboy_req:parse_qs(3)

-

Name

-
-

cowboy_req:parse_qs - Parse the query string

-
-
-
+

cowboy_req:parse_qs - Parse the query string

Description

-
-
-
-
parse_qs(Req :: cowboy_req:req())
-    -> [{Key :: binary(), Value :: binary() | true}]
-

Parse the query string as a list of key/value pairs.

-
-
-
+
parse_qs(Req :: cowboy_req:req())
+    -> [{Key :: binary(), Value :: binary() | true}]
+
+

Parse the query string as a list of key/value pairs.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The parsed query string is returned as a list of key/value pairs. -The key is a binary string. The value is either a binary string, -or the atom true. Both key and value are case sensitive.

-

The atom true is returned when a key is present in the query -string without a value. For example, in the following URIs -the key <<"edit">> will always have the value true:

-
    -
  • -

    -/posts/42?edit -

    +

    The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. Both key and value are case sensitive.

    +

    The atom true is returned when a key is present in the query string without a value. For example, in the following URIs the key <<"edit">> will always have the value true:

    +
    • /posts/42?edit
    • -
    • -

      -/posts/42?edit&exclusive=1 -

      +
    • /posts/42?edit&exclusive=1
    • -
    • -

      -/posts/42?exclusive=1&edit -

      +
    • /posts/42?exclusive=1&edit
    • -
    • -

      -/posts/42?exclusive=1&edit&from=web -

      +
    • /posts/42?exclusive=1&edit&from=web
    • -
-
-
-
+

Changelog

-
-
    -
  • -

    -2.0: The parsed value is not longer cached in the Req object. -

    +
    • 2.0: The parsed value is not longer cached in the Req object.
    • -
    • -

      -2.0: Only the parsed query string is returned, it is no longer wrapped in a tuple. -

      +
    • 2.0: Only the parsed query string is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces qs_val/1 and qs_vals/1. -

      +
    • 2.0: Function introduced. Replaces qs_val/1 and qs_vals/1.
    • -
-
-
-
+

Examples

-
-
-
Parse the query string and convert the keys to atoms
-
-
ParsedQs = cowboy_req:parse_qs(Req),
-AtomsQs = [{binary_to_existing_atom(K, latin1), V}
-    || {K, V} <- ParsedQs].
-
-
-
+
ParsedQs = cowboy_req:parse_qs(Req),
+AtomsQs = [{binary_to_existing_atom(K, latin1), V}
+    || {K, V} <- ParsedQs].
+

See also

- - +

cowboy_req(3), cowboy_req:qs(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.path/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.path/index.html index 4779baf5..0fe2594d 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.path/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.path/index.html @@ -62,90 +62,47 @@

cowboy_req:path(3)

-

Name

-
-

cowboy_req:path - URI path

-
-
-
+

cowboy_req:path - URI path

Description

-
-
-
-
path(Req :: cowboy_req:req()) -> Path :: binary()
-

Return the path of the effective request URI.

-

The path can also be obtained using pattern matching:

-
-
-
#{path := Path} = Req.
-
-
-
+
#{path := Path} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The path is returned as a binary string. It is case sensitive.

-
-
-
+

The path is returned as a binary string. It is case sensitive.

Changelog

-
-
    -
  • -

    -2.0: Only the path is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the path is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s path
-
-
Path = cowboy_req:path(Req).
-
-
-
+
Path = cowboy_req:path(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:path_info(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.path_info/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.path_info/index.html index 9adc2dfd..cc5a9709 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.path_info/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.path_info/index.html @@ -62,87 +62,41 @@

cowboy_req:path_info(3)

-

Name

-
-

cowboy_req:path_info - Access the route’s trailing path segments

-
-
-
+

cowboy_req:path_info - Access the route's trailing path segments

Description

-
-
-
-
path_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
-

Return the tokens for the trailing path segments.

-

This is the part of the host name that was matched using -the ... notation.

-
-
-
+
path_info(Req :: cowboy_req:req()) -> cowboy_router:tokens()
+
+

Return the tokens for the trailing path segments.

+

This is the part of the host name that was matched using the ... notation.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The tokens are returned as a list of case sensitive -binary strings.

-
-
-
+

The tokens are returned as a list of case sensitive binary strings.

Changelog

-
-
    -
  • -

    -2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -

    +
    • 2.0: Only the tokens are returned, they are no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the path_info tokens
-
-
PathInfo = cowboy_req:path_info(Req).
-
-
-
+
PathInfo = cowboy_req:path_info(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:host_info(3), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.peer/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.peer/index.html index bbce29da..9271abc7 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.peer/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.peer/index.html @@ -62,98 +62,51 @@

cowboy_req:peer(3)

-

Name

-
-

cowboy_req:peer - Peer address and port

-
-
-
+

cowboy_req:peer - Peer address and port

Description

-
-
-
-
peer(Req :: cowboy_req:req()) -> Info
+
peer(Req :: cowboy_req:req()) -> Info
 
-Info :: {inet:ip_address(), inet:port_number()}
-

Return the peer’s IP address and port number.

-

The peer information can also be obtained using pattern matching:

-
-
-
#{peer := {IP, Port}} = Req.
-
-
-
+
#{peer := {IP, Port}} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The peer’s IP address and port number.

-

The peer is not necessarily the client’s IP address and port. -It is the IP address of the endpoint connecting directly to -the server, which may be a gateway or a proxy.

-

The forwarded header can be used to get better information -about the different endpoints from the client to the server. -Note however that it is only informative; there is no reliable -way of determining the source of an HTTP request.

-
-
-
+

The peer's IP address and port number.

+

The peer is not necessarily the client's IP address and port. It is the IP address of the endpoint connecting directly to the server, which may be a gateway or a proxy.

+

The forwarded header can be used to get better information about the different endpoints from the client to the server. Note however that it is only informative; there is no reliable way of determining the source of an HTTP request.

Changelog

-
-
    -
  • -

    -2.0: Only the peer is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the peer is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the peer IP address and port number.
-
-
{IP, Port} = cowboy_req:peer(Req).
-
-
-
+
{IP, Port} = cowboy_req:peer(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:sock(3), cowboy_req:cert(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.port/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.port/index.html index 30c8840e..6db57560 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.port/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.port/index.html @@ -62,90 +62,48 @@

cowboy_req:port(3)

-

Name

-
-

cowboy_req:port - URI port number

-
-
-
+

cowboy_req:port - URI port number

Description

-
-
-
-
port(Req :: cowboy_req:req()) -> Port :: inet:port_number()
-

Return the port number of the effective request URI.

-

Note that the port number returned by this function is obtained -by parsing the host header. It may be different from the port -the peer used to connect to Cowboy.

-

The port number can also be obtained using pattern matching:

-
-
-
#{port := Port} = Req.
-
-
-
+
#{port := Port} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The port number is returned as an integer.

-
-
-
+

The port number is returned as an integer.

Changelog

-
-
    -
  • -

    -2.0: Only the port number is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the port number is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s port number
-
-
Port = cowboy_req:port(Req).
-
-
-
+
Port = cowboy_req:port(Req).
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.push/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.push/index.html index 1ad3e8f8..6b2f47a5 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.push/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.push/index.html @@ -62,142 +62,74 @@

cowboy_req:push(3)

-

Name

-
-

cowboy_req:push - Push a resource to the client

-
-
-
+

cowboy_req:push - Push a resource to the client

Description

-
-
-
-
push(Path, Headers, Req :: cowboy_req:req())
-    -> push(Path, Headers, Req, #{})
-
-push(Path, Headers, Req :: cowboy_req:req(), Opts)
-    -> ok
-
-Path    :: iodata()                %% case sensitive
-Headers :: cowboy:http_headers()
-Opts    :: cowboy_req:push_opts()
-

Push a resource to the client.

-

Cowboy handles push requests the same way as if they came -from the client, including the creation of a request handling -process, routing and middlewares and so on.

-

This function does nothing when the HTTP/1.1 protocol is -used. You may call it safely without first checking whether -the connection uses HTTP/2.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Note that the headers must be the headers the client is expected -to send if it were to perform the request. They are therefore -request headers, and not response headers.

-

By default, Cowboy will use the GET method, an empty query string, -and take the scheme, host and port directly from the current -request’s URI. You can override them by passing options.

-

It is not possible to push resources after sending a response. -Any attempt will result in an error.

-
-
-
+
push(Path, Headers, Req :: cowboy_req:req())
+    -> push(Path, Headers, Req, #{})
+
+push(Path, Headers, Req :: cowboy_req:req(), Opts)
+    -> ok
+
+Path    :: iodata()                %% case sensitive
+Headers :: cowboy:http_headers()
+Opts    :: cowboy_req:push_opts()
+
+

Push a resource to the client.

+

Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on.

+

This function does nothing when the HTTP/1.1 protocol is used. You may call it safely without first checking whether the connection uses HTTP/2.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Note that the headers must be the headers the client is expected to send if it were to perform the request. They are therefore request headers, and not response headers.

+

By default, Cowboy will use the GET method, an empty query string, and take the scheme, host and port directly from the current request's URI. You can override them by passing options.

+

It is not possible to push resources after sending a response. Any attempt will result in an error.

Arguments

-
-
-
-Path -
-
-

-The status code for the response. -

+
Path
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Req -
-
-

-The Req object. -

+
+

Header names must be given as lowercase binary strings.

+
Req
+

The Req object.

-
-Opts -
-
-

-Customize the HTTP method or the URI scheme, host, port -or query string. -

+
Opts
+

Customize the HTTP method or the URI scheme, host, port or query string.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Push a resource
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, Req),
-
-
Push a resource with a custom host
-
-
cowboy_req:push("/static/style.css", #{
-    <<"accept">> => <<"text/css">>
-}, #{host => <<"cdn.example.org">>}, Req),
-
-
-
+
cowboy_req:push("/static/style.css", #{
+    <<"accept">> => <<"text/css">>
+}, #{host => <<"cdn.example.org">>}, Req),
+

See also

- - +

cowboy_req(3), cowboy_req:inform(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.qs/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.qs/index.html index ef4fd23f..66e4ebbd 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.qs/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.qs/index.html @@ -62,89 +62,47 @@

cowboy_req:qs(3)

-

Name

-
-

cowboy_req:qs - URI query string

-
-
-
+

cowboy_req:qs - URI query string

Description

-
-
-
-
qs(Req :: cowboy_req:req()) -> Qs :: binary()
-

Return the query string of the effective request URI.

-

The query string can also be obtained using pattern matching:

-
-
-
#{qs := Qs} = Req.
-
-
-
+
#{qs := Qs} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The query string is returned as a binary string. It is case sensitive.

-
-
-
+

The query string is returned as a binary string. It is case sensitive.

Changelog

-
-
    -
  • -

    -2.0: Only the query string is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the query string is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the effective request URI’s query string
-
-
Qs = cowboy_req:qs(Req).
-
-
-
+
Qs = cowboy_req:qs(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:parse_qs(3), cowboy_req:match_qs(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.read_body/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.read_body/index.html index d4c2157a..1be995a0 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.read_body/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.read_body/index.html @@ -62,143 +62,72 @@

cowboy_req:read_body(3)

-

Name

-
-

cowboy_req:read_body - Read the request body

-
-
-
+

cowboy_req:read_body - Read the request body

Description

-
-
-
-
read_body(Req :: cowboy_req:req())
-    -> read_body(Req, #{})
-
-read_body(Req :: cowboy_req:req(), Opts)
-    -> {ok,   Data :: binary(), Req}
-     | {more, Data :: binary(), Req}
-
-Opts :: cowboy_req:read_body_opts()
-

Read the request body.

-

This function reads a chunk of the request body. A more tuple -is returned when more data remains to be read. Call the function -repeatedly until an ok tuple is returned to read the entire body.

-

An ok tuple with empty data is returned when the request has no body, -or when calling this function again after the body has already -been read. It is therefore safe to call this function directly. -Note that the body can only be read once.

-

This function reads the request body from the connection process. -The connection process is responsible for reading from the socket. -The exact behavior varies depending on the protocol.

-

The options therefore are only related to the communication -between the request process and the connection process.

-

Cowboy will automatically handle protocol details including -the expect header, chunked transfer-encoding and others.

-

Once the body has been read fully, Cowboy sets the content-length -header if it was not previously provided.

-
-
-
+
read_body(Req :: cowboy_req:req())
+    -> read_body(Req, #{})
+
+read_body(Req :: cowboy_req:req(), Opts)
+    -> {ok,   Data :: binary(), Req}
+     | {more, Data :: binary(), Req}
+
+Opts :: cowboy_req:read_body_opts()
+
+

Read the request body.

+

This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body.

+

An ok tuple with empty data is returned when the request has no body, or when calling this function again after the body has already been read. It is therefore safe to call this function directly. Note that the body can only be read once.

+

This function reads the request body from the connection process. The connection process is responsible for reading from the socket. The exact behavior varies depending on the protocol.

+

The options therefore are only related to the communication between the request process and the connection process.

+

Cowboy will automatically handle protocol details including the expect header, chunked transfer-encoding and others.

+

Once the body has been read fully, Cowboy sets the content-length header if it was not previously provided.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. -

-

The length option can be used to request smaller or bigger -chunks of data to be sent. It is a best effort approach, Cowboy -may send more data than configured on occasions. It defaults -to 8MB.

-

The period indicates how long the connection process will wait -before it provides us with the data it received. It defaults -to 15 seconds.

-

The connection process sends data to the request process when -either the length of data or the period of time is reached.

-

The timeout option is a safeguard in case the connection -process becomes unresponsive. The function will crash if no -message was received in that interval. The timeout should be -larger than the period. It defaults to the period + 1 second.

+
Opts
+

A map of body reading options.

+

The length option can be used to request smaller or bigger chunks of data to be sent. It is a best effort approach, Cowboy may send more data than configured on occasions. It defaults to 8MB.

+

The period indicates how long the connection process will wait before it provides us with the data it received. It defaults to 15 seconds.

+

The connection process sends data to the request process when either the length of data or the period of time is reached.

+

The timeout option is a safeguard in case the connection process becomes unresponsive. The function will crash if no message was received in that interval. The timeout should be larger than the period. It defaults to the period
1 second.

-
-
- -
+

Return value

-
-

A more tuple is returned when there are more data to be read.

-

An ok tuple is returned when there are no more data to be read, -either because this is the last chunk of data, the body has already -been read, or there was no body to begin with.

-

The data is always returned as a binary.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

A more tuple is returned when there are more data to be read.

+

An ok tuple is returned when there are no more data to be read, either because this is the last chunk of data, the body has already been read, or there was no body to begin with.

+

The data is always returned as a binary.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces body/1,2. -

    +
    • 2.0: Function introduced. Replaces body/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read the entire body
-
-
read_body(Req0, Acc) ->
-    case cowboy_req:read_body(Req0) of
-        {ok, Data, Req} -> {ok, << Acc/binary, Data/binary >>, Req};
-        {more, Data, Req} -> read_body(Req, << Acc/binary, Data/binary >>)
-    end.
-
-
Read the body in small chunks
-
-
cowboy_req:read_body(Req, #{length => 64000}).
-
-
-
+
cowboy_req:read_body(Req, #{length => 64000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.read_part/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.read_part/index.html index 50931838..7746b475 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.read_part/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.read_part/index.html @@ -62,162 +62,94 @@

cowboy_req:read_part(3)

-

Name

-
-

cowboy_req:read_part - Read the next multipart headers

-
-
-
+

cowboy_req:read_part - Read the next multipart headers

Description

-
-
-
-
read_part(Req :: cowboy_req:req())
-    -> read_part(Req, #{})
-
-read_part(Req :: cowboy_req:req(), Opts)
-    -> {ok, Headers, Req} | {done, Req}
-
-Opts    :: cowboy_req:read_body_opts()
-Headers :: #{binary() => binary()}
-

Read the next part of a multipart body.

-

This function reads the request body and parses it as -multipart. Each parts of a multipart representation have -their own headers and body. This function parses and returns -headers. Examples of multipart media types are -multipart/form-data and multipart/byteranges.

-

Cowboy will skip any data remaining until the beginning of -the next part. This includes the preamble to the multipart -message but also the body of a previous part if it hasn’t -been read. Both are skipped automatically when calling this -function.

-

Cowboy will read the body before parsing in chunks of size -up to 64KB, with a period of 5 seconds. This is tailored for -reading part headers and might not be the most efficient for -skipping the previous part’s body.

-

The headers returned are MIME headers, NOT HTTP headers. -They can be parsed using the functions from the cow_multipart -module. In addition, the cow_multipart:form_data/1 function -can be used to quickly extract information from multipart/form-data -representations.

-

Once a part has been read, it can not be read again.

-

Once the body has been read, Cowboy sets the content-length -header if it was not previously provided.

-
-
-
+
read_part(Req :: cowboy_req:req())
+    -> read_part(Req, #{})
+
+read_part(Req :: cowboy_req:req(), Opts)
+    -> {ok, Headers, Req} | {done, Req}
+
+Opts    :: cowboy_req:read_body_opts()
+Headers :: #{binary() => binary()}
+
+

Read the next part of a multipart body.

+

This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. Examples of multipart media types are multipart/form-data and multipart/byteranges.

+

Cowboy will skip any data remaining until the beginning of the next part. This includes the preamble to the multipart message but also the body of a previous part if it hasn't been read. Both are skipped automatically when calling this function.

+

Cowboy will read the body before parsing in chunks of size up to 64KB, with a period of 5 seconds. This is tailored for reading part headers and might not be the most efficient for skipping the previous part's body.

+

The headers returned are MIME headers, NOT HTTP headers. They can be parsed using the functions from the cow_multipart module. In addition, the cow_multipart:form_data/1 function can be used to quickly extract information from multipart/form-data representations.

+ +

Once a part has been read, it can not be read again.

+

Once the body has been read, Cowboy sets the content-length header if it was not previously provided.

+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. Please refer to -cowboy_req:read_body(3) -for details about each option. -

-

This function defaults the length to 64KB and the period -to 5 seconds.

+
Opts
+

A map of body reading options. Please refer to cowboy_req:read_body(3) for details about each option.

+

This function defaults the length to 64KB and the period to 5 seconds.

-
-
- -
+

Return value

-
-

An ok tuple is returned containing the next part’s headers -as a map.

-

A done tuple is returned if there are no more parts to read.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

An ok tuple is returned containing the next part's headers as a map.

+

A done tuple is returned if there are no more parts to read.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces part/1,2. -

    +
    • 2.0: Function introduced. Replaces part/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read all parts
-
-
acc_multipart(Req0, Acc) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, Headers, Req1} ->
-            {ok, Body, Req} = stream_body(Req1, <<>>),
-            acc_multipart(Req, [{Headers, Body}|Acc]);
-        {done, Req} ->
-            {lists:reverse(Acc), Req}
-    end.
-
-stream_body(Req0, Acc) ->
-    case cowboy_req:read_part_body(Req0) of
-        {more, Data, Req} ->
-            stream_body(Req, << Acc/binary, Data/binary >>);
-        {ok, Data, Req} ->
-            {ok, << Acc/binary, Data/binary >>, Req}
-    end.
-
-
Read all part headers, skipping bodies
-
-
skip_body_multipart(Req0, Acc) ->
-    case cowboy_req:read_part(Req0) of
-        {ok, Headers, Req} ->
-            skip_body_multipart(Req, [Headers|Acc]);
-        {done, Req} ->
-            {lists:reverse(Acc), Req}
-    end.
-
-
Read a part header in larger chunks
-
-
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).
-
-
-
+
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.read_part_body/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.read_part_body/index.html index 340bb2cb..403a6271 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.read_part_body/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.read_part_body/index.html @@ -62,130 +62,70 @@

cowboy_req:read_part_body(3)

-

Name

-
-

cowboy_req:read_part_body - Read the current part’s body

-
-
-
+

cowboy_req:read_part_body - Read the current part's body

Description

-
-
-
-
read_part_body(Req :: cowboy_req:req())
-    -> read_part_body(Req, #{})
-
-read_part_body(Req :: cowboy_req:req(), Opts)
-    -> {ok,   Data :: binary(), Req}
-     | {more, Data :: binary(), Req}
-
-Opts :: cowboy_req:read_body_opts()
-

Read the body of the current part of the multipart message.

-

This function reads the request body and parses it as -multipart. Each parts of a multipart representation have -their own headers and body. This function returns the -body of the current part. Examples of multipart media types -are multipart/form-data and multipart/byteranges.

-

This function reads a chunk of the part’s body. A more tuple -is returned when more data remains to be read. Call the function -repeatedly until an ok tuple is returned to read the entire body.

-

Once a part has been read, it can not be read again.

-

Once the body has been read, Cowboy sets the content-length -header if it was not previously provided.

-
-
-
+
read_part_body(Req :: cowboy_req:req())
+    -> read_part_body(Req, #{})
+
+read_part_body(Req :: cowboy_req:req(), Opts)
+    -> {ok,   Data :: binary(), Req}
+     | {more, Data :: binary(), Req}
+
+Opts :: cowboy_req:read_body_opts()
+
+

Read the body of the current part of the multipart message.

+

This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function returns the body of the current part. Examples of multipart media types are multipart/form-data and multipart/byteranges.

+

This function reads a chunk of the part's body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body.

+

Once a part has been read, it can not be read again.

+

Once the body has been read, Cowboy sets the content-length header if it was not previously provided.

+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. Please refer to -cowboy_req:read_body(3) -for details about each option. -

-

This function uses the same default options as the -cowboy_req:read_body(3) -function.

+
Opts
+

A map of body reading options. Please refer to cowboy_req:read_body(3) for details about each option.

+

This function uses the same default options as the cowboy_req:read_body(3) function.

-
-
- -
+

Return value

-
-

A more tuple is returned when there are more data to be read.

-

An ok tuple is returned when there are no more data to be read.

-

The data is always returned as a binary.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

A more tuple is returned when there are more data to be read.

+

An ok tuple is returned when there are no more data to be read.

+

The data is always returned as a binary.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces part_body/1,2. -

    +
    • 2.0: Function introduced. Replaces part_body/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read a full part’s body
-
-
stream_body(Req0, Acc) ->
-    case cowboy_req:read_part_body(Req0) of
-        {more, Data, Req} ->
-            stream_body(Req, << Acc/binary, Data/binary >>);
-        {ok, Data, Req} ->
-            {ok, << Acc/binary, Data/binary >>, Req}
-    end.
-
-
Ensure a part’s body is smaller than 64KB
-
-
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).
-
-
-
+
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.read_urlencoded_body/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.read_urlencoded_body/index.html index 9565153e..be73fe71 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.read_urlencoded_body/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.read_urlencoded_body/index.html @@ -62,126 +62,64 @@

cowboy_req:read_urlencoded_body(3)

-

Name

-
-

cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body

-
-
-
+

cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body

Description

-
-
-
-
read_urlencoded_body(Req :: cowboy_req:req())
-    -> read_urlencoded_body(Req, #{})
-
-read_urlencoded_body(Req :: cowboy_req:req(), Opts)
-    -> {ok, Body, Req}
-
-Opts :: cowboy_req:read_body_opts()
-Body :: [{Key :: binary(), Value :: binary() | true}]
-

Read and parse a urlencoded request body.

-

This function reads the request body and parses it as -application/x-www-form-urlencoded. It returns a list -of key/values.

-

The urlencoded media type is used by Web browsers when -submitting HTML forms using the POST method.

-

Cowboy needs to read the full body before parsing. By default -it will read bodies of size up to 64KB. It is possible to -provide options to read larger bodies if required.

-

Cowboy will automatically handle protocol details including -the expect header, chunked transfer-encoding and others.

-

Once the body has been read, Cowboy sets the content-length -header if it was not previously provided.

-

This function can only be called once. Calling it again will -result in undefined behavior.

-
-
-
+
read_urlencoded_body(Req :: cowboy_req:req())
+    -> read_urlencoded_body(Req, #{})
+
+read_urlencoded_body(Req :: cowboy_req:req(), Opts)
+    -> {ok, Body, Req}
+
+Opts :: cowboy_req:read_body_opts()
+Body :: [{Key :: binary(), Value :: binary() | true}]
+
+

Read and parse a urlencoded request body.

+

This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values.

+

The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method.

+

Cowboy needs to read the full body before parsing. By default it will read bodies of size up to 64KB. It is possible to provide options to read larger bodies if required.

+

Cowboy will automatically handle protocol details including the expect header, chunked transfer-encoding and others.

+

Once the body has been read, Cowboy sets the content-length header if it was not previously provided.

+

This function can only be called once. Calling it again will result in undefined behavior.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-A map of body reading options. Please refer to -cowboy_req:read_body(3) -for details about each option. -

-

This function defaults the length to 64KB and the period -to 5 seconds.

+
Opts
+

A map of body reading options. Please refer to cowboy_req:read_body(3) for details about each option.

+

This function defaults the length to 64KB and the period to 5 seconds.

-
-
- -
+

Return value

-
-

An ok tuple is returned containing a list of key/values found -in the body.

-

The Req object returned in the tuple must be used for that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read.

-
-
-
+

An ok tuple is returned containing a list of key/values found in the body.

+

The Req object returned in the tuple must be used for that point onward. It contains a more up to date representation of the request. For example it may have an added content-length header once the body has been read.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces body_qs/1,2. -

    +
    • 2.0: Function introduced. Replaces body_qs/1,2.
    • -
-
-
-
+

Examples

-
-
-
Read a urlencoded body
-
-
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0),
-{_, Lang} = lists:keyfind(<<"lang">>, 1, Body).
-
-
Allow large urlencoded bodies
-
-
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).
-
-
-
+
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).
+

See also

- - +

cowboy_req(3), cowboy_req:has_body(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.reply/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.reply/index.html index e980e297..bb8a0c83 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.reply/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.reply/index.html @@ -62,165 +62,87 @@

cowboy_req:reply(3)

-

Name

-
-

cowboy_req:reply - Send the response

-
-
-
+

cowboy_req:reply - Send the response

Description

-
-
-
-
reply(Status, Req :: cowboy_req:req())
-    -> reply(StatusCode, #{}, Req)
-
-reply(Status, Headers, Req :: cowboy_req:req())
-    -> Req
-
-reply(Status, Headers, Body, Req :: cowboy_req:req())
-    -> Req
-
-Status  :: cowboy:http_status()
-Headers :: cowboy:http_headers()
-Body    :: cowboy_req:resp_body()
-

Send the response.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may overwrite those set by set_resp_header/3 -and set_resp_headers/2.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-

The reply/2,3 functions will send the body set previously, -if any. The reply/4 function always sends the given body, -overriding any previously set.

-

You do not need to set the content-length header when -sending a response body. Cowboy takes care of it automatically. -You should however provide a content-type header.

-

No further data can be transmitted after this function -returns. This includes the push mechanism. Attempting to -send two replies, or to push resources after a reply has -been sent, will result in an error.

-
-
-
+
reply(Status, Req :: cowboy_req:req())
+    -> reply(StatusCode, #{}, Req)
+
+reply(Status, Headers, Req :: cowboy_req:req())
+    -> Req
+
+reply(Status, Headers, Body, Req :: cowboy_req:req())
+    -> Req
+
+Status  :: cowboy:http_status()
+Headers :: cowboy:http_headers()
+Body    :: cowboy_req:resp_body()
+
+

Send the response.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3 and set_resp_headers/2.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

+

The reply/2,3 functions will send the body set previously, if any. The reply/4 function always sends the given body, overriding any previously set.

+

You do not need to set the content-length header when sending a response body. Cowboy takes care of it automatically. You should however provide a content-type header.

+

No further data can be transmitted after this function returns. This includes the push mechanism. Attempting to send two replies, or to push resources after a reply has been sent, will result in an error.

Arguments

-
-
-
-Status -
-
-

-The status code for the response. -

+
Status
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Body -
-
-

-The body can be either a binary value, an iolist or a -sendfile tuple telling Cowboy to send the contents of -a file. -

+
+

Header names must be given as lowercase binary strings.

+
Body
+

The body can be either a binary value, an iolist or a sendfile tuple telling Cowboy to send the contents of a file.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object should be used from that point onward -as it contains updated information about the state of the request.

-
-
-
+

A new Req object is returned.

+

The returned Req object should be used from that point onward as it contains updated information about the state of the request.

Changelog

-
-
    -
  • -

    -2.0: Only the Req is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the Req is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Reply
-
-
Req = cowboy_req:reply(404, Req0).
-
-
Reply with custom headers
-
-
Req = cowboy_req:reply(401, #{
-    <<"www-authenticate">> => <<"Basic realm=\"erlang.org\"">>
-}, Req0).
-
-
Reply with custom headers and a body
-
-
Req = cowboy_req:reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, "Hello world!", Req0).
-
-
-
+
Req = cowboy_req:reply(200, #{
+    <<"content-type">> => <<"text/plain">>
+}, "Hello world!", Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:set_resp_body(3), cowboy_req:inform(3), cowboy_req:stream_reply(3), cowboy_req:push(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.resp_header/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.resp_header/index.html index 76d70761..9a11c12d 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.resp_header/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.resp_header/index.html @@ -62,113 +62,58 @@

cowboy_req:resp_header(3)

-

Name

-
-

cowboy_req:resp_header - Response header

-
-
-
+

cowboy_req:resp_header - Response header

Description

-
-
-
-
resp_header(Name, Req)          -> resp_header(Name, Req, undefined)
-resp_header(Name, Req, Default) -> binary() | Default
-
-Name    :: binary()          %% lowercase; case insensitive
-Req     :: cowboy_req:req()
-Default :: any()
-

Return the value for the given response header.

-

The response header must have been set previously using -cowboy_req:set_resp_header(3) or -cowboy_req:set_resp_headers(3).

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-
-
-
+
resp_header(Name, Req)          -> resp_header(Name, Req, undefined)
+resp_header(Name, Req, Default) -> binary() | Default
+
+Name    :: binary()          %% lowercase; case insensitive
+Req     :: cowboy_req:req()
+Default :: any()
+
+

Return the value for the given response header.

+

The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3).

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

Arguments

-
-
-
-Name -
-
-

-Desired response header name as a lowercase binary string. -

+
Name
+

Desired response header name as a lowercase binary string.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Default -
-
-

-Default value returned when the header is missing. -

+
Default
+

Default value returned when the header is missing.

-
-
- -
+

Return value

-
-

The header value is returned as a binary string. When the -header is missing, the default argument is returned.

-
-
-
+

The header value is returned as a binary string. When the header is missing, the default argument is returned.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the content-type response header
-
-
Type = cowboy_req:resp_header(<<"content-type">>, Req).
-
-
Get the content-type response header with a default value
-
-
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).
-
-
-
+
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).
+

See also

- - +

cowboy_req(3), cowboy_req:resp_headers(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.resp_headers/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.resp_headers/index.html index 54cc8537..a0c4ff34 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.resp_headers/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.resp_headers/index.html @@ -62,79 +62,38 @@

cowboy_req:resp_headers(3)

-

Name

-
-

cowboy_req:resp_headers - Response headers

-
-
-
+

cowboy_req:resp_headers - Response headers

Description

-
-
-
-
resp_headers(Req :: cowboy_req:req()) -> cowboy:http_headers()
-

Return all response headers.

-
-
-
+
resp_headers(Req :: cowboy_req:req()) -> cowboy:http_headers()
+
+

Return all response headers.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

Headers are returned as a map with keys being lowercase -binary strings, and values as binary strings.

-
-
-
+

Headers are returned as a map with keys being lowercase binary strings, and values as binary strings.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get all response headers
-
-
Headers = cowboy_req:resp_headers(Req).
-
-
-
+
Headers = cowboy_req:resp_headers(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:resp_header(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.scheme/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.scheme/index.html index a1227edf..3f73db92 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.scheme/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.scheme/index.html @@ -62,89 +62,52 @@

cowboy_req:scheme(3)

-

Name

-
-

cowboy_req:scheme - URI scheme

-
-
-
+

cowboy_req:scheme - URI scheme

Description

-
-
-
-
scheme(Req :: cowboy_req:req()) -> Scheme :: binary()
-

Return the scheme of the effective request URI.

-

The scheme can also be obtained using pattern matching:

-
-
-
#{scheme := Scheme} = Req.
-
-
-
+
#{scheme := Scheme} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The scheme is returned as a binary. It is case insensitive.

-

Cowboy will only set the scheme to <<"http">> or <<"https">>.

-
-
-
+

The scheme is returned as a binary. It is case insensitive.

+

Cowboy will only set the scheme to <<"http">> or <<"https">>.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Redirect HTTP to HTTPS
-
-
init(Req0=#{scheme := <<"http">>}, State) ->
-    Req = cowboy_req:reply(302, #{
-        <<"location">> => cowboy_req:uri(Req, #{scheme => <<"https">>})
-    }, Req0),
-    {ok, Req, State};
-init(Req, State) ->
-    {cowboy_rest, Req, State}.
-
-
-
+
init(Req0=#{scheme := <<"http">>}, State) ->
+    Req = cowboy_req:reply(302, #{
+        <<"location">> => cowboy_req:uri(Req, #{scheme => <<"https">>})
+    }, Req0),
+    {ok, Req, State};
+init(Req, State) ->
+    {cowboy_rest, Req, State}.
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_body/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_body/index.html index a41023dd..20331259 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_body/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_body/index.html @@ -62,138 +62,79 @@

cowboy_req:set_resp_body(3)

-

Name

-
-

cowboy_req:set_resp_body - Set the response body

-
-
-
+

cowboy_req:set_resp_body - Set the response body

Description

-
-
-
-
set_resp_body(Body, Req :: cowboy_req:req())
-        -> Req
-
-Body :: cowboy_req:resp_body()
-

Set the response body.

-

The response body will be sent when a reply is initiated. -Note that the functions stream_reply/2,3 and reply/4 -will override the body set by this function.

-

This function can also be used to remove a response body -that was set previously. To do so, simply call this function -with an empty body.

-
-
-
+
set_resp_body(Body, Req :: cowboy_req:req())
+	-> Req
+
+Body :: cowboy_req:resp_body()
+
+

Set the response body.

+

The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function.

+

This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body.

Arguments

-
-
-
-Body -
-
-

-The body can be either a binary value, an iolist or a -sendfile tuple telling Cowboy to send the contents of -a file. -

+
Body
+

The body can be either a binary value, an iolist or a sendfile tuple telling Cowboy to send the contents of a file.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the body will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the body will not be sent in the response.

Changelog

-
-
    -
  • -

    -2.0: The function now accepts a sendfile tuple. -

    +
    • 2.0: The function now accepts a sendfile tuple.
    • -
    • -

      -2.0: The set_resp_body_fun/2,3 functions were removed. -

      +
    • 2.0: The set_resp_body_fun/2,3 functions were removed.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set the response body
-
-
Req = cowboy_req:set_resp_body(<<"Hello world!">>, Req0).
-
-
Set the response body as an iolist
-
-
Req = cowboy_req:set_resp_body([
-    "<html><head><title>",
-    page_title(),
-    "</title></head><body>",
-    page_body(),
-    "</body></html>"
-], Req0).
-
-
Tell Cowboy to send data from a file
-
-
{ok, #file_info{size=Size}} = file:read_file_info(Filename),
-Req = cowboy_req:set_resp_body({sendfile, 0, Size, Filename}, Req0).
-
-
Clear any previously set response body
-
-
Req = cowboy_req:set_resp_body(<<>>, Req0).
-
-
-
+
Req = cowboy_req:set_resp_body(<<>>, Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_cookie/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_cookie/index.html index 157e9162..6844dc8e 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_cookie/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_cookie/index.html @@ -62,167 +62,104 @@

cowboy_req:set_resp_cookie(3)

-

Name

-
-

cowboy_req:set_resp_cookie - Set a cookie

-
-
-
+

cowboy_req:set_resp_cookie - Set a cookie

Description

-
-
-
-
set_resp_cookie(Name, Value, Req :: cowboy_req:req())
-    -> set_resp_cookie(Name, Value, [], Req)
-
-set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts)
-    -> Req
-
-Name  :: binary()                  %% case sensitive
-Value :: iodata()                  %% case sensitive
-Opts  :: cow_cookie:cookie_opts()
-

Set a cookie to be sent with the response.

-

Note that cookie names are case sensitive.

-
-
-
+
set_resp_cookie(Name, Value, Req :: cowboy_req:req())
+    -> set_resp_cookie(Name, Value, [], Req)
+
+set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts)
+    -> Req
+
+Name  :: binary()                  %% case sensitive
+Value :: iodata()                  %% case sensitive
+Opts  :: cow_cookie:cookie_opts()
+
+

Set a cookie to be sent with the response.

+

Note that cookie names are case sensitive.

Arguments

-
-
-
-Name -
-
-

-Cookie name. -

+
Name
+

Cookie name.

-
-Value -
-
-

-Cookie value. -

+
Value
+

Cookie value.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-Cookie options. -

+
Opts
+

Cookie options.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the cookie will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the cookie will not be sent in the response.

Changelog

-
-
    -
  • -

    -2.0: set_resp_cookie/3 introduced as an alias to set_resp_cookie/4 with no options. -

    +
    • 2.0: set_resp_cookie/3 introduced as an alias to set_resp_cookie/4 with no options.
    • -
    • -

      -2.0: The first argument type is now binary() instead of iodata(). -

      +
    • 2.0: The first argument type is now binary() instead of iodata().
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set a session cookie
-
-
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0).
-
-
Set a cookie with an expiration time
-
-
Req = cowboy_req:set_resp_cookie(<<"lang">>, <<"fr-FR">>,
-    Req0, #{max_age => 3600}).
-
-
Delete a cookie
-
-
Req = cowboy_req:set_resp_cookie(<<"sessionid">>, <<>>,
-    Req0, #{max_age => 0}).
-
-
Set a cookie for a specific domain and path
-
-
Req = cowboy_req:set_resp_cookie(<<"inaccount">>, <<"1">>,
-    Req0, #{domain => "my.example.org", path => "/account"}).
-
-
Restrict a cookie to HTTPS
-
-
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID,
-    Req0, #{secure => true}).
-
-
Restrict a cookie to HTTP
-
-
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
-Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID,
-    Req0, #{http_only => true}).
-
-
-
+
SessionID = base64:encode(crypto:strong_rand_bytes(32)),
+Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID,
+    Req0, #{http_only => true}).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_header/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_header/index.html index 9bb6ad4a..64350df0 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_header/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_header/index.html @@ -62,121 +62,60 @@

cowboy_req:set_resp_header(3)

-

Name

-
-

cowboy_req:set_resp_header - Set a response header

-
-
-
+

cowboy_req:set_resp_header - Set a response header

Description

-
-
-
-
set_resp_header(Name, Value, Req :: cowboy_req:req())
-        -> Req
-
-Name  :: binary()  %% lowercase; case insensitive
-Value :: iodata()  %% case depends on header
-

Set a header to be sent with the response.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may be overwritten by those set from the -reply functions.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-
-
-
+
set_resp_header(Name, Value, Req :: cowboy_req:req())
+	-> Req
+
+Name  :: binary()  %% lowercase; case insensitive
+Value :: iodata()  %% case depends on header
+
+

Set a header to be sent with the response.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

Arguments

-
-
-
-Name -
-
-

-Header name as a lowercase binary string. -

+
Name
+

Header name as a lowercase binary string.

-
-Value -
-
-

-Header value. -

+
Value
+

Header value.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the header will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the header will not be sent in the response.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set a header in the response
-
-
Req = cowboy_req:set_resp_header(<<"allow">>, "GET", Req0).
-
-
Construct a header using iolists
-
-
Req = cowboy_req:set_resp_header(<<"allow">>,
-    [allowed_methods(), ", OPTIONS"], Req0).
-
-
-
+
Req = cowboy_req:set_resp_header(<<"allow">>,
+    [allowed_methods(), ", OPTIONS"], Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_headers(3), cowboy_req:has_resp_header(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3), cowboy_req:delete_resp_header(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_headers/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_headers/index.html index cbd6ade8..7481bf57 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_headers/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_headers/index.html @@ -62,109 +62,51 @@

cowboy_req:set_resp_headers(3)

-

Name

-
-

cowboy_req:set_resp_headers - Set several response headers

-
-
-
+

cowboy_req:set_resp_headers - Set several response headers

Description

-
-
-
-
set_resp_headers(Headers, Req :: cowboy_req:req())
-    -> Req
-
-Headers :: cowboy:http_headers()
-

Set several headers to be sent with the response.

-

The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may be overwritten by those set from the -reply functions. Likewise, headers set by this function may -overwrite headers that were set previously.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-
-
-
+
set_resp_headers(Headers, Req :: cowboy_req:req())
+    -> Req
+
+Headers :: cowboy:http_headers()
+
+

Set several headers to be sent with the response.

+

The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. Likewise, headers set by this function may overwrite headers that were set previously.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

Arguments

-
-
-
-Headers -
-
-

-Headers as a map with keys being lowercase binary strings, -and values as binary strings. -

+
Headers
+

Headers as a map with keys being lowercase binary strings, and values as binary strings.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward, -otherwise the headers will not be sent in the response.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward, otherwise the headers will not be sent in the response.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. -

    +
    • 2.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Set several response headers
-
-
Req = cowboy_req:set_resp_headers(#{
-    <<"content-type">>     => <<"text/html">>,
-    <<"content-encoding">> => <<"gzip">>
-}, Req0).
-
-
-
+
Req = cowboy_req:set_resp_headers(#{
+    <<"content-type">>     => <<"text/html">>,
+    <<"content-encoding">> => <<"gzip">>
+}, Req0).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_header(3), cowboy_req:has_resp_header(3), cowboy_req:resp_header(3), cowboy_req:resp_headers(3), cowboy_req:delete_resp_header(3), cowboy_req:reply(3), cowboy_req:stream_reply(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.sock/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.sock/index.html index 5bfb7e57..c9da79f7 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.sock/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.sock/index.html @@ -62,86 +62,47 @@

cowboy_req:sock(3)

-

Name

-
-

cowboy_req:sock - Socket address and port

-
-
-
+

cowboy_req:sock - Socket address and port

Description

-
-
-
-
sock(Req :: cowboy_req:req()) -> Info
+
sock(Req :: cowboy_req:req()) -> Info
 
-Info :: {inet:ip_address(), inet:port_number()}
-

Return the socket’s IP address and port number.

-

The socket information can also be obtained using pattern matching:

-
-
-
#{sock := {IP, Port}} = Req.
-
-
-
+
#{sock := {IP, Port}} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The socket’s local IP address and port number.

-
-
-
+

The socket's local IP address and port number.

Changelog

-
-
    -
  • -

    -2.1: Function introduced. -

    +
    • 2.1: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the socket’s IP address and port number.
-
-
{IP, Port} = cowboy_req:sock(Req).
-
-
-
+
{IP, Port} = cowboy_req:sock(Req).
+

See also

- - +

cowboy_req(3), cowboy_req:peer(3), cowboy_req:cert(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.stream_body/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.stream_body/index.html index 97ae71b6..0a3ca04f 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.stream_body/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.stream_body/index.html @@ -62,119 +62,56 @@

cowboy_req:stream_body(3)

-

Name

-
-

cowboy_req:stream_body - Stream the response body

-
-
-
+

cowboy_req:stream_body - Stream the response body

Description

-
-
-
-
stream_body(Data, IsFin, Req :: cowboy_req:req()) -> ok
-
-Data  :: iodata()
-IsFin :: fin | nofin
-

Stream the response body.

-

This function may be called as many times as needed after -initiating a response using the -cowboy_req:stream_reply(3) -function.

-

The second argument indicates if this call is the final -call. Use the nofin value until you know no more data -will be sent. The final call should use fin (possibly -with an empty data value) or be a call to the -cowboy_req:stream_trailers(3) -function.

-

Note that not using fin for the final call is not an -error; Cowboy will take care of it when the request -handler terminates if needed. Depending on the resource -it may however be more efficient to do it as early as -possible.

-

You do not need to handle HEAD requests specifically as -Cowboy will ensure no data is sent when you call this function.

-
-
-
+
stream_body(Data, IsFin, Req :: cowboy_req:req()) -> ok
+
+Data  :: iodata()
+IsFin :: fin | nofin
+
+

Stream the response body.

+

This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function.

+

The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. The final call should use fin (possibly with an empty data value) or be a call to the cowboy_req:stream_trailers(3) function.

+

Note that not using fin for the final call is not an error; Cowboy will take care of it when the request handler terminates if needed. Depending on the resource it may however be more efficient to do it as early as possible.

+

You do not need to handle HEAD requests specifically as Cowboy will ensure no data is sent when you call this function.

Arguments

-
-
-
-Data -
-
-

-The data to be sent. -

+
Data
+

The data to be sent.

-
-IsFin -
-
-

-A flag indicating whether this is the final piece of data -to be sent. -

+
IsFin
+

A flag indicating whether this is the final piece of data to be sent.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.0: Function introduced. Replaces chunk/2. -

    +
    • 2.0: Function introduced. Replaces chunk/2.
    • -
-
-
-
+

Examples

-
-
-
Stream the response body
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, Req0),
-cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
-timer:sleep(1000),
-cowboy_req:stream_body(<<"World!\n">>, fin, Req).
-
-
-
+
Req = cowboy_req:stream_reply(200, #{
+    <<"content-type">> => <<"text/plain">>
+}, Req0),
+cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
+timer:sleep(1000),
+cowboy_req:stream_body(<<"World!\n">>, fin, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:stream_reply(3), cowboy_req:stream_trailers(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.stream_reply/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.stream_reply/index.html index 9534020b..17382cf6 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.stream_reply/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.stream_reply/index.html @@ -62,152 +62,76 @@

cowboy_req:stream_reply(3)

-

Name

-
-

cowboy_req:stream_reply - Send the response headers

-
-
-
+

cowboy_req:stream_reply - Send the response headers

Description

-
-
-
-
stream_reply(Status, Req :: cowboy_req:req())
-    -> stream_reply(StatusCode, #{}, Req)
-
-stream_reply(Status, Headers, Req :: cowboy_req:req())
-    -> Req
-
-Status  :: cowboy:http_status()
-Headers :: cowboy:http_headers()
-

Send the response headers.

-

The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly.

-

Cowboy does not allow duplicate header names. Headers set -by this function may overwrite those set by set_resp_header/3.

-

Use cowboy_req:set_resp_cookie(3) -instead of this function to set cookies.

-

If a response body was set before calling this function, -it will not be sent.

-

Use cowboy_req:stream_body(3) -to stream the response body and optionally -cowboy_req:stream_trailers(3) -to send response trailer field values.

-

You may want to set the content-length header when using -this function, if it is known in advance. This will allow -clients using HTTP/2 and HTTP/1.0 to process the response -more efficiently.

-

The streaming method varies depending on the protocol being -used. HTTP/2 will use the usual DATA frames. HTTP/1.1 will -use chunked transfer-encoding. HTTP/1.0 will send the body -unmodified and close the connection at the end if no -content-length was set.

-

It is not possible to push resources after this function -returns. Any attempt will result in an error.

-
-
-
+
stream_reply(Status, Req :: cowboy_req:req())
+    -> stream_reply(StatusCode, #{}, Req)
+
+stream_reply(Status, Headers, Req :: cowboy_req:req())
+    -> Req
+
+Status  :: cowboy:http_status()
+Headers :: cowboy:http_headers()
+
+

Send the response headers.

+

The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly.

+

Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3.

+

Use cowboy_req:set_resp_cookie(3) instead of this function to set cookies.

+

If a response body was set before calling this function, it will not be sent.

+

Use cowboy_req:stream_body(3) to stream the response body and optionally cowboy_req:stream_trailers(3) to send response trailer field values.

+

You may want to set the content-length header when using this function, if it is known in advance. This will allow clients using HTTP/2 and HTTP/1.0 to process the response more efficiently.

+

The streaming method varies depending on the protocol being used. HTTP/2 will use the usual DATA frames. HTTP/1.1 will use chunked transfer-encoding. HTTP/1.0 will send the body unmodified and close the connection at the end if no content-length was set.

+

It is not possible to push resources after this function returns. Any attempt will result in an error.

Arguments

-
-
-
-Status -
-
-

-The status code for the response. -

+
Status
+

The status code for the response.

-
-Headers -
-
-

-The response headers. -

+
Headers
+

The response headers.

-
-

Header names must be given as lowercase binary strings.

-
-
-Req -
-
-

-The Req object. -

+
+

Header names must be given as lowercase binary strings.

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

A new Req object is returned.

-

The returned Req object must be used from that point onward -in order to be able to stream the response body.

-
-
-
+

A new Req object is returned.

+

The returned Req object must be used from that point onward in order to be able to stream the response body.

Changelog

-
-
    -
  • -

    -2.0: Only the Req is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the Req is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces chunked_reply/1,2. -

      +
    • 2.0: Function introduced. Replaces chunked_reply/1,2.
    • -
-
-
-
+

Examples

-
-
-
Initiate the response
-
-
Req = cowboy_req:stream_reply(200, Req0).
-
-
Stream the response with custom headers
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/plain">>
-}, Req0),
-cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
-timer:sleep(1000),
-cowboy_req:stream_body(<<"World!\n">>, fin, Req).
-
-
-
+
Req = cowboy_req:stream_reply(200, #{
+    <<"content-type">> => <<"text/plain">>
+}, Req0),
+cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
+timer:sleep(1000),
+cowboy_req:stream_body(<<"World!\n">>, fin, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:set_resp_cookie(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3), cowboy_req:inform(3), cowboy_req:reply(3), cowboy_req:stream_body(3), cowboy_req:stream_trailers(3), cowboy_req:push(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.stream_trailers/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.stream_trailers/index.html index 9f08091c..6a96ed52 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.stream_trailers/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.stream_trailers/index.html @@ -62,107 +62,55 @@

cowboy_req:stream_trailers(3)

-

Name

-
-

cowboy_req:stream_trailers - Send the response trailers

-
-
-
+

cowboy_req:stream_trailers - Send the response trailers

Description

-
-
-
-
stream_trailers(Trailers, Req :: cowboy_req:req()) -> ok
-
-Trailers :: cowboy:http_headers()
-

Send the response trailers and terminate the stream.

-

This function can only be called once, after initiating -a response using -cowboy_req:stream_reply(3) -and sending zero or more body chunks using -cowboy_req:stream_body(3) -with the nofin argument set. The function stream_trailers/2 -implies fin and automatically terminate the response.

-

You must list all field names sent in trailers in the -trailer header, otherwise they might be dropped by intermediaries -or clients.

-
-
-
+
stream_trailers(Trailers, Req :: cowboy_req:req()) -> ok
+
+Trailers :: cowboy:http_headers()
+
+

Send the response trailers and terminate the stream.

+

This function can only be called once, after initiating a response using cowboy_req:stream_reply(3) and sending zero or more body chunks using cowboy_req:stream_body(3) with the nofin argument set. The function stream_trailers/2 implies fin and automatically terminate the response.

+

You must list all field names sent in trailers in the trailer header, otherwise they might be dropped by intermediaries or clients.

Arguments

-
-
-
-Trailers -
-
-

-Trailer field values to be sent. -

+
Trailers
+

Trailer field values to be sent.

-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The atom ok is always returned. It can be safely ignored.

-
-
-
+

The atom ok is always returned. It can be safely ignored.

Changelog

-
-
    -
  • -

    -2.2: Function introduced. -

    +
    • 2.2: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Stream a response body with trailers
-
-
Req = cowboy_req:stream_reply(200, #{
-    <<"content-type">> => <<"text/plain">>,
-    <<"trailer">> => <<"expires, content-md5">>
-}, Req0),
-cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
-timer:sleep(1000),
-cowboy_req:stream_body(<<"World!\n">>, nofin, Req).
-cowboy_req:stream_trailers(#{
-    <<"expires">> => <<"Sun, 10 Dec 2017 19:13:47 GMT">>,
-    <<"content-md5">> => <<"fbf68a8e34b2ded53bba54e68794b4fe">>
-}, Req).
-
-
-
+
Req = cowboy_req:stream_reply(200, #{
+    <<"content-type">> => <<"text/plain">>,
+    <<"trailer">> => <<"expires, content-md5">>
+}, Req0),
+cowboy_req:stream_body(<<"Hello\n">>, nofin, Req),
+timer:sleep(1000),
+cowboy_req:stream_body(<<"World!\n">>, nofin, Req).
+cowboy_req:stream_trailers(#{
+    <<"expires">> => <<"Sun, 10 Dec 2017 19:13:47 GMT">>,
+    <<"content-md5">> => <<"fbf68a8e34b2ded53bba54e68794b4fe">>
+}, Req).
+

See also

- - +

cowboy_req(3), cowboy_req:stream_reply(3), cowboy_req:stream_body(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.uri/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.uri/index.html index c7e9efc4..e70c3d45 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.uri/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.uri/index.html @@ -62,177 +62,106 @@

cowboy_req:uri(3)

-

Name

-
-

cowboy_req:uri - Reconstructed URI

-
-
-
+

cowboy_req:uri - Reconstructed URI

Description

-
-
-
-
uri(Req :: cowboy_req:req())       -> uri(Req, #{})
-uri(Req :: cowboy_req:req(), Opts) -> URI :: iodata()
-
-Opts :: #{
-    scheme   => iodata()           | undefined,
-    host     => iodata()           | undefined,
-    port     => inet:port_number() | undefined,
-    path     => iodata()           | undefined,
-    qs       => iodata()           | undefined,
-    fragment => iodata()           | undefined
-}
-

Reconstruct the effective request URI, optionally modifying components.

-

By default Cowboy will build a URI using the components found -in the request. Options allow disabling or replacing individual -components.

-
-
-
+
uri(Req :: cowboy_req:req())       -> uri(Req, #{})
+uri(Req :: cowboy_req:req(), Opts) -> URI :: iodata()
+
+Opts :: #{
+    scheme   => iodata()           | undefined,
+    host     => iodata()           | undefined,
+    port     => inet:port_number() | undefined,
+    path     => iodata()           | undefined,
+    qs       => iodata()           | undefined,
+    fragment => iodata()           | undefined
+}
+
+

Reconstruct the effective request URI, optionally modifying components.

+

By default Cowboy will build a URI using the components found in the request. Options allow disabling or replacing individual components.

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-Opts -
-
-

-Map for overriding individual components. -

-

To replace a component, provide its new value as a binary -string or an iolist. To disable a component, set its value -to undefined.

-

As this function always returns a valid URI, there are some -things to note:

-
    -
  • -

    -Disabling the host also disables the scheme and port. -

    +
    Opts
    +

    Map for overriding individual components.

    +

    To replace a component, provide its new value as a binary string or an iolist. To disable a component, set its value to undefined.

    +

    As this function always returns a valid URI, there are some things to note:

    +
    • Disabling the host also disables the scheme and port.
    • -
    • -

      -There is no fragment component by default as these are - not sent with the request. -

      +
    • There is no fragment component by default as these are not sent with the request.
    • -
    • -

      -The port number may not appear in the resulting URI if - it is the default port for the given scheme (http: 80; https: 443). -

      +
    • The port number may not appear in the resulting URI if it is the default port for the given scheme (http: 80; https: 443).
    • -
+
-
-
- -
+

Return value

-
-

The reconstructed URI is returned as an iolist or a binary string.

-
-
-
+

The reconstructed URI is returned as an iolist or a binary string.

Changelog

-
-
    -
  • -

    -2.0: Individual components can be replaced or disabled. -

    +
    • 2.0: Individual components can be replaced or disabled.
    • -
    • -

      -2.0: Only the URI is returned, it is no longer wrapped in a tuple. -

      +
    • 2.0: Only the URI is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -2.0: Function introduced. Replaces host_url/1 and url/1. -

      +
    • 2.0: Function introduced. Replaces host_url/1 and url/1.
    • -
-
-
-
+

Examples

-
-

With an effective request URI http://example.org/path/to/res?edit=1 -we can have:

-
-
Protocol relative form
-
-
%% //example.org/path/to/res?edit=1
-cowboy_req:uri(Req, #{scheme => undefined}).
-
-
Serialized origin for use in the origin header
-
-
%% http://example.org
-cowboy_req:uri(Req, #{path => undefined, qs => undefined}).
-
-
HTTP/1.1 origin form (path and query string only)
-
-
%% /path/to/res?edit=1
-cowboy_req:uri(Req, #{host => undefined}).
-
-
Add a fragment to the URI
-
-
%% http://example.org/path/to/res?edit=1#errors
-cowboy_req:uri(Req, #{fragment => <<"errors">>}).
-
-
Ensure the scheme is HTTPS
-
-
%% https://example.org/path/to/res?edit=1
-cowboy_req:uri(Req, #{scheme => <<"https">>}).
-
-
Convert the URI to a binary string
-
-
iolist_to_binary(cowboy_req:uri(Req)).
-
-
-
+
iolist_to_binary(cowboy_req:uri(Req)).
+

See also

- - +

cowboy_req(3), cowboy_req:scheme(3), cowboy_req:host(3), cowboy_req:port(3), cowboy_req:path(3), cowboy_req:qs(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req.version/index.html b/docs/en/cowboy/2.4/manual/cowboy_req.version/index.html index ad6cb189..ecf55796 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req.version/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req.version/index.html @@ -62,88 +62,47 @@

cowboy_req:version(3)

-

Name

-
-

cowboy_req:version - HTTP version

-
-
-
+

cowboy_req:version - HTTP version

Description

-
-
-
-
version(Req :: cowboy_req:req()) -> Version :: cowboy:http_version()
-

Return the HTTP version used for the request.

-

The version can also be obtained using pattern matching:

-
-
-
#{version := Version} = Req.
-
-
-
+
#{version := Version} = Req.
+

Arguments

-
-
-
-Req -
-
-

-The Req object. -

+
Req
+

The Req object.

-
-
- -
+

Return value

-
-

The HTTP version used for the request is returned as an -atom. It is provided for informative purposes only.

-
-
-
+

The HTTP version used for the request is returned as an atom. It is provided for informative purposes only.

Changelog

-
-
    -
  • -

    -2.0: Only the version is returned, it is no longer wrapped in a tuple. -

    +
    • 2.0: Only the version is returned, it is no longer wrapped in a tuple.
    • -
    • -

      -1.0: Function introduced. -

      +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get the HTTP version
-
-
Version = cowboy_req:version(Req).
-
-
-
+
Version = cowboy_req:version(Req).
+

See also

- - +

cowboy_req(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_req/index.html b/docs/en/cowboy/2.4/manual/cowboy_req/index.html index 27795e51..f8d793ab 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_req/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_req/index.html @@ -62,414 +62,218 @@

cowboy_req(3)

-

Name

-
-

cowboy_req - HTTP request and response

-
-
-
+

cowboy_req - HTTP request and response

Description

-
-

The module cowboy_req provides functions to access, manipulate -and respond to requests.

-

There are four types of functions in this module. They can be -differentiated by their name and their return type:

-
- ---- - - - - - - - - - - - +

The module cowboy_req provides functions to access, manipulate and respond to requests.

+

There are four types of functions in this module. They can be differentiated by their name and their return type:

+
Type Name pattern Return type

access

no verb, parse_*, match_*

Value

+ + + + + + - - - - + + + - - - - + + + - - - - + + + - -
TypeName patternReturn type
accessno verb, parse_*, match_*Value

question

has_*

boolean()

questionhas_*boolean()

modification

set_*

Req

modificationset_*Req

action

any other verb

ok | {Result, Value, Req}

actionany other verbok | {Result, Value, Req}
-
-

Any Req returned must be used in place of the one passed as -argument. Functions that perform an action in particular write -state in the Req object to make sure you are using the function -correctly. For example, it’s only possible to send one response, -and to read the body once.

-
-
-
+ +

Any Req returned must be used in place of the one passed as argument. Functions that perform an action in particular write state in the Req object to make sure you are using the function correctly. For example, it's only possible to send one response, and to read the body once.

Exports

-
-

Connection:

-
-

Raw request:

-
-

Processed request:

-
-

Request body:

-
-

Response:

-
-
-
-
+

Connection:

+ +

Raw request:

+ +

Processed request:

+ +

Request body:

+ +

Response:

+

Types

-
-

push_opts()

-
-
-
push_opts() :: #{
-    method => binary(),            %% case sensitive
-    scheme => binary(),            %% lowercase; case insensitive
-    host   => binary(),            %% lowercase; case insensitive
-    port   => inet:port_number(),
-    qs     => binary()             %% case sensitive
-}
-

Push options.

-

By default, Cowboy will use the GET method, an empty query string, -and take the scheme, host and port directly from the current -request’s URI.

-
-
+
push_opts() :: #{
+    method => binary(),            %% case sensitive
+    scheme => binary(),            %% lowercase; case insensitive
+    host   => binary(),            %% lowercase; case insensitive
+    port   => inet:port_number(),
+    qs     => binary()             %% case sensitive
+}
+
+

Push options.

+

By default, Cowboy will use the GET method, an empty query string, and take the scheme, host and port directly from the current request's URI.

read_body_opts()

-
-
-
read_body_opts() :: #{
-    length  => non_neg_integer(),
-    period  => non_neg_integer(),
-    timeout => timeout()
-}
-

Body reading options.

-

The defaults are function-specific.

-
-
+
read_body_opts() :: #{
+    length  => non_neg_integer(),
+    period  => non_neg_integer(),
+    timeout => timeout()
+}
+
+

Body reading options.

+

The defaults are function-specific.

req()

-
-
-
req() :: #{
-    method  := binary(),               %% case sensitive
-    version := cowboy:http_version() | atom(),
-    scheme  := binary(),               %% lowercase; case insensitive
-    host    := binary(),               %% lowercase; case insensitive
-    port    := inet:port_number(),
-    path    := binary(),               %% case sensitive
-    qs      := binary(),               %% case sensitive
-    headers := cowboy:http_headers(),
-    peer    := {inet:ip_address(), inet:port_number()},
-    sock    := {inet:ip_address(), inet:port_number()},
-    cert    := binary() | undefined
-}
-

The Req object.

-

Contains information about the request and response. While -some fields are publicly documented, others aren’t and shouldn’t -be used.

-

You may add custom fields if required. Make sure to namespace -them by prepending an underscore and the name of your application:

-
-
Setting a custom field
-
-
Req#{_myapp_auth_method => pubkey}.
- -
+
Req#{_myapp_auth_method => pubkey}.
+

resp_body()

-
-
-
resp_body() :: iodata()
-    | {sendfile, Offset, Length, Filename}
+
resp_body() :: iodata()
+    | {sendfile, Offset, Length, Filename}
 
-Offset   :: non_neg_integer()
-Length   :: non_neg_integer()
-Filename :: file:name_all()
-

Response body.

-

It can take two forms: the actual data to be sent or a -tuple indicating which file to send.

-

When sending data directly, the type is either a binary or -an iolist. Iolists are an efficient way to build output. -Instead of concatenating strings or binaries, you can simply -build a list containing the fragments you want to send in the -order they should be sent:

-
-
Example iolists usage
-
-
1> RespBody = ["Hello ", [<<"world">>, $!]].
-["Hello ",[<<"world">>,33]]
-2> io:format("~s~n", [RespBody]).
-Hello world!
-

Note that the length must be greater than zero for any data -to be sent. Cowboy will send an empty body when the length -is zero.

- - - -
+
1> RespBody = ["Hello ", [<<"world">>, $!]].
+["Hello ",[<<"world">>,33]]
+2> io:format("~s~n", [RespBody]).
+Hello world!
+
+

Note that the length must be greater than zero for any data to be sent. Cowboy will send an empty body when the length is zero.

See also

- - +

cowboy(7)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_rest/index.html b/docs/en/cowboy/2.4/manual/cowboy_rest/index.html index 1c8bed7c..77a021bb 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_rest/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_rest/index.html @@ -62,670 +62,475 @@

cowboy_rest(3)

-

Name

-
-

cowboy_rest - REST handlers

-
-
-
+

cowboy_rest - REST handlers

Description

-
-

The module cowboy_rest implements the HTTP state machine.

-

Implementing REST handlers is not enough to provide a REST -interface; this interface must also follow the REST -constraints including HATEOAS (hypermedia as the engine -of application state).

-
-
-
+

The module cowboy_rest implements the HTTP state machine.

+

Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state).

Callbacks

-
-

REST handlers implement the following interface:

-
-
-
init(Req, State)
-    -> {cowboy_rest, Req, State}
-
-Callback(Req, State)
-    -> {Result, Req, State}
-     | {stop, Req, State}
-     | {{switch_handler, Module}, Req, State}
-     | {{switch_handler, Module, Opts}, Req, State}
-
-terminate(Reason, Req, State) -> ok  %% optional
-
-Req    :: cowboy_req:req()
-State  :: any()
-Module :: module()
-Opts   :: any()
-Reason :: normal
-        | {crash, error | exit | throw, any()}
-
-Callback - see below
-Result   - see below
-Default  - see below
-

The init/2 callback is common to all handlers. To switch -to the REST handler behavior, it must return cowboy_rest -as the first element of the tuple.

-

The Callback/2 above represents all the REST-specific -callbacks. They are described in the following section -of this manual. REST-specific callbacks differ by their -name, semantics, result and default values. The default -value is the one used when the callback has not been -implemented. They otherwise all follow the same interface.

-

The stop tuple can be returned to stop REST processing. -If no response was sent before then, Cowboy will send a -204 No Content. The stop tuple can be returned from -any callback, excluding expires, generate_etag, -last_modified and variances.

-

A switch_handler tuple can be returned from these same -callbacks to stop REST processing and switch to a different -handler type. This is very useful to, for example, to stream -the response body.

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the handler. -Cowboy will terminate the process right after this. There -is no need to perform any cleanup in this callback.

-

The following terminate reasons are defined for loop handlers:

-
-
-normal -
-
-

- The handler terminated normally. -

+

REST handlers implement the following interface:

+
+
init(Req, State)
+    -> {cowboy_rest, Req, State}
+
+Callback(Req, State)
+    -> {Result, Req, State}
+     | {stop, Req, State}
+     | {{switch_handler, Module}, Req, State}
+     | {{switch_handler, Module, Opts}, Req, State}
+
+terminate(Reason, Req, State) -> ok  %% optional
+
+Req    :: cowboy_req:req()
+State  :: any()
+Module :: module()
+Opts   :: any()
+Reason :: normal
+        | {crash, error | exit | throw, any()}
+
+Callback - see below
+Result   - see below
+Default  - see below
+
+

The init/2 callback is common to all handlers. To switch to the REST handler behavior, it must return cowboy_rest as the first element of the tuple.

+

The Callback/2 above represents all the REST-specific callbacks. They are described in the following section of this manual. REST-specific callbacks differ by their name, semantics, result and default values. The default value is the one used when the callback has not been implemented. They otherwise all follow the same interface.

+

The stop tuple can be returned to stop REST processing. If no response was sent before then, Cowboy will send a 204 No Content. The stop tuple can be returned from any callback, excluding expires, generate_etag, last_modified and variances.

+

A switch_handler tuple can be returned from these same callbacks to stop REST processing and switch to a different handler type. This is very useful to, for example, to stream the response body.

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the handler. Cowboy will terminate the process right after this. There is no need to perform any cleanup in this callback.

+

The following terminate reasons are defined for loop handlers:

+
normal
+

The handler terminated normally.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
-
-
-
+

REST callbacks

-
-

AcceptCallback

-
-
-
AcceptCallback(Req, State) -> {Result, Req, State}
-
-Result  :: true | {true, URI :: iodata()} | false}
-Default  - crash
-

Process the request body.

-

This function should create or update the resource using the -request body.

-

For PUT requests, the body is a representation of the resource -that is being created or replaced.

-

For POST requests, the body is typically application-specific -instructions on how to process the request, but it may also -be a representation of the resource. When creating a new -resource with POST at a different location, return {true, URI} -with URI the new location.

-

For PATCH requests, the body is a series of instructions on -how to update the resource. Patch files or JSON Patch are -examples of such media types.

-

A response body may be sent. The appropriate media type, charset -and language for the response can be retrieved from the Req -object using the media_type, charset and language keys, -respectively. The body can be set using -cowboy_req:set_resp_body(3).

-
-
+
+
AcceptCallback(Req, State) -> {Result, Req, State}
+
+Result  :: true | {true, URI :: iodata()} | false}
+Default  - crash
+
+

Process the request body.

+

This function should create or update the resource using the request body.

+

For PUT requests, the body is a representation of the resource that is being created or replaced.

+

For POST requests, the body is typically application-specific instructions on how to process the request, but it may also be a representation of the resource. When creating a new resource with POST at a different location, return {true, URI} with URI the new location.

+

For PATCH requests, the body is a series of instructions on how to update the resource. Patch files or JSON Patch are examples of such media types.

+

A response body may be sent. The appropriate media type, charset and language for the response can be retrieved from the Req object using the media_type, charset and language keys, respectively. The body can be set using cowboy_req:set_resp_body(3).

allowed_methods

-
-
-
allowed_methods(Req, State) -> {Result, Req, State}
+
allowed_methods(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% case sensitive
-Default :: [<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]
-

Return the list of allowed methods.

-
-
+Result :: [binary()] %% case sensitive +Default :: [<<"GET">>, <<"HEAD">>, <<"OPTIONS">>] +
+

Return the list of allowed methods.

allow_missing_post

-
-
-
allow_missing_post(Req, State) -> {Result, Req, State}
+
allow_missing_post(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether POST is allowed when the resource doesn’t exist.

-

Returning true here means that a new resource will be -created. The URI for the newly created resource should be -returned from the AcceptCallback function.

-
-
+Result :: boolean() +Default :: true +
+

Return whether POST is allowed when the resource doesn't exist.

+

Returning true here means that a new resource will be created. The URI for the newly created resource should be returned from the AcceptCallback function.

charsets_provided

-
-
-
charsets_provided(Req, State) -> {Result, Req, State}
+
charsets_provided(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% lowercase; case insensitive
-Default  - skip this step
-

Return the list of charsets the resource provides in order -of preference.

-

During content negotiation Cowboy will pick the most -appropriate charset for the client. The client advertises -charsets it prefers with the accept-charset header. When -that header is missing, Cowboy picks the first charset -from the resource.

-

Cowboy will add the negotiated charset to the Req object -after this step completes:

-
-
+

Cowboy will add the negotiated charset to the Req object after this step completes:

+
-
req() :: #{
-    charset => binary()  %% lowercase; case insensitive
-}
-
-
+
req() :: #{
+    charset => binary()  %% lowercase; case insensitive
+}
+

content_types_accepted

-
-
-
content_types_accepted(Req, State) -> {Result, Req, State}
-
-Result     :: [{binary() | ParsedMime, AcceptCallback :: atom()}]
-ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-
-Default     - crash
-

Return the list of media types the resource accepts in -order of preference.

-

A media type is made of different parts. The media type -text/html;charset=utf-8 is of type text, subtype html -and has a single parameter charset with value utf-8.

-

Cowboy will match the content-type request header against -the media types the server accepts and select the appropriate -callback. When that header is missing, or when the server does not -accept this media type, the request fails and an error response -is returned. Cowboy will execute the callback immediately otherwise.

-

An empty parameters list [] means that no parameters will be -accepted. When any parameter is acceptable, the tuple form -should be used with parameters as the atom '*'.

-

Cowboy treats all parameters as case sensitive, except for the -charset parameter, which is known to be case insensitive. You -should therefore always provide the charset as a lowercase -binary string.

- -
+
+
content_types_accepted(Req, State) -> {Result, Req, State}
+
+Result     :: [{binary() | ParsedMime, AcceptCallback :: atom()}]
+ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+Default     - crash
+
+ +

Return the list of media types the resource accepts in order of preference.

+

A media type is made of different parts. The media type text/html;charset=utf-8 is of type text, subtype html and has a single parameter charset with value utf-8.

+ + + +

Cowboy will match the content-type request header against the media types the server accepts and select the appropriate callback. When that header is missing, or when the server does not accept this media type, the request fails and an error response is returned. Cowboy will execute the callback immediately otherwise.

+ +

An empty parameters list [] means that no parameters will be accepted. When any parameter is acceptable, the tuple form should be used with parameters as the atom '*'.

+

Cowboy treats all parameters as case sensitive, except for the charset parameter, which is known to be case insensitive. You should therefore always provide the charset as a lowercase binary string.

+ + + + + +

content_types_provided

-
-
-
content_types_provided(Req, State) -> {Result, Req, State}
-
-Result     :: [{binary() | ParsedMime, ProvideCallback :: atom()}]
-ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-
-Default     - [{{ <<"text">>, <<"html">>, '*'}, to_html}]
-

Return the list of media types the resource provides in -order of preference.

-

A media type is made of different parts. The media type -text/html;charset=utf-8 is of type text, subtype html -and has a single parameter charset with value utf-8.

-

During content negotiation Cowboy will pick the most appropriate -media type for the client. The client advertises media types it -prefers with the accept header. When that header is missing, -the content negotiation fails and an error response is returned.

-

The callback given for the selected media type will be called -at the end of the execution of GET and HEAD requests when a -representation must be sent to the client.

-

An empty parameters list [] means that no parameters will be -accepted. When any parameter is acceptable, the tuple form -should be used with parameters as the atom '*'.

-

Cowboy treats all parameters as case sensitive, except for the -charset parameter, which is known to be case insensitive. You -should therefore always provide the charset as a lowercase -binary string.

-

Cowboy will add the negotiated media_type to the Req object -after this step completes:

-
-
-
req() :: #{
-    media_type => ParsedMime
-}
-
-
+
+
content_types_provided(Req, State) -> {Result, Req, State}
+
+Result     :: [{binary() | ParsedMime, ProvideCallback :: atom()}]
+ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+Default     - [{{ <<"text">>, <<"html">>, '*'}, to_html}]
+
+ + +

Return the list of media types the resource provides in order of preference.

+

A media type is made of different parts. The media type text/html;charset=utf-8 is of type text, subtype html and has a single parameter charset with value utf-8.

+ + + +

During content negotiation Cowboy will pick the most appropriate media type for the client. The client advertises media types it prefers with the accept header. When that header is missing, the content negotiation fails and an error response is returned.

+

The callback given for the selected media type will be called at the end of the execution of GET and HEAD requests when a representation must be sent to the client.

+ +

An empty parameters list [] means that no parameters will be accepted. When any parameter is acceptable, the tuple form should be used with parameters as the atom '*'.

+

Cowboy treats all parameters as case sensitive, except for the charset parameter, which is known to be case insensitive. You should therefore always provide the charset as a lowercase binary string.

+

Cowboy will add the negotiated media_type to the Req object after this step completes:

+
+
req() :: #{
+    media_type => ParsedMime
+}
+
+

delete_completed

-
-
-
delete_completed(Req, State) -> {Result, Req, State}
+
delete_completed(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the resource has been fully deleted from the -system, including from any internal cache.

-

Returning false will result in a 202 Accepted response -being sent instead of a 200 OK or 204 No Content.

-
-
+Result :: boolean() +Default :: true +
+

Return whether the resource has been fully deleted from the system, including from any internal cache.

+

Returning false will result in a 202 Accepted response being sent instead of a 200 OK or 204 No Content.

delete_resource

-
-
-
delete_resource(Req, State) -> {Result, Req, State}
+
delete_resource(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Delete the resource.

-

Cowboy will send an error response when this function -returns false.

- -
+Result :: boolean() +Default :: false +
+

Delete the resource.

+

Cowboy will send an error response when this function returns false.

expires

-
-
-
expires(Req, State) -> {Result, Req, State}
+
expires(Req, State) -> {Result, Req, State}
 
-Result  :: calendar:datetime() | binary() | undefined
-Default :: undefined
-

Return the resource’s expiration date.

- -
+Result :: calendar:datetime() | binary() | undefined +Default :: undefined +
+

Return the resource's expiration date.

forbidden

-
-
-
forbidden(Req, State) -> {Result, Req, State}
+
forbidden(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether access to the resource is forbidden.

-

A 403 Forbidden response will be sent if this -function returns true. This status code means that -access is forbidden regardless of authentication, -and that the request shouldn’t be repeated.

- -
+Result :: boolean() +Default :: false +
+

Return whether access to the resource is forbidden.

+

A 403 Forbidden response will be sent if this function returns true. This status code means that access is forbidden regardless of authentication, and that the request shouldn't be repeated.

generate_etag

-
-
-
generate_etag(Req, State) -> {Result, Req, State}
+
generate_etag(Req, State) -> {Result, Req, State}
 
-Result  :: binary() | {weak | strong, binary()}
-Default  - no etag value
-

Return the entity tag of the resource.

-

When a binary is returned, the value is automatically -parsed to a tuple. The binary must be in the same -format as the etag header, including quotes.

- -
+Result :: binary() | {weak | strong, binary()} +Default - no etag value +
+

Return the entity tag of the resource.

+

When a binary is returned, the value is automatically parsed to a tuple. The binary must be in the same format as the etag header, including quotes.

is_authorized

-
-
-
is_authorized(Req, State) -> {Result, Req, State}
+
is_authorized(Req, State) -> {Result, Req, State}
 
-Result  :: true | {false, AuthHeader :: iodata()}
-Default  - true
-

Return whether the user is authorized to perform the action.

-

This function should be used to perform any necessary -authentication of the user before attempting to perform -any action on the resource.

-

When authentication fails, the AuthHeader value will -be sent in the www-authenticate header for the -401 Unauthorized response.

- -
+Result :: true | {false, AuthHeader :: iodata()} +Default - true +
+

Return whether the user is authorized to perform the action.

+

This function should be used to perform any necessary authentication of the user before attempting to perform any action on the resource.

+

When authentication fails, the AuthHeader value will be sent in the www-authenticate header for the 401 Unauthorized response.

is_conflict

-
-
-
is_conflict(Req, State) -> {Result, Req, State}
+
is_conflict(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the PUT request results in a conflict.

-

A 409 Conflict response is sent when true.

- -
+Result :: boolean() +Default :: false +
+

Return whether the PUT request results in a conflict.

+

A 409 Conflict response is sent when true.

known_methods

-
-
-
known_methods(Req, State) -> {Result, Req, State}
+
known_methods(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% case sensitive
-Default :: [<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>,
-            <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]
-

Return the list of known methods.

-

The full list of methods known by the server should be -returned, regardless of their use in the resource.

-

The default value lists the methods Cowboy knows and -implement in cowboy_rest.

- -
+Result :: [binary()] %% case sensitive +Default :: [<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, + <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>] +
+

Return the list of known methods.

+

The full list of methods known by the server should be returned, regardless of their use in the resource.

+

The default value lists the methods Cowboy knows and implement in cowboy_rest.

languages_provided

-
-
-
languages_provided(Req, State) -> {Result, Req, State}
+
languages_provided(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% lowercase; case insensitive
-Default  - skip this step
-

Return the list of languages the resource provides in order -of preference.

-

During content negotiation Cowboy will pick the most -appropriate language for the client. The client advertises -languages it prefers with the accept-language header. When -that header is missing, Cowboy picks the first language -from the resource.

-

Cowboy will add the negotiated language to the Req object -after this step completes:

-
-
+

Cowboy will add the negotiated language to the Req object after this step completes:

+
-
req() :: #{
-    language => binary()  %% lowercase; case insensitive
-}
-
-
+
req() :: #{
+    language => binary()  %% lowercase; case insensitive
+}
+

last_modified

-
-
-
last_modified(Req, State) -> {Result, Req, State}
+
last_modified(Req, State) -> {Result, Req, State}
 
-Result  :: calendar:datetime()
-Default  - no last modified value
-

Return the resource’s last modification date.

-

This date will be used to test against the if-modified-since -and if-unmodified-since headers, and sent as the last-modified -header in the response to GET and HEAD requests.

- -
+Result :: calendar:datetime() +Default - no last modified value +
+

Return the resource's last modification date.

+

This date will be used to test against the if-modified-since and if-unmodified-since headers, and sent as the last-modified header in the response to GET and HEAD requests.

malformed_request

-
-
-
malformed_request(Req, State) -> {Result, Req, State}
+
malformed_request(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the request is malformed.

-

A request is malformed when a component required by the -resource is invalid. This may include the query string -or individual headers. They should be parsed and validated -in this function. The body should not be read at this point.

- -
+Result :: boolean() +Default :: false +
+

Return whether the request is malformed.

+

A request is malformed when a component required by the resource is invalid. This may include the query string or individual headers. They should be parsed and validated in this function. The body should not be read at this point.

moved_permanently

-
-
-
moved_permanently(Req, State) -> {Result, Req, State}
+
moved_permanently(Req, State) -> {Result, Req, State}
 
-Result  :: {true, URI :: iodata()} | false
-Default :: false
-

Return whether the resource was permanently moved, and -what its new location is.

- -
+Result :: {true, URI :: iodata()} | false +Default :: false +
+

Return whether the resource was permanently moved, and what its new location is.

moved_temporarily

-
-
-
moved_temporarily(Req, State) -> {Result, Req, State}
+
moved_temporarily(Req, State) -> {Result, Req, State}
 
-Result  :: {true, URI :: iodata()} | false
-Default :: false
-

Return whether the resource was temporarily moved, and -what its new location is.

- -
+Result :: {true, URI :: iodata()} | false +Default :: false +
+

Return whether the resource was temporarily moved, and what its new location is.

multiple_choices

-
-
-
multiple_choices(Req, State) -> {Result, Req, State}
-
-Result  :: boolean()
-Default :: false
-

Return whether the client should engage in reactive -negotiation.

-

Return true when the server has multiple representations -of a resource, each with their specific identifier, but is -unable to determine which is best for the client. For -example an image might have different sizes and the server -is unable to determine the capabilities of the client.

-

When returning true the server should send a body with -links to the different representations. If the server has -a preferred representation it can send its link inside a -location header.

- -
+
+
multiple_choices(Req, State) -> {Result, Req, State}
+
+Result  :: boolean()
+Default :: false
+
+

Return whether the client should engage in reactive negotiation.

+

Return true when the server has multiple representations of a resource, each with their specific identifier, but is unable to determine which is best for the client. For example an image might have different sizes and the server is unable to determine the capabilities of the client.

+

When returning true the server should send a body with links to the different representations. If the server has a preferred representation it can send its link inside a location header.

options

-
-
-
options(Req, State) -> {ok, Req, State}
-

Respond to an OPTIONS request.

-

The response should inform the client the communication -options available for this resource. By default Cowboy -will send a 200 OK response with the allow header set.

-
-
+
options(Req, State) -> {ok, Req, State}
+
+

Respond to an OPTIONS request.

+

The response should inform the client the communication options available for this resource. By default Cowboy will send a 200 OK response with the allow header set.

previously_existed

-
-
-
previously_existed(Req, State) -> {Result, Req, State}
+
previously_existed(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the resource existed previously.

- -
+Result :: boolean() +Default :: false +
+

Return whether the resource existed previously.

ProvideCallback

-
-
-
ProvideCallback(Req, State) -> {Result, Req, State}
+
ProvideCallback(Req, State) -> {Result, Req, State}
 
-Result  :: cowboy_req:resp_body()
-Default  - crash
-

Return the response body.

-

The response body can be provided either as the actual data -to be sent or a tuple indicating which file to send.

-

This function is called for both GET and HEAD requests. For -the latter the body is not sent, however.

-

Note that there used to be a way to stream the response body. -It was temporarily removed and will be added back in a later -release.

- -
+Result :: cowboy_req:resp_body() +Default - crash +
+

Return the response body.

+

The response body can be provided either as the actual data to be sent or a tuple indicating which file to send.

+

This function is called for both GET and HEAD requests. For the latter the body is not sent, however.

+ + + +

Note that there used to be a way to stream the response body. It was temporarily removed and will be added back in a later release.

+

resource_exists

-
-
-
resource_exists(Req, State) -> {Result, Req, State}
+
resource_exists(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the resource exists.

- -
+Result :: boolean() +Default :: true +
+

Return whether the resource exists.

service_available

-
-
-
service_available(Req, State) -> {Result, Req, State}
+
service_available(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the service is available.

-

A 503 Service Unavailable response will be sent when this -function returns false.

- -
+Result :: boolean() +Default :: true +
+

Return whether the service is available.

+

A 503 Service Unavailable response will be sent when this function returns false.

uri_too_long

-
-
-
uri_too_long(Req, State) -> {Result, Req, State}
+
uri_too_long(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: false
-

Return whether the requested URI is too long.

-

This function can be used to further restrict the length -of the URI for this specific resource.

- -
+Result :: boolean() +Default :: false +
+

Return whether the requested URI is too long.

+

This function can be used to further restrict the length of the URI for this specific resource.

valid_content_headers

-
-
-
valid_content_headers(Req, State) -> {Result, Req, State}
+
valid_content_headers(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the content headers are valid.

-

This callback can be used to reject requests that have -invalid content header values, for example an unsupported -content-encoding.

- -
+Result :: boolean() +Default :: true +
+

Return whether the content headers are valid.

+

This callback can be used to reject requests that have invalid content header values, for example an unsupported content-encoding.

valid_entity_length

-
-
-
valid_entity_length(Req, State) -> {Result, Req, State}
+
valid_entity_length(Req, State) -> {Result, Req, State}
 
-Result  :: boolean()
-Default :: true
-

Return whether the request body length is within acceptable boundaries.

-

A 413 Request Entity Too Large response will be sent if this -function returns false.

- -
+Result :: boolean() +Default :: true +
+

Return whether the request body length is within acceptable boundaries.

+

A 413 Request Entity Too Large response will be sent if this function returns false.

variances

-
-
-
variances(Req, State) -> {Result, Req, State}
+
variances(Req, State) -> {Result, Req, State}
 
-Result  :: [binary()]  %% case insensitive
-Default :: []
-

Return the list of request headers that affect the -representation of the resource.

-

Cowboy automatically adds the accept, accept-charset and -accept-language headers when necessary. It’s also useful -to note that some standard headers also do not need to be -listed here, like the authorization header.

- - - -
+Result :: [binary()] %% case insensitive +Default :: [] +
+

Return the list of request headers that affect the representation of the resource.

+

Cowboy automatically adds the accept, accept-charset and accept-language headers when necessary. It's also useful to note that some standard headers also do not need to be listed here, like the authorization header.

Changelog

-
-
    -
  • -

    -2.1: The switch_handler return value was added. -

    +
    • 2.1: The switch_handler return value was added.
    • -
    • -

      -1.0: Behavior introduced. -

      +
    • 1.0: Behavior introduced.
    • -
-
- -
+

See also

- -
+

cowboy(7), cowboy_handler(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_router.compile/index.html b/docs/en/cowboy/2.4/manual/cowboy_router.compile/index.html index c3eb3884..1aac627b 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_router.compile/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_router.compile/index.html @@ -62,87 +62,48 @@

cowboy_router:compile(3)

-

Name

-
-

cowboy_router:compile - Compile routes to the resources

-
-
-
+

cowboy_router:compile - Compile routes to the resources

Description

-
-
-
-
compile(cowboy_router:routes()) -> cowboy_router:dispatch_rules()
-

Compile routes to the resources.

-

Takes a human readable list of routes and transforms it -into a form more efficient to process.

-
-
-
+
compile(cowboy_router:routes()) -> cowboy_router:dispatch_rules()
+
+

Compile routes to the resources.

+

Takes a human readable list of routes and transforms it into a form more efficient to process.

Arguments

-
-
-
-Routes -
-
-

-Human readable list of routes. -

+
Routes
+

Human readable list of routes.

-
-
- -
+

Return value

-
-

An opaque dispatch rules value is returned. This value -must be given to Cowboy as a middleware environment value.

-
-
-
+

An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Compile routes and start a listener
-
-
Dispatch = cowboy_router:compile([
-    {'_', [
-        {"/", toppage_h, []},
-        {"/[...], cowboy_static, {priv_dir, my_example_app, ""}}
-    ]}
-]),
-
-{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{
-    env => #{dispatch => Dispatch}
-}).
-
-
-
+
Dispatch = cowboy_router:compile([
+    {'_', [
+        {"/", toppage_h, []},
+        {"/[...], cowboy_static, {priv_dir, my_example_app, ""}}
+    ]}
+]),
+
+{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{
+    env => #{dispatch => Dispatch}
+}).
+

See also

- - +

cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_router/index.html b/docs/en/cowboy/2.4/manual/cowboy_router/index.html index 0169ae42..e08c3983 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_router/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_router/index.html @@ -62,110 +62,65 @@

cowboy_router(3)

-

Name

-
-

cowboy_router - Router middleware

-
-
-
+

cowboy_router - Router middleware

Description

-
-

The cowboy_router middleware maps the requested host and -path to the handler to be used for processing the request.

-

The router takes the dispatch rules as input from the -middleware environment. Dispatch rules are generated by -calling the -cowboy_router:compile(3) -function.

-

When a route matches, the router sets the handler and -handler_opts middleware environment values containing -the handler module and initial state, respectively.

-

The router will stop execution when no route matches. -It will send a 400 response if no host was found, and -a 404 response otherwise.

-
-
-
+

The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request.

+

The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function.

+

When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively.

+

The router will stop execution when no route matches. It will send a 400 response if no host was found, and a 404 response otherwise.

Exports

-
-
-
-
-
+

Types

-
-

bindings()

-
-
-
bindings() :: #{atom() => any()}
-

Bindings found during routing.

-
-
+
bindings() :: #{atom() => any()}
+
+

Bindings found during routing.

dispatch_rules()

-

Opaque type containing the compiled routes.

-
-
+

Opaque type containing the compiled routes.

routes()

-
-
-
routes() = [
-    {Host, PathList} |
-    {Host, Fields, PathList}
+
routes() = [
+    {Host, PathList} |
+    {Host, Fields, PathList}
 ]
 
-PathList :: [
-    {Path, Handler, InitialState} |
-    {Path, Fields, Handler, InitialState}
+PathList :: [
+    {Path, Handler, InitialState} |
+    {Path, Fields, Handler, InitialState}
 ]
 
-Host         :: '_' | iodata()
-Path         :: '_' | iodata()
-Fields       :: cowboy:fields()
-Handler      :: module()
-InitialState :: any()
-

Human readable list of routes to handlers.

-

Cowboy uses this list to map hosts and paths, optionally -augmented with constraints applied to the bindings, to -handler modules.

-

The syntax for routes is currently defined in the user guide.

-
-
+Host :: '_' | iodata() +Path :: '_' | iodata() +Fields :: cowboy:fields() +Handler :: module() +InitialState :: any() +
+

Human readable list of routes to handlers.

+

Cowboy uses this list to map hosts and paths, optionally augmented with constraints applied to the bindings, to handler modules.

+

The syntax for routes is currently defined in the user guide.

+ +

tokens()

-
-
-
tokens() :: [binary()]
-

List of host_info and path_info tokens that were found -using the ... syntax.

- - - -
+
tokens() :: [binary()]
+
+

List of host_info and path_info tokens that were found using the ... syntax.

See also

- - +

cowboy(7), cowboy_req:binding(3), cowboy_req:bindings(3), cowboy_req:host_info(3), cowboy_req:path_info(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_static/index.html b/docs/en/cowboy/2.4/manual/cowboy_static/index.html index d1bfd062..0bad63bb 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_static/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_static/index.html @@ -62,175 +62,110 @@

cowboy_static(3)

-

Name

-
-

cowboy_static - Static file handler

-
-
-
+

cowboy_static - Static file handler

Description

-
-

The module cowboy_static implements file serving capabilities -using the REST semantics provided by cowboy_rest.

-

The static file handler is a pre-written handler coming with -Cowboy. To serve files, use it in your routes.

-
-
-
+

The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest.

+

The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes.

Options

-
-
-
-
opts() :: {priv_file, App, Path}
-        | {priv_file, App, Path, Extra}
-        | {file, Path}
-        | {file, Path, Extra}
-        | {priv_dir, App, Path}
-        | {priv_dir, App, Path, Extra}
-        | {dir, Path}
-        | {dir, Path, Extra}
-
-App        :: atom()
-Path       :: binary() | string()
-Extra      :: [Etag | Mimetypes]
-
-Etag       :: {etag, module(), function()}
-            | {etag, false}
-
-Mimetypes  :: {mimetypes, module(), function()}
-            | {mimetypes, binary() | ParsedMime}
-
-ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-

Static handler configuration.

-
-
-priv_file -
-
-

-Send a file. -

-

The path is relative to the given application’s private -directory.

+
opts() :: {priv_file, App, Path}
+        | {priv_file, App, Path, Extra}
+        | {file, Path}
+        | {file, Path, Extra}
+        | {priv_dir, App, Path}
+        | {priv_dir, App, Path, Extra}
+        | {dir, Path}
+        | {dir, Path, Extra}
+
+App        :: atom()
+Path       :: binary() | string()
+Extra      :: [Etag | Mimetypes]
+
+Etag       :: {etag, module(), function()}
+            | {etag, false}
+
+Mimetypes  :: {mimetypes, module(), function()}
+            | {mimetypes, binary() | ParsedMime}
+
+ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+

Static handler configuration.

+
priv_file
+

Send a file.

+

The path is relative to the given application's private directory.

-
-file -
-
-

-Send a file. -

-

The path is either absolute or relative to the Erlang node’s -current directory.

+
file
+

Send a file.

+

The path is either absolute or relative to the Erlang node's current directory.

-
-priv_dir -
-
-

-Recursively serve files from a directory. -

-

The path is relative to the given application’s private -directory.

+
priv_dir
+

Recursively serve files from a directory.

+

The path is relative to the given application's private directory.

-
-dir -
-
-

-Recursively serve files from a directory. -

-

The path is either absolute or relative to the Erlang node’s -current directory.

+
dir
+

Recursively serve files from a directory.

+

The path is either absolute or relative to the Erlang node's current directory.

-
-

The extra options allow you to define how the etag should be -calculated and how the MIME type of files should be detected.

-

By default the static handler will generate an etag based -on the size and modification time of the file. You may disable -the etag entirely with {etag, false} or provide a module -and function that will be called when needed:

-
-
-
generate_etag(Path, Size, Mtime) -> {strong | weak, binary()}
-
-Path  :: binary()
-Size  :: non_neg_integer()
-Mtime :: file:date_time()
-

By default the static handler will detect Web-related MIME types -by looking at the file extension. You can provide a specific -MIME type that will always be used, or a module and function that -will be called when needed:

-
-
-
detect_mimetype(Path) -> ParsedMime
-
-Path       :: binary()
-ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
-Params     :: [{Key :: binary(), Value :: binary()}]
-

Cowboy comes with two such functions; the default function -cow_mimetypes:web/1, and a second function generated from -the Apache mime.types file, cow_mimetypes:all/1.

-

The MIME type function should return -{<<"application">>, <<"octet-stream">>, []} -when it fails to detect a file’s MIME type.

- - -
+
detect_mimetype(Path) -> ParsedMime
+
+Path       :: binary()
+ParsedMime :: {Type :: binary(), SubType :: binary(), Params}
+Params     :: [{Key :: binary(), Value :: binary()}]
+
+ +

Cowboy comes with two such functions; the default function cow_mimetypes:web/1, and a second function generated from the Apache mime.types file, cow_mimetypes:all/1.

+

The MIME type function should return {<<"application">>, <<"octet-stream">>, []} when it fails to detect a file's MIME type.

Changelog

-
-
    -
  • -

    -1.0: Handler introduced. -

    +
    • 1.0: Handler introduced.
    • -
-
- -
+

Examples

-
-
-
Custom etag function
-
-
generate_etag(Path, Size, Mtime) ->
-    {strong, integer_to_binary(
-        erlang:phash2({Path, Size, Mtime}, 16#ffffffff))}.
-
-
Custom MIME type function
-
-
always_octet_stream(_Path) ->
-    case filename:extension(Path) of
-        <<".erl">> -> {<<"text">>, <<"plain">>, []};
-        _ -> {<<"application">>, <<"octet-stream">>, []}
-    end.
-
-
-
+
always_octet_stream(_Path) ->
+    case filename:extension(Path) of
+        <<".erl">> -> {<<"text">>, <<"plain">>, []};
+        _ -> {<<"application">>, <<"octet-stream">>, []}
+    end.
+

See also

- - +

cowboy(7), cowboy_router(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_stream/index.html b/docs/en/cowboy/2.4/manual/cowboy_stream/index.html index bd9ef67b..b3ff1222 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_stream/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_stream/index.html @@ -62,452 +62,306 @@

cowboy_stream(3)

-

Name

-
-

cowboy_handler - Stream handlers

-
-
-
+

cowboy_handler - Stream handlers

Description

-
-

The module cowboy_stream defines a callback interface -and a protocol for handling HTTP streams.

-

An HTTP request and its associated response is called -a stream. A connection may have many streams. In HTTP/1.1 -they are executed sequentially, while in HTTP/2 they are -executed concurrently.

-

Cowboy calls the stream handler for nearly all events -related to a stream. Exceptions vary depending on the -protocol.

-

Extra care must be taken when implementing stream handlers -to ensure compatibility. While some modification of the -events and commands is allowed, it is generally not a good -idea to completely omit them.

-
-
-
+

The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams.

+

An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently.

+

Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol.

+

Extra care must be taken when implementing stream handlers to ensure compatibility. While some modification of the events and commands is allowed, it is generally not a good idea to completely omit them.

Callbacks

-
-

Stream handlers must implement the following interface:

-
-
-
init(StreamID, Req, Opts) -> {Commands, State}
-data(StreamID, IsFin, Data, State) -> {Commands, State}
-info(StreamID, Info, State) -> {Commands, State}
-terminate(StreamID, Reason, State) -> any()
-early_error(StreamID, Reason, PartialReq, Resp, Opts) -> Resp
-
-StreamID   :: cowboy_stream:streamid()
-Req        :: cowboy_req:req()
-Opts       :: cowboy:opts()
-Commands   :: cowboy_stream:commands()
-State      :: any()
-IsFin      :: cowboy_stream:fin()
-Data       :: binary()
-Info       :: any()
-Reason     :: cowboy_stream:reason()
-PartialReq  - cowboy_req:req(), except all fields are optional
-Resp       :: cowboy_stream:resp_command()
-

HTTP/1.1 will initialize a stream only when the request-line -and all headers have been received. When errors occur before -that point Cowboy will call the callback early_error/5 -with a partial request, the error reason and the response -Cowboy intends to send. All other events go throuh the -stream handler using the normal callbacks.

-

HTTP/2 will initialize the stream when the HEADERS block has -been fully received and decoded. Any protocol error occuring -before that will not result in a response being sent and -will therefore not go through the stream handler. In addition -Cowboy may terminate streams without sending an HTTP response -back.

-

The stream is initialized by calling init/3. All streams -that are initialized will eventually be terminated by calling -terminate/3.

-

When Cowboy receives data for the stream it will call data/4. -The data given is the request body after any transfer decoding -has been applied.

-

When Cowboy receives a message addressed to a stream, or when -Cowboy needs to inform the stream handler that an internal -event has occurred, it will call info/3.

-
-
-
+
init(StreamID, Req, Opts) -> {Commands, State}
+data(StreamID, IsFin, Data, State) -> {Commands, State}
+info(StreamID, Info, State) -> {Commands, State}
+terminate(StreamID, Reason, State) -> any()
+early_error(StreamID, Reason, PartialReq, Resp, Opts) -> Resp
+
+StreamID   :: cowboy_stream:streamid()
+Req        :: cowboy_req:req()
+Opts       :: cowboy:opts()
+Commands   :: cowboy_stream:commands()
+State      :: any()
+IsFin      :: cowboy_stream:fin()
+Data       :: binary()
+Info       :: any()
+Reason     :: cowboy_stream:reason()
+PartialReq  - cowboy_req:req(), except all fields are optional
+Resp       :: cowboy_stream:resp_command()
+
+

HTTP/1.1 will initialize a stream only when the request-line and all headers have been received. When errors occur before that point Cowboy will call the callback early_error/5 with a partial request, the error reason and the response Cowboy intends to send. All other events go throuh the stream handler using the normal callbacks.

+

HTTP/2 will initialize the stream when the HEADERS block has been fully received and decoded. Any protocol error occuring before that will not result in a response being sent and will therefore not go through the stream handler. In addition Cowboy may terminate streams without sending an HTTP response back.

+

The stream is initialized by calling init/3. All streams that are initialized will eventually be terminated by calling terminate/3.

+

When Cowboy receives data for the stream it will call data/4. The data given is the request body after any transfer decoding has been applied.

+

When Cowboy receives a message addressed to a stream, or when Cowboy needs to inform the stream handler that an internal event has occurred, it will call info/3.

Commands

-
-

Stream handlers can return a list of commands to be executed -from the init/3, data/4 and info/3 callbacks. In addition, -the early_error/5 callback must return a response command.

-

The following commands are defined:

-
+

Stream handlers can return a list of commands to be executed from the init/3, data/4 and info/3 callbacks. In addition, the early_error/5 callback must return a response command.

+ + + + + +

The following commands are defined:

inform

-

Send an informational response to the client.

-
-
-
{inform, cowboy:http_status(), cowboy:http_headers()}
-

Any number of informational responses may be sent, -but only until the final response is sent.

-
-
+
{inform, cowboy:http_status(), cowboy:http_headers()}
+
+

Any number of informational responses may be sent, but only until the final response is sent.

response

-

Send a response to the client.

-
-
-
{response, cowboy:http_status(), cowboy:http_headers(),
-    cowboy_req:resp_body()}
-

No more data can be sent after this command.

- -
+
{response, cowboy:http_status(), cowboy:http_headers(),
+    cowboy_req:resp_body()}
+
+

No more data can be sent after this command.

headers

-

Initiate a response to the client.

-
-
-
{headers, cowboy:http_status(), cowboy:http_headers()}
-

This initiates a response to the client. The stream -will end when a data command with the fin flag or -a trailer command is returned.

- -
+
{headers, cowboy:http_status(), cowboy:http_headers()}
+
+

This initiates a response to the client. The stream will end when a data command with the fin flag or a trailer command is returned.

data

-

Send data to the client.

-
-
-
{data, fin(), iodata()}
- -
+
{data, fin(), iodata()}
+

trailers

-

Send response trailers to the client.

-
-
-
{trailers, cowboy:http_headers()}
- -
+
{trailers, cowboy:http_headers()}
+

push

-

Push a resource to the client.

-
-
-
{push, Method, Scheme, Host, inet:port_number(),
-    Path, Qs, cowboy:http_headers()}
+
{push, Method, Scheme, Host, inet:port_number(),
+    Path, Qs, cowboy:http_headers()}
 
-Method = Scheme = Host = Path = Qs = binary()
-

The command will be ignored if the protocol does not provide -any server push mechanism.

- -
+Method = Scheme = Host = Path = Qs = binary() +
+

The command will be ignored if the protocol does not provide any server push mechanism.

flow

-
-
-
{flow, pos_integer()}
-

Request more data to be read from the request body. The -exact behavior depends on the protocol.

- -
+
{flow, pos_integer()}
+
+

Request more data to be read from the request body. The exact behavior depends on the protocol.

spawn

-

Inform Cowboy that a process was spawned and should be -supervised.

-
-
-
{spawn, pid(), timeout()}
- -
+
{spawn, pid(), timeout()}
+

error_response

-

Send an error response if no response was sent previously.

-
-
-
{error_response, cowboy:http_status(), cowboy:http_headers(), iodata()}
- -
+
{error_response, cowboy:http_status(), cowboy:http_headers(), iodata()}
+

switch_protocol

-

Switch to a different protocol.

-
-
-
{switch_protocol, cowboy:http_headers(), module(), state()}
-

Contains the headers that will be sent in the 101 response, -along with the module implementing the protocol we are -switching to and its initial state.

- -
+
{switch_protocol, cowboy:http_headers(), module(), state()}
+
+

Contains the headers that will be sent in the 101 response, along with the module implementing the protocol we are switching to and its initial state.

stop

-

Stop the stream.

-
-
-
stop
-

While no more data can be sent after the fin flag was set, -the stream is still tracked by Cowboy until it is stopped by -the handler.

-

The behavior when stopping a stream for which no response -has been sent will vary depending on the protocol. The stream -will end successfully as far as the client is concerned.

-

To indicate that an error occurred, either use error_response -before stopping, or use internal_error.

- -
+
stop
+
+

While no more data can be sent after the fin flag was set, the stream is still tracked by Cowboy until it is stopped by the handler.

+

The behavior when stopping a stream for which no response has been sent will vary depending on the protocol. The stream will end successfully as far as the client is concerned.

+

To indicate that an error occurred, either use error_response before stopping, or use internal_error.

internal_error

-

Stop the stream with an error.

-
-
-
{internal_error, Reason, HumanReadable}
-
-Reason        = any()
-HumanReadable = atom()
-

This command should be used when the stream cannot continue -because of an internal error. An error_response command -may be sent before that to advertise to the client why the -stream is dropped.

- - - -
+
{internal_error, Reason, HumanReadable}
+
+Reason        = any()
+HumanReadable = atom()
+
+

This command should be used when the stream cannot continue because of an internal error. An error_response command may be sent before that to advertise to the client why the stream is dropped.

Predefined events

-
-

Cowboy will forward all messages sent to the stream to -the info/3 callback. To send a message to a stream, -send a message to the connection process with the form -{{Pid, StreamID}, Msg}. The connection process will -then forward Msg to the stream handlers.

-

Cowboy will also forward the exit signals for the -processes that the stream spawned.

-
+

Cowboy will forward all messages sent to the stream to the info/3 callback. To send a message to a stream, send a message to the connection process with the form {{Pid, StreamID}, Msg}. The connection process will then forward Msg to the stream handlers.

+

Cowboy will also forward the exit signals for the processes that the stream spawned.

EXIT

-

A process spawned by this stream has exited.

-
-
+ + +

A process spawned by this stream has exited.

+
-
{'EXIT', pid(), any()}
-

This is the raw exit message without any modification.

-
-
+
{'EXIT', pid(), any()}
+
+

This is the raw exit message without any modification.

+ + + + + + + + + + + + + + + + +

inform

-

Same as the inform command.

-

Sent when the request process reads the body and an -expect: 100-continue header was present in the request, -or when the request process sends an informational -response on its own.

-
-
+

Same as the inform command.

+

Sent when the request process reads the body and an expect: 100-continue header was present in the request, or when the request process sends an informational response on its own.

response

-

Same as the response command.

-

Usually sent when the request process replies to the client. -May also be sent by Cowboy internally.

-
-
+

Same as the response command.

+

Usually sent when the request process replies to the client. May also be sent by Cowboy internally.

headers

-

Same as the headers command.

-

Sent when the request process starts replying to the client.

-
-
+

Same as the headers command.

+

Sent when the request process starts replying to the client.

data

-

Same as the data command.

-

Sent when the request process streams data to the client.

-
-
+

Same as the data command.

+

Sent when the request process streams data to the client.

trailers

-

Same as the trailers command.

-

Sent when the request process sends the trailer field values -to the client.

-
-
+

Same as the trailers command.

+

Sent when the request process sends the trailer field values to the client.

push

-

Same as the push command.

-

Sent when the request process pushes a resource to the client.

-
-
+

Same as the push command.

+

Sent when the request process pushes a resource to the client.

switch_protocol

- -

Sent when switching to the HTTP/2 or Websocket protocol.

-
-
- -
+

Same as the switch_protocol command.

+

Sent when switching to the HTTP/2 or Websocket protocol.

Exports

-
-

The following function should be called by modules implementing -stream handlers to execute the next stream handler in the list:

-
-
-
-
+

Types

-
-

commands()

-
-
-
commands() :: [Command]
-

See the list of commands for details.

-
-
+
commands() :: [Command]
+
+

See the list of commands for details.

fin()

-
-
-
fin() :: fin | nofin
-

Used in commands and events to indicate that this is -the end of the stream.

-
-
+
fin() :: fin | nofin
+
+

Used in commands and events to indicate that this is the end of the stream.

partial_req()

-
-
-
req() :: #{
-    method  => binary(),               %% case sensitive
-    version => cowboy:http_version() | atom(),
-    scheme  => binary(),               %% lowercase; case insensitive
-    host    => binary(),               %% lowercase; case insensitive
-    port    => inet:port_number(),
-    path    => binary(),               %% case sensitive
-    qs      => binary(),               %% case sensitive
-    headers => cowboy:http_headers(),
-    peer    => {inet:ip_address(), inet:port_number()}
-}
-

Partial request information received when an early error is -detected.

- -
+
req() :: #{
+    method  => binary(),               %% case sensitive
+    version => cowboy:http_version() | atom(),
+    scheme  => binary(),               %% lowercase; case insensitive
+    host    => binary(),               %% lowercase; case insensitive
+    port    => inet:port_number(),
+    path    => binary(),               %% case sensitive
+    qs      => binary(),               %% case sensitive
+    headers => cowboy:http_headers(),
+    peer    => {inet:ip_address(), inet:port_number()}
+}
+
+

Partial request information received when an early error is detected.

reason()

-
-
-
reason() :: normal | switch_protocol
-    | {internal_error, timeout | {error | exit | throw, any()}, HumanReadable}
-    | {socket_error, closed | atom(), HumanReadable}
-    | {stream_error, Error, HumanReadable}
-    | {connection_error, Error, HumanReadable}
-    | {stop, cow_http2:frame(), HumanReadable}
-
-Error         = atom()
-HumanReadable = atom()
-

Reason for the stream termination.

- -
+
reason() :: normal | switch_protocol
+    | {internal_error, timeout | {error | exit | throw, any()}, HumanReadable}
+    | {socket_error, closed | atom(), HumanReadable}
+    | {stream_error, Error, HumanReadable}
+    | {connection_error, Error, HumanReadable}
+    | {stop, cow_http2:frame(), HumanReadable}
+
+Error         = atom()
+HumanReadable = atom()
+
+

Reason for the stream termination.

resp_command()

-
-
-
resp_command() :: {response, cowboy:http_status(),
-    cowboy:http_headers(), cowboy_req:resp_body()}
-

See the response command for details.

- -
+
resp_command() :: {response, cowboy:http_status(),
+    cowboy:http_headers(), cowboy_req:resp_body()}
+
+

See the response command for details.

streamid()

-
-
-
streamid() :: any()
-

The identifier for this stream.

-

The identifier is unique over the connection process. -It is possible to form a unique identifier node-wide and -cluster-wide by wrapping it in a {self(), StreamID} -tuple.

- - - -
+
streamid() :: any()
+
+

The identifier for this stream.

+

The identifier is unique over the connection process. It is possible to form a unique identifier node-wide and cluster-wide by wrapping it in a {self(), StreamID} tuple.

Changelog

-
-
    -
  • -

    -2.2: The trailers command was introduced. -

    +
    • 2.2: The trailers command was introduced.
    • -
    • -

      -2.0: Module introduced. -

      +
    • 2.0: Module introduced.
    • -
-
- - +

cowboy(7), cowboy_http(3), cowboy_http2(3)

+ diff --git a/docs/en/cowboy/2.4/manual/cowboy_websocket/index.html b/docs/en/cowboy/2.4/manual/cowboy_websocket/index.html index 01b70c1c..4fd95da2 100644 --- a/docs/en/cowboy/2.4/manual/cowboy_websocket/index.html +++ b/docs/en/cowboy/2.4/manual/cowboy_websocket/index.html @@ -62,308 +62,148 @@

cowboy_websocket(3)

-

Name

-
-

cowboy_websocket - Websocket

-
-
-
+

cowboy_websocket - Websocket

Description

-
-

The module cowboy_websocket implements Websocket -as a Ranch protocol. It also defines a callback interface -for handling Websocket connections.

-
-
-
+

The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections.

Callbacks

-
-

Websocket handlers must implement the following callback -interface:

-
-
-
init(Req, State)
-    -> {cowboy_websocket, Req, State}
-     | {cowboy_websocket, Req, State, Opts}
-
-websocket_init(State)            -> CallResult  %% optional
-websocket_handle(InFrame, State) -> CallResult
-websocket_info(Info, State)      -> CallResult
-
-terminate(Reason, PartialReq, State) -> ok      %% optional
-
-Req        :: cowboy_req:req()
-PartialReq :: map()
-State      :: any()
-Opts       :: cowboy_websocket:opts()
-InFrame    :: {text | binary | ping | pong, binary()}
-OutFrame   :: cow_ws:frame()                    %% see types below
-Info       :: any()
-
-CallResult :: {ok, State}
-            | {ok, State, hibernate}
-            | {reply, OutFrame | [OutFrame], State}
-            | {reply, OutFrame | [OutFrame], State, hibernate}
-            | {stop, State}
-
-Reason     :: normal | stop | timeout
-            | remote | {remote, cow_ws:close_code(), binary()}
-            | {error, badencoding | badframe | closed | atom()}
-            | {crash, error | exit | throw, any()}
-

The init/2 callback is common to all handlers. To upgrade -the connection to Websocket, it must return cowboy_websocket -as the first element of the tuple.

-

Any operation requiring the HTTP request must be done in the -init/2 function, as the Req object will not be available -after it returns. Websocket sub-protocol selection should -therefore be done in this function.

-

The optional websocket_init/1 callback will be called once -the connection has been upgraded to Websocket. It can be used -to perform any required initialization of the handler.

-

Note that the init/2 function does not run in the same -process as the Websocket callbacks. Any Websocket-specific -initialization must be done in websocket_init/1.

-

The websocket_handle/2 callback will be called for every -frame received. The websocket_info/2 callback will be -called for every Erlang message received.

-

All three Websocket callbacks may send one or more frames -back to the client (by returning a reply tuple) or terminate -the connection (by sending a close frame or returning a stop -tuple).

-

The optional terminate/3 callback will ultimately be called -with the reason for the termination of the connection. This -callback is common to all handlers. Note that Websocket will -not provide the full Req object by default, to save memory.

-

Cowboy will terminate the process right after closing the -Websocket connection. This means that there is no need to -perform any cleanup in the terminate/3 callback.

-

The following terminate reasons are defined for Websocket -connections:

-
-
-normal -
-
-

- The connection was closed normally before establishing a Websocket - connection. This typically happens if an ok tuple is returned - from the init/2 callback. -

+
init(Req, State)
+    -> {cowboy_websocket, Req, State}
+     | {cowboy_websocket, Req, State, Opts}
+
+websocket_init(State)            -> CallResult  %% optional
+websocket_handle(InFrame, State) -> CallResult
+websocket_info(Info, State)      -> CallResult
+
+terminate(Reason, PartialReq, State) -> ok      %% optional
+
+Req        :: cowboy_req:req()
+PartialReq :: map()
+State      :: any()
+Opts       :: cowboy_websocket:opts()
+InFrame    :: {text | binary | ping | pong, binary()}
+OutFrame   :: cow_ws:frame()                    %% see types below
+Info       :: any()
+
+CallResult :: {ok, State}
+            | {ok, State, hibernate}
+            | {reply, OutFrame | [OutFrame], State}
+            | {reply, OutFrame | [OutFrame], State, hibernate}
+            | {stop, State}
+
+Reason     :: normal | stop | timeout
+            | remote | {remote, cow_ws:close_code(), binary()}
+            | {error, badencoding | badframe | closed | atom()}
+            | {crash, error | exit | throw, any()}
+
+

The init/2 callback is common to all handlers. To upgrade the connection to Websocket, it must return cowboy_websocket as the first element of the tuple.

+

Any operation requiring the HTTP request must be done in the init/2 function, as the Req object will not be available after it returns. Websocket sub-protocol selection should therefore be done in this function.

+

The optional websocket_init/1 callback will be called once the connection has been upgraded to Websocket. It can be used to perform any required initialization of the handler.

+

Note that the init/2 function does not run in the same process as the Websocket callbacks. Any Websocket-specific initialization must be done in websocket_init/1.

+

The websocket_handle/2 callback will be called for every frame received. The websocket_info/2 callback will be called for every Erlang message received.

+

All three Websocket callbacks may send one or more frames back to the client (by returning a reply tuple) or terminate the connection (by sending a close frame or returning a stop tuple).

+

The optional terminate/3 callback will ultimately be called with the reason for the termination of the connection. This callback is common to all handlers. Note that Websocket will not provide the full Req object by default, to save memory.

+

Cowboy will terminate the process right after closing the Websocket connection. This means that there is no need to perform any cleanup in the terminate/3 callback.

+

The following terminate reasons are defined for Websocket connections:

+
normal
+

The connection was closed normally before establishing a Websocket connection. This typically happens if an ok tuple is returned from the init/2 callback.

-
-remote -
-
-

- The remote endpoint closed the connection without giving any - further details. -

+
remote
+

The remote endpoint closed the connection without giving any further details.

-
-{remote, Code, Payload} -
-
-

- The remote endpoint closed the connection with the given - Code and Payload as the reason. -

+
{remote, Code, Payload}
+

The remote endpoint closed the connection with the given Code and Payload as the reason.

-
-stop -
-
-

- The handler requested to close the connection, either by returning - a stop tuple or by sending a close frame. -

+
stop
+

The handler requested to close the connection, either by returning a stop tuple or by sending a close frame.

-
-timeout -
-
-

- The connection has been closed due to inactivity. The timeout - value can be configured from init/2. -

+
timeout
+

The connection has been closed due to inactivity. The timeout value can be configured from init/2.

-
-{crash, Class, Reason} -
-
-

- A crash occurred in the handler. Class and Reason can be - used to obtain more information about the crash. The function - erlang:get_stacktrace/0 can also be called to obtain the - stacktrace of the process when the crash occurred. -

+
{crash, Class, Reason}
+

A crash occurred in the handler. Class and Reason can be used to obtain more information about the crash. The function erlang:get_stacktrace/0 can also be called to obtain the stacktrace of the process when the crash occurred.

-
-{error, badencoding} -
-
-

- A text frame was sent by the client with invalid encoding. All - text frames must be valid UTF-8. -

+
{error, badencoding}
+

A text frame was sent by the client with invalid encoding. All text frames must be valid UTF-8.

-
-{error, badframe} -
-
-

- A protocol error has been detected. -

+
{error, badframe}
+

A protocol error has been detected.

-
-{error, closed} -
-
-

- The socket has been closed brutally without a close frame being - received first. -

+
{error, closed}
+

The socket has been closed brutally without a close frame being received first.

-
-{error, Reason} -
-
-

- A socket error ocurred. -

+
{error, Reason}
+

A socket error ocurred.

-
- - -
+

Types

-
-

cow_ws:frame()

-
-
-
frame() :: {text, iodata()}
-    | {binary, iodata()}
-    | ping | {ping, iodata()}
-    | pong | {pong, iodata()}
-    | close | {close, iodata()} | {close, close_code(), iodata()}
-
-close_code() :: 1000..1003 | 1006..1011 | 3000..4999
-

Websocket frames that can be sent as a response.

-

Note that there is no need to send pong frames back as -Cowboy does it automatically for you.

-
-
+
frame() :: {text, iodata()}
+    | {binary, iodata()}
+    | ping | {ping, iodata()}
+    | pong | {pong, iodata()}
+    | close | {close, iodata()} | {close, close_code(), iodata()}
+
+close_code() :: 1000..1003 | 1006..1011 | 3000..4999
+
+

Websocket frames that can be sent as a response.

+

Note that there is no need to send pong frames back as Cowboy does it automatically for you.

opts()

-
-
-
opts() :: #{
-    compress => boolean(),
-    idle_timeout => timeout(),
-    max_frame_size => non_neg_integer() | infinity,
-    req_filter => fun((cowboy_req:req()) -> map())
-}
-

Websocket handler options.

-

This configuration is passed to Cowboy from the init/2 -function:

-
-
-
init(Req, State) ->
-    Opts = #{compress => true},
-    {cowboy_websocket, Req, State, Opts}.
-

The default value is given next to the option name:

-
-
-compress (false) -
-
-

- Whether to enable the Websocket frame compression - extension. Frames will only be compressed for the - clients that support this extension. -

+
init(Req, State) ->
+    Opts = #{compress => true},
+    {cowboy_websocket, Req, State, Opts}.
+
+

The default value is given next to the option name:

+
compress (false)
+

Whether to enable the Websocket frame compression extension. Frames will only be compressed for the clients that support this extension.

-
-idle_timeout (60000) -
-
-

- Time in milliseconds that Cowboy will keep the - connection open without receiving anything from - the client. -

+
idle_timeout (60000)
+

Time in milliseconds that Cowboy will keep the connection open without receiving anything from the client.

-
-max_frame_size (infinity) -
-
-

- Maximum frame size allowed by this Websocket - handler. Cowboy will close the connection when - a client attempts to send a frame that goes over - this limit. For fragmented frames this applies - to the size of the reconstituted frame. -

+
max_frame_size (infinity)
+

Maximum frame size allowed by this Websocket handler. Cowboy will close the connection when a client attempts to send a frame that goes over this limit. For fragmented frames this applies to the size of the reconstituted frame.

-
-req_filter -
-
-

- A function applied to the Req to compact it and - only keep required information. The Req is only - given back in the terminate/3 callback. By default - it keeps the method, version, URI components and peer - information. -

+
req_filter
+

A function applied to the Req to compact it and only keep required information. The Req is only given back in the terminate/3 callback. By default it keeps the method, version, URI components and peer information.

-
- - - -
+

Changelog

-
-
    -
  • -

    -2.0: The Req object is no longer passed to Websocket callbacks. -

    +
    • 2.0: The Req object is no longer passed to Websocket callbacks.
    • -
    • -

      -2.0: The callback websocket_terminate/3 was removed in favor of terminate/3. -

      +
    • 2.0: The callback websocket_terminate/3 was removed in favor of terminate/3.
    • -
    • -

      -1.0: Protocol introduced. -

      +
    • 1.0: Protocol introduced.
    • -
-
-
- +

cowboy(7), cowboy_handler(3), cowboy_http(3), cowboy_http2(3)

+ diff --git a/docs/en/cowboy/2.4/manual/http_status_codes/index.html b/docs/en/cowboy/2.4/manual/http_status_codes/index.html index e6d2cc5a..0d858a45 100644 --- a/docs/en/cowboy/2.4/manual/http_status_codes/index.html +++ b/docs/en/cowboy/2.4/manual/http_status_codes/index.html @@ -62,271 +62,92 @@

HTTP status codes(7)

-

Name

-
-

HTTP status codes - status codes used by Cowboy

-
-
-
+

HTTP status codes - status codes used by Cowboy

Description

-
-

This chapter aims to list all HTTP status codes that Cowboy -may return, with details on the reasons why. The list given -here only includes the replies that Cowboy sends, not user -replies.

-
-
-
+

This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies.

100 Continue

-
-

When the client sends an expect: 100-continue header, -Cowboy automatically sends a this status code before -trying to read the request body. This behavior can be -disabled using the appropriate body option.

-
-
-
+

When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. This behavior can be disabled using the appropriate body option.

101 Switching Protocols

-
-

This is the status code sent when switching to the -Websocket protocol.

-
-
-
+

This is the status code sent when switching to the Websocket protocol.

200 OK

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

201 Created

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

202 Accepted

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

204 No Content

-
-

This status code is sent when the processing of a request -ends without any reply having been sent. It may also be -sent by cowboy_rest under normal conditions.

-
-
-
+

This status code is sent when the processing of a request ends without any reply having been sent. It may also be sent by cowboy_rest under normal conditions.

300 Multiple Choices

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

301 Moved Permanently

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

303 See Other

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

304 Not Modified

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

307 Temporary Redirect

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

400 Bad Request

-
-

Cowboy will send this status code for any of the -following reasons:

-
    -
  • -

    -Too many empty lines were sent before the request. -

    +

    Cowboy will send this status code for any of the following reasons:

    +
    • Too many empty lines were sent before the request.
    • -
    • -

      -The request-line could not be parsed. -

      +
    • The request-line could not be parsed.
    • -
    • -

      -Too many headers were sent. -

      +
    • Too many headers were sent.
    • -
    • -

      -A header name was too long. -

      +
    • A header name was too long.
    • -
    • -

      -A header value was too long. -

      +
    • A header value was too long.
    • -
    • -

      -The host header was missing from an HTTP/1.1 request. -

      +
    • The host header was missing from an HTTP/1.1 request.
    • -
    • -

      -The host header could not be parsed. -

      +
    • The host header could not be parsed.
    • -
    • -

      -The requested host was not found. -

      +
    • The requested host was not found.
    • -
    • -

      -The requested path could not be parsed. -

      +
    • The requested path could not be parsed.
    • -
    • -

      -The accept header could not be parsed when using REST. -

      +
    • The accept header could not be parsed when using REST.
    • -
    • -

      -REST under normal conditions. -

      +
    • REST under normal conditions.
    • -
    • -

      -A Websocket upgrade failed. -

      +
    • A Websocket upgrade failed.
    • -
-
-
-
+

401 Unauthorized

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

403 Forbidden

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

404 Not Found

-
-

This status code is sent when the router successfully -resolved the host but didn’t find a matching path for -the request. It may also be sent by cowboy_rest under -normal conditions.

-
-
-
+

This status code is sent when the router successfully resolved the host but didn't find a matching path for the request. It may also be sent by cowboy_rest under normal conditions.

405 Method Not Allowed

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

406 Not Acceptable

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

408 Request Timeout

-
-

Cowboy will send this status code to the client if the -client started to send a request, indicated by the -request-line being received fully, but failed to send -all headers in a reasonable time.

-
-
-
+

Cowboy will send this status code to the client if the client started to send a request, indicated by the request-line being received fully, but failed to send all headers in a reasonable time.

409 Conflict

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

410 Gone

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

412 Precondition Failed

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

413 Request Entity Too Large

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

414 Request-URI Too Long

-
-

Cowboy will send this status code to the client if the -request-line is too long. It may also be sent by -cowboy_rest under normal conditions.

-
-
-
+

Cowboy will send this status code to the client if the request-line is too long. It may also be sent by cowboy_rest under normal conditions.

415 Unsupported Media Type

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

500 Internal Server Error

-
-

This status code is sent when a crash occurs in HTTP, loop -or REST handlers, or when an invalid return value is -returned. It may also be sent by cowboy_rest under -normal conditions.

-
-
-
+

This status code is sent when a crash occurs in HTTP, loop or REST handlers, or when an invalid return value is returned. It may also be sent by cowboy_rest under normal conditions.

501 Not Implemented

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

503 Service Unavailable

-
-

This status code is sent by cowboy_rest.

-
-
-
+

This status code is sent by cowboy_rest.

505 HTTP Version Not Supported

-
-

Cowboy only supports the versions 1.0 and 1.1 of HTTP. -In all other cases this status code is sent back to the -client and the connection is closed.

-
-
+

Cowboy only supports the versions 1.0 and 1.1 of HTTP. In all other cases this status code is sent back to the client and the connection is closed.

+ diff --git a/docs/en/cowboy/2.4/manual/index.html b/docs/en/cowboy/2.4/manual/index.html index 78e44814..91caacbe 100644 --- a/docs/en/cowboy/2.4/manual/index.html +++ b/docs/en/cowboy/2.4/manual/index.html @@ -62,171 +62,77 @@

Cowboy Function Reference

-

Name

-
-

cowboy - Small, fast, modern HTTP server for Erlang/OTP

-
-
-
+

cowboy - Small, fast, modern HTTP server for Erlang/OTP

Description

-
-

Cowboy is an HTTP server for Erlang/OTP with support for the -HTTP/1.1, HTTP/2 and Websocket protocols.

-

Cowboy aims to provide a complete HTTP stack. This includes -the implementation of the HTTP RFCs but also any directly -related standards, like Websocket or Server-Sent Events.

-
-
-
+

Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols.

+

Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events.

Modules

-
-

Functions:

-
-

Protocols:

-
+

Protocols:

+
-

Handlers:

-
+

Handlers:

+
-

Behaviors:

-
+

Behaviors:

+
-

Middlewares:

-
+

Middlewares:

+
-
-
-
+ +

Dependencies

-
-
    -
  • -

    -ranch(7) - Socket acceptor pool for TCP protocols -

    +
    • ranch(7) - Socket acceptor pool for TCP protocols
    • -
    • -

      -cowlib(7) - Support library for manipulating Web protocols -

      +
    • cowlib(7) - Support library for manipulating Web protocols
    • -
    • -

      -ssl - Secure communication over sockets -

      +
    • ssl - Secure communication over sockets
    • -
    • -

      -crypto - Crypto functions -

      +
    • crypto - Crypto functions
    • -
-

All these applications must be started before the cowboy -application. To start Cowboy and all dependencies at once:

-
-
-
{ok, _} = application:ensure_all_started(cowboy).
-
-
-
+
{ok, _} = application:ensure_all_started(cowboy).
+

Environment

-
-

The cowboy application does not define any application -environment configuration parameters.

-
- -
+

The cowboy application does not define any application environment configuration parameters.

See also

- -
+

ranch(7), cowlib(7)

+ diff --git a/docs/en/erlang.mk/1/guide/app/index.html b/docs/en/erlang.mk/1/guide/app/index.html index 55c2d223..3c4d62d3 100644 --- a/docs/en/erlang.mk/1/guide/app/index.html +++ b/docs/en/erlang.mk/1/guide/app/index.html @@ -62,642 +62,348 @@

Building

-

Erlang.mk can do a lot of things, but it is, first and -foremost, a build tool. In this chapter we will cover -the basics of building a project with Erlang.mk.

-

For most of this chapter, we will assume that you are -using a project generated by Erlang.mk.

-
+

Erlang.mk can do a lot of things, but it is, first and foremost, a build tool. In this chapter we will cover the basics of building a project with Erlang.mk.

+

For most of this chapter, we will assume that you are using a project generated by Erlang.mk.

How to build

-
-

To build a project, all you have to do is type make:

-
-
-
$ make
-

It will work regardless of your project: OTP applications, -library applications, NIFs, port drivers or even releases. -Erlang.mk also automatically downloads and compiles the -dependencies for your project.

-

All this is possible thanks to a combination of configuration -and conventions. Most of the conventions come from Erlang/OTP -itself so any seasoned Erlang developers should feel right at -home.

-
-
-
+
$ make
+
+

It will work regardless of your project: OTP applications, library applications, NIFs, port drivers or even releases. Erlang.mk also automatically downloads and compiles the dependencies for your project.

+

All this is possible thanks to a combination of configuration and conventions. Most of the conventions come from Erlang/OTP itself so any seasoned Erlang developers should feel right at home.

What to build

-
-

Erlang.mk gives you control over three steps of the build -process, allowing you to do a partial build if needed.

-

A build has three phases: first any dependency is fetched -and built, then the project itself is built and finally a -release may be generated when applicable. A release is only -generated for projects specifically configured to do so.

-

Erlang.mk handles those three phases automatically when you -type make. But sometimes you just want to repeat one or -two of them.

-

The commands detailed in this section are most useful after -you have a successful build as they allow you to quickly -redo a step instead of going through everything. This is -especially useful for large projects or projects that end -up generating releases.

-
+

Erlang.mk gives you control over three steps of the build process, allowing you to do a partial build if needed.

+

A build has three phases: first any dependency is fetched and built, then the project itself is built and finally a release may be generated when applicable. A release is only generated for projects specifically configured to do so.

+

Erlang.mk handles those three phases automatically when you type make. But sometimes you just want to repeat one or two of them.

+

The commands detailed in this section are most useful after you have a successful build as they allow you to quickly redo a step instead of going through everything. This is especially useful for large projects or projects that end up generating releases.

Application

-

You can build your application and dependencies without -generating a release by running the following command:

-
-
-
$ make app
-

To build your application without touching dependencies -at all, you can use the SKIP_DEPS variable:

-
-
-
$ make app SKIP_DEPS=1
-

This command is very useful if you have a lot of dependencies -and develop on a machine with slow file access, like the -Raspberry Pi and many other embedded devices.

-

Note that this command may fail if a required dependency -is missing.

-
-
+
$ make app SKIP_DEPS=1
+
+

This command is very useful if you have a lot of dependencies and develop on a machine with slow file access, like the Raspberry Pi and many other embedded devices.

+

Note that this command may fail if a required dependency is missing.

Dependencies

-

You can build all dependencies, and nothing else, by -running the following command:

-
-
-
$ make deps
-

This will fetch and compile all dependencies and their -dependencies, recursively.

-

Packages and dependencies are covered -in the next chapter.

- -
+
$ make deps
+
+

This will fetch and compile all dependencies and their dependencies, recursively.

+

Packages and dependencies are covered in the next chapter.

Release

-

It is not possible to build the release without at least -building the application itself, unless of course if there’s -no application to begin with.

-

To generate the release, make will generally suffice with -a normal Erlang.mk. A separate target is however available, -and will take care of building the release, after building -the application and all dependencies:

-
-
-
$ make rel
-

Consult the Releases chapter for more -information about what releases are and how they are generated.

- - - -
+
$ make rel
+
+

Consult the Releases chapter for more information about what releases are and how they are generated.

Application resource file

-
-

When building your application, Erlang.mk will generate the -application resource file. -This file is mandatory for all Erlang applications and is -found in ebin/$(PROJECT).app.

-

PROJECT is a variable defined in your Makefile and taken -from the name of the directory when Erlang.mk bootstraps -your project.

-

Erlang.mk can build the ebin/$(PROJECT).app in two different -ways: from the configuration found in the Makefile, or from -the src/$(PROJECT).app.src file.

-
+

When building your application, Erlang.mk will generate the application resource file. This file is mandatory for all Erlang applications and is found in ebin/$(PROJECT).app.

+

PROJECT is a variable defined in your Makefile and taken from the name of the directory when Erlang.mk bootstraps your project.

+

Erlang.mk can build the ebin/$(PROJECT).app in two different ways: from the configuration found in the Makefile, or from the src/$(PROJECT).app.src file.

Application configuration

-

Erlang.mk automatically fills the PROJECT variable when -bootstrapping a new project, but everything else is up to -you. None of the values are required to build your project, -although it is recommended to fill everything relevant to -your situation.

-
-
-PROJECT -
-
-

- The name of the OTP application or library. -

+

Erlang.mk automatically fills the PROJECT variable when bootstrapping a new project, but everything else is up to you. None of the values are required to build your project, although it is recommended to fill everything relevant to your situation.

+
PROJECT
+

The name of the OTP application or library.

-
-PROJECT_DESCRIPTION -
-
-

- Short description of the project. -

+
PROJECT_DESCRIPTION
+

Short description of the project.

-
-PROJECT_VERSION -
-
-

- Current version of the project. -

+
PROJECT_VERSION
+

Current version of the project.

-
-PROJECT_MOD -
-
-

- The application callback module. -

+
PROJECT_MOD
+

The application callback module.

-
-PROJECT_REGISTERED -
-
-

- List of the names of all registered processes. -

+
PROJECT_REGISTERED
+

List of the names of all registered processes.

-
-PROJECT_ENV -
-
-

- Configuration parameters used by the application. -

+
PROJECT_ENV
+

Configuration parameters used by the application.

-
-PROJECT_APP_EXTRA_KEYS -
-
-

- Other keys you want to add to the application .app file. - The variable content is written as-is to the .app file, - so be sure to format valid Erlang terms. For example: - PROJECT_APP_EXTRA_KEYS = {maxT, 10000}, {start_phases, [...]}. -

+
PROJECT_APP_EXTRA_KEYS
+

Other keys you want to add to the application .app file. The variable content is written as-is to the .app file, so be sure to format valid Erlang terms. For example: PROJECT_APP_EXTRA_KEYS = {maxT, 10000}, {start_phases, [...]}.

-
-LOCAL_DEPS -
-
-

- List of Erlang/OTP applications this project depends on, - excluding erts, kernel and stdlib, or list of - dependencies local to this repository (in APPS_DIR). -

+
LOCAL_DEPS
+

List of Erlang/OTP applications this project depends on, excluding erts, kernel and stdlib, or list of dependencies local to this repository (in APPS_DIR).

-
-DEPS -
-
-

- List of applications this project depends on that need - to be fetched by Erlang.mk. -

+
DEPS
+

List of applications this project depends on that need to be fetched by Erlang.mk.

-
-

There’s no need for quotes or anything. The relevant part of -the Cowboy Makefile follows, if you need an example:

-
-
-
PROJECT = cowboy
-PROJECT_DESCRIPTION = Small, fast, modular HTTP server.
-PROJECT_VERSION = 2.0.0-pre.2
-PROJECT_REGISTERED = cowboy_clock
-
-LOCAL_DEPS = crypto
-DEPS = cowlib ranch
-

Any space before and after the value is dropped.

-

Dependencies are covered in details in -the next chapter.

-
-
+
PROJECT = cowboy
+PROJECT_DESCRIPTION = Small, fast, modular HTTP server.
+PROJECT_VERSION = 2.0.0-pre.2
+PROJECT_REGISTERED = cowboy_clock
+
+LOCAL_DEPS = crypto
+DEPS = cowlib ranch
+
+

Any space before and after the value is dropped.

+

Dependencies are covered in details in the next chapter.

Application environment

-

The PROJECT_ENV variable is used to set the application -environment:

-
-
define PROJECT_ENV
-[
-  {chips, [currysauce,{mushypeas,false}]},
-  {pizza, [{size,large},{toppings,[anchovies]}]}
-]
-endef
-

If you have a large set of environment variables, you may find it -easier to use a separate file. Do this by including the following -in your Makefile:

-
-
-
PROJECT_ENV_FILE = src/env.src
-PROJECT_ENV = $(subst \n,$(newline),$(shell cat $(PROJECT_ENV_FILE) | sed -e 's/$$/\\n/;'))
-ebin/$(PROJECT).app:: $(PROJECT_ENV_FILE)
-

The file has the same contents as the PROJECT_ENV variable:

-
-
[
-  {chips, [currysauce,{mushypeas,false}]},
-  {pizza, [{size,large},{toppings,[anchovies]}]}
-]
- -
+ {chips, [currysauce,{mushypeas,false}]}, + {pizza, [{size,large},{toppings,[anchovies]}]} +] +

Legacy method

-

The src/$(PROJECT).app.src file is a legacy method of -building Erlang applications. It was introduced by the original -rebar build tool, of which Erlang.mk owes a great deal as it -is its main inspiration.

-

The .app.src file serves as a template to generate the .app -file. Erlang.mk will take it, fill in the modules value -dynamically, and save the result in ebin/$(PROJECT).app.

-

When using this method, Erlang.mk cannot fill the applications -key from dependencies automatically, which means you need to -add them to Erlang.mk and to the .app.src at the same time, -duplicating the work.

-

If you really can’t live without the legacy method, for one -reason or another, worry not; Erlang.mk will support it. And -if you need to create a new project that uses this method, you -just have to say so when bootstrapping:

-
-
-
$ make -f erlang.mk bootstrap-lib LEGACY=1
- - - -
+
$ make -f erlang.mk bootstrap-lib LEGACY=1
+

Automatic application resource file values

-
-

When building the application resource file, Erlang.mk may -automatically add an id key with information about the -Git commit (if using Git), or an empty string otherwise. -It will only do this under specific conditions:

-
    -
  • -

    -The application was built as a dependency of another, or -

    +

    When building the application resource file, Erlang.mk may automatically add an id key with information about the Git commit (if using Git), or an empty string otherwise. It will only do this under specific conditions:

    +
    • The application was built as a dependency of another, or
    • -
    • -

      -The legacy method was used, and the .app.src file contained {id, "git"} -

      +
    • The legacy method was used, and the .app.src file contained {id, "git"}
    • -
-

This value is most useful when you need to help your users, -as it allows you to know which version they run exactly by -asking them to look in the file, or by running a simple -command on their production server:

-
-
-
1> application:get_all_key(cowboy).
-{ok,[{description,"Small, fast, modular HTTP server."},
-     {id,"2.0.0-pre.2-25-g0ffde50-dirty"},
-
- -
+
1> application:get_all_key(cowboy).
+{ok,[{description,"Small, fast, modular HTTP server."},
+     {id,"2.0.0-pre.2-25-g0ffde50-dirty"},
+

File formats

-
-

Erlang.mk supports a variety of different source file formats. -The following formats are supported natively:

-
- ----- - - - - - +

Erlang.mk supports a variety of different source file formats. The following formats are supported natively:

+
Extension Location Description Output
+ + + + + + + + - - - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - +
ExtensionLocationDescriptionOutput
.erlsrc/Erlang sourceebin/*.beam

.erl

src/

Erlang source

ebin/*.beam

.coresrc/Core Erlang sourceebin/*.beam

.core

src/

Core Erlang source

ebin/*.beam

.xrlsrc/Leex sourcesrc/*.erl

.xrl

src/

Leex source

src/*.erl

.yrlsrc/Yecc sourcesrc/*.erl

.yrl

src/

Yecc source

src/*.erl

.asn1asn1/ASN.1 filesinclude/*.hrl include/*.asn1db src/*.erl

.asn1

asn1/

ASN.1 files

include/.hrl include/.asn1db src/*.erl

.mibmibs/SNMP MIB filesinclude/*.hrl priv/mibs/*.bin

.mib

mibs/

SNMP MIB files

include/.hrl priv/mibs/.bin

+

Files are always searched recursively.

+

The build is ordered, so that files that generate Erlang source files are run before, and the resulting Erlang source files are then built normally.

+

In addition, Erlang.mk keeps track of header files (.hrl) as described at the end of this chapter. It can also compile C code, as described in the NIFs and port drivers chapter.

+

Erlang.mk also comes with plugins for the following formats:

+ + + + + + + + + - -
ExtensionLocationDescriptionOutput
.dtltemplates/Django templatesebin/*.beam
-
-

Files are always searched recursively.

-

The build is ordered, so that files that generate Erlang source -files are run before, and the resulting Erlang source files are -then built normally.

-

In addition, Erlang.mk keeps track of header files (.hrl) -as described at the end of this chapter. It can also compile -C code, as described in the NIFs and port drivers -chapter.

-

Erlang.mk also comes with plugins for the following formats:

-
- ----- - - - - - - - - - - - - - + + + + - - - - - - - -
Extension Location Description Output

.dtl

templates/

Django templates

ebin/*.beam

.protosrc/Protocol buffersebin/*.beam

.proto

src/

Protocol buffers

ebin/*.beam

-
-
- -
+

Compilation options

-
-

Erlang.mk provides a few variables that you can use to customize -the build process and the resulting files.

-
+

Erlang.mk provides a few variables that you can use to customize the build process and the resulting files.

ERLC_OPTS

-

ERLC_OPTS can be used to pass some options to erlc, the Erlang -compiler. Erlang.mk does not restrict any option. Please refer to -the erlc Manual for the -full list.

-

By default, Erlang.mk will set the following options:

-
-
-
ERLC_OPTS = -Werror +debug_info +warn_export_vars +warn_shadow_vars +warn_obsolete_guard
-

In other words: warnings as errors, debug info (recommended) and -enable warnings for exported variables, shadow variables and -obsolete guard functions.

-

You can redefine this variable in your Makefile to change it -completely, either before or after including Erlang.mk:

-
-
-
ERLC_OPTS = +debug_info
-

You can also filter out some options from the defaults Erlang.mk -sets, by defining ERLC_OPTS after including Erlang.mk using the -:= operator.

-
-
include erlang.mk
 
-ERLC_OPTS := $(filter-out -Werror,$(ERLC_OPTS))
-
-
+ERLC_OPTS := $(filter-out -Werror,$(ERLC_OPTS)) +

ERLC_ASN1_OPTS

-

ERLC_ASN1_OPTS can be used to pass compiler options when compiling -ASN.1 files. Please refer to the -asn1ct manual for the full list.

-

By default, Erlang.mk will leave this empty.

-

You can redefine this variable in your Makefile. -Please see the ERLC_OPTS section for instructions.

-
-
+

ERLC_ASN1_OPTS can be used to pass compiler options when compiling ASN.1 files. Please refer to the asn1ct manual for the full list.

+

By default, Erlang.mk will leave this empty.

+

You can redefine this variable in your Makefile. Please see the ERLC_OPTS section for instructions.

ERLC_EXCLUDE

-

ERLC_EXCLUDE can be used to exclude some modules from the -compilation. It’s there for handling special cases, you should -not normally need it.

-

To exclude a module, simply list it in the variable, either -before or after including Erlang.mk:

-
-
-
ERLC_EXCLUDE = cowboy_http2
-
- - -
+
ERLC_EXCLUDE = cowboy_http2
+

Cold and hot builds

-
-

The first time you run make, Erlang.mk will build everything.

-

The second time you run make, and all subsequent times, Erlang.mk -will only rebuild what changed. Erlang.mk has been optimized for -this use case, as it is the most common during development.

-

Erlang.mk figures out what changed by using the dependency tracking -feature of Make. Make automatically rebuilds a target if one of its -dependency has changed (for example if a header file has changed, -all the source files that include it will be rebuilt), and Erlang.mk -leverages this feature to cut down on rebuild times.

-

Note that this applies only to building; some other features of -Erlang.mk will run every time they are called regardless of files -changed.

-
- -
+

The first time you run make, Erlang.mk will build everything.

+

The second time you run make, and all subsequent times, Erlang.mk will only rebuild what changed. Erlang.mk has been optimized for this use case, as it is the most common during development.

+

Erlang.mk figures out what changed by using the dependency tracking feature of Make. Make automatically rebuilds a target if one of its dependency has changed (for example if a header file has changed, all the source files that include it will be rebuilt), and Erlang.mk leverages this feature to cut down on rebuild times.

+

Note that this applies only to building; some other features of Erlang.mk will run every time they are called regardless of files changed.

Dependency tracking

-
-
- - - -
-
Note
-
This section is about the dependency tracking between files -inside your project, not application dependencies.
-
-

Erlang.mk keeps track of the dependencies between the different -files in your project. This information is kept in the $(PROJECT).d -file in your directory. It is generated if missing, and will be -generated again after every file change, by default.

-

Dependency tracking is what allows Erlang.mk to know when to -rebuild Erlang files when header files, behaviors or parse -transforms have changed. Erlang.mk also automatically keeps -track of which files should be compiled first, for example -when you have behaviors used by other modules in your project.

-

If your project is stable, you may want to disable generating -the dependency tracking file every time you compile. You can -do this by adding the following line to your Makefile:

-
-
-
NO_MAKEDEP ?= 1
-

As you can see, the snippet above uses ?= instead of a -simple equal sign. This is to allow you to temporarily override -this value when you do make substantial changes to your project -(including a new header file, new module with dependencies, etc.) -and want to rebuild the dependency tracking file. You’ll be -able to use the following command:

-
-
-
$ NO_MAKEDEP= make
-

Otherwise, make clean app will of course force the -recompilation of your project.

-

Erlang.mk can also keep track of the source files generated -by other means, for example if you generate code from a data -file in your repository.

-
-
-
+
$ NO_MAKEDEP= make
+
+

Otherwise, make clean app will of course force the recompilation of your project.

+

Erlang.mk can also keep track of the source files generated by other means, for example if you generate code from a data file in your repository.

Generating Erlang source

-
-

Erlang.mk provides hooks at different stages of the build process. -When your goal is to generate Erlang source files, you can -add your own rules before or after the dependency tracking -file is generated. To do this, you would add your hook before -or after including the erlang.mk file.

-

The easiest way is after:

-
-
-
PROJECT = example
+
PROJECT = example
 
 include erlang.mk
 
-$(PROJECT).d:: src/generated_mod.erl
-
-src/generated_mod.erl:: gen-mod.sh
-        $(gen_verbose) ./gen-mod.sh $@
-

In this case we use $(gen_verbose) to hide the details of -the build by default. Erlang.mk will simply say what file -is it currently generating.

-

When using an external script to generate the Erlang source -file, it is recommended to depend on that script, so that -the source file gets generated again when the script gets -modified.

-

If for whatever reason you prefer to hook before including -Erlang.mk, don’t forget to set the .DEFAULT_GOAL variable, -otherwise nothing will get built:

-
-
-
PROJECT = example
+
PROJECT = example
 
-.DEFAULT_GOAL = all
+.DEFAULT_GOAL = all
 
-$(PROJECT).d:: src/generated_mod.erl
+$(PROJECT).d:: src/generated_mod.erl
 
 include erlang.mk
 
-src/generated_mod.erl:: gen-mod.sh
-        $(gen_verbose) ./gen-mod.sh $@
-
- -
+src/generated_mod.erl:: gen-mod.sh + $(gen_verbose) ./gen-mod.sh $@ +

Cleaning

-
-

Building typically involves creating a lot of new files. Some -are reused in rebuilds, some are simply replaced. All can be -removed safely.

-

Erlang.mk provides two commands to remove them: clean and -distclean. clean removes all the intermediate files that -were created as a result of building, including the BEAM files, -the dependency tracking file and the generated documentation. -distclean removes these and more, including the downloaded -dependencies, Dialyzer’s PLT file and the generated release, -putting your directory back to the state it was before you -started working on it.

-

To clean:

-
-
-
$ make clean
-

Or distclean:

-
-
-
$ make distclean
-

That is the question.

-

Note that Erlang.mk will automatically clean some files as -part of other targets, but it will never run distclean if -you don’t explicitly use it.

-
- +
$ make distclean
+ +

That is the question.

+

Note that Erlang.mk will automatically clean some files as part of other targets, but it will never run distclean if you don't explicitly use it.

+ diff --git a/docs/en/erlang.mk/1/guide/asciidoc/index.html b/docs/en/erlang.mk/1/guide/asciidoc/index.html index bb13a400..530c81cc 100644 --- a/docs/en/erlang.mk/1/guide/asciidoc/index.html +++ b/docs/en/erlang.mk/1/guide/asciidoc/index.html @@ -62,100 +62,63 @@

AsciiDoc documentation

-

Erlang.mk provides rules for generating documentation from -AsciiDoc files. It can automatically build a user guide PDF, -chunked HTML documentation and Unix manual pages.

-
+

Erlang.mk provides rules for generating documentation from AsciiDoc files. It can automatically build a user guide PDF, chunked HTML documentation and Unix manual pages.

Requirements

-
-

It is necessary to have AsciiDoc, -xsltproc and -dblatex installed on your -system for Erlang.mk to generate documentation from AsciiDoc sources.

-
-
-
+

It is necessary to have AsciiDoc, xsltproc and dblatex installed on your system for Erlang.mk to generate documentation from AsciiDoc sources.

Writing AsciiDoc documentation

-
-

AsciiDoc is a text document format for -writing notes, documentation, articles, books, ebooks, slideshows, -web pages, man pages and blogs. AsciiDoc files can be translated -to many formats including HTML, PDF, EPUB, man page.

-

The AsciiDoc user guide -describes the AsciiDoc syntax.

-

The Erlang.mk user guide -is written in AsciiDoc and can be used as an example. The entry -file is book.asciidoc.

-

Erlang.mk expects you to put your documentation in a specific -location. This is doc/src/guide/ for the user guide, and -doc/src/manual/ for the function reference. In the case of -the user guide, the entry point is always doc/src/guide/book.asciidoc.

-

For manual pages, it is good practice to use section 3 for -modules, and section 7 for the application itself.

-
-
-
+

AsciiDoc is a text document format for writing notes, documentation, articles, books, ebooks, slideshows, web pages, man pages and blogs. AsciiDoc files can be translated to many formats including HTML, PDF, EPUB, man page.

+

The AsciiDoc user guide describes the AsciiDoc syntax.

+

The Erlang.mk user guide is written in AsciiDoc and can be used as an example. The entry file is book.asciidoc.

+

Erlang.mk expects you to put your documentation in a specific location. This is doc/src/guide/ for the user guide, and doc/src/manual/ for the function reference. In the case of the user guide, the entry point is always doc/src/guide/book.asciidoc.

+

For manual pages, it is good practice to use section 3 for modules, and section 7 for the application itself.

Configuration

-
-

All of the AsciiDoc related configuration can be done directly -inside the files themselves.

-
-
-
+

All of the AsciiDoc related configuration can be done directly inside the files themselves.

Usage

-
-

To build all documentation:

-
-
-
$ make docs
-

To build only the AsciiDoc documentation:

-
-
-
$ make asciidoc
-

To build only the user guide:

-
-
-
$ make asciidoc-guide
-

To build only the manual:

-
-
-
$ make asciidoc-manual
-

To install man pages on Unix:

-
-
-
$ make install-docs
-

Erlang.mk allows customizing the installation path and sections -of the man pages to be installed. The MAN_INSTALL_PATH variable -defines where man pages will be installed. It defaults to -/usr/local/share/man. The MAN_SECTIONS variable defines -which manual sections are to be installed. It defaults to 3 7.

-

To install man pages to a custom location:

-
-
-
$ make install-docs MAN_INSTALL_PATH=/opt/share/man
-

Note that you may need to run the install commands using -sudo or equivalent if the location is not writeable by -your user.

-
-
+
$ make install-docs MAN_INSTALL_PATH=/opt/share/man
+ +

Note that you may need to run the install commands using sudo or equivalent if the location is not writeable by your user.

+ diff --git a/docs/en/erlang.mk/1/guide/ci/index.html b/docs/en/erlang.mk/1/guide/ci/index.html index cacdb813..c5cd6e97 100644 --- a/docs/en/erlang.mk/1/guide/ci/index.html +++ b/docs/en/erlang.mk/1/guide/ci/index.html @@ -62,80 +62,51 @@

Continuous integration

-

Erlang.mk comes with some support for continuous integration, -aimed at open source projects that need to support more than -one specific Erlang/OTP release. (If you target one specific -release, check the OTP version pinning -section of the OTP version management chapter.)

-
+

Erlang.mk comes with some support for continuous integration, aimed at open source projects that need to support more than one specific Erlang/OTP release. (If you target one specific release, check the OTP version pinning section of the OTP version management chapter.)

Configuring Erlang/OTP versions to test

-
-

To use the CI plugin you must first configure which versions -of Erlang/OTP will be used. Erlang.mk provides three separate -configuration variables depending on whether you need a normal -OTP release, a HiPE-enabled release or an ErLLVM-enabled release.

-

At the time of writing, this is how you would test against all -the most recent patch releases of Erlang/OTP 19 and above:

-
-
-
CI_OTP = OTP-19.0.7 OTP-19.1.6 OTP-19.2.3 OTP-19.3.6.2 OTP-20.0.4
-

If you want to test against HiPE and ErLLVM but only with the -latest version of Erlang/OTP, the following could work:

-
-
-
CI_HIPE = $(lastword $(CI_OTP))
-CI_ERLLVM = $(CI_HIPE)
-

Consult the OTP version management chapter for more -information about Erlang/OTP versions and customization of the -Erlang/OTP builds.

-
-
-
+
CI_HIPE = $(lastword $(CI_OTP))
+CI_ERLLVM = $(CI_HIPE)
+
+

Consult the OTP version management chapter for more information about Erlang/OTP versions and customization of the Erlang/OTP builds.

Running tests across all configured versions

-
-

The recommended way to run the ci target is with the option --k. It will ensure that tests are run for all configured -Erlang/OTP versions, even if there are errors:

-
-
-
$ make ci -k
-
- -
+
$ make ci -k
+

Extending the CI targets

-
-

The ci target can be extended. For example to run Dialyzer -at the end of CI:

-
-
-
ci:: dialyze
-

Additional setup can be done by extending the ci-setup -target. This target is ran before testing each individual -Erlang/OTP version.

-

For example, to ensure dependencies are re-fetched/built -before testing individual Erlang/OTP releases:

-
-
-
ci-setup:: distclean
-

Similarly, the ci-extra target can be extended to run -extra commands after an Erlang/OTP version has been tested.

-
- +
ci-setup:: distclean
+ +

Similarly, the ci-extra target can be extended to run extra commands after an Erlang/OTP version has been tested.

+ diff --git a/docs/en/erlang.mk/1/guide/common_test/index.html b/docs/en/erlang.mk/1/guide/common_test/index.html index f6430831..a5af0283 100644 --- a/docs/en/erlang.mk/1/guide/common_test/index.html +++ b/docs/en/erlang.mk/1/guide/common_test/index.html @@ -62,127 +62,92 @@

Common Test

-

Common Test is Erlang’s functional testing framework. -Erlang.mk automates the discovery and running of Common -Test suites.

-
+

Common Test is Erlang's functional testing framework. Erlang.mk automates the discovery and running of Common Test suites.

Writing tests

-
-

The Common Test user guide -is the best place to learn how to write tests. Erlang.mk -requires that file names for test suites end with _SUITE.erl -and that the files be located in the $(TEST_DIR) directory. -This defaults to test/.

-
-
-
+

The Common Test user guide is the best place to learn how to write tests. Erlang.mk requires that file names for test suites end with _SUITE.erl and that the files be located in the $(TEST_DIR) directory. This defaults to test/.

Configuration

-
-

The CT_OPTS variable allows you to set extra Common Test -options. Options are documented in the -Common Test user guide. -You can use it to set Common Test hooks, for example:

-
-
-
CT_OPTS = -ct_hooks cowboy_ct_hook
-

The CT_SUITES variable can be used to override what -Common Test suites Erlang.mk will be aware of. It does -not normally need to be set as Erlang.mk will find the -test suites automatically.

-

The name of the suite is the part before _SUITE.erl. -If the file is named http_SUITE.erl, the test suite -is http:

-
-
-
CT_SUITES = http ws
-

The CT_LOGS_DIR variable can be used to set where HTML -log files are to be written. This defaults to logs/.

-
-
-
CT_LOGS_DIR = ct_output_log_dir
-
-
-
+
CT_LOGS_DIR = ct_output_log_dir
+

Usage

-
-

To run all tests (including Common Test):

-
-
-
$ make tests
-

To run all tests and static checks (including Common Test):

-
-
-
$ make check
-

You can also run Common Test separately:

-
-
-
$ make ct
-

Erlang.mk will create targets for all test suites it finds. -If you have a file named test/http_SUITE.erl, then the -target ct-http will run that specific test suite:

-
-
-
$ make ct-http
-

Erlang.mk provides a convenient way to run a specific -group or a specific test case within a specific group, -using the variable t. Note that this only applies to -suite-specific targets, like the ct-http example above.

-

To run all tests from the http_compress group in the -http_SUITE test suite, write:

-
-
-
$ make ct-http t=http_compress
-

Similarly, to run a specific test case in that group:

-
-
-
$ make ct-http t=http_compress:headers_dupe
-

To do the same against a multi-application repository, -you can use the -C option:

-
-
-
$ make -C apps/my_app ct-http t=my_group:my_case
-

Note that this also applies to dependencies. When using Cowboy -as a dependency, you can run the following directly:

-
-
-
$ make -C deps/cowboy ct-http t=http_compress
-

Finally, code coverage is available, -but covered in its own chapter.

-
- +
$ make -C deps/cowboy ct-http t=http_compress
+ +

Finally, code coverage is available, but covered in its own chapter.

+ diff --git a/docs/en/erlang.mk/1/guide/compat/index.html b/docs/en/erlang.mk/1/guide/compat/index.html index 56ec41dc..a4420e66 100644 --- a/docs/en/erlang.mk/1/guide/compat/index.html +++ b/docs/en/erlang.mk/1/guide/compat/index.html @@ -62,90 +62,39 @@

Compatibility with other build tools

-

Erlang.mk tries its best to be compatible with the other Erlang -build tools. It can use dependencies written with other build -tools in mind, and can also make your projects usable by those -build tools as well. Erlang.mk is like the cool kid that gets -along with everybody.

-

In this chapter I will use the term Rebar project to refer -to a project built using Rebar 2, Rebar 3 or Mad. These three -build tools are very similar and share the same configuration -file.

-
+

Erlang.mk tries its best to be compatible with the other Erlang build tools. It can use dependencies written with other build tools in mind, and can also make your projects usable by those build tools as well. Erlang.mk is like the cool kid that gets along with everybody.

+

In this chapter I will use the term Rebar project to refer to a project built using Rebar 2, Rebar 3 or Mad. These three build tools are very similar and share the same configuration file.

Rebar projects as Erlang.mk dependencies

-
-

Erlang.mk comes with a feature called Autoload which will -use Rebar 2 to patch any Rebar project and make it compatible -with Erlang.mk. This feature essentially patches Rebar out -and adds a Makefile to the project that Erlang.mk can then -use for building:

-

Autoload is documented in more details in the -Packages and dependencies chapter.

-
-
-
+

Erlang.mk comes with a feature called Autoload which will use Rebar 2 to patch any Rebar project and make it compatible with Erlang.mk. This feature essentially patches Rebar out and adds a Makefile to the project that Erlang.mk can then use for building:

+

Autoload is documented in more details in the Packages and dependencies chapter.

Erlang.mk projects as Rebar dependencies

-
-

Erlang.mk projects can be made compatible with the Rebar family -of build tools pretty easily, as Erlang.mk will generate -all the files they require for building.

-

The Rebar family requires two files: a rebar.config file -containing compilation options and the list of dependencies, -and the application resource file, found either at -ebin/$(PROJECT).app or at src/$(PROJECT).app.src.

-
+

Erlang.mk projects can be made compatible with the Rebar family of build tools pretty easily, as Erlang.mk will generate all the files they require for building.

+

The Rebar family requires two files: a rebar.config file containing compilation options and the list of dependencies, and the application resource file, found either at ebin/$(PROJECT).app or at src/$(PROJECT).app.src.

Rebar configuration

-

Erlang.mk comes with a target that generates a rebar.config -file when invoked:

-
-
-
$ make rebar.config
-

Careful! This will build the file even if it already existed -before.

-

To build this file, Erlang.mk uses information it finds in -the DEPS and ERLC_OPTS variables, among others. This -means that the Rebar family builds your project much the -same way as Erlang.mk.

-

Careful though! Different build tools have different fetching -strategies. If some applications provide differing dependencies, -they might be fetched differently by other build tools. Check -the upcoming Sanity check chapter to find out how to detect such -issues.

-

You can automatically generate this file when you build -your application, by making it a dependency of the app -target:

-
-
+

Careful though! Different build tools have different fetching strategies. If some applications provide differing dependencies, they might be fetched differently by other build tools. Check the upcoming Sanity check chapter to find out how to detect such issues.

+

You can automatically generate this file when you build your application, by making it a dependency of the app target:

+
-
app:: rebar.config
-

Don’t forget to commit the file when it changes!

-

If you run into other issues, it’s probably because you use a -feature specific to Erlang.mk, like the cp fetch method. -It could also be that we forgot to handle something! Sorry. -We are of course interested to hear about any compatibility -problems you may have, just open a ticket!

-
-
+
app:: rebar.config
+
+

Don't forget to commit the file when it changes!

+

If you run into other issues, it's probably because you use a feature specific to Erlang.mk, like the cp fetch method. It could also be that we forgot to handle something! Sorry. We are of course interested to hear about any compatibility problems you may have, just open a ticket!

Application resource file

-

Erlang.mk has two ways to generate an application resource -file: from the information found in the Makefile, or from -the information found in the src/$(PROJECT).app.src file. -Needless to say, if you have this file in your repository, -then you don’t need to worry about compatibility with other -build tools.

-

If you don’t, however, it’s not much harder. Every time -Erlang.mk will compile your application, it will produce -a new ebin/$(PROJECT).app file. Simply commit this file -when it changes. It will only change when you modify the -configuration, add or remove modules.

-
-
-
+

Erlang.mk has two ways to generate an application resource file: from the information found in the Makefile, or from the information found in the src/$(PROJECT).app.src file. Needless to say, if you have this file in your repository, then you don't need to worry about compatibility with other build tools.

+

If you don't, however, it's not much harder. Every time Erlang.mk will compile your application, it will produce a new ebin/$(PROJECT).app file. Simply commit this file when it changes. It will only change when you modify the configuration, add or remove modules.

+ diff --git a/docs/en/erlang.mk/1/guide/contributing/index.html b/docs/en/erlang.mk/1/guide/contributing/index.html index 97a00e86..9ba72273 100644 --- a/docs/en/erlang.mk/1/guide/contributing/index.html +++ b/docs/en/erlang.mk/1/guide/contributing/index.html @@ -62,131 +62,57 @@

Contributing

-

You are welcome and encouraged to contribute.

-

This is how.

-
+

You are welcome and encouraged to contribute.

+

This is how.

Priorities

-
-

From the most important to the least important:

-
    -
  • -

    -Bugs -

    +

    From the most important to the least important:

    +
    • Bugs
    • -
    • -

      -Package issues/additions -

      +
    • Package issues/additions
    • -
    • -

      -Refactoring -

      +
    • Refactoring
    • -
    • -

      -Features -

      +
    • Features
    • -
-
-
-
+

Bugs

-
-

If you have found a bug, you should open a ticket. Include -everything relevant including the command you used, output, -a link to the code that triggers the issue, why you think -this is a bug, etc.

-

If you think you have found a bug but you are not sure, you -should open a ticket as previously explained.

-

If you have found a bug and you need it to be solved RIGHT -NOW, open a ticket as previously explained.

-

Once you have opened a ticket, be patient, try to answer -questions in a timely manner and confirm that the bug was -indeed fixed when it is.

-

If you can’t be patient, either try to solve the bug and -contribute the fix back or become a paying customer.

-
-
-
+

If you have found a bug, you should open a ticket. Include everything relevant including the command you used, output, a link to the code that triggers the issue, why you think this is a bug, etc.

+

If you think you have found a bug but you are not sure, you should open a ticket as previously explained.

+

If you have found a bug and you need it to be solved RIGHT NOW, open a ticket as previously explained.

+

Once you have opened a ticket, be patient, try to answer questions in a timely manner and confirm that the bug was indeed fixed when it is.

+

If you can't be patient, either try to solve the bug and contribute the fix back or become a paying customer.

Code

-
-

The code is located in the core/*.mk and plugins/*.mk files. -The tests are located in the test/Makefile and test/*.mk files.

-

If you have a fix or a hack for a bug, you should open a -pull request. Any fix should include a test case that fails -before the fix and is working after.

-

If you have a test case that reproduces a bug, but no fix for -it, you should open a pull request.

-

Changes need to be tested with at least the make check -command. A specific test case can be tested using make check c=CASE -with CASE the name of the target to run. Output can be -modulated using the V variable, which is an integer -from 0 to 4. A typical use would be make check c=dialyzer V=3. -The value 4 is particular and shows expanded commands right -before they are executed.

-

To run tests in parallel, use the -j option. It is generally -a good idea to also use the -k option to run all tests even -if one fails. For example: make check -j 32 -k.

-

Some changes should be tested against all packages. Continue -reading for more details on testing them.

-
-
-
+

The code is located in the core/\*.mk and plugins/\*.mk files. The tests are located in the test/Makefile and test/*.mk files.

+

If you have a fix or a hack for a bug, you should open a pull request. Any fix should include a test case that fails before the fix and is working after.

+

If you have a test case that reproduces a bug, but no fix for it, you should open a pull request.

+

Changes need to be tested with at least the make check command. A specific test case can be tested using make check c=CASE with CASE the name of the target to run. Output can be modulated using the V variable, which is an integer from 0 to 4. A typical use would be make check c=dialyzer V=3. The value 4 is particular and shows expanded commands right before they are executed.

+

To run tests in parallel, use the -j option. It is generally a good idea to also use the -k option to run all tests even if one fails. For example: make check -j 32 -k.

+

Some changes should be tested against all packages. Continue reading for more details on testing them.

Packages

-
-

You can search existing packages using the make search q=STRING -command. This can be done both from an Erlang.mk project or -directly from the Erlang.mk repository.

-

Packages can be added to the index using the pkg_add.sh script.

-
-
-
$ git clone https://github.com/$YOURUSERNAME/erlang.mk
-$ cd erlang.mk
-$ ./pkg_add.sh cowboy git https://github.com/ninenines/cowboy 1.0.0
-  http://ninenines.eu "Small, fast and modular HTTP server."
-$ git push origin master
-

Before sending a pull request, you should test your package. -You can use the following command: make check p=PACKAGE, -where PACKAGE is the name of the package, for example -cowboy.

-

To test all packages, the make packages command can be used. -This can take a long time. Some packages will fail with certain -versions of Erlang, or if a prerequisite is missing from your system. -You can of course speed things up using the -j and -k flags.

-

After all packages have been tested, you can run the command -make summary to know what changed since the previous run.

-
-
-
+
$ git clone https://github.com/$YOURUSERNAME/erlang.mk
+$ cd erlang.mk
+$ ./pkg_add.sh cowboy git https://github.com/ninenines/cowboy 1.0.0
+  http://ninenines.eu "Small, fast and modular HTTP server."
+$ git push origin master
+
+

Before sending a pull request, you should test your package. You can use the following command: make check p=PACKAGE, where PACKAGE is the name of the package, for example cowboy.

+

To test all packages, the make packages command can be used. This can take a long time. Some packages will fail with certain versions of Erlang, or if a prerequisite is missing from your system. You can of course speed things up using the -j and -k flags.

+

After all packages have been tested, you can run the command make summary to know what changed since the previous run.

Documentation

-
-

The documentation is always right.

-

If you think you have found a mistake in the documentation, -this is a bug. You can either open a ticket or send a pull -request.

-

To make sure that the documentation changes work, install -the listed Requirements on your system and -run make docs.

-
- -
+

The documentation is always right.

+

If you think you have found a mistake in the documentation, this is a bug. You can either open a ticket or send a pull request.

+

To make sure that the documentation changes work, install the listed Requirements on your system and run make docs.

Feature requests

-
-

If you have an awesome idea or need something that Erlang.mk -doesn’t provide yet, open a ticket. Provide as much detail as -possible.

-

If you have code, great! Open a pull request as previously -explained.

-

If not, you can still improve your feature request by writing -the related documentation.

-
-
+

If you have an awesome idea or need something that Erlang.mk doesn't provide yet, open a ticket. Provide as much detail as possible.

+

If you have code, great! Open a pull request as previously explained.

+

If not, you can still improve your feature request by writing the related documentation.

+ diff --git a/docs/en/erlang.mk/1/guide/coverage/index.html b/docs/en/erlang.mk/1/guide/coverage/index.html index aa986318..b740872c 100644 --- a/docs/en/erlang.mk/1/guide/coverage/index.html +++ b/docs/en/erlang.mk/1/guide/coverage/index.html @@ -62,7 +62,9 @@

Code coverage

-

Placeholder chapter.

+ +

Placeholder chapter.

+ diff --git a/docs/en/erlang.mk/1/guide/deps/index.html b/docs/en/erlang.mk/1/guide/deps/index.html index 845cfd09..a582e021 100644 --- a/docs/en/erlang.mk/1/guide/deps/index.html +++ b/docs/en/erlang.mk/1/guide/deps/index.html @@ -62,708 +62,387 @@

Packages and dependencies

-

Erlang.mk can fetch and compile the dependencies that your -project requires. Erlang.mk improves upon the concepts -introduced by Rebar, so they should be familiar to many -seasoned Erlang developers.

-

Erlang.mk is not a package manager, nor is it trying to be, -but it does include an index of Erlang packages to make -discovering useful projects easier.

-

This chapter will explain how to use packages, add -dependencies to your project or bundle them directly -in a single repository.

-
+

Erlang.mk can fetch and compile the dependencies that your project requires. Erlang.mk improves upon the concepts introduced by Rebar, so they should be familiar to many seasoned Erlang developers.

+

Erlang.mk is not a package manager, nor is it trying to be, but it does include an index of Erlang packages to make discovering useful projects easier.

+

This chapter will explain how to use packages, add dependencies to your project or bundle them directly in a single repository.

Searching packages

-
-

Erlang.mk gives you access to nearly 500 packages, with more -being added regularly.

-

To find a package, search for it:

-
-
-
$ make search q=pool
-

This will return all packages matching this word, like worker -pool and acceptor pool projects.

-

You can also list everything and use regular command line -tools to find what you need, for example:

-
-
-
$ make search | less
-
-
-
+
$ make search | less
+
+ +

Adding dependencies to your project

-
-

Once you find the package you need, adding it as a dependency -to your project is a one-liner:

-
-
-
DEPS = cowboy
-

And that’s it! The next time you run make, Erlang.mk will -fetch and compile Cowboy. Erlang.mk will also ensure Cowboy -is available whenever you use the shell, run tests and any -other operations.

-

Erlang.mk will fill in the application resource file with -all applications found in DEPS. But not all dependencies -are Erlang applications, and not all dependencies need to -be a runtime dependency. That’s where the BUILD_DEPS -variable comes in: it works just like DEPS, except the -dependencies listed there will not be added as runtime -dependencies.

-

For example, you could add a parse transform project like -this to make it available only at build time:

-
-
-
BUILD_DEPS = erlando
-

Or you could depend on a C project directly, if you are -building a NIF:

-
-
-
BUILD_DEPS = leveldb
-dep_leveldb = git https://github.com/basho/leveldb 2.1.3
-

This dependency will be built before your application, so -you could easily copy the resulting shared file into your -priv/ directory as part of the build process. More information -about that in the NIFs and port drivers -chapter.

-

Another variable, LOCAL_DEPS, allows specifying runtime -dependencies which are part of Erlang/OTP itself, but also -dependencies that are included in the repository. Since they -are already on your system, there is no need to fetch them. -Do note that there is no way to choose the version, the -application used will be the one already on your system.

-

You could depend on the Crypto application, for example:

-
-
-
LOCAL_DEPS = crypto
-

Erlang.mk comes with additional types of dependencies. -It has TEST_DEPS for dependencies used only for testing:

-
-
-
TEST_DEPS = ct_helper
-dep_ct_helper = git https://github.com/ninenines/ct_helper master
-

DOC_DEPS for dependencies used only when building documentation:

-
-
-
DOC_DEPS = edown
-

REL_DEPS for dependencies required to build the release, -or to include extra applications in the release:

-
-
-
REL_DEPS = recon
-

And SHELL_DEPS for dependencies to make available when running -the make shell command:

-
-
-
SHELL_DEPS = tddreloader
-

All these will be documented in more details in their respective -chapters.

-
+
SHELL_DEPS = tddreloader
+
+

All these will be documented in more details in their respective chapters.

Modifying the dependency source or version

-

By default, Erlang.mk will look into its package index to -find the project you are looking for, if you only provide -its name. This is this case:

-
-
-
DEPS = cowboy
-

If you need a different version, you need to define another -variable. There are two ways to do this, each being useful -for different reasons.

-

If you simply want to change the commit number, all you -need to do is to define the dep_$(DEP_NAME)_commit -variable. In the case of Cowboy, this would look like this:

-
-
-
DEPS = cowboy
-dep_cowboy_commit = 2.0.0-pre.2
-

Erlang.mk will use the package index to get all information -about Cowboy, except the commit number which will be overriden.

-

If you need to set the fetch method or repository information -too, for example because you want to use your own fork, or -simply because the project is missing from the index, you -can define the dep_$(DEP_NAME) variable with everything:

-
-
-
DEPS = cowboy
-dep_cowboy = git https://github.com/essen/cowboy 2.0.0-pre.2
-

This will fetch Cowboy from your fork at the given commit.

- -
+
DEPS = cowboy
+dep_cowboy = git https://github.com/essen/cowboy 2.0.0-pre.2
+
+

This will fetch Cowboy from your fork at the given commit.

Fetch methods

-

Erlang.mk comes with a number of different fetch methods. -You can fetch from Git, Mercurial, SVN, to name a few. -There are fetch methods that will work everywhere, and -fetch methods that will only work in a given environment.

-

The following table lists all existing methods:

-
- ---- - - - - - - - - - - - +

Erlang.mk comes with a number of different fetch methods. You can fetch from Git, Mercurial, SVN, to name a few. There are fetch methods that will work everywhere, and fetch methods that will only work in a given environment.

+

The following table lists all existing methods:

+
Name Format Description

git

git repo commit

Clone the Git repository and checkout the given version

+ + + + + + - - - - + + + - - - - + + + - - - - + + + - - - - + + + - - - - + + + - - - - + + + - - - - + + + - - - - + + + - -
NameFormatDescription
gitgit repo commitClone the Git repository and checkout the given version

git-submodule

git-submodule

Initialize and update the Git submodule

git-submodulegit-submoduleInitialize and update the Git submodule

hg

hg repo commit

Clone the Mercurial repository and update to the given version

hghg repo commitClone the Mercurial repository and update to the given version

svn

svn repo

Checkout the given SVN repository

svnsvn repoCheckout the given SVN repository

cp

cp path/to/repo

Recursively copy a local directory

cpcp path/to/repoRecursively copy a local directory

ln

ln path/to/repo

Symbolically link a local directory

lnln path/to/repoSymbolically link a local directory

hex

hex version

Download the given project version from hex.pm

hexhex versionDownload the given project version from hex.pm

fail

N/A

Always fail, reserved for internal use

failN/AAlways fail, reserved for internal use

legacy

N/A

Legacy Erlang.mk fetcher, reserved for internal use

legacyN/ALegacy Erlang.mk fetcher, reserved for internal use
-
-

The git and hg methods both have a repository and commit. -You can use any valid commit, tag or branch in that repository -for the commit value.

-

For example, to fetch Cowboy with tag 2.0.0-pre.2 from Git:

-
-
-
dep_cowboy = git https://github.com/ninenines/cowboy 2.0.0-pre.2
-

Or to fetch Ehsa tag 4.0.3 from Mercurial:

-
-
-
dep_ehsa = hg https://bitbucket.org/a12n/ehsa 4.0.3
-

Git also comes with a concept of submodules. Erlang.mk can -automatically initializes and updates submodules for dependencies, -as long as they were added beforehand using git submodule add:

-
-
-
dep_cowboy = git-submodule
-

The svn method only has a repository value, but that’s -simply because the SVN repository URL can also contain -the path and commit.

-

This would fetch an example project from the trunk:

-
-
-
dep_ex1 = svn https://example.com/svn/trunk/project/ex1
-

And this would fetch a separate example project from a -specific commit:

-
-
-
dep_ex2 = svn svn://example.com/svn/branches/erlang-proj/ex2@264
-

You can copy a directory from your machine using the cp method. -It only takes the path to copy from:

-
-
-
dep_cowboy = cp $(HOME)/ninenines/cowboy
-

Finally, you can use a package from the -Hex repository:

-
-
-
dep_cowboy = hex 1.0.3
- -
+
dep_cowboy = hex 1.0.3
+

Custom fetch methods

-

If none of the existing methods fit your use, you can simply -define your own. Erlang.mk will consider all variables that -are named as dep_fetch_$(METHOD) to be available fetch -methods. You can do anything inside this variable, as long -as you create a folder named $(DEPS_DIR)/$(call dep_name,$1). -Or in layman terms, if your dependency is Cowboy, this would -become deps/cowboy.

-

To give an example, this is what the Git method does:

-
-
define dep_fetch_git
-        git clone -q -n -- $(call dep_repo,$1) $(DEPS_DIR)/$(call dep_name,$1); \
-        cd $(DEPS_DIR)/$(call dep_name,$1) && git checkout -q $(call dep_commit,$1);
-endef
-

Note that, like dependency information, this custom fetch method -must be written before including erlang.mk.

- - - -
+ git clone -q -n -- $(call dep_repo,$1) $(DEPS_DIR)/$(call dep_name,$1); \ + cd $(DEPS_DIR)/$(call dep_name,$1) && git checkout -q $(call dep_commit,$1); +endef +
+

Note that, like dependency information, this custom fetch method must be written before including erlang.mk.

How deps are fetched and built

-
-

The order in which dependencies are fetched and built is well -defined. This means that Erlang.mk will get the same applications -regardless of the command or options being used.

-

In tree traversal terms, where the list of dependencies is a -tree, Erlang.mk fetches everything using the pre-order traversal -method. The steps can be summarized like this, starting from -the root application:

-
    -
  1. -

    -Fetch all dependencies for the application -

    +

    The order in which dependencies are fetched and built is well defined. This means that Erlang.mk will get the same applications regardless of the command or options being used.

    +

    In tree traversal terms, where the list of dependencies is a tree, Erlang.mk fetches everything using the pre-order traversal method. The steps can be summarized like this, starting from the root application:

    +
    1. Fetch all dependencies for the application
    2. -
    3. -

      -Build first dependency -

      +
    4. Build first dependency
    5. -
    6. -

      -Build Nth dependency -

      +
    7. Build Nth dependency
    8. -
    9. -

      -Build last dependency -

      +
    10. Build last dependency
    11. -
-

Every time a dependency is built, these same steps are followed, -recursively.

-

Do note that the first step, fetching all dependencies of -an application, is not guaranteed to be ordered. The reason -for this is that it is not possible to have the same dependency -listed twice in a single application, and therefore there can -be no conflicts. Remember, this step only fetches, at no point -are different applications built in parallel.

-

What about conflicts between the dependencies of different -applications? Simple. Since builds are ordered, this means -that the first version of an application that is fetched -will be the one that wins.

-

This means that if project A depends on projects B and C, -in this order, and that both B and C depend on a different -version of D, it will always be B’s version of D that wins, -because we fetch the dependencies of B before fetching -those from C.

-

Similarly, if project A depends on projects B, C and D, -regardless of the order, and A, B and C depend on a -different version of D, it will always be A’s version -that wins, because we fetch all dependencies of A before -fetching those from B or C.

-
- -
+ +

Every time a dependency is built, these same steps are followed, recursively.

+

Do note that the first step, fetching all dependencies of an application, is not guaranteed to be ordered. The reason for this is that it is not possible to have the same dependency listed twice in a single application, and therefore there can be no conflicts. Remember, this step only fetches, at no point are different applications built in parallel.

+

What about conflicts between the dependencies of different applications? Simple. Since builds are ordered, this means that the first version of an application that is fetched will be the one that wins.

+

This means that if project A depends on projects B and C, in this order, and that both B and C depend on a different version of D, it will always be B's version of D that wins, because we fetch the dependencies of B before fetching those from C.

+

Similarly, if project A depends on projects B, C and D, regardless of the order, and A, B and C depend on a different version of D, it will always be A's version that wins, because we fetch all dependencies of A before fetching those from B or C.

Fetching and listing dependencies only

-
-

You can fetch all dependencies recursively without building anything, -with the make fetch-deps command. It follows the same rules described -in the section above.

-

You can list all dependencies recursively, again without building -anything, with the make list-deps command. It will obviously need -to fetch all dependencies exactly like make fetch-deps. Once -everything is fetched, it prints a sorted list of absolute paths to the -dependencies.

-

By default, fetch-deps and list-deps work on the BUILD_DEPS -and DEPS lists only. To also fetch/list TEST_DEPS, DOC_DEPS, -REL_DEPS and/or SHELL_DEPS, you have two possibilities:

-
    -
  • -

    -You can use make fetch-test-deps, make fetch-doc-deps, make - fetch-rel-deps and make fetch-shell-deps commands respectively. - If you want to list them, you can use make list-test-deps, make - list-doc-deps, make list-rel-deps and make list-shell-deps - respectively. -

    +

    You can fetch all dependencies recursively without building anything, with the make fetch-deps command. It follows the same rules described in the section above.

    +

    You can list all dependencies recursively, again without building anything, with the make list-deps command. It will obviously need to fetch all dependencies exactly like make fetch-deps. Once everything is fetched, it prints a sorted list of absolute paths to the dependencies.

    +

    By default, fetch-deps and list-deps work on the BUILD_DEPS and DEPS lists only. To also fetch/list TEST_DEPS, DOC_DEPS, REL_DEPS and/or SHELL_DEPS, you have two possibilities:

    +
    • You can use make fetch-test-deps, make fetch-doc-deps, make +fetch-rel-deps and make fetch-shell-deps commands respectively. If you want to list them, you can use make list-test-deps, make +list-doc-deps, make list-rel-deps and make list-shell-deps respectively.
    • -
    • -

      -You can use make fetch-deps or make list-deps with the Makefile - variable DEP_TYPES set to a list of dependency types you want. - The types are test, doc, rel and shell respectively. For - example, you can list test and doc dependencies with make list-deps - DEP_TYPES='test doc'. -

      +
    • You can use make fetch-deps or make list-deps with the Makefile variable DEP_TYPES set to a list of dependency types you want. The types are test, doc, rel and shell respectively. For example, you can list test and doc dependencies with make list-deps +DEP_TYPES='test doc'.
    • -
-

Note that only first level ‘TEST_DEPS, `DOC_DEPS, REL_DEPS and -SHELL_DEPS are included, not dependencies’ one. In other word, -make list-test-deps lists the TEST_DEPS of your project, but not -TEST_DEPS of the projects yours depend on.

-

No matter which method you use, BUILD_DEPS and DEPS are always -included.

-

Internally, the make fetch-* commands store the complete list of -dependencies in files named $(ERLANG_MK_RECURSIVE_DEPS_LIST), -$(ERLANG_MK_RECURSIVE_TEST_DEPS_LIST), -$(ERLANG_MK_RECURSIVE_DOC_DEPS_LIST), -$(ERLANG_MK_RECURSIVE_REL_DEPS_LIST) and -$(ERLANG_MK_RECURSIVE_SHELL_DEPS_LIST). Those files are simply printed -by the make list-* commands.

-

make list-* commands are made for human beings. If you need the list -of dependencies in a Makefile or a script, you should use the content -of those files directly instead. The reason is that make fetch-* and -make list-* may have unwanted content in their output, such as actual -fetching of dependencies.

-
-
-
+ +

Note that only first level TEST_DEPS, DOC_DEPS, REL_DEPS and SHELL_DEPS are included, not dependencies' one. In other word, make list-test-deps lists the TEST_DEPS of your project, but not TEST_DEPS of the projects yours depend on.

+

No matter which method you use, BUILD_DEPS and DEPS are always included.

+

Internally, the make fetch-* commands store the complete list of dependencies in files named $(ERLANG_MK_RECURSIVE_DEPS_LIST), $(ERLANG_MK_RECURSIVE_TEST_DEPS_LIST), $(ERLANG_MK_RECURSIVE_DOC_DEPS_LIST), $(ERLANG_MK_RECURSIVE_REL_DEPS_LIST) and $(ERLANG_MK_RECURSIVE_SHELL_DEPS_LIST). Those files are simply printed by the make list-* commands.

+

make list-* commands are made for human beings. If you need the list of dependencies in a Makefile or a script, you should use the content of those files directly instead. The reason is that make fetch-* and make list-* may have unwanted content in their output, such as actual fetching of dependencies.

Ignoring unwanted dependencies

-
-

Sometimes, you may want to ignore dependencies entirely. -Not even fetch them. You may want to do this because a -project you depend on depends on an application you do -not need (like a dependency for building documentation -or testing). Or maybe the dependency is already installed -on your system.

-

To ignore a dependency, simply add it to the IGNORE_DEPS -variable:

-
-
-
IGNORE_DEPS += edown proper
-

This will only ignore dependencies that are needed for -building. It is therefore safe to write:

-
-
-
IGNORE_DEPS += edown proper
-TEST_DEPS = proper
-

The PropEr application will be fetched as intended when -running make tests or make check. It will however -not be fetched when running make or make deps.

-
-
-
+
IGNORE_DEPS += edown proper
+TEST_DEPS = proper
+
+

The PropEr application will be fetched as intended when running make tests or make check. It will however not be fetched when running make or make deps.

Dependencies directory

-
-

Dependencies are fetched in $(DEPS_DIR). By default this is -the deps directory. You can change this default, but you -should only do so if it was not defined previously. Erlang.mk -uses this variable to tell dependencies where to fetch their -own dependencies.

-

You will therefore need to use ?= instead of =. Of course, -if you know you will never use this project as a dependency, -= will work. But to avoid it biting you later on, do this:

-
-
-
DEPS_DIR ?= $(CURDIR)/libs
-

The $(CURDIR) part is important, otherwise dependencies of -dependencies will be fetched in the wrong directory.

-

Erlang.mk will also export the REBAR_DEPS_DIR variable for -compatibility with Rebar build tools, as long as they are -recent enough.

-
- -
+
DEPS_DIR ?= $(CURDIR)/libs
+
+

The $(CURDIR) part is important, otherwise dependencies of dependencies will be fetched in the wrong directory.

+

Erlang.mk will also export the REBAR_DEPS_DIR variable for compatibility with Rebar build tools, as long as they are recent enough.

Many applications in one repository

-
-

In addition to the dependencies that are fetched, Erlang.mk -also allows you to have dependencies local to your repository. -This kind of layout is sometimes called multi-application -repositories, or repositories with multiple applications.

-

They work exactly the same as remote dependencies, except:

-
    -
  • -

    -They are not fetched -

    +

    In addition to the dependencies that are fetched, Erlang.mk also allows you to have dependencies local to your repository. This kind of layout is sometimes called multi-application repositories, or repositories with multiple applications.

    +

    They work exactly the same as remote dependencies, except:

    +
    • They are not fetched
    • -
    • -

      -They are not autopatched -

      +
    • They are not autopatched
    • -
    • -

      -They are not deleted on make distclean -

      +
    • They are not deleted on make distclean
    • -
    • -

      -They are not automatically added to the application resource file -

      +
    • They are not automatically added to the application resource file
    • -
-

To properly fill the application resource file and compile apps in -the right order, you will need to define the LOCAL_DEPS variable -for each relevant application, the same as for OTP applications. Apps -can depend on each other in this way, and their compilation order -will follow the same rules as regular dependencies in DEPS.

-

The top-level LOCAL_DEPS variable, if defined, will determine which -apps (along with their dependencies) to build, and also which apps -should be added to the top-level application resource file, if there -is one. This may be useful, for example, for specifying a different -set of apps to build for different releases. If LOCAL_DEPS is not -defined, then all apps in the $(APPS_DIR) will be built, but none -will be automatically added to the top-level application resource -file.

-

If there is a conflict between a local dependency and a -remote dependency, then the local dependency always wins; -an error will be triggered when trying to fetch the -conflicting remote dependency.

-

To start using dependencies local to the repository, simply -create a folder named $(APPS_DIR). By default, this folder -is the apps/ directory.

-

You can use Erlang.mk to bootstrap local dependencies by -using the command make new-app or make new-lib. This -command will create the necessary directories and bootstrap -the application.

-

For example, to create a full fledged OTP application as -a local dependency:

-
-
-
$ make new-app in=webchat
-

Or, the same as an OTP library:

-
-
-
$ make new-lib in=webchat
-

Templates also work with local dependencies, from the root -directory of the project. You do need however to tell -Erlang.mk to create the files in the correct application:

-
-
-
$ make new t=gen_server n=my_server in=webchat
-
- -
+
$ make new t=gen_server n=my_server in=webchat
+

Repositories with no application at the root level

-
-

It’s possible to use Erlang.mk with only applications in -$(APPS_DIR), and nothing at the root of the repository. -Just create a folder, put the erlang.mk file in it, -write a Makefile that includes it, and start creating -your applications.

-

Similarly, it’s possible to have a repository with only -dependencies found in $(DEPS_DIR). You just need to -create a Makefile and specify the dependencies you want. -This allows you to create a repository for handling the -building of releases, for example.

-
- -
+

It's possible to use Erlang.mk with only applications in $(APPS_DIR), and nothing at the root of the repository. Just create a folder, put the erlang.mk file in it, write a Makefile that includes it, and start creating your applications.

+

Similarly, it's possible to have a repository with only dependencies found in $(DEPS_DIR). You just need to create a Makefile and specify the dependencies you want. This allows you to create a repository for handling the building of releases, for example.

Autopatch

-
-

Erlang.mk will automatically patch all the dependencies it -fetches. It needs to do this to ensure that the dependencies -become compatible with not only Erlang.mk, but also with -the version of Erlang.mk that is currently used.

-

When fetching a dependency, the following operations are -performed:

-
    -
  • -

    -Fetch the dependency using the configured fetch method -

    +

    Erlang.mk will automatically patch all the dependencies it fetches. It needs to do this to ensure that the dependencies become compatible with not only Erlang.mk, but also with the version of Erlang.mk that is currently used.

    +

    When fetching a dependency, the following operations are performed:

    +
    • Fetch the dependency using the configured fetch method
    • -
    • -

      -If it contains a configure.ac or configure.in file, run autoreconf -Wall -vif -I m4 -

      +
    • If it contains a configure.ac or configure.in file, run autoreconf -Wall -vif -I m4
    • -
    • -

      -If it contains a configure script, run it -

      +
    • If it contains a configure script, run it
    • -
    • -

      -Run autopatch on the project -

      +
    • Run autopatch on the project
    • -
-

Autopatch first checks if there is any project-specific patch -enabled. There are currently two: RABBITMQ_CLIENT_PATCH for -the amqp_client dependency, and RABBITMQ_SERVER_PATCH for -the rabbit dependency. These are needed only for RabbitMQ -versions before 3.6.0 (assuming you are using upstream RabbitMQ, -and not a fork).

-

Otherwise, autopatch performs different operations depending -on the kind of project it finds the dependency to be.

-
    -
  • -

    -Rebar projects are automatically converted to use Erlang.mk -as their build tool. This essentially patches Rebar out, and -fixes and converts the project to be compatible with Erlang.mk. -

    +
+

Autopatch first checks if there is any project-specific patch enabled. There are currently two: RABBITMQ_CLIENT_PATCH for the amqp_client dependency, and RABBITMQ_SERVER_PATCH for the rabbit dependency. These are needed only for RabbitMQ versions before 3.6.0 (assuming you are using upstream RabbitMQ, and not a fork).

+

Otherwise, autopatch performs different operations depending on the kind of project it finds the dependency to be.

+
  • Rebar projects are automatically converted to use Erlang.mk as their build tool. This essentially patches Rebar out, and fixes and converts the project to be compatible with Erlang.mk.
  • -
  • -

    -Erlang.mk projects have their Makefile patched, if necessary, -to include the top-level project’s Erlang.mk. This is to ensure -that functionality works across all dependencies, even if the -dependency’s Erlang.mk is outdated. The patched Makefile -can be safely committed if necessary. -

    +
  • Erlang.mk projects have their Makefile patched, if necessary, to include the top-level project's Erlang.mk. This is to ensure that functionality works across all dependencies, even if the dependency's Erlang.mk is outdated. The patched Makefile can be safely committed if necessary.
  • -
  • -

    -Other Erlang projects get a small Erlang.mk Makefile -generated automatically. -

    +
  • Other Erlang projects get a small Erlang.mk Makefile generated automatically.
  • -
  • -

    -Projects with no source directory and no Makefile get an -empty Makefile generated, for compatibility purposes. -

    +
  • Projects with no source directory and no Makefile get an empty Makefile generated, for compatibility purposes.
  • -
  • -

    -Other projects with no Makefile are left untouched. -

    +
  • Other projects with no Makefile are left untouched.
  • -
-

You can disable the replacing of the erlang.mk file by -defining the NO_AUTOPATCH_ERLANG_MK variable:

-
-
-
NO_AUTOPATCH_ERLANG_MK = 1
-

You can also disable autopatch entirely for a few select -projects using the NO_AUTOPATCH variable:

-
-
-
NO_AUTOPATCH = cowboy ranch cowlib
-
-
-
+
NO_AUTOPATCH = cowboy ranch cowlib
+

Skipping deps

-
-

It is possible to temporarily skip all dependency operations. -This is done by defining the SKIP_DEPS variable. Use cases -include being somewhere with no connection to download them, -or perhaps a peculiar setup.

-

A typical usage would be:

-
-
-
$ make SKIP_DEPS=1
-

When the variable is defined:

-
    -
  • -

    -Dependencies will not be compiled or downloaded when required -

    +
    $ make SKIP_DEPS=1
    +
+

When the variable is defined:

+
  • Dependencies will not be compiled or downloaded when required
  • -
  • -

    -The dependency directory $(DEPS_DIR) will not be removed on make distclean -

    +
  • The dependency directory $(DEPS_DIR) will not be removed on make distclean
  • -
-

This variable only applies to remote dependencies.

- - + +

This variable only applies to remote dependencies.

+ diff --git a/docs/en/erlang.mk/1/guide/dialyzer/index.html b/docs/en/erlang.mk/1/guide/dialyzer/index.html index fedd4cae..e548daf4 100644 --- a/docs/en/erlang.mk/1/guide/dialyzer/index.html +++ b/docs/en/erlang.mk/1/guide/dialyzer/index.html @@ -62,77 +62,37 @@

Dialyzer

-

Dialyzer is a tool that will detect discrepancies in your -program. It does so using a technique known as success -typing analysis which has the advantage of providing no -false positives. Dialyzer is able to detect type errors, -dead code and more.

-

Erlang.mk provides a wrapper around Dialyzer.

-
+

Dialyzer is a tool that will detect discrepancies in your program. It does so using a technique known as success typing analysis which has the advantage of providing no false positives. Dialyzer is able to detect type errors, dead code and more.

+

Erlang.mk provides a wrapper around Dialyzer.

How it works

-
-

Dialyzer requires a PLT file to work. The PLT file contains -the analysis information from all applications which are not -expected to change, or rarely do. These would be all the -dependencies of the application or applications you are -currently working on, including standard applications in -Erlang/OTP itself.

-

Dialyzer can generate this PLT file. Erlang.mk includes rules -to automatically generate the PLT file when it is missing.

-

Once the PLT file is generated, Dialyzer can perform the -analysis in record time.

-
-
-
+

Dialyzer requires a PLT file to work. The PLT file contains the analysis information from all applications which are not expected to change, or rarely do. These would be all the dependencies of the application or applications you are currently working on, including standard applications in Erlang/OTP itself.

+

Dialyzer can generate this PLT file. Erlang.mk includes rules to automatically generate the PLT file when it is missing.

+

Once the PLT file is generated, Dialyzer can perform the analysis in record time.

Configuration

-
-

In a typical usage scenario, no variable needs to be set. -The defaults should be enough. Do note however that the -dependencies need to be set properly using the DEPS and -LOCAL_DEPS variables.

-

The DIALYZER_PLT file indicates where the PLT file will -be written to (and read from). By default this is -$(PROJECT).plt in the project’s directory. Note that -the DIALYZER_PLT variable is exported and is understood -by Dialyzer directly.

-

The PLT_APPS variable can be used to add additional -applications to the PLT. You can either list application -names or paths to these applications.

-

Erlang.mk defines two variables for specifying options -for the analysis: DIALYZER_DIRS and DIALYZER_OPTS. -The former one defines which directories should be part -of the analysis. The latter defines what extra warnings -Dialyzer should report.

-

Note that Erlang.mk enables the race condition warnings -by default. As it can take considerably large resources -to run, you may want to disable it on larger projects.

-
-
-
+

In a typical usage scenario, no variable needs to be set. The defaults should be enough. Do note however that the dependencies need to be set properly using the DEPS and LOCAL_DEPS variables.

+

The DIALYZER_PLT file indicates where the PLT file will be written to (and read from). By default this is $(PROJECT).plt in the project's directory. Note that the DIALYZER_PLT variable is exported and is understood by Dialyzer directly.

+

The PLT_APPS variable can be used to add additional applications to the PLT. You can either list application names or paths to these applications.

+

Erlang.mk defines two variables for specifying options for the analysis: DIALYZER_DIRS and DIALYZER_OPTS. The former one defines which directories should be part of the analysis. The latter defines what extra warnings Dialyzer should report.

+

Note that Erlang.mk enables the race condition warnings by default. As it can take considerably large resources to run, you may want to disable it on larger projects.

Usage

-
-

To perform an analysis, run the following command:

-
-
-
$ make dialyze
-

This will create the PLT file if it doesn’t exist.

-

The analysis will also be performed when you run the -following command, alongside tests:

-
-
-
$ make check
-

You can use the plt target to create the PLT file if -it doesn’t exist. This is normally not necessary as -Dialyzer creates it automatically.

-

The PLT file will be removed when you run make distclean.

-
-
+
$ make check
+ +

You can use the plt target to create the PLT file if it doesn't exist. This is normally not necessary as Dialyzer creates it automatically.

+

The PLT file will be removed when you run make distclean.

+ diff --git a/docs/en/erlang.mk/1/guide/edoc/index.html b/docs/en/erlang.mk/1/guide/edoc/index.html index cb234d92..06f620ad 100644 --- a/docs/en/erlang.mk/1/guide/edoc/index.html +++ b/docs/en/erlang.mk/1/guide/edoc/index.html @@ -62,63 +62,43 @@

EDoc comments

-

Erlang.mk provides a thin wrapper on top of EDoc, an application -that generates documentation based on comments found in modules.

-
+

Erlang.mk provides a thin wrapper on top of EDoc, an application that generates documentation based on comments found in modules.

Writing EDoc comments

-
-

The EDoc user guide -explains everything you need to know about EDoc comments.

-
-
-
+

The EDoc user guide explains everything you need to know about EDoc comments.

Configuration

-
-

The EDOC_OPTS variable allows you to specify additional -EDoc options. Options are documented in the -EDoc manual.

-

A common use for this variable is to enable Markdown in doc -comments, using the edown application:

-
-
-
DOC_DEPS = edown
-EDOC_OPTS = {doclet, edown_doclet}
-
-
-
+
DOC_DEPS = edown
+EDOC_OPTS = {doclet, edown_doclet}
+

Usage

-
-

To build all documentation, you would typically use:

-
-
-
$ make docs
-

Do note, however, that EDoc comments will only be generated -automatically if the doc/overview.edoc file exists. If you -do not want that file and still want to generate doc comments, -two solutions are available.

-

You can generate EDoc documentation directly:

-
-
-
$ make edoc
-

You can enable automatic generation on make docs by adding -the following to your Makefile:

-
-
-
docs:: edoc
-
- +
docs:: edoc
+ + diff --git a/docs/en/erlang.mk/1/guide/escripts/index.html b/docs/en/erlang.mk/1/guide/escripts/index.html index fbe0a336..b33b5841 100644 --- a/docs/en/erlang.mk/1/guide/escripts/index.html +++ b/docs/en/erlang.mk/1/guide/escripts/index.html @@ -62,96 +62,53 @@

Escripts

-

Escripts are an alternative to release. They are meant to be -used for small command line executables written in Erlang.

-

They are not self-contained, unlike releases. -Erlang must be installed for them to run. This however means -that they are fairly small compared to releases.

-

For self-contained executables, check self-extracting releases.

-
+

Escripts are an alternative to release. They are meant to be used for small command line executables written in Erlang.

+

They are not self-contained, unlike releases. Erlang must be installed for them to run. This however means that they are fairly small compared to releases.

+

For self-contained executables, check self-extracting releases.

Requirements

-
-

Erlang.mk uses p7zip by default to generate the escript -archive. Make sure it is installed. On most systems the -package is named p7zip; on Ubuntu you need p7zip-full.

-

If p7zip is unavailable, zip may be used by setting -the ESCRIPT_ZIP variable. For example:

-
-
-
$ make escript ESCRIPT_ZIP=zip
-
-
-
+
$ make escript ESCRIPT_ZIP=zip
+

Generating an escript

-
-

Run the following command to generate an escript:

-
-
-
$ make escript
-

This will by default create an escript with the same name as -the project, in the project’s directory. If the project is -called relx then the escript will be in ./relx.

-

You can run the escript as you would any executable:

-
-
-
$ ./relx
-
- -
+
$ ./relx
+

Configuration

-
-

You can change the name of the escript by setting ESCRIPT_NAME. -The name determines both the default output file name and the -entry module containing the function main/1.

-

ESCRIPT_FILE can be set if you need a different file name -or location.

-

The escript header can be entirely customized. The first line -is the shebang, set by ESCRIPT_SHEBANG. The second line is -a comment, set by ESCRIPT_COMMENT. The third line is the -arguments the VM will use when running the escript, set by -ESCRIPT_EMU_ARGS.

-

Finally, ESCRIPT_ZIP can be set to customize the command used -to create the zip file. Read on for more information.

-
- -
+

You can change the name of the escript by setting ESCRIPT_NAME. The name determines both the default output file name and the entry module containing the function main/1.

+

ESCRIPT_FILE can be set if you need a different file name or location.

+

The escript header can be entirely customized. The first line is the shebang, set by ESCRIPT_SHEBANG. The second line is a comment, set by ESCRIPT_COMMENT. The third line is the arguments the VM will use when running the escript, set by ESCRIPT_EMU_ARGS.

+

Finally, ESCRIPT_ZIP can be set to customize the command used to create the zip file. Read on for more information.

Extra files

-
-

Generating an escript is a two-part process. First, a zip file -is created with the contents of the escript. Then a header is -added to this file to create the escript.

-

It is possible to add commands that will be executed between -the two steps. You can for example add extra files to the zip -archive:

-
-
-
escript-zip::
-    $(verbose) $(ESCRIPT_ZIP) $(ESCRIPT_ZIP_FILE) priv/templates/*
-

The ESCRIPT_ZIP variable contains the command to run to add -files to the zip archive ESCRIPT_ZIP_FILE.

-
-
-
+
escript-zip::
+    $(verbose) $(ESCRIPT_ZIP) $(ESCRIPT_ZIP_FILE) priv/templates/*
+
+

The ESCRIPT_ZIP variable contains the command to run to add files to the zip archive ESCRIPT_ZIP_FILE.

Optimizing for size

-
-

Erlang.mk will by default compile BEAM files with debug -information. You may want to disable this behavior to obtain -smaller escript files. Simply set ERLC_OPTS to a value that -does not include +debug_info.

-
- +

Erlang.mk will by default compile BEAM files with debug information. You may want to disable this behavior to obtain smaller escript files. Simply set ERLC_OPTS to a value that does not include +debug_info.

+ diff --git a/docs/en/erlang.mk/1/guide/eunit/index.html b/docs/en/erlang.mk/1/guide/eunit/index.html index b1d257c2..6073d3f8 100644 --- a/docs/en/erlang.mk/1/guide/eunit/index.html +++ b/docs/en/erlang.mk/1/guide/eunit/index.html @@ -62,149 +62,110 @@

EUnit

-

EUnit is the tool of choice for unit testing. Erlang.mk -automates a few things on top of EUnit, including the -discovery and running of unit tests.

-
+

EUnit is the tool of choice for unit testing. Erlang.mk automates a few things on top of EUnit, including the discovery and running of unit tests.

Writing tests

-
-

The EUnit user guide -is the best place to learn how to write tests. Of note is -that all functions ending with _test or _test_ will be -picked up as EUnit test cases.

-

Erlang.mk will automatically pick up tests found in any of -the Erlang modules of your application. It will also pick up -tests located in the $(TEST_DIR) directory, which defaults -to test/.

-

It is generally a good practice to hide test code from -the code you ship to production. With Erlang.mk, you can -do this thanks to the TEST macro. It is only defined -when running tests:

-
-
-
-ifdef(TEST).
+
-ifdef(TEST).
 
-%% Insert tests here.
+%% Insert tests here.
 
--endif.
-

Be careful, however, if you include the EUnit header file, -as it also defines the TEST macro. Make sure to only include -it inside an ifdef block, otherwise tests will always be -compiled.

-
-
-
-ifdef(TEST).
+
-ifdef(TEST).
 
--include_lib(\"eunit/include/eunit.hrl\").
+-include_lib(\"eunit/include/eunit.hrl\").
 
-%% Insert tests here.
+%% Insert tests here.
 
--endif.
-

Erlang.mk will automatically recompile your code when you -perform a normal build after running tests, and vice versa.

-
-
-
+-endif. +
+

Erlang.mk will automatically recompile your code when you perform a normal build after running tests, and vice versa.

Configuration

-
-

The EUNIT_OPTS variable allows you to specify additional -EUnit options. Options are documented in the -EUnit manual. -At the time of writing, the only available option is verbose:

-
-
-
EUNIT_OPTS = verbose
-

The EUNIT_ERL_OPTS variable allows you to specify options -to be passed to erl when running EUnit tests. For example, -you can load the vm.args and sys.config files:

-
-
-
EUNIT_ERL_OPTS = -args_file rel/vm.args -config rel/sys.config
-
- -
+
EUNIT_ERL_OPTS = -args_file rel/vm.args -config rel/sys.config
+

Usage

-
-

To run all tests (including EUnit):

-
-
-
$ make tests
-

To run all tests and static checks (including EUnit):

-
-
-
$ make check
-

You can also run EUnit separately:

-
-
-
$ make eunit
-

EUnit will be quiet by default, only outputting errors. -You can easily make it verbose for a single invocation:

-
-
-
$ make eunit EUNIT_OPTS=verbose
-

Erlang.mk allows you to run all tests from a specific -module, or a specific test case from that module, using -the variable t.

-

For example, to run all tests from the cow_http_hd -module (instead of all tests from the entire project), -one could write:

-
-
-
$ make eunit t=cow_http_hd
-

Similarly, to run a specific test case:

-
-
-
$ make eunit t=cow_http_hd:parse_accept_test_
-

To do the same against a multi-application repository, -you can use the -C option:

-
-
-
$ make -C apps/my_app eunit t=my_module:hello_test
-

Note that this also applies to dependencies. From Cowboy, -you can run the following directly:

-
-
-
$ make -C deps/cowlib eunit t=cow_http_hd
-

Finally, code coverage is available, -but covered in its own chapter.

-
- +
$ make -C deps/cowlib eunit t=cow_http_hd
+ +

Finally, code coverage is available, but covered in its own chapter.

+ diff --git a/docs/en/erlang.mk/1/guide/external_plugins/index.html b/docs/en/erlang.mk/1/guide/external_plugins/index.html index da596541..3eaac0d6 100644 --- a/docs/en/erlang.mk/1/guide/external_plugins/index.html +++ b/docs/en/erlang.mk/1/guide/external_plugins/index.html @@ -62,154 +62,92 @@

External plugins

-

It is often convenient to be able to keep the build files -used by all your projects in one place. Those files could -be Makefiles, configuration files, templates and more.

-

Erlang.mk allows you to automatically load plugins from -dependencies. Plugins can do anything, including defining -new variables, defining file templates, hooking themselves -inside the normal Erlang.mk processing or even adding new -rules.

-

You can load plugins using one of two methods. You can -either load all plugins from a dependency, or just one. -We will also cover conventions about writing external -plugins.

-
+

It is often convenient to be able to keep the build files used by all your projects in one place. Those files could be Makefiles, configuration files, templates and more.

+

Erlang.mk allows you to automatically load plugins from dependencies. Plugins can do anything, including defining new variables, defining file templates, hooking themselves inside the normal Erlang.mk processing or even adding new rules.

+

You can load plugins using one of two methods. You can either load all plugins from a dependency, or just one. We will also cover conventions about writing external plugins.

Loading all plugins from a dependency

-
-

To load plugins from a dependency, all you need to do is add -the dependency name to DEP_PLUGINS in addition to the list -of dependencies.

-

For example, if you have cowboy in DEPS, add cowboy in -DEP_PLUGINS also:

-
-
-
DEPS = cowboy
-DEP_PLUGINS = cowboy
-

This will load the file plugins.mk in the root folder of -the Cowboy repository.

-
-
-
+
DEPS = cowboy
+DEP_PLUGINS = cowboy
+
+

This will load the file plugins.mk in the root folder of the Cowboy repository.

Loading one plugin from a dependency

-
-

Now that we know how to load all plugins, let’s take a look -at how to load one specific plugin from a dependency.

-

To do this, instead of writing only the name of the dependency, -we will write its name and the path to the plugin file. This -means that writing DEP_PLUGINS = cowboy is equivalent to -writing DEP_PLUGINS = cowboy/plugins.mk.

-

Knowing this, if we were to load the plugin mk/dist.mk -from Cowboy and no other, we would write the following in -our Makefile:

-
-
-
DEPS = cowboy
-DEP_PLUGINS = cowboy/mk/dist.mk
-
- -
+
DEPS = cowboy
+DEP_PLUGINS = cowboy/mk/dist.mk
+

Writing external plugins

-
-

The plugins.mk file is a convention. It is meant to load -all the plugins from the dependency. The code for the plugin -can be written directly in plugins.mk or be separate.

-

If you are providing more than one plugin with your repository, -the recommended way is to create one file per plugin in the -mk/ folder in your repository, and then include those -individual plugins in plugins.mk.

-

For example, if you have two plugins mk/dist.mk and -mk/templates.mk, you could write the following plugins.mk -file:

-
-
-
THIS := $(dir $(realpath $(lastword $(MAKEFILE_LIST))))
-include $(THIS)/mk/dist.mk
-include $(THIS)/mk/templates.mk
-

The THIS variable is required to relatively include files.

-

This allows users to not only be able to select individual -plugins, but also select all plugins from the dependency -in one go if they wish to do so.

-
- -
+
THIS := $(dir $(realpath $(lastword $(MAKEFILE_LIST))))
+include $(THIS)/mk/dist.mk
+include $(THIS)/mk/templates.mk
+
+

The THIS variable is required to relatively include files.

+

This allows users to not only be able to select individual plugins, but also select all plugins from the dependency in one go if they wish to do so.

Early-stage plugins

-
-

Plugins declared in DEP_PLUGINS are loaded near the end of Erlang.mk. -That’s why you have access to all previously initialized variables. -However, if you want your plugin to add common dependencies to -your applications, a regular is loaded too late in the process. -You need to use "Early-stage plugins". They are declared using the -DEP_EARLY_PLUGINS variable instead. Plugins listed in this variable -are loaded near the beginning of Erlang.mk Otherwise, they work exactly -the same.

-

If you only give the name of a dependency, the default file loaded is -early-plugins.mk. You can specify a filename exactly like you would -have done it with regular plugins.

-
-
-
# In your application's Makefile
-BUILD_DEPS = common_deps
-DEP_EARLY_PLUGINS = common_deps
-
-
-
# In the plugin's early-plugins.mk
-DEPS += cowboy
-TEST_DEPS = ct_helper
-dep_ct_helper = git https://github.com/ninenines/ct_helper master
-
- -
-

Loading plugins local to the application

-
-

If the Erlang.mk plugin lives in the same directory or repository as your -application or library, then you can load it exactly like an external -plugin: the dependency name is simply the name of your application or -library.

-

For example, the following Makefile loads a plugin in the mk -subdirectory:

-
-
-
DEP_PLUGINS = $(PROJECT)/mk/dist.mk
-

This also works with early-stage plugins:

-
-
-
DEP_EARLY_PLUGINS = $(PROJECT)/mk/variables.mk
-

Like external plugins, if you do not specify the path to the plugin, it -defaults to plugins.mk or early-plugins.mk, located at the root of -your application:

-
-
-
# Loads ./early-plugins.mk
-DEP_EARLY_PLUGINS = $(PROJECT)
-# Loads ./plugins.mk
-DEP_PLUGINS = $(PROJECT)
-
-
+
# Loads ./early-plugins.mk
+DEP_EARLY_PLUGINS = $(PROJECT)
+# Loads ./plugins.mk
+DEP_PLUGINS = $(PROJECT)
+ + diff --git a/docs/en/erlang.mk/1/guide/external_plugins_list/index.html b/docs/en/erlang.mk/1/guide/external_plugins_list/index.html index 37c88134..ddcd559d 100644 --- a/docs/en/erlang.mk/1/guide/external_plugins_list/index.html +++ b/docs/en/erlang.mk/1/guide/external_plugins_list/index.html @@ -62,87 +62,30 @@

List of plugins

-

This is a non-exhaustive list of Erlang.mk plugins, sorted -alphabetically.

-
+

This is a non-exhaustive list of Erlang.mk plugins, sorted alphabetically.

efene.mk

-
-

An Efene plugin for Erlang.mk. -Efene is an alternative language for the BEAM.

-
-
-
+

An Efene plugin for Erlang.mk. Efene is an alternative language for the BEAM.

elixir.mk

-
-

An Elixir plugin for -Erlang.mk. Elixir is an alternative -language for the BEAM.

-
-
-
+

An Elixir plugin for Erlang.mk. Elixir is an alternative language for the BEAM.

elvis.mk

-
-

An Elvis plugin for Erlang.mk. -Elvis is an Erlang style reviewer.

-
-
-
+

An Elvis plugin for Erlang.mk. Elvis is an Erlang style reviewer.

geas

-
-

Geas gives aggregated -information on a project and its dependencies, and is available -as an Erlang.mk plugin.

-
-
-
+

Geas gives aggregated information on a project and its dependencies, and is available as an Erlang.mk plugin.

hexer.mk

-
-

An Hex plugin for Erlang.mk -using the hexer tool.

-
-
-
+

An Hex plugin for Erlang.mk using the hexer tool.

hexpm.mk

-
-

Another Hex plugin for -Erlang.mk, with support for Hex dependency operators.

-
-
-
+

Another Hex plugin for Erlang.mk, with support for Hex dependency operators.

jorel

-
-

Jorel is Just anOther RELease -assembler for Erlang/OTP, and is available as an Erlang.mk plugin.

-
-
-
+

Jorel is Just anOther RELease assembler for Erlang/OTP, and is available as an Erlang.mk plugin.

lfe.mk

-
-

An LFE plugin for Erlang.mk. -LFE, or Lisp Flavoured Erlang, is an alternative -language for the BEAM.

-
-
-
+

An LFE plugin for Erlang.mk. LFE, or Lisp Flavoured Erlang, is an alternative language for the BEAM.

mix.mk

-
-

A Mix plugin for Erlang.mk, -to generate a compatible configuration file for -Mix.

-
-
-
+

A Mix plugin for Erlang.mk, to generate a compatible configuration file for Mix.

reload.mk

-
-

A live reload plugin for Erlang.mk.

-
-
-
+

A live reload plugin for Erlang.mk.

rust.mk

-
-

A plugin to build Rust crates and install binaries into priv/.

-
-
+

A plugin to build Rust crates and install binaries into priv/.

+ diff --git a/docs/en/erlang.mk/1/guide/getting_started/index.html b/docs/en/erlang.mk/1/guide/getting_started/index.html index 70ea7527..e6f3b05f 100644 --- a/docs/en/erlang.mk/1/guide/getting_started/index.html +++ b/docs/en/erlang.mk/1/guide/getting_started/index.html @@ -62,362 +62,258 @@

Getting started

-

This chapter explains how to get started using Erlang.mk.

-
+

This chapter explains how to get started using Erlang.mk.

Creating a folder for your project

-
-

The first step is always to create a new folder that will -contain your project.

-
-
$ mkdir hello_joe
-$ cd hello_joe
-

Most people tend to put all their projects side by side in -a common folder. We recommend keeping an organization similar -to your remote repositories. For example, for GitHub users, -put all your projects in a common folder with the same name -as your username. For example $HOME/ninenines/cowboy for -the Cowboy project.

-
-
-
+$ cd hello_joe +
+

Most people tend to put all their projects side by side in a common folder. We recommend keeping an organization similar to your remote repositories. For example, for GitHub users, put all your projects in a common folder with the same name as your username. For example $HOME/ninenines/cowboy for the Cowboy project.

Downloading Erlang.mk

-
-

At the time of writing, Erlang.mk is unlikely to be present -in your Erlang distribution, or even in your OS packages.

-

The next step is therefore to download it:

-
-
-
$ wget https://erlang.mk/erlang.mk
-

Or:

-
-
-
$ curl -O https://erlang.mk/erlang.mk
-

Alternatively, just click on this link.

-

Make sure you put the file inside the folder we created previously.

-
- -
+
$ curl -O https://erlang.mk/erlang.mk
+
+

Alternatively, just click on this link.

+

Make sure you put the file inside the folder we created previously.

Getting started with OTP applications

-
-

An OTP application is an Erlang application that has a supervision -tree. In other words, it will always have processes running.

-

This kind of project can be automatically generated by Erlang.mk. -All you need to do is use the bootstrap target:

-
-
-
$ make -f erlang.mk bootstrap
-

Something similar to the following snippet will then appear -on your screen:

-
-
-
git clone https://github.com/ninenines/erlang.mk .erlang.mk.build
-Cloning into '.erlang.mk.build'...
-remote: Counting objects: 4035, done.
-remote: Compressing objects: 100% (12/12), done.
-remote: Total 4035 (delta 8), reused 4 (delta 4), pack-reused 4019
-Receiving objects: 100% (4035/4035), 1.10 MiB | 784.00 KiB/s, done.
-Resolving deltas: 100% (2442/2442), done.
-Checking connectivity... done.
-if [ -f build.config ]; then cp build.config .erlang.mk.build; fi
-cd .erlang.mk.build && make
-make[1]: Entering directory '/home/essen/tmp/hello_joe/.erlang.mk.build'
-awk 'FNR==1 && NR!=1{print ""}1' core/core.mk index/*.mk core/index.mk core/deps.mk plugins/protobuffs.mk core/erlc.mk core/docs.mk core/test.mk plugins/asciidoc.mk plugins/bootstrap.mk plugins/c_src.mk plugins/ci.mk plugins/ct.mk plugins/dialyzer.mk plugins/edoc.mk plugins/elvis.mk plugins/erlydtl.mk plugins/escript.mk plugins/eunit.mk plugins/relx.mk plugins/shell.mk plugins/triq.mk plugins/xref.mk plugins/cover.mk \
-        | sed 's/^ERLANG_MK_VERSION = .*/ERLANG_MK_VERSION = 1.2.0-642-gccd2b9f/' > erlang.mk
-make[1]: Leaving directory '/home/essen/tmp/hello_joe/.erlang.mk.build'
-cp .erlang.mk.build/erlang.mk ./erlang.mk
-rm -rf .erlang.mk.build
-

This is Erlang.mk bootstrapping itself. Indeed, the file you -initially downloaded contains nothing more than the code needed -to bootstrap. This operation is done only once. Consult the -Updating Erlang.mk chapter for more -information.

-

Of course, the generated project can now be compiled:

-
-
-
$ make
-

Cheers!

-
- -
+
$ make
+
+

Cheers!

Getting started with OTP libraries

-
-

An OTP library is an Erlang application that has no supervision -tree. In other words, it is nothing but modules.

-

This kind of project can also be generated by Erlang.mk, using -the bootstrap-lib target:

-
-
-
$ make -f erlang.mk bootstrap-lib
-

Erlang.mk will once again bootstrap itself and generate all -the files for your project. You can now compile it:

-
-
-
$ make
-

Enjoy!

-
- -
+
$ make
+
+

Enjoy!

Getting started with OTP releases

-
-

An OTP release is the combination of the Erlang RunTime System (ERTS) -along with all the libraries and files that your node will need -to run. It is entirely self contained, and can often be sent as-is -to your production system and run without any extra setup.

-

Erlang.mk can of course bootstrap your project to generate releases. -You can use the bootstrap-rel target for this purpose:

-
-
-
$ make bootstrap-rel
-

This target can be combined with bootstrap or bootstrap-lib to -create a project that will build a release:

-
-
-
$ make -f erlang.mk bootstrap-lib bootstrap-rel
-

It is often very useful to keep the top-level project for -commands useful during operations, and put the components -of the system in separate applications that you will then -depend on. Consult the Packages and dependencies -chapter for more information.

-

When you run make from now on, Erlang.mk will compile your -project and build the release:

-
-
$ make
- APP    hello_joe.app.src
+ APP    hello_joe.app.src
  GEN    distclean-relx-rel
  GEN    /home/essen/tmp/hello_joe/relx
-===> Starting relx build process ...
-===> Resolving OTP Applications from directories:
+===> Starting relx build process ...
+===> Resolving OTP Applications from directories:
           /home/essen/tmp/hello_joe/ebin
           /usr/lib/erlang/lib
           /home/essen/tmp/hello_joe/deps
-===> Resolved hello_joe_release-1
-===> Including Erts from /usr/lib/erlang
-===> release successfully created!
-

The first time you run this command, Erlang.mk will download -relx, the release building tool. So don’t worry if you see -more output than above.

-

If building the release is slow, no need to upgrade your -hardware just yet. Just consult the Releases -chapter for various tips to speed up build time during -development.

-

You can start the release using the ./_rel/hello_joe_release/bin/hello_joe_release -script, or simply run make run. The latter will also compile -your project and build the release if it wasn’t already:

-
-
$ make run
- APP    hello_joe.app.src
+ APP    hello_joe.app.src
  GEN    distclean-relx-rel
-===> Starting relx build process ...
-===> Resolving OTP Applications from directories:
+===> Starting relx build process ...
+===> Resolving OTP Applications from directories:
           /home/essen/tmp/hello_joe/ebin
           /usr/lib/erlang/lib
           /home/essen/tmp/hello_joe/deps
-===> Resolved hello_joe_release-1
-===> Including Erts from /usr/lib/erlang
-===> release successfully created!
-Exec: /home/essen/tmp/hello_joe/_rel/hello_joe_release/erts-7.0/bin/erlexec -boot /home/essen/tmp/hello_joe/_rel/hello_joe_release/releases/1/hello_joe_release -boot_var ERTS_LIB_DIR /home/essen/tmp/hello_joe/_rel/hello_joe_release/erts-7.0/../lib -env ERL_LIBS /home/essen/tmp/hello_joe/_rel/hello_joe_release/releases/1/lib -config /home/essen/tmp/hello_joe/_rel/hello_joe_release/releases/1/sys.config -args_file /home/essen/tmp/hello_joe/_rel/hello_joe_release/releases/1/vm.args -- console
-Root: /home/essen/tmp/hello_joe/_rel/hello_joe_release
-/home/essen/tmp/hello_joe/_rel/hello_joe_release
-heart_beat_kill_pid = 16389
-Erlang/OTP 18 [erts-7.0] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]
-
-Eshell V7.0  (abort with ^G)
-(hello_joe@127.0.0.1)1>
-

Simple as that!

-
- -
+===> Resolved hello_joe_release-1 +===> Including Erts from /usr/lib/erlang +===> release successfully created! +Exec: /home/essen/tmp/hello_joe/_rel/hello_joe_release/erts-7.0/bin/erlexec -boot /home/essen/tmp/hello_joe/_rel/hello_joe_release/releases/1/hello_joe_release -boot_var ERTS_LIB_DIR /home/essen/tmp/hello_joe/_rel/hello_joe_release/erts-7.0/../lib -env ERL_LIBS /home/essen/tmp/hello_joe/_rel/hello_joe_release/releases/1/lib -config /home/essen/tmp/hello_joe/_rel/hello_joe_release/releases/1/sys.config -args_file /home/essen/tmp/hello_joe/_rel/hello_joe_release/releases/1/vm.args -- console +Root: /home/essen/tmp/hello_joe/_rel/hello_joe_release +/home/essen/tmp/hello_joe/_rel/hello_joe_release +heart_beat_kill_pid = 16389 +Erlang/OTP 18 [erts-7.0] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] + +Eshell V7.0 (abort with ^G) +(hello_joe@127.0.0.1)1> +
+

Simple as that!

Getting started from scratch

-
-

If you already have an application, or you want to have full -control over what files will be created, you can setup Erlang.mk -manually.

-

Erlang.mk is very easy to setup: all that you need to do is to -create a folder, put Erlang.mk in it, and write a one line -Makefile containing:

-
-
-
include erlang.mk
-

For a step by step:

-
-
$ mkdir hello_joe
 $ cd hello_joe
-$ curl https://erlang.mk/erlang.mk -o erlang.mk
-$ echo "include erlang.mk" > Makefile
-$ make
-

From that point onward you can create an src/ folder or start -using templates.

-
- -
+$ curl https://erlang.mk/erlang.mk -o erlang.mk +$ echo "include erlang.mk" > Makefile +$ make +
+

From that point onward you can create an src/ folder or start using templates.

Using spaces instead of tabs

-
-

Erlang.mk defaults to tabs when creating files from templates. -This is in part because of a personal preference, and in part -because it is much easier to convert tabs to spaces than the -opposite.

-

Use the SP variable if you prefer spaces. Set it to the number -of spaces per indentation level you want.

-

For example, if you prefer two spaces per indentation level:

-
-
-
$ make -f erlang.mk bootstrap SP=2
-

When you bootstrap the project initially, the variable automatically -gets added to the Makefile, so you only need to provide it when -you get started.

-
- -
+
$ make -f erlang.mk bootstrap SP=2
+
+

When you bootstrap the project initially, the variable automatically gets added to the Makefile, so you only need to provide it when you get started.

Using templates

-
-

It is no secret that Erlang’s OTP behaviors tend to have some -boilerplate. It is rarely an issue of course, except when -creating new modules. That’s why Erlang.mk not only comes with -templates for generating projects, but also individual modules!

-

You can list all available templates with the list-templates -target:

-
-
$ make list-templates
-Available templates: cowboy_http cowboy_loop cowboy_rest cowboy_ws gen_fsm gen_server gen_statem ranch_protocol supervisor
-

To generate a module, let’s say a gen_server, all you need to -do is to call make new with the appropriate arguments:

-
-
-
$ make new t=gen_server n=my_server
-

This will create a module located in src/my_server.erl -using the gen_server template.

-

This module is automatically compiled the next time you run -make:

-
-
$ make
- ERLC   my_server.erl
- APP    hello_joe.app.src
-

All that’s left to do is to open it in your favorite editor -and make it do something!

-
- -
-

Hiding Erlang.mk from git

-
-

Erlang.mk is a large text file. It can easily take a large part of -a git diff or a git grep command. You can avoid this by telling -Git that erlang.mk is a binary file.

-

Add this to your .gitattributes file. This is a file that you -can create at the root of your repository:

-
-
-
erlang.mk -diff
+ ERLC my_server.erl + APP hello_joe.app.src
-

The erlang.mk file will still appear in diffs and greps, but -as a binary file, meaning its contents won’t be shown by default -anymore.

-
-
-
+

All that's left to do is to open it in your favorite editor and make it do something!

+

Hiding Erlang.mk from git

+

Erlang.mk is a large text file. It can easily take a large part of a git diff or a git grep command. You can avoid this by telling Git that erlang.mk is a binary file.

+

Add this to your .gitattributes file. This is a file that you can create at the root of your repository:

+
erlang.mk -diff
+

The erlang.mk file will still appear in diffs and greps, but as a binary file, meaning its contents won't be shown by default anymore.

Getting help

-
-

During development, if you don’t remember the name of a target, -you can always run make help:

-
-
-
$ make help
-erlang.mk (version 1.2.0-642-gccd2b9f) is distributed under the terms of the ISC License.
-Copyright (c) 2013-2016 Loïc Hoguin <essen@ninenines.eu>
+
$ make help
+erlang.mk (version 1.2.0-642-gccd2b9f) is distributed under the terms of the ISC License.
+Copyright (c) 2013-2016 Loïc Hoguin <essen@ninenines.eu>
 
-Usage: [V=1] make [target]...
+Usage: [V=1] make [target]...
 
-Core targets:
-  all           Run deps, app and rel targets in that order
+Core targets:
+  all           Run deps, app and rel targets in that order
   app           Compile the project
-  deps          Fetch dependencies (if needed) and compile them
-  search q=...  Search for a package in the built-in index
-  rel           Build a release for this project, if applicable
-  docs          Build the documentation for this project
-  install-docs  Install the man pages for this project
-  check         Compile and run all tests and analysis for this project
-  tests         Run the tests for this project
+  deps          Fetch dependencies (if needed) and compile them
+  search q=...  Search for a package in the built-in index
+  rel           Build a release for this project, if applicable
+  docs          Build the documentation for this project
+  install-docs  Install the man pages for this project
+  check         Compile and run all tests and analysis for this project
+  tests         Run the tests for this project
   clean         Delete temporary and output files from most targets
   distclean     Delete all temporary and output files
-  help          Display this help and exit
-  erlang-mk     Update erlang.mk to the latest version
+  help          Display this help and exit
+  erlang-mk     Update erlang.mk to the latest version
 
-Bootstrap targets:
+Bootstrap targets:
   bootstrap          Generate a skeleton of an OTP application
   bootstrap-lib      Generate a skeleton of an OTP library
   bootstrap-rel      Generate the files needed to build a release
-  new t=TPL n=NAME   Generate a module NAME based on the template TPL
+  new t=TPL n=NAME   Generate a module NAME based on the template TPL
   list-templates     List available templates
-...
-

This guide should provide any other answer. If not, please -open a ticket on the official repository -and we will work on improving the guide.

-

Commercial support is available through Nine Nines. Please contact -Loïc Hoguin by sending an email to contact@ninenines.eu.

-
-
+... + +

This guide should provide any other answer. If not, please open a ticket on the official repository and we will work on improving the guide.

+

Commercial support is available through Nine Nines. Please contact Loïc Hoguin by sending an email to contact@ninenines.eu.

+ diff --git a/docs/en/erlang.mk/1/guide/history/index.html b/docs/en/erlang.mk/1/guide/history/index.html index 8ca7ac35..9f4af14a 100644 --- a/docs/en/erlang.mk/1/guide/history/index.html +++ b/docs/en/erlang.mk/1/guide/history/index.html @@ -62,61 +62,24 @@

Short history

-

This chapter aims to be a brief record of the life of the -Erlang.mk project.

-
+

This chapter aims to be a brief record of the life of the Erlang.mk project.

Before Erlang.mk

-
-

Erlang.mk originates from the Cowboy project. Cowboy started -as a Rebar project and I, Loïc Hoguin, was very happy with it -for a couple years. Over time however I started getting annoyed -and frustrated by a number of things, including bad defaults, -changing defaults and overall slowness.

-

In particular, at the time I gave up on Rebar, the Cowboy -test suite was taking about five minutes to run. A quick experiment -showed I could get much lower times by simply invoking ct_run -directly. On January 4th, 2013, the Cowboy test suite took less -than a minute to complete.

-

Following this success I started removing a little more and, -on the fateful day of January 5th, 2013, removed the dependency -on Rebar entirely. Rebar, and in particular the concept of -dependencies, was, and still is, a pretty strong influence.

-

Erlang.mk was conceived.

-

A few months passed and, on May 1st, 2013, the Erlang.mk -repository was created. Erlang.mk was born.

-

Little did I know how much it would grow.

-
-
-
+

Erlang.mk originates from the Cowboy project. Cowboy started as a Rebar project and I, Loïc Hoguin, was very happy with it for a couple years. Over time however I started getting annoyed and frustrated by a number of things, including bad defaults, changing defaults and overall slowness.

+

In particular, at the time I gave up on Rebar, the Cowboy test suite was taking about five minutes to run. A quick experiment showed I could get much lower times by simply invoking ct_run directly. On January 4th, 2013, the Cowboy test suite took less than a minute to complete.

+

Following this success I started removing a little more and, on the fateful day of January 5th, 2013, removed the dependency on Rebar entirely. Rebar, and in particular the concept of dependencies, was, and still is, a pretty strong influence.

+

Erlang.mk was conceived.

+

A few months passed and, on May 1st, 2013, the Erlang.mk repository was created. Erlang.mk was born.

+

Little did I know how much it would grow.

Lifetime of the project

-
-

Erlang.mk would eventually become a much larger file able to -deal with many more projects than just Cowboy. From the birth -of the project, the biggest force for growth was user contributions, -because Erlang.mk appealed to a variety of people with different -needs, needs that Erlang.mk was not fulfilling yet.

-

The project was split into smaller files focused on a different -feature each, and a build script was written to build the single -Erlang.mk file.

-

A test suite was contributed by a user, and later taken as a basis -for the current, much more complete test suite. Turns out testing -a Makefile is pretty straightforward.

-

A package index was added to solve the problem of discovering -Erlang projects.

-

After trying to see if Erlang build tools could cooperate, the -decision was made to improve compatibility with existing Rebar -projects by patching Rebar out, using Rebar. This feature, called -autopatch, proved very successful and made Erlang.mk compatible -with more than 90% of all Erlang projects.

-

Erlang.mk documentation was much improved and the Erlang.mk website -was created in the summer of 2015.

-

Over the year of 2015, Erlang.mk went from curiosity to a serious -alternative to other Erlang build tools. The user base increased -immensely and large projects started using it, including RabbitMQ -from the 3.6.0 release onward.

-

A bright future lies ahead.

-
-
+

Erlang.mk would eventually become a much larger file able to deal with many more projects than just Cowboy. From the birth of the project, the biggest force for growth was user contributions, because Erlang.mk appealed to a variety of people with different needs, needs that Erlang.mk was not fulfilling yet.

+

The project was split into smaller files focused on a different feature each, and a build script was written to build the single Erlang.mk file.

+

A test suite was contributed by a user, and later taken as a basis for the current, much more complete test suite. Turns out testing a Makefile is pretty straightforward.

+

A package index was added to solve the problem of discovering Erlang projects.

+

After trying to see if Erlang build tools could cooperate, the decision was made to improve compatibility with existing Rebar projects by patching Rebar out, using Rebar. This feature, called autopatch, proved very successful and made Erlang.mk compatible with more than 90% of all Erlang projects.

+

Erlang.mk documentation was much improved and the Erlang.mk website was created in the summer of 2015.

+

Over the year of 2015, Erlang.mk went from curiosity to a serious alternative to other Erlang build tools. The user base increased immensely and large projects started using it, including RabbitMQ from the 3.6.0 release onward.

+

A bright future lies ahead.

+ diff --git a/docs/en/erlang.mk/1/guide/index.html b/docs/en/erlang.mk/1/guide/index.html index 3c66d012..79f94c2f 100644 --- a/docs/en/erlang.mk/1/guide/index.html +++ b/docs/en/erlang.mk/1/guide/index.html @@ -62,188 +62,76 @@

Erlang.mk User Guide

- - - - -
+

Third-party plugins

- -
-
+

About Erlang.mk

- -
+ + diff --git a/docs/en/erlang.mk/1/guide/installation/index.html b/docs/en/erlang.mk/1/guide/installation/index.html index 867fb9ed..e1d4284e 100644 --- a/docs/en/erlang.mk/1/guide/installation/index.html +++ b/docs/en/erlang.mk/1/guide/installation/index.html @@ -62,183 +62,95 @@

Installation

-

On Unix

-
-

Erlang.mk requires GNU Make to be installed. While it will -currently work with GNU Make 3.81, support for this version -is deprecated and will be removed in 2017. We recommend -GNU Make 4.1 or later.

-

Git and Erlang/OTP must also be installed.

-

Some functionality requires that Autoconf 2.59 or later be -installed, in order to compile Erlang/OTP. Erlang/OTP may -have further requirements depending on your needs.

-

Some packages may require additional libraries.

-
+

Erlang.mk requires GNU Make to be installed. While it will currently work with GNU Make 3.81, support for this version is deprecated and will be removed in 2017. We recommend GNU Make 4.1 or later.

+

Git and Erlang/OTP must also be installed.

+

Some functionality requires that Autoconf 2.59 or later be installed, in order to compile Erlang/OTP. Erlang/OTP may have further requirements depending on your needs.

+

Some packages may require additional libraries.

Linux

-

The commands to install packages vary between distributions:

-
-
Arch Linux
-
-
$ pacman -S erlang git make
-

Alpine Linux and other distributions based on BusyBox come -with an incompatible awk program. Installing the GNU Awk -(gawk on Alpine) solves this issue.

-
-
+
$ pacman -S erlang git make
+
+

Alpine Linux and other distributions based on BusyBox come with an incompatible awk program. Installing the GNU Awk (gawk on Alpine) solves this issue.

FreeBSD

-

FreeBSD comes with binary and source packages:

-
-
Install binary packages
-
-
$ pkg install erlang git gmake
-

On FreeBSD the make command is BSD Make. Use gmake instead.

-
-
+
$ pkg install erlang git gmake
+
+

On FreeBSD the make command is BSD Make. Use gmake instead.

OS X and macOS

-

While Apple distributes their own GNU Make, their version is -very old and plagued with numerous bugs. It is recommended -to install a more recent version from either Homebrew or -MacPorts:

-
-
Homebrew
-
-
$ brew install erlang git make
-

Homebrew installs GNU Make as gmake. The make command -is the one provided by Apple.

-
-
MacPorts
-
-
$ sudo port install erlang git gmake
- - - -
+
$ sudo port install erlang git gmake
+

On Windows

-
-

Erlang.mk can be used on Windows inside an MSYS2 environment. -Cygwin, MSYS (the original) and native Windows (both Batch -and PowerShell) are currently not supported.

-
- - - -
-
Note
-
Erlang.mk expects Unix line breaks in most of the files -(LF instead of CRLF). Make sure to configure your text editor -adequately.
-
-

The rest of this section details how to setup Erlang/OTP and -MSYS2 in order to use Erlang.mk.

-
+

Erlang.mk can be used on Windows inside an MSYS2 environment. Cygwin, MSYS (the original) and native Windows (both Batch and PowerShell) are currently not supported.

+

NOTE: Erlang.mk expects Unix line breaks in most of the files (LF instead of CRLF). Make sure to configure your text editor adequately.

+

The rest of this section details how to setup Erlang/OTP and MSYS2 in order to use Erlang.mk.

Installing Erlang/OTP

-

Erlang.mk requires Erlang/OTP to be installed. The OTP team -provides binaries of Erlang/OTP for all major and minor releases, -available from the official download page. -It is recommended that you use the 64-bit installer unless -technically impossible. Please follow the instructions from -the installer to complete the installation.

-

The OTP team also provides a short guide to -installing Erlang/OTP on Windows -if you need additional references.

-

You can install Erlang/OTP silently using the /S switch -on the command line:

-
-
-
C:\Users\essen\Downloads> otp_win64_18.0.exe /S
-
-
-
+

Erlang.mk requires Erlang/OTP to be installed. The OTP team provides binaries of Erlang/OTP for all major and minor releases, available from the official download page. It is recommended that you use the 64-bit installer unless technically impossible. Please follow the instructions from the installer to complete the installation.

+

The OTP team also provides a short guide to installing Erlang/OTP on Windows if you need additional references.

+

You can install Erlang/OTP silently using the /S switch on the command line:

+
C:\Users\essen\Downloads> otp_win64_18.0.exe /S

Installing MSYS2

-

The only supported environment on Windows is MSYS2. MSYS2 is -a lightweight Unix-like environment for Windows that comes -with the Arch Linux package manager, pacman.

-

The MSYS2 project provides a one click installer -and instructions to set things up post-installation.

-

It is currently not possible to use the installer silently. -Thankfully, the MSYS2 project provides an archive that can -be used in lieu of the installer. The archive however requires -7zip to decompress it.

-

First, download the -MSYS2 base archive -and extract it under C:\. Assuming you downloaded the -archive as msys2.tar.xz and put it in C:\, you can -use the following commands to extract it:

-
-
-
C:\> 7z x msys2.tar.xz
-C:\> 7z x msys2.tar > NUL
-
-

Then you can run the two commands needed to perform the -post-installation setup:

-
-
-
C:\> C:\msys64\usr\bin\bash -lc "pacman --needed --noconfirm -Sy bash pacman pacman-mirrors msys2-runtime"
-C:\> C:\msys64\usr\bin\bash -lc "pacman --noconfirm -Syu"
-
-
-
+

The only supported environment on Windows is MSYS2. MSYS2 is a lightweight Unix-like environment for Windows that comes with the Arch Linux package manager, pacman.

+

The MSYS2 project provides a one click installer and instructions to set things up post-installation.

+

It is currently not possible to use the installer silently. Thankfully, the MSYS2 project provides an archive that can be used in lieu of the installer. The archive however requires 7zip to decompress it.

+

First, download the MSYS2 base archive and extract it under C:\. Assuming you downloaded the archive as msys2.tar.xz and put it in C:\, you can use the following commands to extract it:

+
C:\> 7z x msys2.tar.xz
+C:\> 7z x msys2.tar > NUL
+

Then you can run the two commands needed to perform the post-installation setup:

+
C:\> C:\msys64\usr\bin\bash -lc "pacman --needed --noconfirm -Sy bash pacman pacman-mirrors msys2-runtime"
+C:\> C:\msys64\usr\bin\bash -lc "pacman --noconfirm -Syu"

Installing the required MSYS2 packages

-

After following these instructions, you can install GNU Make, -Git and any other required softwares. From an MSYS2 shell, -you can call pacman directly:

-
-
-
$ pacman -S git make
-

You can use pacman -Ss to search packages. For example, -to find all packages related to GCC:

-
-
-
$ pacman -Ss gcc
-

If you are going to compile C/C++ code, you will need to -install this package, as Erlang.mk cannot use the normal -"gcc" package:

-
-
-
$ pacman -S mingw-w64-x86_64-gcc
-

You can also run commands under the MSYS2 environment from -the Windows command line or batch files. This command will -install GNU Make and Git:

-
-
-
C:\> C:\msys64\usr\bin\bash -lc "pacman --noconfirm -S git make"
+
$ pacman -S mingw-w64-x86_64-gcc
-

You can use similar bash commands if you need to run programs -inside the MSYS2 environment from a batch file.

-
-
+

You can also run commands under the MSYS2 environment from the Windows command line or batch files. This command will install GNU Make and Git:

+
C:\> C:\msys64\usr\bin\bash -lc "pacman --noconfirm -S git make"
+

You can use similar bash commands if you need to run programs inside the MSYS2 environment from a batch file.

Gotchas

-

While most of the basic functionality will just work, there are -still some issues. Erlang.mk needs to be fixed to pass the -right paths when running Erlang scripts. We are working on it. -Erlang.mk is fully tested on both Linux and Windows, but is -lacking tests in the areas not yet covered by this guide, -so expect bugs to be fixed as more tests are added.

-
-
- +

While most of the basic functionality will just work, there are still some issues. Erlang.mk needs to be fixed to pass the right paths when running Erlang scripts. We are working on it. Erlang.mk is fully tested on both Linux and Windows, but is lacking tests in the areas not yet covered by this guide, so expect bugs to be fixed as more tests are added.

+ diff --git a/docs/en/erlang.mk/1/guide/kerl/index.html b/docs/en/erlang.mk/1/guide/kerl/index.html index 4fc8f102..eb9fe097 100644 --- a/docs/en/erlang.mk/1/guide/kerl/index.html +++ b/docs/en/erlang.mk/1/guide/kerl/index.html @@ -62,84 +62,36 @@

OTP version management

-

Erlang.mk comes with integrated support for -Kerl, a shell script that -automates the downloading, building and installing of -Erlang/OTP. It can be used to easily build a specific -Erlang/OTP version (with or without custom build options) -or maintain different versions side by side.

-
+

Erlang.mk comes with integrated support for Kerl, a shell script that automates the downloading, building and installing of Erlang/OTP. It can be used to easily build a specific Erlang/OTP version (with or without custom build options) or maintain different versions side by side.

Erlang versions

-
-

Erlang.mk uses the Git tags from Erlang/OTP to identify -OTP versions. The most recent tag at the time of writing -is OTP-20.0.4, which is a patch release of OTP-20.0. -A patch release is a non-official release containing a -few fixes on top of the official release.

-

Older versions used a slightly different versioning scheme -and tag format, for example: OTP_R16B03. Beware though, -there also was an OTP_R16B03-1 release that fixed a -critical issue in the initial release.

-

The README file for all official Erlang/OTP releases can -be found on erlang.org. -To obtain information about patch releases when they are -released you need to be subscribed to the -erlang-questions mailing list.

-
-
-
+

Erlang.mk uses the Git tags from Erlang/OTP to identify OTP versions. The most recent tag at the time of writing is OTP-20.0.4, which is a patch release of OTP-20.0. A patch release is a non-official release containing a few fixes on top of the official release.

+

Older versions used a slightly different versioning scheme and tag format, for example: OTP_R16B03. Beware though, there also was an OTP_R16B03-1 release that fixed a critical issue in the initial release.

+

The README file for all official Erlang/OTP releases can be found on erlang.org. To obtain information about patch releases when they are released you need to be subscribed to the erlang-questions mailing list.

OTP version pinning

-
-

Erlang.mk can use a specific version of Erlang/OTP when -interacting with your project. This can be very useful -when you are working with a team because you can define -the version you need in the Makefile and Erlang.mk will -ensure this version is used by everyone in your team.

-

To pin the version all you need to do is to set the -ERLANG_OTP variable in your Makefile before including -Erlang.mk. For example, to use OTP-20.0.4:

-
-
-
ERLANG_OTP = OTP-20.0.4
-
-include erlang.mk
-

The next time you run make Erlang.mk will build and -use the version you configured.

-

Note that there has been reports that this functionality -is not compatible with the .ONESHELL feature from -GNU Make.

-
-
-
+
ERLANG_OTP = OTP-20.0.4
+
+include erlang.mk
+
+

The next time you run make Erlang.mk will build and use the version you configured.

+

Note that there has been reports that this functionality is not compatible with the .ONESHELL feature from GNU Make.

Continuous integration

-
-

Erlang.mk can automatically test your project against -many different Erlang/OTP versions. This functionality -is documented in the Continuous integration chapter.

-
- -
+

Erlang.mk can automatically test your project against many different Erlang/OTP versions. This functionality is documented in the Continuous integration chapter.

Configuring Kerl

-
-

All of the Kerl variables can be configured directly in the -Makefile. All you need to do is to export them. For example, -to change the installation directory for the Erlang/OTP -versions managed by Kerl, you could add the following to -your Makefile:

-
-
-
export KERL_INSTALL_DIR = $(CURDIR)/erlang
-

When configuring paths like this, always make sure to provide -an absolute path in the value. Erlang.mk will NOT expand them -automatically for you.

-
-
+
export KERL_INSTALL_DIR = $(CURDIR)/erlang
+ +

When configuring paths like this, always make sure to provide an absolute path in the value. Erlang.mk will NOT expand them automatically for you.

+ diff --git a/docs/en/erlang.mk/1/guide/limitations/index.html b/docs/en/erlang.mk/1/guide/limitations/index.html index 431a3ab8..659fb209 100644 --- a/docs/en/erlang.mk/1/guide/limitations/index.html +++ b/docs/en/erlang.mk/1/guide/limitations/index.html @@ -62,49 +62,20 @@

Limitations

-

No software is perfect.

-

It’s very important, when evaluating and when using a tool, -to understand its limitations, so as to avoid making mistakes -and wasting valuable time.

-

This chapter lists all known limitations of Erlang.mk.

-
+

No software is perfect.

+

It's very important, when evaluating and when using a tool, to understand its limitations, so as to avoid making mistakes and wasting valuable time.

+

This chapter lists all known limitations of Erlang.mk.

Erlang must be available

-
-

Currently Erlang.mk requires you to install Erlang beforehand. -Installing Erlang is not always easy, particularly if you need -a specific version of Erlang for a specific project.

-

In addition, the Erlang being used must be in your $PATH -before you use Erlang.mk.

-

In the future we envision, Erlang.mk could manage the Erlang -version you need to use a project. Erlang.mk already does this -for running tests when using make ci, so doing this during -development is just a step away.

-
-
-
+

Currently Erlang.mk requires you to install Erlang beforehand. Installing Erlang is not always easy, particularly if you need a specific version of Erlang for a specific project.

+

In addition, the Erlang being used must be in your $PATH before you use Erlang.mk.

+

In the future we envision, Erlang.mk could manage the Erlang version you need to use a project. Erlang.mk already does this for running tests when using make ci, so doing this during development is just a step away.

Spaces in path

-
-

Erlang.mk will currently not work properly if the path to the -project contains spaces. To check if that is the case, use the -command pwd.

-

This issue is due to how Makefiles work. There might be ways -to solve it, we have not given up on it, but it’s very low -priority considering how simple the workaround is.

-
-
-
+

Erlang.mk will currently not work properly if the path to the project contains spaces. To check if that is the case, use the command pwd.

+

This issue is due to how Makefiles work. There might be ways to solve it, we have not given up on it, but it's very low priority considering how simple the workaround is.

Dependency tracking and modification times

-
-

Erlang source files that depend on other files will have their -modification time updated when they need to be recompiled due -to a dependency having changed. This could cause some editors to -think the file changed when it didn’t.

-

Erlang.mk must use this method in order to be able to compile -files in one erlc invocation. The benefits greatly outweigh -the issue in this case and so there are currently no plans to -fix this behavior.

-
-
+

Erlang source files that depend on other files will have their modification time updated when they need to be recompiled due to a dependency having changed. This could cause some editors to think the file changed when it didn't.

+

Erlang.mk must use this method in order to be able to compile files in one erlc invocation. The benefits greatly outweigh the issue in this case and so there are currently no plans to fix this behavior.

+ diff --git a/docs/en/erlang.mk/1/guide/overview/index.html b/docs/en/erlang.mk/1/guide/overview/index.html index 1a4b2b9d..9fa002de 100644 --- a/docs/en/erlang.mk/1/guide/overview/index.html +++ b/docs/en/erlang.mk/1/guide/overview/index.html @@ -62,94 +62,42 @@

Overview

-

Now that you know how to get started, let’s take a look at -what Erlang.mk can do for you.

-
+

Now that you know how to get started, let's take a look at what Erlang.mk can do for you.

Building your project

-
-

Erlang.mk is first and foremost a build tool. It is especially -tailored for Erlang developers and follows widely accepted -practices in the Erlang community.

-

Erlang.mk will happily build all Erlang-specific files -you throw at it. Other kinds of files too, like C or C++ code -when you are working on a NIF or a port driver.

-

Erlang.mk embraces the concept of source dependencies. -It can fetch dependency source code using a variety of mechanisms, -including fetching from Git, Mercurial or SVN.

-

Erlang.mk will automatically generate releases -when applicable. It can also generate escripts.

-
-
-
+

Erlang.mk is first and foremost a build tool. It is especially tailored for Erlang developers and follows widely accepted practices in the Erlang community.

+

Erlang.mk will happily build all Erlang-specific files you throw at it. Other kinds of files too, like C or C++ code when you are working on a NIF or a port driver.

+

Erlang.mk embraces the concept of source dependencies. It can fetch dependency source code using a variety of mechanisms, including fetching from Git, Mercurial or SVN.

+

Erlang.mk will automatically generate releases when applicable. It can also generate escripts.

Exploring the package index

-
-

Erlang.mk comes with a built-in package index. -It is built as an extension of the dependency system and is -meant to be used for discovery purposes.

-

No package is ever installed, they are only used as dependencies -and are always project-specific. They can be thought of as a -shortcut over plain dependencies.

-

You can get a list of all packages known to Erlang.mk by using -the search target:

-
-
-
$ make search
-

You can also use this target to search across all packages, for -example to find all packages related to Cowboy:

-
-
-
$ make search q=cowboy
-
-
-
+
$ make search q=cowboy
+

Generating documentation

-
-

Erlang.mk supports EDoc and Asciidoc.

-

EDoc generates HTML documentation directly from -your source code.

-

While it is convenient, ask yourself: if all the documentation is -inside the source code, why not just open the source code directly? -That’s where Asciidoc comes in.

-

The Asciidoc plugin expects all documentation -to be separate from source. It will generate HTML, PDF, man pages and -more from the documentation you write in the doc/src/ folder in -your repository.

-
- -
+

Erlang.mk supports EDoc and Asciidoc.

+

EDoc generates HTML documentation directly from your source code.

+

While it is convenient, ask yourself: if all the documentation is inside the source code, why not just open the source code directly? That's where Asciidoc comes in.

+

The Asciidoc plugin expects all documentation to be separate from source. It will generate HTML, PDF, man pages and more from the documentation you write in the doc/src/ folder in your repository.

Running tests

-
-

Erlang.mk supports a lot of different testing and static -analysis tools.

-

The make shell command allows you -to test your project manually. You can automate these -unit tests with EUnit and test -your entire system with Common Test. -Code coverage can of course -be enabled during tests.

-

Erlang.mk comes with features to make your life easier when -setting up and using Continuous integration.

-

On the static analysis side of things, Erlang.mk comes with -support for Dialyzer and Xref, -to perform success typing analysis and cross referencing -of the code.

-
-
-
+

Erlang.mk supports a lot of different testing and static analysis tools.

+

The make shell command allows you to test your project manually. You can automate these unit tests with EUnit and test your entire system with Common Test. Code coverage can of course be enabled during tests.

+

Erlang.mk comes with features to make your life easier when setting up and using Continuous integration.

+

On the static analysis side of things, Erlang.mk comes with support for Dialyzer and Xref, to perform success typing analysis and cross referencing of the code.

Need more?

-
-

Not convinced yet? You can read about why you should use Erlang.mk -and its history. And if you’re still not -convinced after that, it’s OK! The world would be boring if -everyone agreed on everything all the time.

-
-
+

Not convinced yet? You can read about why you should use Erlang.mk and its history. And if you're still not convinced after that, it's OK! The world would be boring if everyone agreed on everything all the time.

+ diff --git a/docs/en/erlang.mk/1/guide/ports/index.html b/docs/en/erlang.mk/1/guide/ports/index.html index 39744520..99478311 100644 --- a/docs/en/erlang.mk/1/guide/ports/index.html +++ b/docs/en/erlang.mk/1/guide/ports/index.html @@ -62,193 +62,97 @@

NIFs and port drivers

-

Erlang.mk can not only build Erlang projects, but also the C code -that some projects come with, like NIFs and port drivers.

-

There are two ways to build the C code: using a custom Makefile, -or making Erlang.mk do it directly. The C code will be built -as needed when you run make.

-
+

Erlang.mk can not only build Erlang projects, but also the C code that some projects come with, like NIFs and port drivers.

+

There are two ways to build the C code: using a custom Makefile, or making Erlang.mk do it directly. The C code will be built as needed when you run make.

+

C source code location and Erlang environment

-
-

The C source code should be located in the $(C_SRC_DIR) directory. -It defaults to c_src/. Should you need to modify it, all you -need to do is to set the variable in your Makefile before including -Erlang.mk:

-
-
-
C_SRC_DIR = $(CURDIR)/my_nif_source
-

When this directory exists, Erlang.mk will automatically create a -file named $(C_SRC_ENV). This file defaults to $(C_SRC_DIR)/env.mk. -This can also be changed:

-
-
-
C_SRC_ENV = $(C_SRC_DIR)/erlang_env.mk
-

It contains a few variable definitions for the environment used for the build:

-
-
-ERTS_INCLUDE_DIR -
-
-

- Path to the ERTS include files (erl_driver.h, erl_nif.h and more). -

+
C_SRC_ENV = $(C_SRC_DIR)/erlang_env.mk
+
+

It contains a few variable definitions for the environment used for the build:

+
ERTS_INCLUDE_DIR
+

Path to the ERTS include files (erl_driver.h, erl_nif.h and more).

-
-ERL_INTERFACE_INCLUDE_DIR -
-
-

- Path to the Erl_Interface include files (ei.h and related). -

+
ERL_INTERFACE_INCLUDE_DIR
+

Path to the Erl_Interface include files (ei.h and related).

-
-ERL_INTERFACE_LIB_DIR -
-
-

- Path to the Erl_Interface static libraries. -

+
ERL_INTERFACE_LIB_DIR
+

Path to the Erl_Interface static libraries.

-
- - -
+

Using a custom Makefile

-
-

Erlang.mk will automatically run make if it detects a Makefile -in $(C_SRC_DIR)/Makefile.

-

The Makefile should have at least two targets: a default target -(which can be anything, for example all) which is invoked when -building the C code, and a clean target invoked when cleaning -it.

-

You can include the env.mk file to benefit from the Erlang -environment detection:

-
-
-
include env.mk
-
-
-
+
include env.mk
+

Using Erlang.mk directly

-
-

You don’t need to write a Makefile to build C source code, however. -Erlang.mk comes with rules to build both shared libraries and -executables, using the source files it finds in $(C_SRC_DIR).

-

By default, Erlang.mk will create a shared library. To change -this and create an executable instead, put this in your Makefile -before including Erlang.mk:

-
-
-
C_SRC_TYPE = executable
-

The generated file name varies depending on the type of project -you have (shared library or executable) and on the platform you -build the project on.

-

For shared libraries, the generated file name will be -$(C_SRC_OUTPUT)$(C_SRC_SHARED_EXTENSION), with the default -being $(CURDIR)/priv/$(PROJECT) followed by the extension: -.dll on Windows, .so everywhere else.

-

For executables, the generated file name is -$(C_SRC_OUTPUT)$(C_SRC_EXECUTABLE_EXTENSION), with the same -default except for the extension: .exe on Windows, and otherwise -nothing.

-

Erlang.mk sets appropriate compile and linker flags by default. -These flags vary depending on the platform, and can of course -be overriden.

-
-
-CC -
-
-

- The compiler to be used. -

+
C_SRC_TYPE = executable
+
+

The generated file name varies depending on the type of project you have (shared library or executable) and on the platform you build the project on.

+

For shared libraries, the generated file name will be $(C_SRC_OUTPUT)$(C_SRC_SHARED_EXTENSION), with the default being $(CURDIR)/priv/$(PROJECT) followed by the extension: .dll on Windows, .so everywhere else.

+

For executables, the generated file name is $(C_SRC_OUTPUT)$(C_SRC_EXECUTABLE_EXTENSION), with the same default except for the extension: .exe on Windows, and otherwise nothing.

+

Erlang.mk sets appropriate compile and linker flags by default. These flags vary depending on the platform, and can of course be overriden.

+
CC
+

The compiler to be used.

-
-CFLAGS -
-
-

- C compiler flags. -

+
CFLAGS
+

C compiler flags.

-
-CXXFLAGS -
-
-

- C++ compiler flags. -

+
CXXFLAGS
+

C++ compiler flags.

-
-LDFLAGS -
-
-

- Linker flags. -

+
LDFLAGS
+

Linker flags.

-
-LDLIBS -
-
-

- Libraries to link against. -

+
LDLIBS
+

Libraries to link against.

-
-

The source files are automatically gathered from the contents -of $(C_SRC_DIR). Erlang.mk looks for .c, .C, .cc and .cpp -source files. You can define the variable SOURCES to manually -list the files to compile.

- - -
+ +

The source files are automatically gathered from the contents of $(C_SRC_DIR). Erlang.mk looks for .c, .C, .cc and .cpp source files. You can define the variable SOURCES to manually list the files to compile.

Propagating compile and linker flags to sub-Makefiles

-
-

In some cases it might be necessary to propagate the flags -you just defined to the sub-Makefiles of your local project. -You generally can’t just export those as this could impact -the building of dependencies.

-

Makefiles allow you to export variables for specific targets. -When doing this, the variables will be exported only when -this target runs, and not for other targets. It is therefore -possible to export them when building the C code without -impacting other build steps.

-

By adding this to your Makefile all five variables will be -made available to sub-Makefiles when building C code:

-
-
-
app-c_src: export CC +=
-app-c_src: export CFLAGS +=
-app-c_src: export CPPFLAGS +=
-app-c_src: export LDFLAGS +=
-app-c_src: export LDLIBS +=
-

Appending an empty string to the existing value is necessary -because Makefiles expect an assignment for target-specific -exports. Alternatively you can set a new value:

-
-
-
app-c_src: export CFLAGS = -O3
-
-
+
app-c_src: export CFLAGS = -O3
+ + diff --git a/docs/en/erlang.mk/1/guide/releases/index.html b/docs/en/erlang.mk/1/guide/releases/index.html index f731a3d9..09b27b21 100644 --- a/docs/en/erlang.mk/1/guide/releases/index.html +++ b/docs/en/erlang.mk/1/guide/releases/index.html @@ -62,217 +62,159 @@

Releases

-

Erlang.mk relies on Relx for generating releases. This -chapter covers the Erlang.mk-specific bits. Consult the -Relx website for more information.

-
+

Erlang.mk relies on Relx for generating releases. This chapter covers the Erlang.mk-specific bits. Consult the Relx website for more information.

Setup

-
-

Erlang.mk will create a release if it detects a Relx configuration -file in the $(RELX_CONFIG) location. This defaults to -$(CURDIR)/relx.config. You can override it by defining -the variable before including Erlang.mk:

-
-
-
RELX_CONFIG = $(CURDIR)/webchat.config
-

Relx does not need to be installed. Erlang.mk will download -and build it automatically.

-

The Relx executable will be saved in the $(RELX) file. This -location defaults to $(CURDIR)/relx and can be overriden.

-
-
-
+
RELX_CONFIG = $(CURDIR)/webchat.config
+
+

Relx does not need to be installed. Erlang.mk will download and build it automatically.

+

The Relx executable will be saved in the $(RELX) file. This location defaults to $(CURDIR)/relx and can be overriden.

+

Configuration

-
-

You can specify additional Relx options using the RELX_OPTS -variable. For example, to enable dev_mode:

-
-
-
RELX_OPTS = -d true
-

While you can specify the output directory for the release -in the Relx options directly, Erlang.mk provides a specific -variable for it: RELX_OUTPUT_DIR. It defaults to the _rel -directory. You can also override it:

-
-
-
RELX_OUTPUT_DIR = /path/to/staging/directory
-
- -
+
RELX_OUTPUT_DIR = /path/to/staging/directory
+

Generating the release

-
-

Now that you’re all set, all you need to do is generate the -release. As mentioned before, Erlang.mk will automatically -generate it when it detects the $(RELX_CONFIG) file. This -means the following command will also build the release:

-
-
-
$ make
-

If you need to generate the release, and only the release, -the rel target can be used:

-
-
-
$ make rel
-

Erlang.mk always generates a tarball alongside the release, -which can be directly uploaded to a server. The tarball is -located at $(RELX_OUTPUT_DIR)/<name>/<name>-<vsn>.tar.gz.

-
- -
+
$ make rel
+
+

Erlang.mk always generates a tarball alongside the release, which can be directly uploaded to a server. The tarball is located at $(RELX_OUTPUT_DIR)/<name>/<name>-<vsn>.tar.gz.

Running the release

-
-

Erlang.mk provides a convenience function for running the -release with one simple command:

-
-
-
$ make run
-

This command will also build the project and generate the -release if they weren’t already. It starts the release in -console mode, meaning you will also have a shell ready to -use to check things as needed.

-
- -
+
$ make run
+
+

This command will also build the project and generate the release if they weren't already. It starts the release in console mode, meaning you will also have a shell ready to use to check things as needed.

Upgrading a release

-
-

Erlang.mk provides a relup target for generating release -upgrades. Release upgrades allow updating the code and the -state of a running release without restarting it.

-

Once your changes are done, you need to update the version -of the application(s) that will be updated. You also need -to update the version of the release.

-

For each application that needs to be updated, an -appup file -must be written. Refer to the Erlang/OTP documentation -for more details.

-

For the purpose of this section, assume the initial release -version was 1, and the new version is 2. The name of the -release will be example.

-

Once all this is done, you can build the tarball for the -release upgrade:

-
-
-
$ make relup
-

This will create an archive at the root directory of the -release, $RELX_OUTPUT_DIR/example/example-2.tar.gz.

-

Move the archive to the correct location on the running -node. From the release’s root directory:

-
-
-
$ mkdir releases/2/
-$ mv path/to/example-2.tar.gz releases/2/
-

Finally, upgrade the release:

-
-
-
$ bin/example_release upgrade "2/example_release"
-

Or on Windows:

-
-
-
$ bin/example_release.cmd upgrade "2/example_release"
-

Your release was upgraded!

-
- -
+
$ bin/example_release.cmd upgrade "2/example_release"
+
+

Your release was upgraded!

Getting Relx semver value

-
-

There is a workaround to get the semver value which is -generated by Relx based on VCS history.

-

Create a file rel/version with only one line inside:

-
-
-
{{ release_version }}
-

Add/Update the overlay section of your relx.config:

-
-
-
{overlay, [
-    {template, "rel/version", "version"}
-]}.
-

When you run make rel it creates the file $(RELX_OUTPUT_DIR)/example/version -which contains the version value generated by Relx.

-
-
$ cat _rel/app/release
-1.0.0+build.11.ref5612aa0
-

In your Makefile you can use this simple snippet to get the version, -but please keep in mind that this should depend on the rel target:

-
-
-
$(shell cat $(RELX_OUTPUT_DIR)/$(RELX_REL_NAME)/version)
-

For example:

-
-
include erlang.mk
 
-APP_VERSION = $(shell cat $(RELX_OUTPUT_DIR)/$(RELX_REL_NAME)/version)
-myrecipe: all
-        echo APP_VERSION = $(APP_VERSION)
-

Would output:

-
-
$ make myrecipe
-...
-===> Starting relx build process ...
-===> Resolving OTP Applications from directories:
+...
+===> Starting relx build process ...
+===> Resolving OTP Applications from directories:
           /home/username/example/apps
           /home/username/example/deps
           /usr/lib/erlang/lib
-          /home/username/example/_rel
-===> Resolved example-0.3.10+build.11.ref5612aa0
-===> Including Erts from /usr/lib/erlang
-===> release successfully created!
-===> tarball /home/username/example/_rel/example/example-0.3.10+build.11.ref5612aa0.tar.gz successfully created!
-echo APP_VERSION = 0.3.10+build.11.ref5612aa0
-APP_VERSION = 0.3.10+build.11.ref5612aa0
-
- + /home/username/example/_rel +===> Resolved example-0.3.10+build.11.ref5612aa0 +===> Including Erts from /usr/lib/erlang +===> release successfully created! +===> tarball /home/username/example/_rel/example/example-0.3.10+build.11.ref5612aa0.tar.gz successfully created! +echo APP_VERSION = 0.3.10+build.11.ref5612aa0 +APP_VERSION = 0.3.10+build.11.ref5612aa0
+ + diff --git a/docs/en/erlang.mk/1/guide/sfx/index.html b/docs/en/erlang.mk/1/guide/sfx/index.html index b9942e94..10b337f4 100644 --- a/docs/en/erlang.mk/1/guide/sfx/index.html +++ b/docs/en/erlang.mk/1/guide/sfx/index.html @@ -62,55 +62,36 @@

Self-extracting releases

-

Erlang.mk allows you to package Relx releases as -self-extracting archives. These archives contain all the -files in the release and come in the form of a script that -will extract and run the release automatically.

-

This allows you to package the release as a single file -that can then be executed.

-

This feature is currently experimental. Feedback is much -appreciated.

-
+

Erlang.mk allows you to package Relx releases as self-extracting archives. These archives contain all the files in the release and come in the form of a script that will extract and run the release automatically.

+

This allows you to package the release as a single file that can then be executed.

+

This feature is currently experimental. Feedback is much appreciated.

Generating the self-extracting archive

-
-

To generate a self-extracting release, all you need to do -is pass the SFX=1 variable to Make when you build the -release:

-
-
-
$ make SFX=1
-

This will create a self-extracting archive in -$RELX_OUTPUT_DIR/<name>.run. For example if the release -is named hello_world and $RELX_OUTPUT_DIR is the default, -the file will be located at _rel/hello_world.run.

-
-
-
+
$ make SFX=1
+
+

This will create a self-extracting archive in $RELX_OUTPUT_DIR/<name>.run. For example if the release is named hello_world and $RELX_OUTPUT_DIR is the default, the file will be located at _rel/hello_world.run.

Running the release

-
-

Simply execute the script to get started:

-
-
-
$ ./_rel/hello_world.run
-Exec: /tmp/tmp.3eeEq7E1ta/erts-8.1/bin/erlexec ...
-Root: /tmp/tmp.3eeEq7E1ta
-/tmp/tmp.3eeEq7E1ta
-Erlang/OTP 19 [erts-8.1] [source] [64-bit] [smp:4:4] ...
-
-Eshell V8.1  (abort with ^G)
-(hello_world@localhost)1>
-

As you can see the archive is extracted to a temporary -directory before the release can be started.

-

The self-extracting script currently only supports starting -the release in console mode.

-
- +
$ ./_rel/hello_world.run
+Exec: /tmp/tmp.3eeEq7E1ta/erts-8.1/bin/erlexec ...
+Root: /tmp/tmp.3eeEq7E1ta
+/tmp/tmp.3eeEq7E1ta
+Erlang/OTP 19 [erts-8.1] [source] [64-bit] [smp:4:4] ...
+
+Eshell V8.1  (abort with ^G)
+(hello_world@localhost)1>
+ +

As you can see the archive is extracted to a temporary directory before the release can be started.

+

The self-extracting script currently only supports starting the release in console mode.

+ diff --git a/docs/en/erlang.mk/1/guide/shell/index.html b/docs/en/erlang.mk/1/guide/shell/index.html index ff3f3524..c287d6b1 100644 --- a/docs/en/erlang.mk/1/guide/shell/index.html +++ b/docs/en/erlang.mk/1/guide/shell/index.html @@ -62,66 +62,48 @@

Erlang shell

-

Erlang.mk provides a convenient target for starting a shell -with all the paths set properly to experiment with your code.

-
+

Erlang.mk provides a convenient target for starting a shell with all the paths set properly to experiment with your code.

Configuration

-
-

The SHELL_DEPS variable can be used to define dependencies -that are only to be used when the make shell command is called. -For example, if you want to use kjell as your shell:

-
-
-
SHELL_DEPS = kjell
-

Dependencies are downloaded and compiled the first time you -run the make shell command.

-

You can customize the executable used to start the Erlang shell. -To continue with our example, if you want to use kjell as your -shell, you also need to change SHELL_ERL and point it to the -kjell executable:

-
-
-
SHELL_ERL = $(DEPS_DIR)/kjell/bin/kjell
-

You can specify additional options to be used when starting the -shell using the SHELL_OPTS variable:

-
-
-
SHELL_OPTS = -setcookie chocolate
-

Any of the usual erl options can be used, including -eval:

-
-
-
SHELL_OPTS = -eval 'my_app:run()'
-
-
-
+
SHELL_OPTS = -eval 'my_app:run()'
+

Usage

-
-

To start the shell, all you need is the following command:

-
-
-
$ make shell
-

The shell can be stopped as usual with a double Ctrl+C or the -command q()..

-

Note that the shell target does not build the application. To do it, -use either the app target or, if you want to include also test -modules, the test-build target.

-
- +
$ make shell
+ +

The shell can be stopped as usual with a double Ctrl+C or the command q()..

+

Note that the shell target does not build the application. To do it, use either the app target or, if you want to include also test modules, the test-build target.

+ diff --git a/docs/en/erlang.mk/1/guide/sphinx/index.html b/docs/en/erlang.mk/1/guide/sphinx/index.html index 379dc8a6..c6956ea4 100644 --- a/docs/en/erlang.mk/1/guide/sphinx/index.html +++ b/docs/en/erlang.mk/1/guide/sphinx/index.html @@ -62,34 +62,16 @@

Sphinx documentation

-

Erlang.mk includes targets for running the -Sphinx documentation generator, which can produce -documentation in various formats, like HTML, man pages, Texinfo, LaTeX, and -others.

-
+

Erlang.mk includes targets for running the Sphinx documentation generator, which can produce documentation in various formats, like HTML, man pages, Texinfo, LaTeX, and others.

Writing Sphinx documentation

-
-

Sphinx generates documentation from a set of -reST documents. There is -a quick start guide on -Sphinx' website. For Erlang.mk, we’ll set up a minimal environment instead.

-
-
-
+

Sphinx generates documentation from a set of reST documents. There is a quick start guide on Sphinx' website. For Erlang.mk, we'll set up a minimal environment instead.

Basic setup

-
-

By default, Erlang.mk expects Sphinx documentation to be placed in the doc -directory, with doc/conf.py config file in particular. The file contains -information about the project, among the other things.

-

A minimal doc/conf.py will look similar to this:

-
-
-

It points to a doc/index.rst document. A simple skeleton includes a table of -contents for all documentation, and links to generated index of terms and -a search page:

-
-
-
My Project
+

By default, Erlang.mk expects Sphinx documentation to be placed in the doc directory, with doc/conf.py config file in particular. The file contains information about the project, among the other things.

+

A minimal doc/conf.py will look similar to this:

+
source-highlight: could not find a language definition for python +
+

It points to a doc/index.rst document. A simple skeleton includes a table of contents for all documentation, and links to generated index of terms and a search page:

+
My Project
 ==========
 
 Contents:
@@ -103,104 +85,51 @@ Indices and tables
 ==================
 
 * :ref:`genindex`
-* :ref:`search`
-
-

The skeleton above has a link to one other page, doc/other_page.rst. Simple -header with some text will do for now:

-
-
-
Other Page
+* :ref:`search`
+

The skeleton above has a link to one other page, doc/other_page.rst. Simple header with some text will do for now:

+
Other Page
 ==========
 
-Lorem ipsum dolor sit amet...
-
-

The files above are enough to build HTML documentation to the html directory.

-
-
-
$ make docs     # all the docs, including EDoc and AsciiDoc if applicable
-$ make sphinx   # Sphinx docs specifically
-
-
-
+
$ make docs     # all the docs, including EDoc and AsciiDoc if applicable
+$ make sphinx   # Sphinx docs specifically
+

Erlang.mk configuration

-
-

Erlang.mk defaults to the following configuration:

-
-
-
SPHINX_FORMATS = html
-SPHINX_SOURCE = doc
-

To change the location of Sphinx sources, you need to set the $(SPHINX_SOURCE) -variable. The conf.py file should also be placed in that directory, unless you -specify $(SPHINX_CONFDIR).

-

The variable $(SPHINX_OPTS) allows to provide options to sphinx-build, which -is particularly useful for -D name=value options. You can even forego -doc/conf.py file, using -D name=value in combination with the -C option, -though in this case you will need to manually call make sphinx or add the -sphinx target to dependencies of docs.

-

The $(SPHINX_FORMATS) variable lists formats to generate. By default only HTML -is generated, but it can also build man pages or LaTeX documents which can later -be converted to PDF. See the -description of the -b option -for sphinx-build for a list of known formats.

-

Formats are by default generated to a directory called after the format -(html for HTML, man for man pages, and so on). To change this behaviour -for a specific format, you can set the $(sphinx_$(format)_output) variable, e.g. -$(sphinx_html_output) for html or $(sphinx_man_output) for man. -There are also $(sphinx_$(format)_opts) variables for setting sphinx-build -options for a single format only.

-
-
-
+
SPHINX_FORMATS = html
+SPHINX_SOURCE = doc
+
+

To change the location of Sphinx sources, you need to set the $(SPHINX_SOURCE) variable. The conf.py file should also be placed in that directory, unless you specify $(SPHINX_CONFDIR).

+

The variable $(SPHINX_OPTS) allows to provide options to sphinx-build, which is particularly useful for -D name=value options. You can even forego doc/conf.py file, using -D name=value in combination with the -C option, though in this case you will need to manually call make sphinx or add the sphinx target to dependencies of docs.

+

The $(SPHINX_FORMATS) variable lists formats to generate. By default only HTML is generated, but it can also build man pages or LaTeX documents which can later be converted to PDF. See the description of the `-b` option for sphinx-build for a list of known formats.

+

Formats are by default generated to a directory called after the format (html for HTML, man for man pages, and so on). To change this behaviour for a specific format, you can set the $(sphinx_$(format)_output) variable, e.g. $(sphinx_html_output) for html or $(sphinx_man_output) for man. There are also $(sphinx_$(format)_opts) variables for setting sphinx-build options for a single format only.

Generating man pages

-
-

To generate man pages, you need to include man in $(SPHINX_FORMATS) in -your Makefile and define the man_pages option in doc/conf.py:

-
-
-

As the -Sphinx documentation -indicates, the structure is:

-
    -
  • -

    -doc_name is the path to the man page’s source (relative $(SPHINX_SOURCE)), - without the .rst suffix -

    +

    To generate man pages, you need to include man in $(SPHINX_FORMATS) in your Makefile and define the man_pages option in doc/conf.py:

    +
    source-highlight: could not find a language definition for python +
    +

    As the Sphinx documentation indicates, the structure is:

    +
    • doc_name is the path to the man page's source (relative $(SPHINX_SOURCE)), without the .rst suffix
    • -
    • -

      -page_name is the name of the resulting man page, which will be used as a base - for the output file name and will be included in the generated man page -

      +
    • page_name is the name of the resulting man page, which will be used as a base for the output file name and will be included in the generated man page
    • -
    • -

      -Manpage Title is a short, one-line description, which will be included in - the generated man page on a position that’s used by the apropos command -

      +
    • Manpage Title is a short, one-line description, which will be included in the generated man page on a position that's used by the apropos command
    • -
    • -

      -Page Author (or more of them) will be included in the autogenerated AUTHOR - section. Leaving this field empty disables generating the AUTHOR section -

      +
    • Page Author (or more of them) will be included in the autogenerated AUTHOR section. Leaving this field empty disables generating the AUTHOR section
    • -
    • -

      -1 is the man page section number -

      +
    • 1 is the man page section number
    • -
-

With the above configuration (and Erlang.mk’s defaults), doc/doc_name.rst will -be used to generate man/page_name.1.

-
- + +

With the above configuration (and Erlang.mk's defaults), doc/doc_name.rst will be used to generate man/page_name.1.

+ diff --git a/docs/en/erlang.mk/1/guide/triq/index.html b/docs/en/erlang.mk/1/guide/triq/index.html index 5b478a0b..5f1f5608 100644 --- a/docs/en/erlang.mk/1/guide/triq/index.html +++ b/docs/en/erlang.mk/1/guide/triq/index.html @@ -62,44 +62,43 @@

Triq

-

Triq is a QuickCheck-like library for -property-based testing. Erlang.mk automates discovery and checking of -Triq properties.

-

To run all tests (including Triq):

-
-
-
$ make tests
-

To run all tests and static checks (including Triq):

-
-
-
$ make check
-

You can also run Triq separately:

-
-
-
$ make triq
-

To check properties from a single module:

-
-
-
$ make triq t=foo_tests
-

To check a single property:

-
-
-
$ make triq t=foo_tests:bar
+
$ make triq t=foo_tests:bar
+ + diff --git a/docs/en/erlang.mk/1/guide/updating/index.html b/docs/en/erlang.mk/1/guide/updating/index.html index 44f5adb4..86e18069 100644 --- a/docs/en/erlang.mk/1/guide/updating/index.html +++ b/docs/en/erlang.mk/1/guide/updating/index.html @@ -62,89 +62,56 @@

Updating Erlang.mk

-

This chapter describes how to update the erlang.mk file -in your repository.

-
+

This chapter describes how to update the erlang.mk file in your repository.

Initial bootstrap

-
-

The first time you use Erlang.mk, it will bootstrap itself. -It always uses the most recent version for this, so you don’t -have to update after creating your project.

-
-
-
+

The first time you use Erlang.mk, it will bootstrap itself. It always uses the most recent version for this, so you don't have to update after creating your project.

Updating

-
-

Later on though, updating becomes a necessity. Erlang.mk -developers and contributors relentlessly improve the project -and add new features; it would be a waste not to benefit -from this.

-

That’s why updating Erlang.mk is so simple. All you need -to do is to call make erlang-mk:

-
-
$ make erlang-mk
-git clone https://github.com/ninenines/erlang.mk .erlang.mk.build
-Cloning into '.erlang.mk.build'...
-remote: Counting objects: 4035, done.
-remote: Compressing objects: 100% (12/12), done.
-remote: Total 4035 (delta 8), reused 4 (delta 4), pack-reused 4019
-Receiving objects: 100% (4035/4035), 1.10 MiB | 1000.00 KiB/s, done.
-Resolving deltas: 100% (2442/2442), done.
-Checking connectivity... done.
-if [ -f build.config ]; then cp build.config .erlang.mk.build; fi
-cd .erlang.mk.build && make
-make[1]: Entering directory '/home/essen/tmp/emkg/hello_joe/.erlang.mk.build'
-awk 'FNR==1 && NR!=1{print ""}1' core/core.mk index/*.mk core/index.mk core/deps.mk plugins/protobuffs.mk core/erlc.mk core/docs.mk core/test.mk plugins/asciidoc.mk plugins/bootstrap.mk plugins/c_src.mk plugins/ci.mk plugins/ct.mk plugins/dialyzer.mk plugins/edoc.mk plugins/elvis.mk plugins/erlydtl.mk plugins/escript.mk plugins/eunit.mk plugins/relx.mk plugins/shell.mk plugins/triq.mk plugins/xref.mk plugins/cover.mk \
-        | sed 's/^ERLANG_MK_VERSION = .*/ERLANG_MK_VERSION = 1.2.0-642-gccd2b9f/' > erlang.mk
-make[1]: Leaving directory '/home/essen/tmp/emkg/hello_joe/.erlang.mk.build'
-cp .erlang.mk.build/erlang.mk ./erlang.mk
-rm -rf .erlang.mk.build
-

All that’s left to do is to commit the file!

-

Yep, it’s that easy.

-
-
-
+git clone https://github.com/ninenines/erlang.mk .erlang.mk.build +Cloning into '.erlang.mk.build'... +remote: Counting objects: 4035, done. +remote: Compressing objects: 100% (12/12), done. +remote: Total 4035 (delta 8), reused 4 (delta 4), pack-reused 4019 +Receiving objects: 100% (4035/4035), 1.10 MiB | 1000.00 KiB/s, done. +Resolving deltas: 100% (2442/2442), done. +Checking connectivity... done. +if [ -f build.config ]; then cp build.config .erlang.mk.build; fi +cd .erlang.mk.build && make +make[1]: Entering directory '/home/essen/tmp/emkg/hello_joe/.erlang.mk.build' +awk 'FNR==1 && NR!=1{print ""}1' core/core.mk index/*.mk core/index.mk core/deps.mk plugins/protobuffs.mk core/erlc.mk core/docs.mk core/test.mk plugins/asciidoc.mk plugins/bootstrap.mk plugins/c_src.mk plugins/ci.mk plugins/ct.mk plugins/dialyzer.mk plugins/edoc.mk plugins/elvis.mk plugins/erlydtl.mk plugins/escript.mk plugins/eunit.mk plugins/relx.mk plugins/shell.mk plugins/triq.mk plugins/xref.mk plugins/cover.mk \ + | sed 's/^ERLANG_MK_VERSION = .*/ERLANG_MK_VERSION = 1.2.0-642-gccd2b9f/' > erlang.mk +make[1]: Leaving directory '/home/essen/tmp/emkg/hello_joe/.erlang.mk.build' +cp .erlang.mk.build/erlang.mk ./erlang.mk +rm -rf .erlang.mk.build +
+

All that's left to do is to commit the file!

+

Yep, it's that easy.

Customizing the build

-
-

Erlang.mk allows you to customize which components are to be included -in the erlang.mk file. The WITHOUT variable allows you to -remove components from the default Erlang.mk build. The build.config -file lets you define exactly what goes in (including your own code!), -and in what order.

-

The WITHOUT file contains the list of components to exclude from -the build. For example, to exclude the package index and the EDoc -plugin when bootstrapping your application:

-
-
-
$ make -f erlang.mk bootstrap WITHOUT="index plugins/edoc"
-

The generated Erlang.mk will never include those components when -you update it, until you change your mind and use the WITHOUT -variable again when you upgrade:

-
-
-
$ make erlang-mk WITHOUT=index
-

The build.config file is automatically used when you bootstrap -Erlang.mk or when you update it with make erlang-mk.

-

The build.config file contains the list of all files that will -be built into the resulting erlang.mk file. You can start from -the most recent version -and customize to your needs.

-

You can also name the file differently or put it in a separate folder -by modifying the value for ERLANG_MK_BUILD_CONFIG. You can also -tell Erlang.mk to use a different temporary directory by changing -the ERLANG_MK_BUILD_DIR variable.

-
- +
$ make erlang-mk WITHOUT=index
+ +

The build.config file is automatically used when you bootstrap Erlang.mk or when you update it with make erlang-mk.

+

The build.config file contains the list of all files that will be built into the resulting erlang.mk file. You can start from the most recent version and customize to your needs.

+

You can also name the file differently or put it in a separate folder by modifying the value for ERLANG_MK_BUILD_CONFIG. You can also tell Erlang.mk to use a different temporary directory by changing the ERLANG_MK_BUILD_DIR variable.

+ diff --git a/docs/en/erlang.mk/1/guide/why/index.html b/docs/en/erlang.mk/1/guide/why/index.html index a18ba0d2..659a4a99 100644 --- a/docs/en/erlang.mk/1/guide/why/index.html +++ b/docs/en/erlang.mk/1/guide/why/index.html @@ -62,86 +62,30 @@

Why Erlang.mk

-

Why would you choose Erlang.mk, if not for its -many features? This chapter will -attempt to answer that.

-
+

Why would you choose Erlang.mk, if not for its many features? This chapter will attempt to answer that.

Erlang.mk is fast

-
-

Erlang.mk is as fast as it gets.

-

Erlang.mk will group the compilation of files so as to avoid -running the BEAM more than necessary. This saves many seconds -compared to traditional Makefiles, even on small projects.

-

Erlang.mk will not try to be too smart. It provides a simple -solution that works for most people, and gives additional -options for projects that run into edge cases, often in the -form of extra variables or rules to be defined.

-
-
-
+

Erlang.mk is as fast as it gets.

+

Erlang.mk will group the compilation of files so as to avoid running the BEAM more than necessary. This saves many seconds compared to traditional Makefiles, even on small projects.

+

Erlang.mk will not try to be too smart. It provides a simple solution that works for most people, and gives additional options for projects that run into edge cases, often in the form of extra variables or rules to be defined.

Erlang.mk gives you the full power of Unix

-
-

Erlang.mk is a Makefile.

-

You could use Erlang.mk directly without configuring anything -and it would just work. But you can also extend it greatly -either through configuration or hooks, and you can of course -add your own rules to the Makefile.

-

In all cases: for configuration, hooks or custom rules, you -have all the power of Unix at your disposal, and can call -any utility or even any language interpreter you want, -every time you need to. Erlang.mk also allows you to write -scripts in this small language called Erlang directly inside -your Makefile if you ever need to…

-
-
-
+

Erlang.mk is a Makefile.

+

You could use Erlang.mk directly without configuring anything and it would just work. But you can also extend it greatly either through configuration or hooks, and you can of course add your own rules to the Makefile.

+

In all cases: for configuration, hooks or custom rules, you have all the power of Unix at your disposal, and can call any utility or even any language interpreter you want, every time you need to. Erlang.mk also allows you to write scripts in this small language called Erlang directly inside your Makefile if you ever need to...

Erlang.mk is a text file

-
-

Erlang.mk is a Makefile.

-

Which means Erlang.mk is a simple text file. You can edit a -text file. Nothing stops you. If you run into any bug, or -behavior that does not suit you, you can just open the -erlang.mk file in your favorite editor, fix and/or comment -a few lines, save, and try again. It’s as simple as it gets.

-

Currently using a binary build tool? Good luck with that.

-
-
-
+

Erlang.mk is a Makefile.

+

Which means Erlang.mk is a simple text file. You can edit a text file. Nothing stops you. If you run into any bug, or behavior that does not suit you, you can just open the erlang.mk file in your favorite editor, fix and/or comment a few lines, save, and try again. It's as simple as it gets.

+

Currently using a binary build tool? Good luck with that.

Erlang.mk can manage Erlang itself

-
-

Erlang.mk isn’t written in Erlang.

-

That’s not a good thing, you say? Well, here’s one thing -that Erlang.mk and Makefiles can do for you that Erlang -build tool can’t easily: choose what version of Erlang is -to be used for compiling the project.

-

This really is a one-liner in Erlang.mk (a few more lines -if you also let it download and build Erlang directly) -and allows for even greater things, like testing your -project across all supported Erlang versions in one small -command: make -k ci.

-
-
-
+

Erlang.mk isn't written in Erlang.

+

That's not a good thing, you say? Well, here's one thing that Erlang.mk and Makefiles can do for you that Erlang build tool can't easily: choose what version of Erlang is to be used for compiling the project.

+

This really is a one-liner in Erlang.mk (a few more lines if you also let it download and build Erlang directly) and allows for even greater things, like testing your project across all supported Erlang versions in one small command: make -k ci.

Erlang.mk can do more than Erlang

-
-

Erlang.mk doesn’t care what your dependencies are written in.

-

Erlang.mk will happily compile any dependency, as long as -they come with a Makefile. The dependency can be written -in C, C++ or even Javascript… Who cares, really? If you -need Erlang.mk to fetch it, then Erlang.mk will fetch it -and compile it as needed.

-
-
-
+

Erlang.mk doesn't care what your dependencies are written in.

+

Erlang.mk will happily compile any dependency, as long as they come with a Makefile. The dependency can be written in C, C++ or even Javascript... Who cares, really? If you need Erlang.mk to fetch it, then Erlang.mk will fetch it and compile it as needed.

Erlang.mk integrates nicely in Make and Automake projects

-
-

If you are planning to put your project in the middle of -a Make or Automake-based build environment, then the most -logical thing to do is to use a Makefile.

-

Erlang.mk will happily sit in such an environment and behave -as you expect it to.

-
-
+

If you are planning to put your project in the middle of a Make or Automake-based build environment, then the most logical thing to do is to use a Makefile.

+

Erlang.mk will happily sit in such an environment and behave as you expect it to.

+ diff --git a/docs/en/erlang.mk/1/guide/xref/index.html b/docs/en/erlang.mk/1/guide/xref/index.html index 6de10fea..8459f374 100644 --- a/docs/en/erlang.mk/1/guide/xref/index.html +++ b/docs/en/erlang.mk/1/guide/xref/index.html @@ -62,7 +62,9 @@

Xref

-

Placeholder chapter.

+ +

Placeholder chapter.

+ diff --git a/docs/en/gun/1.0/guide/connect/index.html b/docs/en/gun/1.0/guide/connect/index.html index ac1e6eb3..427b7450 100644 --- a/docs/en/gun/1.0/guide/connect/index.html +++ b/docs/en/gun/1.0/guide/connect/index.html @@ -62,145 +62,104 @@

Connection

-

This chapter describes how to open, monitor and close -a connection using the Gun client.

-
+

This chapter describes how to open, monitor and close a connection using the Gun client.

Gun connections

-
-

Gun is designed with the HTTP/2 and Websocket protocols in mind. -They are built for long-running connections that allow concurrent -exchange of data, either in the form of request/responses for -HTTP/2 or in the form of messages for Websocket.

-

A Gun connection is an Erlang process that manages a socket to -a remote endpoint. This Gun connection is owned by a user -process that is called the owner of the connection, and is -managed by the supervision tree of the gun application.

-

The owner process communicates with the Gun connection -by calling functions from the module gun. All functions -perform their respective operations asynchronously. The Gun -connection will send Erlang messages to the owner process -whenever needed.

-

When the remote endpoint closes the connection, Gun attempts -to reconnect automatically.

-
-
-
+

Gun is designed with the HTTP/2 and Websocket protocols in mind. They are built for long-running connections that allow concurrent exchange of data, either in the form of request/responses for HTTP/2 or in the form of messages for Websocket.

+

A Gun connection is an Erlang process that manages a socket to a remote endpoint. This Gun connection is owned by a user process that is called the owner of the connection, and is managed by the supervision tree of the gun application.

+

The owner process communicates with the Gun connection by calling functions from the module gun. All functions perform their respective operations asynchronously. The Gun connection will send Erlang messages to the owner process whenever needed.

+

When the remote endpoint closes the connection, Gun attempts to reconnect automatically.

Opening a new connection

-
-

The gun:open/2,3 function must be used to open a connection.

-
-
Opening a connection to example.org on port 443
-
-
{ok, ConnPid} = gun:open("example.org", 443).
-

If the port given is 443, Gun will attempt to connect using -TLS. The protocol will be selected automatically using the -ALPN extension for TLS. By default Gun supports HTTP/2 -and HTTP/1.1 when connecting using TLS.

-

For any other port, Gun will attempt to connect using -plain TCP and will use the HTTP/1.1 protocol.

-

The transport and protocol used can be overriden via -options. The manual documents all available options.

-

Options can be provided as a third argument, and take the -form of a map.

-
-
Opening a TLS connection to example.org on port 8443
-
-
{ok, ConnPid} = gun:open("example.org", 8443, #{transport => tls}).
-
-
-
+
{ok, ConnPid} = gun:open("example.org", 8443, #{transport => tls}).
+

Waiting for the connection to be established

-
-

When Gun successfully connects to the server, it sends a -gun_up message with the protocol that has been selected -for the connection.

-

Gun provides the functions gun:await_up/1,2,3 that wait -for the gun_up message. They can optionally take a monitor -reference and/or timeout value. If no monitor is provided, -one will be created for the duration of the function call.

-
-
Synchronous opening of a connection
-
-
{ok, ConnPid} = gun:open("example.org", 443),
-{ok, Protocol} = gun:await_up(ConnPid).
-
- -
+
{ok, ConnPid} = gun:open("example.org", 443),
+{ok, Protocol} = gun:await_up(ConnPid).
+

Handling connection loss

-
-

When the connection is lost, Gun will send a gun_down -message indicating the current protocol, the reason the -connection was lost and two lists of stream references.

-

The first list indicates open streams that may have been -processed by the server. The second list indicates open -streams that the server did not process.

-
- -
+

When the connection is lost, Gun will send a gun_down message indicating the current protocol, the reason the connection was lost and two lists of stream references.

+

The first list indicates open streams that may have been processed by the server. The second list indicates open streams that the server did not process.

Monitoring the connection process

-
-

Because software errors are unavoidable, it is important to -detect when the Gun process crashes. It is also important -to detect when it exits normally. Erlang provides two ways -to do that: links and monitors.

-

Gun leaves you the choice as to which one will be used. -However, if you use the gun:await/2,3 or gun:await_body/2,3 -functions, a monitor may be used for you to avoid getting -stuck waiting for a message that will never come.

-

If you choose to monitor yourself you can do it on a permanent -basis rather than on every message you will receive, saving -resources. Indeed, the gun:await/3,4 and gun:await_body/3,4 -functions both accept a monitor argument if you have one already.

-
-
Monitoring the connection process
-
-
{ok, ConnPid} = gun:open("example.org", 443).
-MRef = monitor(process, ConnPid).
-

This monitor reference can be kept and used until the connection -process exits.

-
-
Handling DOWN messages
-
-
receive
-    %% Receive Gun messages here...
-    {'DOWN', Mref, process, ConnPid, Reason} ->
-        error_logger:error_msg("Oops!"),
-        exit(Reason)
-end.
-

What to do when you receive a DOWN message is entirely up to you.

-
-
-
+
receive
+    %% Receive Gun messages here...
+    {'DOWN', Mref, process, ConnPid, Reason} ->
+        error_logger:error_msg("Oops!"),
+        exit(Reason)
+end.
+
+

What to do when you receive a DOWN message is entirely up to you.

Closing the connection abruptly

-
-

The connection can be stopped abruptly at any time by calling -the gun:close/1 function.

-
-
Immediate closing of the connection
-
-
gun:close(ConnPid).
-

The process is stopped immediately without having a chance to -perform the protocol’s closing handshake, if any.

-
- +
gun:close(ConnPid).
+ +

The process is stopped immediately without having a chance to perform the protocol's closing handshake, if any.

+ + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/en/gun/1.0/guide/http/index.html b/docs/en/gun/1.0/guide/http/index.html index 6c32ab5d..0d132edc 100644 --- a/docs/en/gun/1.0/guide/http/index.html +++ b/docs/en/gun/1.0/guide/http/index.html @@ -62,395 +62,279 @@

HTTP

-

This chapter describes how to use the Gun client for -communicating with an HTTP/1.1 or HTTP/2 server.

-
+

This chapter describes how to use the Gun client for communicating with an HTTP/1.1 or HTTP/2 server.

Streams

-
-

Every time a request is initiated, Gun creates a stream. -A stream reference uniquely identifies a set of request and -response and must be used to perform additional operations -with a stream or to identify its messages.

-

Stream references use the Erlang reference data type and -are therefore unique.

-

Streams can be canceled at any time. This will stop any further -messages from being sent to the owner process. Depending on -its capabilities, the server will also be instructed to cancel -the request.

-

Canceling a stream may result in Gun dropping the connection -temporarily, to avoid uploading or downloading data that will -not be used.

-
-
Cancelling a stream
-
-
gun:cancel(ConnPid, StreamRef).
-
-
-
+
gun:cancel(ConnPid, StreamRef).
+

Sending requests

-
-

Gun provides many convenient functions for performing common -operations, like GET, POST or DELETE. It also provides a -general purpose function in case you need other methods.

-

The availability of these methods on the server can vary -depending on the software used but also on a per-resource -basis.

-

Gun will automatically set a few headers depending on the -method used. For all methods however it will set the host -header if it has not been provided in the request arguments.

-

This section focuses on the act of sending a request. The -handling of responses will be explained further on.

-
+

Gun provides many convenient functions for performing common operations, like GET, POST or DELETE. It also provides a general purpose function in case you need other methods.

+

The availability of these methods on the server can vary depending on the software used but also on a per-resource basis.

+

Gun will automatically set a few headers depending on the method used. For all methods however it will set the host header if it has not been provided in the request arguments.

+

This section focuses on the act of sending a request. The handling of responses will be explained further on.

GET and HEAD

-

Use gun:get/2,3,4 to request a resource.

-
-
GET "/organizations/ninenines"
-
-
StreamRef = gun:get(ConnPid, "/organizations/ninenines").
-
-
GET "/organizations/ninenines" with custom headers
-
-
StreamRef = gun:get(ConnPid, "/organizations/ninenines", [
-    {<<"accept">>, "application/json"},
-    {<<"user-agent">>, "revolver/1.0"}
-]).
-

Note that the list of headers has the field name as a binary. -The field value is iodata, which is either a binary or an -iolist.

-

Use gun:head/2,3,4 if you don’t need the response body.

-
-
HEAD "/organizations/ninenines"
-
-
StreamRef = gun:head(ConnPid, "/organizations/ninenines").
-
-
HEAD "/organizations/ninenines" with custom headers
-
-
StreamRef = gun:head(ConnPid, "/organizations/ninenines", [
-    {<<"accept">>, "application/json"},
-    {<<"user-agent">>, "revolver/1.0"}
-]).
-

It is not possible to send a request body with a GET or HEAD -request.

-
-
-

POST, PUT and PATCH

-

HTTP defines three methods to create or update a resource.

-

POST is generally used when the resource identifier (URI) isn’t known -in advance when creating a resource. POST can also be used to -replace an existing resource, although PUT is more appropriate -in that situation.

-

PUT creates or replaces a resource identified by the URI.

-

PATCH provides instructions on how to modify the resource.

-

Both POST and PUT send the entire resource representation in their -request body. The PATCH method can be used when this is not -desirable. The request body of a PATCH method may be a partial -representation or a list of instructions on how to update the -resource.

-

The gun:post/4,5, gun:put/4,5 and gun:patch/4,5 functions -take a body as their fourth argument. These functions do -not require any body-specific header to be set, although -it is always recommended to set the content-type header. -Gun will set the other headers automatically.

-

In this and the following examples in this section, gun:post -can be replaced by gun:put or gun:patch for performing -a PUT or PATCH request, respectively.

-
-
POST "/organizations/ninenines"
-
-
Body = "{\"msg\": \"Hello world!\"}",
-StreamRef = gun:post(ConnPid, "/organizations/ninenines", [
-    {<<"content-type">>, "application/json"}
-], Body).
-

The gun:post/3, gun:put/3 and gun:patch/3 functions -do not take a body in their arguments. If a body is to be -provided later on, using the gun:data/4 function, then -the request headers must indicate this. This can be done -by setting the content-length or content-type request -headers. If these headers are not set then Gun will assume -the request has no body.

-

It is recommended to send the content-length header if you -know it in advance, although this is not required. If it -is not set, HTTP/1.1 will use the chunked transfer-encoding, -and HTTP/2 will continue normally as it is chunked by design.

-
-
POST "/organizations/ninenines" with delayed body
-
-
Body = "{\"msg\": \"Hello world!\"}",
-StreamRef = gun:post(ConnPid, "/organizations/ninenines", [
-    {<<"content-length">>, integer_to_binary(length(Body))},
-    {<<"content-type">>, "application/json"}
+
Body = "{\"msg\": \"Hello world!\"}",
+StreamRef = gun:post(ConnPid, "/organizations/ninenines", [
+    {<<"content-length">>, integer_to_binary(length(Body))},
+    {<<"content-type">>, "application/json"}
 ]),
-gun:data(ConnPid, StreamRef, fin, Body).
-

The atom fin indicates this is the last chunk of data to -be sent. You can call the gun:data/4 function as many -times as needed until you have sent the entire body. The -last call must use fin and all the previous calls must -use nofin. The last chunk may be empty.

-
-
Streaming the request body
-
-
sendfile(ConnPid, StreamRef, Filepath) ->
-    {ok, IoDevice} = file:open(Filepath, [read, binary, raw]),
-    do_sendfile(ConnPid, StreamRef, IoDevice).
-
-do_sendfile(ConnPid, StreamRef, IoDevice) ->
-    case file:read(IoDevice, 8000) of
-        eof ->
-            gun:data(ConnPid, StreamRef, fin, <<>>),
-            file:close(IoDevice);
-        {ok, Bin} ->
-            gun:data(ConnPid, StreamRef, nofin, Bin),
-            do_sendfile(ConnPid, StreamRef, IoDevice)
-    end.
-
-
+
sendfile(ConnPid, StreamRef, Filepath) ->
+    {ok, IoDevice} = file:open(Filepath, [read, binary, raw]),
+    do_sendfile(ConnPid, StreamRef, IoDevice).
+
+do_sendfile(ConnPid, StreamRef, IoDevice) ->
+    case file:read(IoDevice, 8000) of
+        eof ->
+            gun:data(ConnPid, StreamRef, fin, <<>>),
+            file:close(IoDevice);
+        {ok, Bin} ->
+            gun:data(ConnPid, StreamRef, nofin, Bin),
+            do_sendfile(ConnPid, StreamRef, IoDevice)
+    end.
+

DELETE

-

Use gun:delete/2,3,4 to delete a resource.

-
-
DELETE "/organizations/ninenines"
-
-
StreamRef = gun:delete(ConnPid, "/organizations/ninenines").
-
-
DELETE "/organizations/ninenines" with custom headers
-
-
StreamRef = gun:delete(ConnPid, "/organizations/ninenines", [
-    {<<"user-agent">>, "revolver/1.0"}
-]).
- -
+
StreamRef = gun:delete(ConnPid, "/organizations/ninenines", [
+    {<<"user-agent">>, "revolver/1.0"}
+]).
+

OPTIONS

-

Use gun:options/2,3 to request information about a resource.

-
-
OPTIONS "/organizations/ninenines"
-
-
StreamRef = gun:options(ConnPid, "/organizations/ninenines").
-
-
OPTIONS "/organizations/ninenines" with custom headers
-
-
StreamRef = gun:options(ConnPid, "/organizations/ninenines", [
-    {<<"user-agent">>, "revolver/1.0"}
-]).
-

You can also use this function to request information about -the server itself.

-
-
OPTIONS "*"
-
-
StreamRef = gun:options(ConnPid, "*").
- -
+
StreamRef = gun:options(ConnPid, "*").
+

Requests with an arbitrary method

-

The gun:request/4,5,6 function can be used to send requests -with a configurable method name. It is mostly useful when you -need a method that Gun does not understand natively.

-
-
Example of a TRACE request
-
-
gun:request(ConnPid, "TRACE", "/", [
-    {<<"max-forwards">>, "30"}
-]).
- - - -
+
gun:request(ConnPid, "TRACE", "/", [
+    {<<"max-forwards">>, "30"}
+]).
+

Processing responses

-
-

All data received from the server is sent to the owner -process as a message. First a gun_response message is sent, -followed by zero or more gun_data messages. If something goes wrong, -a gun_error message is sent instead.

-

The response message will inform you whether there will be -data messages following. If it contains fin there will be -no data messages. If it contains nofin then one or more data -messages will follow.

-

When using HTTP/2 this value is sent with the frame and simply -passed on in the message. When using HTTP/1.1 however Gun must -guess whether data will follow by looking at the response headers.

-

You can receive messages directly, or you can use the await -functions to let Gun receive them for you.

-
-
Receiving a response using receive
-
-
print_body(ConnPid, MRef) ->
-    StreamRef = gun:get(ConnPid, "/"),
-    receive
-        {gun_response, ConnPid, StreamRef, fin, Status, Headers} ->
-            no_data;
-        {gun_response, ConnPid, StreamRef, nofin, Status, Headers} ->
-            receive_data(ConnPid, MRef, StreamRef);
-        {'DOWN', MRef, process, ConnPid, Reason} ->
-            error_logger:error_msg("Oops!"),
-            exit(Reason)
-    after 1000 ->
-        exit(timeout)
-    end.
-
-receive_data(ConnPid, MRef, StreamRef) ->
-    receive
-        {gun_data, ConnPid, StreamRef, nofin, Data} ->
-            io:format("~s~n", [Data]),
-            receive_data(ConnPid, MRef, StreamRef);
-        {gun_data, ConnPid, StreamRef, fin, Data} ->
-            io:format("~s~n", [Data]);
-        {'DOWN', MRef, process, ConnPid, Reason} ->
-            error_logger:error_msg("Oops!"),
-            exit(Reason)
-    after 1000 ->
-        exit(timeout)
-    end.
-

While it may seem verbose, using messages like this has the -advantage of never locking your process, allowing you to -easily debug your code. It also allows you to start more than -one connection and concurrently perform queries on all of them -at the same time.

-

You can also use Gun in a synchronous manner by using the await -functions.

-

The gun:await/2,3,4 function will wait until it receives -a response to, a pushed resource related to, or data from -the given stream.

-

When calling gun:await/2,3 and not passing a monitor -reference, one is automatically created for you for the -duration of the call.

-

The gun:await_body/2,3,4 works similarly, but returns the -body received. Both functions can be combined to receive the -response and its body sequentially.

-
-
Receiving a response using await
-
-
StreamRef = gun:get(ConnPid, "/"),
-case gun:await(ConnPid, StreamRef) of
-    {response, fin, Status, Headers} ->
-        no_data;
-    {response, nofin, Status, Headers} ->
-        {ok, Body} = gun:await_body(ConnPid, StreamRef),
-        io:format("~s~n", [Body])
-end.
-
- -
+
StreamRef = gun:get(ConnPid, "/"),
+case gun:await(ConnPid, StreamRef) of
+    {response, fin, Status, Headers} ->
+        no_data;
+    {response, nofin, Status, Headers} ->
+        {ok, Body} = gun:await_body(ConnPid, StreamRef),
+        io:format("~s~n", [Body])
+end.
+

Handling streams pushed by the server

-
-

The HTTP/2 protocol allows the server to push more than one -resource for every request. It will start sending those -extra resources before it starts sending the response itself, -so Gun will send you gun_push messages before gun_response -when that happens.

-

You can safely choose to ignore gun_push messages, or -you can handle them. If you do, you can either receive the -messages directly or use await functions.

-

The gun_push message contains both the new stream reference -and the stream reference of the original request.

-
-
Receiving a pushed response using receive
-
-
receive
-    {gun_push, ConnPid, OriginalStreamRef, PushedStreamRef,
-            Method, Host, Path, Headers} ->
-        enjoy()
-end.
-

If you use the gun:await/2,3,4 function, however, Gun -will use the original reference to identify the message but -will return a tuple that doesn’t contain it.

-
-
Receiving a pushed response using await
-
-
{push, PushedStreamRef, Method, URI, Headers}
-    = gun:await(ConnPid, OriginalStreamRef).
-

The PushedStreamRef variable can then be used with gun:await/2,3,4 -and gun:await_body/2,3,4.

-
- -
+
{push, PushedStreamRef, Method, URI, Headers}
+    = gun:await(ConnPid, OriginalStreamRef).
+
+

The PushedStreamRef variable can then be used with gun:await/2,3,4 and gun:await_body/2,3,4.

Flushing unwanted messages

-
-

Gun provides the function gun:flush/1 to quickly get rid -of unwanted messages sitting in the process mailbox. You -can use it to get rid of all messages related to a connection, -or just the messages related to a stream.

-
-
Flush all messages from a Gun connection
-
-
gun:flush(ConnPid).
-
-
Flush all messages from a specific stream
-
-
gun:flush(StreamRef).
-
- -
+
gun:flush(StreamRef).
+

Redirecting responses to a different process

-
-

Gun allows you to specify which process will handle responses -to a request via the reply_to request option.

-
-
GET "/organizations/ninenines" to a different process
-
-
StreamRef = gun:get(ConnPid, "/organizations/ninenines", [],
-    #{reply_to => Pid}).
-
- +
StreamRef = gun:get(ConnPid, "/organizations/ninenines", [],
+    #{reply_to => Pid}).
+ + diff --git a/docs/en/gun/1.0/guide/index.html b/docs/en/gun/1.0/guide/index.html index cb30dd5b..78eff528 100644 --- a/docs/en/gun/1.0/guide/index.html +++ b/docs/en/gun/1.0/guide/index.html @@ -62,38 +62,20 @@

Gun User Guide

- + + diff --git a/docs/en/gun/1.0/guide/introduction/index.html b/docs/en/gun/1.0/guide/introduction/index.html index 6a3ed2e7..c2f99ea1 100644 --- a/docs/en/gun/1.0/guide/introduction/index.html +++ b/docs/en/gun/1.0/guide/introduction/index.html @@ -62,61 +62,35 @@

Introduction

-

Gun is an HTTP client for Erlang/OTP.

-

Gun supports the HTTP/2, HTTP/1.1 and Websocket protocols.

-
+

Gun is an HTTP client for Erlang/OTP.

+

Gun supports the HTTP/2, HTTP/1.1 and Websocket protocols.

Prerequisites

-
-

Knowledge of Erlang, but also of the HTTP/1.1, HTTP/2 and Websocket -protocols is required in order to read this guide.

-
-
-
+

Knowledge of Erlang, but also of the HTTP/1.1, HTTP/2 and Websocket protocols is required in order to read this guide.

Supported platforms

-
-

Gun is tested and supported on Linux, FreeBSD, Windows and OSX.

-

Gun is developed for Erlang/OTP 19.0 and newer.

-
-
-
+

Gun is tested and supported on Linux, FreeBSD, Windows and OSX.

+

Gun is developed for Erlang/OTP 19.0 and newer.

License

-
-

Gun uses the ISC License.

-
-
-
Copyright (c) 2013-2018, Loïc Hoguin <essen@ninenines.eu>
+

Gun uses the ISC License.

+
Copyright (c) 2013-2018, Loïc Hoguin <essen@ninenines.eu>
 
 Permission to use, copy, modify, and/or distribute this software for any
 purpose with or without fee is hereby granted, provided that the above
 copyright notice and this permission notice appear in all copies.
 
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-
-
-
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Versioning

- -
-
+

Gun uses Semantic Versioning 2.0.0.

Conventions

-
-

In the HTTP protocol, the method name is case sensitive. All standard -method names are uppercase.

-

Header names are case insensitive. Gun converts all the header names -to lowercase, and expects your application to provide lowercase header -names.

-

The same applies to any other case insensitive value.

-
-
+

In the HTTP protocol, the method name is case sensitive. All standard method names are uppercase.

+

Header names are case insensitive. Gun converts all the header names to lowercase, and expects your application to provide lowercase header names.

+

The same applies to any other case insensitive value.

+ diff --git a/docs/en/gun/1.0/guide/protocols/index.html b/docs/en/gun/1.0/guide/protocols/index.html index 00d70ad6..586ce865 100644 --- a/docs/en/gun/1.0/guide/protocols/index.html +++ b/docs/en/gun/1.0/guide/protocols/index.html @@ -62,270 +62,158 @@

Supported protocols

-

This chapter describes the protocols supported and the -operations available to them.

-
+

This chapter describes the protocols supported and the operations available to them.

HTTP/1.1

-
-

HTTP/1.1 is a text request-response protocol. The client -sends a request, the server sends back a response.

-

Gun provides convenience functions for performing GET, HEAD, -OPTIONS, POST, PATCH, PUT, and DELETE requests. All these -functions are aliases of gun:request/4,5,6 for the respective -methods. Gun also provides a gun:data/4 function for streaming -the request body.

-

Gun will send a gun_inform message for every intermediate -informational responses received. They will always be sent -before the gun_response message.

-

Gun will send a gun_response message for every response -received, followed by zero or more gun_data messages for -the response body, which is optionally terminated by a -gun_trailers message. If something goes wrong, a gun_error -will be sent instead.

-

Gun provides convenience functions for dealing with messages. -The gun:await/2,3,4 function waits for a response to the given -request, and the gun:await_body/2,3,4 function for the -response body. The gun:flush/1 function can be used to clear all -messages related to a request or a connection from the mailbox -of the calling process.

-

The function gun:cancel/2 can be used to silence the -response to a request previously sent if it is no longer -needed. When using HTTP/1.1 there is no multiplexing so -Gun will have to receive the response fully before any -other responses can be received.

-

Finally, Gun can upgrade an HTTP/1.1 connection to Websocket. -It provides the gun:ws_upgrade/2,3,4 function for that -purpose. A gun_upgrade message will be sent on success; -a gun_response message otherwise.

-
-
-
+

HTTP/1.1 is a text request-response protocol. The client sends a request, the server sends back a response.

+

Gun provides convenience functions for performing GET, HEAD, OPTIONS, POST, PATCH, PUT, and DELETE requests. All these functions are aliases of gun:request/4,5,6 for the respective methods. Gun also provides a gun:data/4 function for streaming the request body.

+

Gun will send a gun_inform message for every intermediate informational responses received. They will always be sent before the gun_response message.

+

Gun will send a gun_response message for every response received, followed by zero or more gun_data messages for the response body, which is optionally terminated by a gun_trailers message. If something goes wrong, a gun_error will be sent instead.

+

Gun provides convenience functions for dealing with messages. The gun:await/2,3,4 function waits for a response to the given request, and the gun:await_body/2,3,4 function for the response body. The gun:flush/1 function can be used to clear all messages related to a request or a connection from the mailbox of the calling process.

+

The function gun:cancel/2 can be used to silence the response to a request previously sent if it is no longer needed. When using HTTP/1.1 there is no multiplexing so Gun will have to receive the response fully before any other responses can be received.

+

Finally, Gun can upgrade an HTTP/1.1 connection to Websocket. It provides the gun:ws_upgrade/2,3,4 function for that purpose. A gun_upgrade message will be sent on success; a gun_response message otherwise.

HTTP/2

-
-

HTTP/2 is a binary protocol based on HTTP, compatible with -the HTTP semantics, that reduces the complexity of parsing -requests and responses, compresses the HTTP headers and -allows the server to push additional resources along with -the normal response to the original request.

-

The HTTP/2 interface is very similar to HTTP/1.1, so this -section instead focuses on the differences in the interface -for the two protocols.

-

Gun will send gun_push messages for every push received. -They will always be sent before the gun_response message. -They can be ignored safely if they are not needed, or they -can be canceled.

-

The gun:cancel/2 function will use the HTTP/2 stream -cancellation mechanism which allows Gun to inform the -server to stop sending a response for this particular -request, saving resources.

-

It is not currently possible to upgrade an HTTP/2 connection -to Websocket. Support for this will be added in a future -release.

-
-
-
+

HTTP/2 is a binary protocol based on HTTP, compatible with the HTTP semantics, that reduces the complexity of parsing requests and responses, compresses the HTTP headers and allows the server to push additional resources along with the normal response to the original request.

+

The HTTP/2 interface is very similar to HTTP/1.1, so this section instead focuses on the differences in the interface for the two protocols.

+

Gun will send gun_push messages for every push received. They will always be sent before the gun_response message. They can be ignored safely if they are not needed, or they can be canceled.

+

The gun:cancel/2 function will use the HTTP/2 stream cancellation mechanism which allows Gun to inform the server to stop sending a response for this particular request, saving resources.

+

It is not currently possible to upgrade an HTTP/2 connection to Websocket. Support for this will be added in a future release.

Websocket

-
-

Websocket is a binary protocol built on top of HTTP that -allows asynchronous concurrent communication between the -client and the server. A Websocket server can push data to -the client at any time.

-

Websocket is only available as a connection upgrade over -an HTTP/1.1 connection.

-

Once the Websocket connection is established, the only -operation available on this connection is sending Websocket -frames using gun:ws_send/2.

-

Gun will send a gun_ws message for every frame received.

-
-
-
+

Websocket is a binary protocol built on top of HTTP that allows asynchronous concurrent communication between the client and the server. A Websocket server can push data to the client at any time.

+

Websocket is only available as a connection upgrade over an HTTP/1.1 connection.

+

Once the Websocket connection is established, the only operation available on this connection is sending Websocket frames using gun:ws_send/2.

+

Gun will send a gun_ws message for every frame received.

Summary

-
-

The two following tables summarize the supported operations -and the messages Gun sends depending on the connection’s -current protocol.

-
- ----- - - - - - +

The two following tables summarize the supported operations and the messages Gun sends depending on the connection's current protocol.

+
Operation HTTP/1.1 HTTP/2 Websocket
+ + + + + + + + - - - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - +
Supported operations per protocol
OperationHTTP/1.1HTTP/2Websocket
deleteyesyesno

delete

yes

yes

no

getyesyesno

get

yes

yes

no

headyesyesno

head

yes

yes

no

optionsyesyesno

options

yes

yes

no

patchyesyesno

patch

yes

yes

no

postyesyesno

post

yes

yes

no

putyesyesno

put

yes

yes

no

requestyesyesno

request

yes

yes

no

datayesyesno

data

yes

yes

no

awaityesyesno

await

yes

yes

no

await_bodyyesyesno

await_body

yes

yes

no

flushyesyesno

flush

yes

yes

no

cancelyesyesno

cancel

yes

yes

no

ws_upgradeyesnono

ws_upgrade

yes

no

no

ws_sendnonoyes

ws_send

no

no

yes

+ + + + + + + + + - -
Messages sent per protocol
MessageHTTP/1.1HTTP/2Websocket
gun_pushnoyesno
-
-
- ----- - - - - - + + + + - - - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - + + + + - - - - - - - - - - - - - -
Message HTTP/1.1 HTTP/2 Websocket
gun_informyesyesno

gun_push

no

yes

no

gun_responseyesyesno

gun_inform

yes

yes

no

gun_datayesyesno

gun_response

yes

yes

no

gun_trailersyesyesno

gun_data

yes

yes

no

gun_erroryesyesyes

gun_trailers

yes

yes

no

gun_upgradeyesnono

gun_error

yes

yes

yes

gun_wsnonoyes

gun_upgrade

yes

no

no

gun_ws

no

no

yes

-
-
-
+ + diff --git a/docs/en/gun/1.0/guide/start/index.html b/docs/en/gun/1.0/guide/start/index.html index 6611c3ea..8eda77a7 100644 --- a/docs/en/gun/1.0/guide/start/index.html +++ b/docs/en/gun/1.0/guide/start/index.html @@ -62,54 +62,37 @@

Starting and stopping

-

This chapter describes how to start and stop the Gun application.

-
+

This chapter describes how to start and stop the Gun application.

Setting up

-
-

Specify Gun as a dependency to your application in your favorite -build tool.

-

With Erlang.mk this is done by adding gun to the DEPS variable -in your Makefile.

-
-
Adding Gun as an Erlang.mk dependency
-
-
DEPS = gun
-
-
-
+
DEPS = gun
+

Starting

-
-

Gun is an OTP application. It needs to be started before you can -use it.

-
-
Starting Gun in an Erlang shell
-
-
1> application:ensure_all_started(gun).
-{ok,[crypto,cowlib,asn1,public_key,ssl,gun]}
-
- -
+
1> application:ensure_all_started(gun).
+{ok,[crypto,cowlib,asn1,public_key,ssl,gun]}
+

Stopping

-
-

You can stop Gun using the application:stop/1 function, however -only Gun will be stopped. This is the reverse of application:start/1. -The application_ensure_all_started/1 function has no equivalent for -stopping all applications.

-
-
Stopping Gun
-
-
application:stop(gun).
-
- +
application:stop(gun).
+ + diff --git a/docs/en/gun/1.0/guide/websocket/index.html b/docs/en/gun/1.0/guide/websocket/index.html index a77f1319..67becc45 100644 --- a/docs/en/gun/1.0/guide/websocket/index.html +++ b/docs/en/gun/1.0/guide/websocket/index.html @@ -62,102 +62,88 @@

Websocket

-

This chapter describes how to use the Gun client for -communicating with a Websocket server.

-
+

This chapter describes how to use the Gun client for communicating with a Websocket server.

+

HTTP upgrade

-
-

Websocket is a protocol built on top of HTTP. To use Websocket, -you must first request for the connection to be upgraded. Only -HTTP/1.1 connections can be upgraded to Websocket, so you might -need to restrict the protocol to HTTP/1.1 if you are planning -to use Websocket over TLS.

-

You must use the gun:ws_upgrade/2,3,4 function to upgrade -to Websocket. This function can be called anytime after connection, -so you can send HTTP requests before upgrading to Websocket.

-
-
Upgrade to Websocket
-
-
gun:ws_upgrade(ConnPid, "/websocket").
-

Gun will set all the necessary headers for performing the -Websocket upgrade, but you can specify additional headers -if needed. For example you can request a custom sub-protocol.

-
-
Upgrade to Websocket and request a protocol
-
-
gun:ws_upgrade(ConnPid, "/websocket", [
-    {<<"sec-websocket-protocol">>, "mychat"}
-]).
-

You can pass the Websocket options as part of the gun:open/2,3 -call when opening the connection, or using the gun:ws_upgrade/4. -The fourth argument is those same options.

-

When the upgrade succeeds, a gun_upgrade message is sent. -If the server does not understand Websocket or refused the -upgrade, a gun_response message is sent. If Gun couldn’t -perform the upgrade due to an error (for example attempting -to upgrade to Websocket on an HTTP/1.0 connection) then a -gun_error message is sent.

-

When the server does not understand Websocket, it may send -a meaningful response which should be processed. In the -following example we however ignore it:

-
-
-
receive
-    {gun_upgrade, ConnPid, StreamRef, [<<"websocket">>], Headers} ->
-        upgrade_success(ConnPid, StreamRef);
-    {gun_response, ConnPid, _, _, Status, Headers} ->
-        exit({ws_upgrade_failed, Status, Headers});
-    {gun_error, ConnPid, StreamRef, Reason} ->
-        exit({ws_upgrade_failed, Reason})
-    %% More clauses here as needed.
-after 1000 ->
-    exit(timeout)
-end.
-
-
-
+
receive
+    {gun_upgrade, ConnPid, StreamRef, [<<"websocket">>], Headers} ->
+        upgrade_success(ConnPid, StreamRef);
+    {gun_response, ConnPid, _, _, Status, Headers} ->
+        exit({ws_upgrade_failed, Status, Headers});
+    {gun_error, ConnPid, StreamRef, Reason} ->
+        exit({ws_upgrade_failed, Reason})
+    %% More clauses here as needed.
+after 1000 ->
+    exit(timeout)
+end.
+

Sending data

-
-

Once the Websocket upgrade has completed successfully, you no -longer have access to functions for performing requests. You -can only send and receive Websocket messages.

-

Use gun:ws_send/2 to send messages to the server.

-
-
Send a text frame
-
-
gun:ws_send(ConnPid, {text, "Hello!"}).
-

Note that if you send a close frame, Gun will close the connection -cleanly and will not attempt to reconnect afterwards.

-
- -
+
gun:ws_send(ConnPid, {text, "Hello!"}).
+
+ + + + + + + + + + + +

Note that if you send a close frame, Gun will close the connection cleanly and will not attempt to reconnect afterwards.

Receiving data

-
-

Gun sends an Erlang message to the owner process for every -Websocket message it receives.

-
-
-
receive
-    {gun_ws, ConnPid, StreamRef, Frame} ->
-        handle_frame(ConnPid, StreamRef, Frame)
-end.
-
- +
receive
+    {gun_ws, ConnPid, StreamRef, Frame} ->
+        handle_frame(ConnPid, StreamRef, Frame)
+end.
+ + + + + + + + + diff --git a/docs/en/gun/1.0/manual/gun.await/index.html b/docs/en/gun/1.0/manual/gun.await/index.html index a0a9d77b..dd857dad 100644 --- a/docs/en/gun/1.0/manual/gun.await/index.html +++ b/docs/en/gun/1.0/manual/gun.await/index.html @@ -62,180 +62,94 @@

gun:await(3)

-

Name

-
-

gun:await - Wait for a response

-
-
-
+

gun:await - Wait for a response

Description

-
-
-
-
await(ConnPid, StreamRef)
-    -> await(ConnPid, StreamRef, 5000, MonitorRef)
-
-await(ConnPid, StreamRef, MonitorRef)
-    -> await(ConnPid, StreamRef, 5000, MonitorRef)
-
-await(ConnPid, StreamRef, Timeout)
-    -> await(ConnPid, StreamRef, Timeout, MonitorRef)
-
-await(ConnPid, StreamRef, Timeout, MonitorRef)
-    -> Result
-
-ConnPid    :: pid()
-StreamRef  :: reference()
-MonitorRef :: reference()
-Timeout    :: timeout()
-Result     :: tuple() - see below
-

Wait for a response.

-

This function waits for a message from the given stream and -returns it as a tuple. An error will be returned should the -process fail or a relevant message is not received within -the specified duration.

-
-
-
+
await(ConnPid, StreamRef)
+    -> await(ConnPid, StreamRef, 5000, MonitorRef)
+
+await(ConnPid, StreamRef, MonitorRef)
+    -> await(ConnPid, StreamRef, 5000, MonitorRef)
+
+await(ConnPid, StreamRef, Timeout)
+    -> await(ConnPid, StreamRef, Timeout, MonitorRef)
+
+await(ConnPid, StreamRef, Timeout, MonitorRef)
+    -> Result
+
+ConnPid    :: pid()
+StreamRef  :: reference()
+MonitorRef :: reference()
+Timeout    :: timeout()
+Result     :: tuple() - see below
+
+

Wait for a response.

+

This function waits for a message from the given stream and returns it as a tuple. An error will be returned should the process fail or a relevant message is not received within the specified duration.

Arguments

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-StreamRef -
-
-

-Identifier of the stream for the original request. -

+
StreamRef
+

Identifier of the stream for the original request.

-
-Timeout -
-
-

-How long to wait for a message, in milliseconds. -

+
Timeout
+

How long to wait for a message, in milliseconds.

-
-MonitorRef -
-
-

-Monitor for the Gun connection process. -

-

A monitor is automatically created for the duration of this -call when one is not provided.

+
MonitorRef
+

Monitor for the Gun connection process.

+

A monitor is automatically created for the duration of this call when one is not provided.

-
-
- -
+

Return value

-
-

A number of different tuples can be returned. They correspond -to the message of the same name and they contain the same -elements minus the pid and stream reference. Error tuples -may also be returned when a timeout or an error occur.

-
-
-
Result :: {inform, Status, Headers}
-          {response, IsFin, Status, Headers}
-          {data, IsFin, Data}
-          {trailers, Trailers}
-          {push, NewStreamRef, Method, URI, Headers}
-          {error, Reason}
-
-Reason :: timeout | any()
-

Because the messages and returned tuples are equivalent, -please refer to the manual pages for each message for -further information:

-
    -
  • -

    -gun_push(3) - Server-initiated push -

    +
    Result :: {inform, Status, Headers}
    +          {response, IsFin, Status, Headers}
    +          {data, IsFin, Data}
    +          {trailers, Trailers}
    +          {push, NewStreamRef, Method, URI, Headers}
    +          {error, Reason}
    +
    +Reason :: timeout | any()
    +
+

Because the messages and returned tuples are equivalent, please refer to the manual pages for each message for further information:

+
- - -
+

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Wait for a response
-
-
StreamRef = gun:get(ConnPid, "/articles", [
-    {<<"accept">>, <<"text/html;q=1.0, application/xml;q=0.1">>}
-]).
-{response, nofin, 200, _Headers} = gun:await(ConnPid, StreamRef).
-{data, fin, <<"Hello world!">>} = gun:await(ConnPid, StreamRef).
-
-
-
+
StreamRef = gun:get(ConnPid, "/articles", [
+    {<<"accept">>, <<"text/html;q=1.0, application/xml;q=0.1">>}
+]).
+{response, nofin, 200, _Headers} = gun:await(ConnPid, StreamRef).
+{data, fin, <<"Hello world!">>} = gun:await(ConnPid, StreamRef).
+

See also

- - +

gun(3), gun:get(3), gun:head(3), gun:options(3), gun:patch(3), gun:post(3), gun:put(3), gun:delete(3), gun:request(3), gun:await_body(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.await_body/index.html b/docs/en/gun/1.0/manual/gun.await_body/index.html index 56a94dbc..a3759bed 100644 --- a/docs/en/gun/1.0/manual/gun.await_body/index.html +++ b/docs/en/gun/1.0/manual/gun.await_body/index.html @@ -62,134 +62,70 @@

gun:await_body(3)

-

Name

-
-

gun:await_body - Wait for the complete response body

-
-
-
+

gun:await_body - Wait for the complete response body

Description

-
-
-
-
await_body(ConnPid, StreamRef)
-    -> await_body(ConnPid, StreamRef, 5000, MonitorRef)
-
-await_body(ConnPid, StreamRef, MonitorRef)
-    -> await_body(ConnPid, StreamRef, 5000, MonitorRef)
-
-await_body(ConnPid, StreamRef, Timeout)
-    -> await_body(ConnPid, StreamRef, Timeout, MonitorRef)
-
-await_body(ConnPid, StreamRef, Timeout, MonitorRef)
-    -> {ok, Body} | {ok, Body, Trailers} | {error, Reason}
-
-ConnPid    :: pid()
-StreamRef  :: reference()
-MonitorRef :: reference()
-Timeout    :: timeout()
-Body       :: binary()
-Trailers   :: [{binary(), binary()}]
-Reason     :: timeout | any()
-

Wait for the complete response body.

-
-
-
+
await_body(ConnPid, StreamRef)
+    -> await_body(ConnPid, StreamRef, 5000, MonitorRef)
+
+await_body(ConnPid, StreamRef, MonitorRef)
+    -> await_body(ConnPid, StreamRef, 5000, MonitorRef)
+
+await_body(ConnPid, StreamRef, Timeout)
+    -> await_body(ConnPid, StreamRef, Timeout, MonitorRef)
+
+await_body(ConnPid, StreamRef, Timeout, MonitorRef)
+    -> {ok, Body} | {ok, Body, Trailers} | {error, Reason}
+
+ConnPid    :: pid()
+StreamRef  :: reference()
+MonitorRef :: reference()
+Timeout    :: timeout()
+Body       :: binary()
+Trailers   :: [{binary(), binary()}]
+Reason     :: timeout | any()
+
+

Wait for the complete response body.

Arguments

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-StreamRef -
-
-

-Identifier of the stream for the original request. -

+
StreamRef
+

Identifier of the stream for the original request.

-
-Timeout -
-
-

-How long to wait for each message, in milliseconds. -

+
Timeout
+

How long to wait for each message, in milliseconds.

-
-MonitorRef -
-
-

-Monitor for the Gun connection process. -

-

A monitor is automatically created for the duration of this -call when one is not provided.

+
MonitorRef
+

Monitor for the Gun connection process.

+

A monitor is automatically created for the duration of this call when one is not provided.

-
-
- -
+

Return value

-
-

The body is returned, possibly with trailers if the -request contained a te: trailers header. Error tuples -may also be returned when a timeout or an error occur.

-
-
-
+

The body is returned, possibly with trailers if the request contained a te: trailers header. Error tuples may also be returned when a timeout or an error occur.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Wait for the complete response body
-
-
StreamRef = gun:get(ConnPid, "/articles", [
-    {<<"accept">>, <<"text/html;q=1.0, application/xml;q=0.1">>}
-]).
-{response, nofin, 200, _Headers} = gun:await(ConnPid, StreamRef).
-{ok, _Body} = gun:await_body(ConnPid, StreamRef).
-
-
-
+
StreamRef = gun:get(ConnPid, "/articles", [
+    {<<"accept">>, <<"text/html;q=1.0, application/xml;q=0.1">>}
+]).
+{response, nofin, 200, _Headers} = gun:await(ConnPid, StreamRef).
+{ok, _Body} = gun:await_body(ConnPid, StreamRef).
+

See also

- - +

gun(3), gun:get(3), gun:head(3), gun:options(3), gun:patch(3), gun:post(3), gun:put(3), gun:delete(3), gun:request(3), gun:await(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.await_up/index.html b/docs/en/gun/1.0/manual/gun.await_up/index.html index dc3eea5c..b437925e 100644 --- a/docs/en/gun/1.0/manual/gun.await_up/index.html +++ b/docs/en/gun/1.0/manual/gun.await_up/index.html @@ -62,115 +62,62 @@

gun:await_up(3)

-

Name

-
-

gun:await_up - Wait for the connection to be up

-
-
-
+

gun:await_up - Wait for the connection to be up

Description

-
-
-
-
await_up(ConnPid)
-    -> await_up(ConnPid, 5000, MonitorRef)
+
await_up(ConnPid)
+    -> await_up(ConnPid, 5000, MonitorRef)
 
-await_up(ConnPid, MonitorRef)
-    -> await_up(ConnPid, 5000, MonitorRef)
+await_up(ConnPid, MonitorRef)
+    -> await_up(ConnPid, 5000, MonitorRef)
 
-await_up(ConnPid, Timeout)
-    -> await_up(ConnPid, Timeout, MonitorRef)
+await_up(ConnPid, Timeout)
+    -> await_up(ConnPid, Timeout, MonitorRef)
 
-await_up(ConnPid, Timeout, MonitorRef)
-    -> {ok, Protocol} | {error, Reason}
+await_up(ConnPid, Timeout, MonitorRef)
+    -> {ok, Protocol} | {error, Reason}
 
-ConnPid    :: pid()
-MonitorRef :: reference()
-Timeout    :: timeout()
-Protocol   :: http | http2
-Reason     :: timeout | any()
-

Wait for the connection to be up.

-
-
-
+ConnPid :: pid() +MonitorRef :: reference() +Timeout :: timeout() +Protocol :: http | http2 +Reason :: timeout | any() +
+

Wait for the connection to be up.

Arguments

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-Timeout -
-
-

-How long to wait for, in milliseconds. -

+
Timeout
+

How long to wait for, in milliseconds.

-
-MonitorRef -
-
-

-Monitor for the Gun connection process. -

-

A monitor is automatically created for the duration of this -call when one is not provided.

+
MonitorRef
+

Monitor for the Gun connection process.

+

A monitor is automatically created for the duration of this call when one is not provided.

-
-
- -
+

Return value

-
-

The protocol selected for this connection. It can be used -to determine the capabilities of the server. Error tuples -may also be returned when a timeout or an error occur.

-
-
-
+

The protocol selected for this connection. It can be used to determine the capabilities of the server. Error tuples may also be returned when a timeout or an error occur.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Wait for the connection to be up
-
-
{ok, ConnPid} = gun:open("example.org", 443).
-{ok, _} = gun:await_up(ConnPid).
-
-
-
+
{ok, ConnPid} = gun:open("example.org", 443).
+{ok, _} = gun:await_up(ConnPid).
+

See also

- - +

gun(3), gun:open(3), gun:open_unix(3), gun_up(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.cancel/index.html b/docs/en/gun/1.0/manual/gun.cancel/index.html index ea356f54..76e8d19b 100644 --- a/docs/en/gun/1.0/manual/gun.cancel/index.html +++ b/docs/en/gun/1.0/manual/gun.cancel/index.html @@ -62,103 +62,48 @@

gun:cancel(3)

-

Name

-
-

gun:cancel - Cancel the given stream

-
-
-
+

gun:cancel - Cancel the given stream

Description

-
-
-
-
cancel(ConnPid, StreamRef) -> ok
-
-ConnPid   :: pid()
-StreamRef :: reference()
-

Cancel the given stream.

-

The behavior of this function depends on the protocol -selected.

-

HTTP/1.1 does not support this feature. Gun will simply -silence the stream and stop relaying messages. Gun may -also decide to close the connection if the response body -is too large, to avoid wasting time and bandwidth.

-

HTTP/2 allows cancelling streams at any time.

-

This function is asynchronous. Messages related to this -stream may still be sent after the function returns.

-
-
-
+
cancel(ConnPid, StreamRef) -> ok
+
+ConnPid   :: pid()
+StreamRef :: reference()
+
+

Cancel the given stream.

+

The behavior of this function depends on the protocol selected.

+

HTTP/1.1 does not support this feature. Gun will simply silence the stream and stop relaying messages. Gun may also decide to close the connection if the response body is too large, to avoid wasting time and bandwidth.

+

HTTP/2 allows cancelling streams at any time.

+

This function is asynchronous. Messages related to this stream may still be sent after the function returns.

Arguments

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-StreamRef -
-
-

-Identifier of the stream for the original request. -

+
StreamRef
+

Identifier of the stream for the original request.

-
-
- -
+

Return value

-
-

The atom ok is returned.

-
-
-
+

The atom ok is returned.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Cancel a stream
-
-
gun:cancel(ConnPid, StreamRef).
-
-
-
+
gun:cancel(ConnPid, StreamRef).
+

See also

- - +

gun(3), gun:get(3), gun:head(3), gun:options(3), gun:patch(3), gun:post(3), gun:put(3), gun:delete(3), gun:request(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.close/index.html b/docs/en/gun/1.0/manual/gun.close/index.html index ab536f8d..6c0b82e1 100644 --- a/docs/en/gun/1.0/manual/gun.close/index.html +++ b/docs/en/gun/1.0/manual/gun.close/index.html @@ -62,79 +62,40 @@

gun:close(3)

-

Name

-
-

gun:close - Brutally close the connection

-
-
-
+

gun:close - Brutally close the connection

Description

-
-
-
-
close(ConnPid) -> ok
+
close(ConnPid) -> ok
 
-ConnPid :: pid()
-

Brutally close the connection.

-
-
-
+ConnPid :: pid() +
+

Brutally close the connection.

Arguments

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-
- -
+

Return value

-
-

The atom ok is returned.

-
-
-
+

The atom ok is returned.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Close the connection
-
-
ok = gun:close(ConnPid).
-
-
-
+
ok = gun:close(ConnPid).
+

See also

- - +

gun(3), gun:open(3), gun:open_unix(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.data/index.html b/docs/en/gun/1.0/manual/gun.data/index.html index 8382616e..97b689bd 100644 --- a/docs/en/gun/1.0/manual/gun.data/index.html +++ b/docs/en/gun/1.0/manual/gun.data/index.html @@ -62,119 +62,59 @@

gun:data(3)

-

Name

-
-

gun:data - Stream the body of a request

-
-
-
+

gun:data - Stream the body of a request

Description

-
-
-
-
data(ConnPid, StreamRef, IsFin, Data) -> ok
-
-ConnPid   :: pid()
-StreamRef :: reference()
-IsFin     :: fin | nofin
-Data      :: iodata()
-

Stream the body of a request.

-

This function can only be used if the original request -had headers indicating that a body would be streamed.

-

All calls to this function must use the nofin flag -except for the last which must use fin to indicate -the end of the request body.

-

Empty data is allowed regardless of the value of IsFin. -Gun may or may not send empty data chunks, however.

-
-
-
+
data(ConnPid, StreamRef, IsFin, Data) -> ok
+
+ConnPid   :: pid()
+StreamRef :: reference()
+IsFin     :: fin | nofin
+Data      :: iodata()
+
+

Stream the body of a request.

+

This function can only be used if the original request had headers indicating that a body would be streamed.

+

All calls to this function must use the nofin flag except for the last which must use fin to indicate the end of the request body.

+

Empty data is allowed regardless of the value of IsFin. Gun may or may not send empty data chunks, however.

Arguments

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-StreamRef -
-
-

-Identifier of the stream for the original request. -

+
StreamRef
+

Identifier of the stream for the original request.

-
-IsFin -
-
-

-Whether this message terminates the request. -

+
IsFin
+

Whether this message terminates the request.

-
-Data -
-
-

-All or part of the response body. -

+
Data
+

All or part of the response body.

-
-
- -
+

Return value

-
-

The atom ok is returned.

-
-
-
+

The atom ok is returned.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Stream the body of a request
-
-
StreamRef = gun:put(ConnPid, "/lang/fr_FR/hello", [
-    {<<"content-type">>, <<"text/plain">>}
-]).
-gun:data(ConnPid, StreamRef, nofin, <<"Bonjour !\n">>).
-gun:data(ConnPid, StreamRef, fin, <<"Bonsoir !\n">>).
-
-
-
+
StreamRef = gun:put(ConnPid, "/lang/fr_FR/hello", [
+    {<<"content-type">>, <<"text/plain">>}
+]).
+gun:data(ConnPid, StreamRef, nofin, <<"Bonjour !\n">>).
+gun:data(ConnPid, StreamRef, fin, <<"Bonsoir !\n">>).
+

See also

- - +

gun(3), gun:patch(3), gun:post(3), gun:put(3), gun:request(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.delete/index.html b/docs/en/gun/1.0/manual/gun.delete/index.html index 62c25d81..d13544b4 100644 --- a/docs/en/gun/1.0/manual/gun.delete/index.html +++ b/docs/en/gun/1.0/manual/gun.delete/index.html @@ -62,130 +62,68 @@

gun:delete(3)

-

Name

-
-

gun:delete - Delete a resource

-
-
-
+

gun:delete - Delete a resource

Description

-
-
-
-
delete(ConnPid, Path)
-    -> delete(ConnPid, Path, [], #{}).
-
-delete(ConnPid, Path, Headers)
-    -> delete(ConnPid, Path, Headers, #{})
-
-delete(ConnPid, Path, Headers, ReqOpts)
-    -> StreamRef
-
-ConnPid   :: pid()
-Path      :: iodata()
-Headers   :: [{binary(), iodata()}]
-ReqOpts   :: gun:req_opts()
-StreamRef :: reference()
-

Delete a resource.

-
-
-
+
delete(ConnPid, Path)
+    -> delete(ConnPid, Path, [], #{}).
+
+delete(ConnPid, Path, Headers)
+    -> delete(ConnPid, Path, Headers, #{})
+
+delete(ConnPid, Path, Headers, ReqOpts)
+    -> StreamRef
+
+ConnPid   :: pid()
+Path      :: iodata()
+Headers   :: [{binary(), iodata()}]
+ReqOpts   :: gun:req_opts()
+StreamRef :: reference()
+
+

Delete a resource.

Arguments

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-Path -
-
-

-Path to the resource. -

+
Path
+

Path to the resource.

-
-Headers -
-
-

-Additional request headers. -

+
Headers
+

Additional request headers.

-
-ReqOpts -
-
-

-Request options. -

+
ReqOpts
+

Request options.

-
-
- -
+

Return value

-
-

A reference that identifies the newly created stream is -returned. It is this reference that must be passed in -subsequent calls and will be received in messages related -to this new stream.

-
-
-
+

A reference that identifies the newly created stream is returned. It is this reference that must be passed in subsequent calls and will be received in messages related to this new stream.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Delete a resource
-
-
StreamRef = gun:delete(ConnPid, "/drafts/123").
-
-
Delete a resource with request options
-
-
StreamRef = gun:delete(ConnPid, "/drafts/123", [],
-    #{reply_to => ReplyToPid}).
-
-
-
+
StreamRef = gun:delete(ConnPid, "/drafts/123", [],
+    #{reply_to => ReplyToPid}).
+

See also

- - +

gun(3), gun:put(3), gun:await(3), gun:await_body(3), gun_push(3), gun_inform(3), gun_response(3), gun_data(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.flush/index.html b/docs/en/gun/1.0/manual/gun.flush/index.html index 13263727..43420e8d 100644 --- a/docs/en/gun/1.0/manual/gun.flush/index.html +++ b/docs/en/gun/1.0/manual/gun.flush/index.html @@ -62,98 +62,53 @@

gun:flush(3)

-

Name

-
-

gun:flush - Flush all messages related to a connection or a stream

-
-
-
+

gun:flush - Flush all messages related to a connection or a stream

Description

-
-
-
-
flush(ConnPid) -> ok
-flush(StreamRef) -> ok
+
flush(ConnPid) -> ok
+flush(StreamRef) -> ok
 
-ConnPid    :: pid()
-StreamRef  :: reference()
-

Flush all messages related to a connection or a stream.

-
-
-
+ConnPid :: pid() +StreamRef :: reference() +
+

Flush all messages related to a connection or a stream.

Arguments

-
-

Either of these arguments may be provided:

-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+

Either of these arguments may be provided:

+
ConnPid
+

The pid of the Gun connection process.

-
-StreamRef -
-
-

-Identifier of the stream for the original request. -

+
StreamRef
+

Identifier of the stream for the original request.

-
-
- -
+

Return value

-
-

The atom ok is returned.

-
-
-
+

The atom ok is returned.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Flush all messages from a connection
-
-
gun:flush(ConnPid).
-
-
Flush messages from a single stream
-
-
gun:flush(StreamRef).
-
-
-
+
gun:flush(StreamRef).
+

See also

- - +

gun(3), gun:await(3), gun:await_body(3), gun:await_up(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.get/index.html b/docs/en/gun/1.0/manual/gun.get/index.html index a1864b6c..5945cfc9 100644 --- a/docs/en/gun/1.0/manual/gun.get/index.html +++ b/docs/en/gun/1.0/manual/gun.get/index.html @@ -62,133 +62,71 @@

gun:get(3)

-

Name

-
-

gun:get - Get a resource representation

-
-
-
+

gun:get - Get a resource representation

Description

-
-
-
-
get(ConnPid, Path)
-    -> get(ConnPid, Path, [], #{}).
-
-get(ConnPid, Path, Headers)
-    -> get(ConnPid, Path, Headers, #{})
-
-get(ConnPid, Path, Headers, ReqOpts)
-    -> StreamRef
-
-ConnPid   :: pid()
-Path      :: iodata()
-Headers   :: [{binary(), iodata()}]
-ReqOpts   :: gun:req_opts()
-StreamRef :: reference()
-

Get a resource representation.

-
-
-
+
get(ConnPid, Path)
+    -> get(ConnPid, Path, [], #{}).
+
+get(ConnPid, Path, Headers)
+    -> get(ConnPid, Path, Headers, #{})
+
+get(ConnPid, Path, Headers, ReqOpts)
+    -> StreamRef
+
+ConnPid   :: pid()
+Path      :: iodata()
+Headers   :: [{binary(), iodata()}]
+ReqOpts   :: gun:req_opts()
+StreamRef :: reference()
+
+

Get a resource representation.

Arguments

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-Path -
-
-

-Path to the resource. -

+
Path
+

Path to the resource.

-
-Headers -
-
-

-Additional request headers. -

+
Headers
+

Additional request headers.

-
-ReqOpts -
-
-

-Request options. -

+
ReqOpts
+

Request options.

-
-
- -
+

Return value

-
-

A reference that identifies the newly created stream is -returned. It is this reference that must be passed in -subsequent calls and will be received in messages related -to this new stream.

-
-
-
+

A reference that identifies the newly created stream is returned. It is this reference that must be passed in subsequent calls and will be received in messages related to this new stream.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get a resource representation
-
-
StreamRef = gun:get(ConnPid, "/articles", [
-    {<<"accept">>, <<"text/html;q=1.0, application/xml;q=0.1">>}
-]).
-
-
Get a resource representation with request options
-
-
StreamRef = gun:get(ConnPid, "/articles", [], #{
-    reply_to => ReplyToPid
-}).
-
-
-
+
StreamRef = gun:get(ConnPid, "/articles", [], #{
+    reply_to => ReplyToPid
+}).
+

See also

- - +

gun(3), gun:head(3), gun:await(3), gun:await_body(3), gun_push(3), gun_inform(3), gun_response(3), gun_data(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.head/index.html b/docs/en/gun/1.0/manual/gun.head/index.html index 8afd0163..1341d833 100644 --- a/docs/en/gun/1.0/manual/gun.head/index.html +++ b/docs/en/gun/1.0/manual/gun.head/index.html @@ -62,138 +62,73 @@

gun:head(3)

-

Name

-
-

gun:head - Get headers of a resource representation

-
-
-
+

gun:head - Get headers of a resource representation

Description

-
-
-
-
head(ConnPid, Path)
-    -> head(ConnPid, Path, [], #{}).
-
-head(ConnPid, Path, Headers)
-    -> head(ConnPid, Path, Headers, #{})
-
-head(ConnPid, Path, Headers, ReqOpts)
-    -> StreamRef
-
-ConnPid   :: pid()
-Path      :: iodata()
-Headers   :: [{binary(), iodata()}]
-ReqOpts   :: gun:req_opts()
-StreamRef :: reference()
-

Get headers of a resource representation.

-

This function performs the same operation as -gun:get(3), except the server will not -send the resource representation, only the response’s status -code and headers.

-

While servers are supposed to send the same headers as for -a GET request, they sometimes will not. For example the -content-length header may be dropped from the response.

-
-
-
+
head(ConnPid, Path)
+    -> head(ConnPid, Path, [], #{}).
+
+head(ConnPid, Path, Headers)
+    -> head(ConnPid, Path, Headers, #{})
+
+head(ConnPid, Path, Headers, ReqOpts)
+    -> StreamRef
+
+ConnPid   :: pid()
+Path      :: iodata()
+Headers   :: [{binary(), iodata()}]
+ReqOpts   :: gun:req_opts()
+StreamRef :: reference()
+
+

Get headers of a resource representation.

+

This function performs the same operation as gun:get(3), except the server will not send the resource representation, only the response's status code and headers.

+

While servers are supposed to send the same headers as for a GET request, they sometimes will not. For example the content-length header may be dropped from the response.

Arguments

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-Path -
-
-

-Path to the resource. -

+
Path
+

Path to the resource.

-
-Headers -
-
-

-Additional request headers. -

+
Headers
+

Additional request headers.

-
-ReqOpts -
-
-

-Request options. -

+
ReqOpts
+

Request options.

-
-
- -
+

Return value

-
-

A reference that identifies the newly created stream is -returned. It is this reference that must be passed in -subsequent calls and will be received in messages related -to this new stream.

-
-
-
+

A reference that identifies the newly created stream is returned. It is this reference that must be passed in subsequent calls and will be received in messages related to this new stream.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Get headers of a resource representation
-
-
StreamRef = gun:head(ConnPid, "/articles", [
-    {<<"accept">>, <<"text/html;q=1.0, application/xml;q=0.1">>}
-]).
-
-
Get headers of a resource representation with request options
-
-
StreamRef = gun:head(ConnPid, "/articles", [], #{
-    reply_to => ReplyToPid
-}).
-
-
-
+
StreamRef = gun:head(ConnPid, "/articles", [], #{
+    reply_to => ReplyToPid
+}).
+

See also

- - +

gun(3), gun:head(3), gun:await(3), gun_push(3), gun_inform(3), gun_response(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.info/index.html b/docs/en/gun/1.0/manual/gun.info/index.html index 7b94f600..2206a94e 100644 --- a/docs/en/gun/1.0/manual/gun.info/index.html +++ b/docs/en/gun/1.0/manual/gun.info/index.html @@ -62,84 +62,44 @@

gun:info(3)

-

Name

-
-

gun:info - Obtain information about the connection

-
-
-
+

gun:info - Obtain information about the connection

Description

-
-
-
-
info(ConnPid) -> Info
-
-ConnPid :: pid()
-Info :: #{
-    sock_ip   => inet:ip_address(),
-    sock_port => inet:port_number()
-}
-

Obtain information about the connection.

-
-
-
+
info(ConnPid) -> Info
+
+ConnPid :: pid()
+Info :: #{
+    sock_ip   => inet:ip_address(),
+    sock_port => inet:port_number()
+}
+
+

Obtain information about the connection.

Arguments

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-
- -
+

Return value

-
-

A map is returned containing various informations about -the connection.

-
-
-
+

A map is returned containing various informations about the connection.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Obtain information about the connection
-
-
Info = gun:info(ConnPid).
-
-
-
+
Info = gun:info(ConnPid).
+

See also

- - +

gun(3), gun:open(3), gun:open_unix(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.open/index.html b/docs/en/gun/1.0/manual/gun.open/index.html index 2f1548fe..86cb145b 100644 --- a/docs/en/gun/1.0/manual/gun.open/index.html +++ b/docs/en/gun/1.0/manual/gun.open/index.html @@ -62,117 +62,64 @@

gun:open(3)

-

Name

-
-

gun:open - Open a connection to the given host and port

-
-
-
+

gun:open - Open a connection to the given host and port

Description

-
-
-
-
open(Host, Port)       -> open(Host, Port, #{})
-open(Host, Port, Opts) -> {ok, pid()} | {error, any()}
-
-Host :: inet:hostname() | inet:ip_address()
-Port :: inet:port_number()
-Opts :: gun:opts()
-

Open a connection to the given host and port.

-
-
-
+
open(Host, Port)       -> open(Host, Port, #{})
+open(Host, Port, Opts) -> {ok, pid()} | {error, any()}
+
+Host :: inet:hostname() | inet:ip_address()
+Port :: inet:port_number()
+Opts :: gun:opts()
+
+

Open a connection to the given host and port.

Arguments

-
-
-
-Host -
-
-

-Host or IP address to connect to. -

+
Host
+

Host or IP address to connect to.

-
-Port -
-
-

-Port to connect to. -

+
Port
+

Port to connect to.

-
-Opts -
-
-

-Options for this connection. -

+
Opts
+

Options for this connection.

-
-
- -
+

Return value

-
-

The pid of the newly created Gun process is returned. -Note that this does not indicate that the connection -has been successfully opened; the gun_up(3) -message will be sent for that.

-
-
-
+

The pid of the newly created Gun process is returned. Note that this does not indicate that the connection has been successfully opened; the gun_up(3) message will be sent for that.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Connect to a server
-
-
{ok, ConnPid} = gun:open("example.org", 443).
-
-
Connect to a server with custom options
-
-
{ok, ConnPid} = gun:open("example.org", 443,
-    #{protocols => [http2]}).
-
-
Connect to a server using its IP address
-
-
{ok, ConnPid} = gun:open({127,0,0,1}, 443).
-
-
-
+
{ok, ConnPid} = gun:open({127,0,0,1}, 443).
+

See also

- - +

gun(3), gun:open_unix(3), gun:await_up(3), gun_up(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.open_unix/index.html b/docs/en/gun/1.0/manual/gun.open_unix/index.html index 96253f64..60b9c630 100644 --- a/docs/en/gun/1.0/manual/gun.open_unix/index.html +++ b/docs/en/gun/1.0/manual/gun.open_unix/index.html @@ -62,100 +62,52 @@

gun:open_unix(3)

-

Name

-
-

gun:open_unix - Open a connection to the given Unix domain socket

-
-
-
+

gun:open_unix - Open a connection to the given Unix domain socket

Description

-
-
-
-
open_unix(SocketPath, Opts) -> {ok, pid()} | {error, any()}
+
open_unix(SocketPath, Opts) -> {ok, pid()} | {error, any()}
 
-SocketPath :: string()
-Opts       :: gun:opts()
-

Open a connection to the given Unix domain socket.

-
-
-
+SocketPath :: string() +Opts :: gun:opts() +
+

Open a connection to the given Unix domain socket.

Arguments

-
-
-
-SocketPath -
-
-

-Path to the Unix domain socket to connect to. -

+
SocketPath
+

Path to the Unix domain socket to connect to.

-
-Opts -
-
-

-Options for this connection. -

+
Opts
+

Options for this connection.

-
-
- -
+

Return value

-
-

The pid of the newly created Gun process is returned. -Note that this does not indicate that the connection -has been successfully opened; the gun_up(3) -message will be sent for that.

-
-
-
+

The pid of the newly created Gun process is returned. Note that this does not indicate that the connection has been successfully opened; the gun_up(3) message will be sent for that.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Connect to a server via a Unix domain socket
-
-
{ok, ConnPid} = gun:open_unix("/var/run/dbus/system_bus_socket", #{}).
-
-
Connect to a server via a Unix domain socket with custom options
-
-
{ok, ConnPid} = gun:open_unix("/var/run/dbus/system_bus_socket",
-    #{protocols => [http2]}).
-
-
-
+
{ok, ConnPid} = gun:open_unix("/var/run/dbus/system_bus_socket",
+    #{protocols => [http2]}).
+

See also

- - +

gun(3), gun:open(3), gun:await_up(3), gun_up(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.options/index.html b/docs/en/gun/1.0/manual/gun.options/index.html index 4a3c50aa..e2bcb8be 100644 --- a/docs/en/gun/1.0/manual/gun.options/index.html +++ b/docs/en/gun/1.0/manual/gun.options/index.html @@ -62,130 +62,68 @@

gun:options(3)

-

Name

-
-

gun:options - Query the capabilities of the server or a resource

-
-
-
+

gun:options - Query the capabilities of the server or a resource

Description

-
-
-
-
options(ConnPid, Path)
-    -> options(ConnPid, Path, [], #{}).
-
-options(ConnPid, Path, Headers)
-    -> options(ConnPid, Path, Headers, #{})
-
-options(ConnPid, Path, Headers, ReqOpts)
-    -> StreamRef
-
-ConnPid   :: pid()
-Path      :: iodata()
-Headers   :: [{binary(), iodata()}]
-ReqOpts   :: gun:req_opts()
-StreamRef :: reference()
-

Query the capabilities of the server or a resource.

-

The special path "*" can be used to obtain information about -the server as a whole. Any other path will return information -about that resource specifically.

-
-
-
+
options(ConnPid, Path)
+    -> options(ConnPid, Path, [], #{}).
+
+options(ConnPid, Path, Headers)
+    -> options(ConnPid, Path, Headers, #{})
+
+options(ConnPid, Path, Headers, ReqOpts)
+    -> StreamRef
+
+ConnPid   :: pid()
+Path      :: iodata()
+Headers   :: [{binary(), iodata()}]
+ReqOpts   :: gun:req_opts()
+StreamRef :: reference()
+
+

Query the capabilities of the server or a resource.

+

The special path "*" can be used to obtain information about the server as a whole. Any other path will return information about that resource specifically.

Arguments

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-Path -
-
-

-Path to the resource. -

+
Path
+

Path to the resource.

-
-Headers -
-
-

-Additional request headers. -

+
Headers
+

Additional request headers.

-
-ReqOpts -
-
-

-Request options. -

+
ReqOpts
+

Request options.

-
-
- -
+

Return value

-
-

A reference that identifies the newly created stream is -returned. It is this reference that must be passed in -subsequent calls and will be received in messages related -to this new stream.

-
-
-
+

A reference that identifies the newly created stream is returned. It is this reference that must be passed in subsequent calls and will be received in messages related to this new stream.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Query the capabilities of the server
-
-
StreamRef = gun:options(ConnPid, "*").
-
-
Query the capabilities of a resource
-
-
StreamRef = gun:options(ConnPid, "/articles").
-
-
-
+
StreamRef = gun:options(ConnPid, "/articles").
+

See also

- - +

gun(3), gun:await(3), gun:await_body(3), gun_inform(3), gun_response(3), gun_data(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.patch/index.html b/docs/en/gun/1.0/manual/gun.patch/index.html index 54ab78b4..00befe21 100644 --- a/docs/en/gun/1.0/manual/gun.patch/index.html +++ b/docs/en/gun/1.0/manual/gun.patch/index.html @@ -62,168 +62,91 @@

gun:patch(3)

-

Name

-
-

gun:patch - Apply a set of changes to a resource

-
-
-
+

gun:patch - Apply a set of changes to a resource

Description

-
-
-
-
patch(ConnPid, Path, Headers)
-    -> StreamRef
-
-patch(ConnPid, Path, Headers, Body)
-    -> patch(ConnPid, Path, Headers, Body, #{})
-
-patch(ConnPid, Path, Headers, Body, ReqOpts)
-    -> StreamRef
-
-ConnPid   :: pid()
-Path      :: iodata()
-Headers   :: [{binary(), iodata()}]
-Body      :: iodata()
-ReqOpts   :: gun:req_opts()
-StreamRef :: reference()
-

Apply a set of changes to a resource.

-

The behavior of this function varies depending on whether -a body is provided.

-

The function patch/3 expects either a content-length -or content-type header to indicate that a body will be -sent afterwards. The body can then be sent using -gun:data(3).

-

The function patch/4,5 sends the entire request, including -the request body, immediately. It is therefore not possible -to use gun:data(3) after that. You -should provide a content-type header. Gun will set the -content-length header automatically.

-

The body sent in this request should be a patch document -with instructions on how to update the resource.

-
-
-
+
patch(ConnPid, Path, Headers)
+    -> StreamRef
+
+patch(ConnPid, Path, Headers, Body)
+    -> patch(ConnPid, Path, Headers, Body, #{})
+
+patch(ConnPid, Path, Headers, Body, ReqOpts)
+    -> StreamRef
+
+ConnPid   :: pid()
+Path      :: iodata()
+Headers   :: [{binary(), iodata()}]
+Body      :: iodata()
+ReqOpts   :: gun:req_opts()
+StreamRef :: reference()
+
+

Apply a set of changes to a resource.

+

The behavior of this function varies depending on whether a body is provided.

+

The function patch/3 expects either a content-length or content-type header to indicate that a body will be sent afterwards. The body can then be sent using gun:data(3).

+

The function patch/4,5 sends the entire request, including the request body, immediately. It is therefore not possible to use gun:data(3) after that. You should provide a content-type header. Gun will set the content-length header automatically.

+

The body sent in this request should be a patch document with instructions on how to update the resource.

Arguments

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-Path -
-
-

-Path to the resource. -

+
Path
+

Path to the resource.

-
-Headers -
-
-

-Additional request headers. -

+
Headers
+

Additional request headers.

-
-Body -
-
-

-Request body. -

+
Body
+

Request body.

-
-ReqOpts -
-
-

-Request options. -

+
ReqOpts
+

Request options.

-
-
- -
+

Return value

-
-

A reference that identifies the newly created stream is -returned. It is this reference that must be passed in -subsequent calls and will be received in messages related -to this new stream.

-
-
-
+

A reference that identifies the newly created stream is returned. It is this reference that must be passed in subsequent calls and will be received in messages related to this new stream.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Patch a resource
-
-
StreamRef = gun:patch(ConnPid, "/users/1",
-    [{<<"content-type">>, <<"application/json-patch+json">>}],
-    <<"[{\"op\":\"add\",\"path\":\"/baz\",\"value\":\"qux\"}]">>).
-
-
Patch a resource in multiple calls
-
-
StreamRef = gun:patch(ConnPid, "/users/1", [
-    {<<"content-type">>, <<"application/json-patch+json">>}
-]).
-gun:data(ConnPid, StreamRef, fin,
-    <<"[{\"op\":\"add\",\"path\":\"/baz\",\"value\":\"qux\"}]">>).
-
-
Patch a resource with request options
-
-
StreamRef = gun:patch(ConnPid, "/users/1",
-    [{<<"content-type">>, <<"application/json-patch+json">>}],
-    <<"[{\"op\":\"add\",\"path\":\"/baz\",\"value\":\"qux\"}]">>,
-    #{reply_to => ReplyToPid}).
-
-
-
+
StreamRef = gun:patch(ConnPid, "/users/1",
+    [{<<"content-type">>, <<"application/json-patch+json">>}],
+    <<"[{\"op\":\"add\",\"path\":\"/baz\",\"value\":\"qux\"}]">>,
+    #{reply_to => ReplyToPid}).
+

See also

- - +

gun(3), gun:post(3), gun:put(3), gun:await(3), gun:await_body(3), gun_push(3), gun_inform(3), gun_response(3), gun_data(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.post/index.html b/docs/en/gun/1.0/manual/gun.post/index.html index 9f6ee6e2..782e8346 100644 --- a/docs/en/gun/1.0/manual/gun.post/index.html +++ b/docs/en/gun/1.0/manual/gun.post/index.html @@ -62,166 +62,89 @@

gun:post(3)

-

Name

-
-

gun:post - Process the enclosed representation according to a resource’s own semantics

-
-
-
+

gun:post - Process the enclosed representation according to a resource's own semantics

Description

-
-
-
-
post(ConnPid, Path, Headers)
-    -> StreamRef
-
-post(ConnPid, Path, Headers, Body)
-    -> post(ConnPid, Path, Headers, Body, #{})
-
-post(ConnPid, Path, Headers, Body, ReqOpts)
-    -> StreamRef
-
-ConnPid   :: pid()
-Path      :: iodata()
-Headers   :: [{binary(), iodata()}]
-Body      :: iodata()
-ReqOpts   :: gun:req_opts()
-StreamRef :: reference()
-

Process the enclosed representation according to a resource’s -own semantics.

-

The behavior of this function varies depending on whether -a body is provided.

-

The function post/3 expects either a content-length -or content-type header to indicate that a body will be -sent afterwards. The body can then be sent using -gun:data(3).

-

The function post/4,5 sends the entire request, including -the request body, immediately. It is therefore not possible -to use gun:data(3) after that. You -should provide a content-type header. Gun will set the -content-length header automatically.

-
-
-
+
post(ConnPid, Path, Headers)
+    -> StreamRef
+
+post(ConnPid, Path, Headers, Body)
+    -> post(ConnPid, Path, Headers, Body, #{})
+
+post(ConnPid, Path, Headers, Body, ReqOpts)
+    -> StreamRef
+
+ConnPid   :: pid()
+Path      :: iodata()
+Headers   :: [{binary(), iodata()}]
+Body      :: iodata()
+ReqOpts   :: gun:req_opts()
+StreamRef :: reference()
+
+

Process the enclosed representation according to a resource's own semantics.

+

The behavior of this function varies depending on whether a body is provided.

+

The function post/3 expects either a content-length or content-type header to indicate that a body will be sent afterwards. The body can then be sent using gun:data(3).

+

The function post/4,5 sends the entire request, including the request body, immediately. It is therefore not possible to use gun:data(3) after that. You should provide a content-type header. Gun will set the content-length header automatically.

Arguments

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-Path -
-
-

-Path to the resource. -

+
Path
+

Path to the resource.

-
-Headers -
-
-

-Additional request headers. -

+
Headers
+

Additional request headers.

-
-Body -
-
-

-Request body. -

+
Body
+

Request body.

-
-ReqOpts -
-
-

-Request options. -

+
ReqOpts
+

Request options.

-
-
- -
+

Return value

-
-

A reference that identifies the newly created stream is -returned. It is this reference that must be passed in -subsequent calls and will be received in messages related -to this new stream.

-
-
-
+

A reference that identifies the newly created stream is returned. It is this reference that must be passed in subsequent calls and will be received in messages related to this new stream.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Post to a resource
-
-
StreamRef = gun:post(ConnPid, "/search",
-    [{<<"content-type">>, <<"application/x-www-form-urlencoded">>}],
-    <<"q=nine%20nines">>).
-
-
Post to a resource in multiple calls
-
-
StreamRef = gun:post(ConnPid, "/search", [
-    {<<"content-type">>, <<"application/x-www-form-urlencoded">>}
-]).
-gun:data(ConnPid, StreamRef, fin, <<"q=nine%20nines">>).
-
-
Post to a resource with request options
-
-
StreamRef = gun:post(ConnPid, "/search",
-    [{<<"content-type">>, <<"application/x-www-form-urlencoded">>}],
-    <<"q=nine%20nines">>,
-    #{reply_to => ReplyToPid}).
-
-
-
+
StreamRef = gun:post(ConnPid, "/search",
+    [{<<"content-type">>, <<"application/x-www-form-urlencoded">>}],
+    <<"q=nine%20nines">>,
+    #{reply_to => ReplyToPid}).
+

See also

- - +

gun(3), gun:patch(3), gun:put(3), gun:await(3), gun:await_body(3), gun_push(3), gun_inform(3), gun_response(3), gun_data(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.put/index.html b/docs/en/gun/1.0/manual/gun.put/index.html index ae72aded..71f3f345 100644 --- a/docs/en/gun/1.0/manual/gun.put/index.html +++ b/docs/en/gun/1.0/manual/gun.put/index.html @@ -62,165 +62,89 @@

gun:put(3)

-

Name

-
-

gun:put - Create or replace a resource

-
-
-
+

gun:put - Create or replace a resource

Description

-
-
-
-
put(ConnPid, Path, Headers)
-    -> StreamRef
-
-put(ConnPid, Path, Headers, Body)
-    -> put(ConnPid, Path, Headers, Body, #{})
-
-put(ConnPid, Path, Headers, Body, ReqOpts)
-    -> StreamRef
-
-ConnPid   :: pid()
-Path      :: iodata()
-Headers   :: [{binary(), iodata()}]
-Body      :: iodata()
-ReqOpts   :: gun:req_opts()
-StreamRef :: reference()
-

Create or replace a resource.

-

The behavior of this function varies depending on whether -a body is provided.

-

The function put/3 expects either a content-length -or content-type header to indicate that a body will be -sent afterwards. The body can then be sent using -gun:data(3).

-

The function put/4,5 sends the entire request, including -the request body, immediately. It is therefore not possible -to use gun:data(3) after that. You -should provide a content-type header. Gun will set the -content-length header automatically.

-
-
-
+
put(ConnPid, Path, Headers)
+    -> StreamRef
+
+put(ConnPid, Path, Headers, Body)
+    -> put(ConnPid, Path, Headers, Body, #{})
+
+put(ConnPid, Path, Headers, Body, ReqOpts)
+    -> StreamRef
+
+ConnPid   :: pid()
+Path      :: iodata()
+Headers   :: [{binary(), iodata()}]
+Body      :: iodata()
+ReqOpts   :: gun:req_opts()
+StreamRef :: reference()
+
+

Create or replace a resource.

+

The behavior of this function varies depending on whether a body is provided.

+

The function put/3 expects either a content-length or content-type header to indicate that a body will be sent afterwards. The body can then be sent using gun:data(3).

+

The function put/4,5 sends the entire request, including the request body, immediately. It is therefore not possible to use gun:data(3) after that. You should provide a content-type header. Gun will set the content-length header automatically.

Arguments

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-Path -
-
-

-Path to the resource. -

+
Path
+

Path to the resource.

-
-Headers -
-
-

-Additional request headers. -

+
Headers
+

Additional request headers.

-
-Body -
-
-

-Request body. -

+
Body
+

Request body.

-
-ReqOpts -
-
-

-Request options. -

+
ReqOpts
+

Request options.

-
-
- -
+

Return value

-
-

A reference that identifies the newly created stream is -returned. It is this reference that must be passed in -subsequent calls and will be received in messages related -to this new stream.

-
-
-
+

A reference that identifies the newly created stream is returned. It is this reference that must be passed in subsequent calls and will be received in messages related to this new stream.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Put a resource
-
-
StreamRef = gun:put(ConnPid, "/lang/fr_FR/hello",
-    [{<<"content-type">>, <<"text/plain">>}],
-    <<"Bonjour !">>).
-
-
Put a resource in multiple calls
-
-
StreamRef = gun:put(ConnPid, "/lang/fr_FR/hello", [
-    {<<"content-type">>, <<"text/plain">>}
-]).
-gun:data(ConnPid, StreamRef, fin, <<"Bonjour !">>).
-
-
Put a resource with request options
-
-
StreamRef = gun:put(ConnPid, "/lang/fr_FR/hello",
-    [{<<"content-type">>, <<"text/plain">>}],
-    <<"Bonjour !">>,
-    #{reply_to => ReplyToPid}).
-
-
-
+
StreamRef = gun:put(ConnPid, "/lang/fr_FR/hello",
+    [{<<"content-type">>, <<"text/plain">>}],
+    <<"Bonjour !">>,
+    #{reply_to => ReplyToPid}).
+

See also

- - +

gun(3), gun:patch(3), gun:post(3), gun:await(3), gun:await_body(3), gun_push(3), gun_inform(3), gun_response(3), gun_data(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.request/index.html b/docs/en/gun/1.0/manual/gun.request/index.html index e5dad30d..6567c699 100644 --- a/docs/en/gun/1.0/manual/gun.request/index.html +++ b/docs/en/gun/1.0/manual/gun.request/index.html @@ -62,156 +62,75 @@

gun:request(3)

-

Name

-
-

gun:request - Perform the given request

-
-
-
+

gun:request - Perform the given request

Description

-
-
-
-
request(ConnPid, Method, Path, Headers)
-    -> StreamRef
-
-request(ConnPid, Method, Path, Headers, Body)
-    -> request(ConnPid, Method, Path, Headers, Body, #{})
-
-request(ConnPid, Method, Path, Headers, Body, ReqOpts)
-    -> StreamRef
-
-ConnPid   :: pid()
-Method    :: binary()
-Path      :: iodata()
-Headers   :: [{binary(), iodata()}]
-Body      :: iodata()
-ReqOpts   :: gun:req_opts()
-StreamRef :: reference()
-

Perform the given request.

-

This is a general purpose function that should only be -used when other method-specific functions do not apply.

-

The behavior of this function varies depending on whether -a body is provided.

-

The function request/4 expects either a content-length -or content-type header to indicate that a body will be -sent afterwards. Gun will assume the request has no body -otherwise. The body can then be sent using -gun:data(3).

-

The function request/5,6 sends the entire request, including -the request body, immediately. It is therefore not possible -to use gun:data(3) after that. You -should provide a content-type header. Gun will set the -content-length header automatically.

-
-
-
+
request(ConnPid, Method, Path, Headers)
+    -> StreamRef
+
+request(ConnPid, Method, Path, Headers, Body)
+    -> request(ConnPid, Method, Path, Headers, Body, #{})
+
+request(ConnPid, Method, Path, Headers, Body, ReqOpts)
+    -> StreamRef
+
+ConnPid   :: pid()
+Method    :: binary()
+Path      :: iodata()
+Headers   :: [{binary(), iodata()}]
+Body      :: iodata()
+ReqOpts   :: gun:req_opts()
+StreamRef :: reference()
+
+

Perform the given request.

+

This is a general purpose function that should only be used when other method-specific functions do not apply.

+

The behavior of this function varies depending on whether a body is provided.

+

The function request/4 expects either a content-length or content-type header to indicate that a body will be sent afterwards. Gun will assume the request has no body otherwise. The body can then be sent using gun:data(3).

+

The function request/5,6 sends the entire request, including the request body, immediately. It is therefore not possible to use gun:data(3) after that. You should provide a content-type header. Gun will set the content-length header automatically.

Arguments

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-Method -
-
-

-Method to be used for the request. -

+
Method
+

Method to be used for the request.

-
-Path -
-
-

-Path to the resource. -

+
Path
+

Path to the resource.

-
-Headers -
-
-

-Additional request headers. -

+
Headers
+

Additional request headers.

-
-Body -
-
-

-Request body. -

+
Body
+

Request body.

-
-ReqOpts -
-
-

-Request options. -

+
ReqOpts
+

Request options.

-
-
- -
+

Return value

-
-

A reference that identifies the newly created stream is -returned. It is this reference that must be passed in -subsequent calls and will be received in messages related -to this new stream.

-
-
-
+

A reference that identifies the newly created stream is returned. It is this reference that must be passed in subsequent calls and will be received in messages related to this new stream.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Perform a request
-
-
StreamRef = gun:request(ConnPid, <<"PUT">>,
-    "/lang/fr_FR/hello",
-    [{<<"content-type">>, <<"text/plain">>}],
-    <<"Bonjour !">>).
-
-
-
+
StreamRef = gun:request(ConnPid, <<"PUT">>,
+    "/lang/fr_FR/hello",
+    [{<<"content-type">>, <<"text/plain">>}],
+    <<"Bonjour !">>).
+

See also

- - +

gun(3), gun:await(3), gun:await_body(3), gun_push(3), gun_inform(3), gun_response(3), gun_data(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.ws_send/index.html b/docs/en/gun/1.0/manual/gun.ws_send/index.html index 8892da18..a0b34903 100644 --- a/docs/en/gun/1.0/manual/gun.ws_send/index.html +++ b/docs/en/gun/1.0/manual/gun.ws_send/index.html @@ -62,94 +62,57 @@

gun:ws_send(3)

-

Name

-
-

gun:ws_send - Send Websocket frames

-
-
-
+

gun:ws_send - Send Websocket frames

Description

-
-
-
-
ws_send(ConnPid, Frames) -> ok
-
-ConnPid :: pid()
-Frames  :: Frame | [Frame]
-Frame   :: close | ping | pong
-         | {text | binary | close | ping | pong, iodata()}
-         | {close, non_neg_integer(), iodata()}
-

Send Websocket frames.

-

The connection must first be upgraded to Websocket using -the function gun:ws_upgrade(3).

-
-
-
+
ws_send(ConnPid, Frames) -> ok
+
+ConnPid :: pid()
+Frames  :: Frame | [Frame]
+Frame   :: close | ping | pong
+         | {text | binary | close | ping | pong, iodata()}
+         | {close, non_neg_integer(), iodata()}
+
+

Send Websocket frames.

+

The connection must first be upgraded to Websocket using the function gun:ws_upgrade(3).

Arguments

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-Frames -
-
-

-A Websocket frame. -

+
Frames
+

A Websocket frame.

-
-
- -
+ +

Return value

-
-

The atom ok is returned.

-
-
-
+

The atom ok is returned.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Send a single frame
-
-
gun:ws_send(ConnPid, {text, <<"Hello world!">>}).
-
-
-
+
gun:ws_send(ConnPid, {text, <<"Hello world!">>}).
+
+ + + + + + + +

See also

- - +

gun(3), gun:ws_upgrade(3), gun_upgrade(3), gun_ws(3)

+ diff --git a/docs/en/gun/1.0/manual/gun.ws_upgrade/index.html b/docs/en/gun/1.0/manual/gun.ws_upgrade/index.html index d74702db..998ffe89 100644 --- a/docs/en/gun/1.0/manual/gun.ws_upgrade/index.html +++ b/docs/en/gun/1.0/manual/gun.ws_upgrade/index.html @@ -62,144 +62,81 @@

gun:ws_upgrade(3)

-

Name

-
-

gun:ws_upgrade - Upgrade to Websocket

-
-
-
+

gun:ws_upgrade - Upgrade to Websocket

Description

-
-
-
-
ws_upgrade(ConnPid, Path)
-    -> ws_upgrade(ConnPid, Path, [])
-
-ws_upgrade(ConnPid, Path, Headers)
-    -> StreamRef
-
-ws_upgrade(ConnPid, Path, Headers, WsOpts)
-    -> StreamRef
-
-ConnPid   :: pid()
-Path      :: iodata()
-Headers   :: [{binary(), iodata()}]
-WsOpts    :: gun:ws_opts
-StreamRef :: reference()
-

Upgrade to Websocket.

-

The behavior of this function depends on the protocol -selected.

-

HTTP/1.1 cannot handle Websocket and HTTP requests -concurrently. The upgrade, if successful, will result -in the complete takeover of the connection. Any -subsequent HTTP requests will be rejected.

-

Gun does not currently support Websocket over HTTP/2.

-

By default Gun will take the Websocket options from -the connection’s ws_opts.

-
-
-
+
ws_upgrade(ConnPid, Path)
+    -> ws_upgrade(ConnPid, Path, [])
+
+ws_upgrade(ConnPid, Path, Headers)
+    -> StreamRef
+
+ws_upgrade(ConnPid, Path, Headers, WsOpts)
+    -> StreamRef
+
+ConnPid   :: pid()
+Path      :: iodata()
+Headers   :: [{binary(), iodata()}]
+WsOpts    :: gun:ws_opts
+StreamRef :: reference()
+
+

Upgrade to Websocket.

+

The behavior of this function depends on the protocol selected.

+

HTTP/1.1 cannot handle Websocket and HTTP requests concurrently. The upgrade, if successful, will result in the complete takeover of the connection. Any subsequent HTTP requests will be rejected.

+

Gun does not currently support Websocket over HTTP/2.

+

By default Gun will take the Websocket options from the connection's ws_opts.

Arguments

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-Path -
-
-

-Path to the resource. -

+
Path
+

Path to the resource.

-
-Headers -
-
-

-Additional request headers. -

+
Headers
+

Additional request headers.

-
-WsOpts -
-
-

-Configuration for the Websocket protocol. -

+
WsOpts
+

Configuration for the Websocket protocol.

-
-
- -
+

Return value

-
-

A reference that identifies the newly created stream is -returned. It is this reference that must be passed in -subsequent calls and will be received in messages related -to this new stream.

-
-
-
+

A reference that identifies the newly created stream is returned. It is this reference that must be passed in subsequent calls and will be received in messages related to this new stream.

Changelog

-
-
    -
  • -

    -1.0: Function introduced. -

    +
    • 1.0: Function introduced.
    • -
-
-
-
+

Examples

-
-
-
Upgrade to Websocket
-
-
StreamRef = gun:ws_upgrade(ConnPid, "/ws", [
-    {<<"sec-websocket-protocol">>, <<"chat">>}
-]).
-receive
-    {gun_upgrade, ConnPid, StreamRef, [<<"websocket">>], _} ->
-        ok
-after 5000 ->
-    error(timeout)
-end.
-
-
Upgrade to Websocket with different options
-
-
StreamRef = gun:ws_upgrade(ConnPid, "/ws", [], #{
-    compress => false
-}).
-
-
-
+
StreamRef = gun:ws_upgrade(ConnPid, "/ws", [], #{
+    compress => false
+}).
+

See also

- - +

gun(3), gun:ws_send(3), gun_upgrade(3), gun_ws(3)

+ diff --git a/docs/en/gun/1.0/manual/gun/index.html b/docs/en/gun/1.0/manual/gun/index.html index e08aca7f..a9d5905e 100644 --- a/docs/en/gun/1.0/manual/gun/index.html +++ b/docs/en/gun/1.0/manual/gun/index.html @@ -62,454 +62,219 @@

gun(3)

-

Name

-
-

gun - Asynchronous HTTP client

-
-
-
+

gun - Asynchronous HTTP client

Description

-
-

The gun module provides an asynchronous interface for -connecting and communicating with Web servers over HTTP, -HTTP/2 or Websocket.

-
-
-
+

The gun module provides an asynchronous interface for connecting and communicating with Web servers over HTTP, HTTP/2 or Websocket.

Exports

-
-

Connection:

-
    -
  • -

    -gun:open(3) - Open a connection to the given host and port -

    +

    Connection:

    + + +
-

Requests:

-
    -
  • -

    -gun:get(3) - Get a resource representation -

    +
+

Requests:

+
-

Messages:

-
+

Messages:

+
-

Streams:

-
+

Streams:

+
-

Websocket:

-
+

Websocket:

+
-
-
-
+

Messages

-
-

Gun will inform the calling process of events asynchronously -by sending any of the following messages:

-

Connection:

-
    -
  • -

    -gun_up(3) - The connection is up -

    +

    Gun will inform the calling process of events asynchronously by sending any of the following messages:

    +

    Connection:

    +
-

Responses:

-
+

Responses:

+
-

Websocket:

-
+

Websocket:

+
-

The response messages will be sent to the process that opened -the connection by default. The reply_to request option can -be used to redirect request-specific messages to a different -process.

-
-
-
+ +

The response messages will be sent to the process that opened the connection by default. The reply_to request option can be used to redirect request-specific messages to a different process.

Types

-
-

http_opts()

-
-
-
http_opts() :: #{
-    keepalive             => timeout(),
-    transform_header_name => fun((binary()) -> binary()),
-    version               => 'HTTP/1.1' | 'HTTP/1.0'
-}
-

Configuration for the HTTP protocol.

-

The default value is given next to the option name:

-
-
-keepalive (5000) -
-
-

-Time between pings in milliseconds. Since the HTTP protocol has -no standardized way to ping the server, Gun will simply send an -empty line when the connection is idle. Gun only makes a best -effort here as servers usually have configurable limits to drop -idle connections. Use infinity to disable. -

+
http_opts() :: #{
+    keepalive             => timeout(),
+    transform_header_name => fun((binary()) -> binary()),
+    version               => 'HTTP/1.1' | 'HTTP/1.0'
+}
+
+

Configuration for the HTTP protocol.

+

The default value is given next to the option name:

+ +
keepalive (5000)
+

Time between pings in milliseconds. Since the HTTP protocol has no standardized way to ping the server, Gun will simply send an empty line when the connection is idle. Gun only makes a best effort here as servers usually have configurable limits to drop idle connections. Use infinity to disable.

-
-transform_header_name - see below -
-
-

-A function that will be applied to all header names before they -are sent to the server. Gun assumes that all header names are in -lower case. This function is useful if you, for example, need to -re-case header names in the event that the server incorrectly -considers the case of header names to be significant. -

+
transform_header_name - see below
+

A function that will be applied to all header names before they are sent to the server. Gun assumes that all header names are in lower case. This function is useful if you, for example, need to re-case header names in the event that the server incorrectly considers the case of header names to be significant.

-
-version ('HTTP/1.1') -
-
-

-HTTP version to use. -

+
version ('HTTP/1.1')
+

HTTP version to use.

-
-
-
+

http2_opts()

-
-
-
http2_opts() :: #{
-    keepalive => timeout()
-}
-

Configuration for the HTTP/2 protocol.

-

The default value is given next to the option name:

-
-
-keepalive (5000) -
-
-

-Time between pings in milliseconds. -

+
http2_opts() :: #{
+    keepalive => timeout()
+}
+
+

Configuration for the HTTP/2 protocol.

+

The default value is given next to the option name:

+ +
keepalive (5000)
+

Time between pings in milliseconds.

-
- -
+ +

opts()

-
-
-
opts() :: #{
-    connect_timeout => timeout(),
-    http_opts       => http_opts(),
-    http2_opts      => http2_opts(),
-    protocols       => [http | http2],
-    retry           => non_neg_integer(),
-    retry_timeout   => pos_integer(),
-    trace           => boolean(),
-    transport       => tcp | tls,
-    transport_opts  => [gen_tcp:connect_option()] | [ssl:connect_option()],
-    ws_opts         => ws_opts()
-}
-

Configuration for the connection.

-

The default value is given next to the option name:

-
-
-connect_timeout (infinity) -
-
-

-Connection timeout. -

+
opts() :: #{
+    connect_timeout => timeout(),
+    http_opts       => http_opts(),
+    http2_opts      => http2_opts(),
+    protocols       => [http | http2],
+    retry           => non_neg_integer(),
+    retry_timeout   => pos_integer(),
+    trace           => boolean(),
+    transport       => tcp | tls,
+    transport_opts  => [gen_tcp:connect_option()] | [ssl:connect_option()],
+    ws_opts         => ws_opts()
+}
+
+

Configuration for the connection.

+

The default value is given next to the option name:

+
connect_timeout (infinity)
+

Connection timeout.

-
-http_opts (#{}) -
-
-

-Options specific to the HTTP protocol. -

+
http_opts (#{})
+

Options specific to the HTTP protocol.

-
-http2_opts (#{}) -
-
-

-Options specific to the HTTP/2 protocol. -

+
http2_opts (#{})
+

Options specific to the HTTP/2 protocol.

-
-protocols - see below -
-
-

-Ordered list of preferred protocols. When the transport is tcp, -this list must contain exactly one protocol. When the transport -is tls, this list must contain at least one protocol and will be -used to negotiate a protocol via ALPN. When the server does not -support ALPN then http will always be used. Defaults to -[http] when the transport is tcp, and [http2, http] when the -transport is tls. -

+
protocols - see below
+

Ordered list of preferred protocols. When the transport is tcp, this list must contain exactly one protocol. When the transport is tls, this list must contain at least one protocol and will be used to negotiate a protocol via ALPN. When the server does not support ALPN then http will always be used. Defaults to [http] when the transport is tcp, and [http2, http] when the transport is tls.

-
-retry (5) -
-
-

-Number of times Gun will try to reconnect on failure before giving up. -

+
retry (5)
+

Number of times Gun will try to reconnect on failure before giving up.

-
-retry_timeout (5000) -
-
-

-Time between retries in milliseconds. -

+
retry_timeout (5000)
+

Time between retries in milliseconds.

-
-trace (false) -
-
-

-Whether to enable dbg tracing of the connection process. Should -only be used during debugging. -

+
trace (false)
+

Whether to enable dbg tracing of the connection process. Should only be used during debugging.

-
-transport - see below -
-
-

-Whether to use TLS or plain TCP. The default varies depending on the -port used. Port 443 defaults to tls. All other ports default to tcp. -

+
transport - see below
+

Whether to use TLS or plain TCP. The default varies depending on the port used. Port 443 defaults to tls. All other ports default to tcp.

-
-transport_opts ([]) -
-
-

-Transport options. They are TCP options or TLS options depending on -the selected transport. -

+
transport_opts ([])
+

Transport options. They are TCP options or TLS options depending on the selected transport.

-
-ws_opts (#{}) -
-
-

-Options specific to the Websocket protocol. -

+
ws_opts (#{})
+

Options specific to the Websocket protocol.

-
- -
+

req_opts()

-
-
-
req_opts() :: #{
-    reply_to => pid()
-}
-

Configuration for a particular request.

-

The default value is given next to the option name:

-
-
-reply_to (self()) -
-
-

-The pid of the process that will receive the response messages. -

+
req_opts() :: #{
+    reply_to => pid()
+}
+
+

Configuration for a particular request.

+

The default value is given next to the option name:

+
reply_to (self())
+

The pid of the process that will receive the response messages.

-
- -
+

ws_opts()

-
-
-
ws_opts() :: #{
-    compress => boolean()
-}
-

Configuration for the Websocket protocol.

-

The default value is given next to the option name:

-
-
-compress ⇒ boolean() -
-
-

-Whether to enable permessage-deflate compression. This does -not guarantee that compression will be used as it is the -server that ultimately decides. Defaults to false. -

+
ws_opts() :: #{
+    compress => boolean()
+}
+
+

Configuration for the Websocket protocol.

+

The default value is given next to the option name:

+
compress => boolean()
+

Whether to enable permessage-deflate compression. This does not guarantee that compression will be used as it is the server that ultimately decides. Defaults to false.

-
- - - -
+ +

See also

-
- -
-
+

gun(7)

+ diff --git a/docs/en/gun/1.0/manual/gun_app/index.html b/docs/en/gun/1.0/manual/gun_app/index.html index de6942c4..d1706ea0 100644 --- a/docs/en/gun/1.0/manual/gun_app/index.html +++ b/docs/en/gun/1.0/manual/gun_app/index.html @@ -62,72 +62,33 @@

gun(7)

-

Name

-
-

gun - HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP

-
-
-
+

gun - HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP

Description

-
-

Gun is an HTTP client for Erlang/OTP with support for the -HTTP/1.1, HTTP/2 and Websocket protocols.

-

Gun aims to provide an easy to use, asynchronous and -always-connected client. It maintains a permanent connection -to the server and reconnects automatically when necessary.

-
-
-
+

Gun is an HTTP client for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols.

+

Gun aims to provide an easy to use, asynchronous and always-connected client. It maintains a permanent connection to the server and reconnects automatically when necessary.

Modules

-
-
    -
  • -

    -gun(3) - Asynchronous HTTP client -

    +
    • gun(3) - Asynchronous HTTP client
    • -
-
-
-
+

Dependencies

-
-
    -
  • -

    -cowlib(7) - Support library for manipulating Web protocols -

    +
    • cowlib(7) - Support library for manipulating Web protocols
    • -
    • -

      -ssl - Secure communication over sockets -

      +
    • ssl - Secure communication over sockets
    • -
-

All these applications must be started before the gun -application. To start Gun and all dependencies at once:

-
-
-
{ok, _} = application:ensure_all_started(gun).
-
-
-
+
{ok, _} = application:ensure_all_started(gun).
+

Environment

-
-

The gun application does not define any application -environment configuration parameters.

-
- -
+

The gun application does not define any application environment configuration parameters.

See also

- -
+

cowlib(7)

+ diff --git a/docs/en/gun/1.0/manual/gun_data/index.html b/docs/en/gun/1.0/manual/gun_data/index.html index 31da2d23..bc3a5dc4 100644 --- a/docs/en/gun/1.0/manual/gun_data/index.html +++ b/docs/en/gun/1.0/manual/gun_data/index.html @@ -62,119 +62,57 @@

gun_data(3)

-

Name

-
-

gun_data - Response body

-
-
-
+

gun_data - Response body

Description

-
-
-
-
{gun_data, ConnPid, StreamRef, IsFin, Data}
-
-ConnPid   :: pid()
-StreamRef :: reference()
-IsFin     :: fin | nofin
-Data      :: binary()
-

Response body.

-

This message informs the relevant process that the server -sent a all or part of the body for the response to the -original request.

-

A data message is always preceded by a response message.

-

The response body may be terminated either by a data -message with the flag fin set or by a -gun_trailers(3) message.

-
-
-
+
{gun_data, ConnPid, StreamRef, IsFin, Data}
+
+ConnPid   :: pid()
+StreamRef :: reference()
+IsFin     :: fin | nofin
+Data      :: binary()
+
+

Response body.

+

This message informs the relevant process that the server sent a all or part of the body for the response to the original request.

+

A data message is always preceded by a response message.

+

The response body may be terminated either by a data message with the flag fin set or by a gun_trailers(3) message.

Elements

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-StreamRef -
-
-

-Identifier of the stream for the original request. -

+
StreamRef
+

Identifier of the stream for the original request.

-
-IsFin -
-
-

-Whether this message terminates the response. -

+
IsFin
+

Whether this message terminates the response.

-
-Data -
-
-

-All or part of the response body. -

+
Data
+

All or part of the response body.

-
-
- -
+

Changelog

-
-
    -
  • -

    -1.0: Message introduced. -

    +
    • 1.0: Message introduced.
    • -
-
-
-
+

Examples

-
-
-
Receive a gun_data message in a gen_server
-
-
handle_info({gun_data, ConnPid, _StreamRef,
-             _IsFin, _Data},
-            State=#state{conn_pid=ConnPid}) ->
-    %% Do something.
-    {noreply, State}.
-
-
-
+
handle_info({gun_data, ConnPid, _StreamRef,
+             _IsFin, _Data},
+            State=#state{conn_pid=ConnPid}) ->
+    %% Do something.
+    {noreply, State}.
+

See also

- - +

gun(3), gun:get(3), gun:head(3), gun:patch(3), gun:post(3), gun:put(3), gun:delete(3), gun:options(3), gun:request(3), gun_response(3), gun_trailers(3)

+ diff --git a/docs/en/gun/1.0/manual/gun_down/index.html b/docs/en/gun/1.0/manual/gun_down/index.html index ddc7c7e1..40698e50 100644 --- a/docs/en/gun/1.0/manual/gun_down/index.html +++ b/docs/en/gun/1.0/manual/gun_down/index.html @@ -62,130 +62,63 @@

gun_down(3)

-

Name

-
-

gun_down - The connection is down

-
-
-
+

gun_down - The connection is down

Description

-
-
-
-
{gun_down, ConnPid, Protocol, Reason, KilledStreams, UnprocessedStreams}
-
-ConnPid            :: pid()
-Protocol           :: http | http2 | ws
-Reason             :: any()
-KilledStreams      :: [reference()]
-UnprocessedStreams :: [reference()]
-

The connection is down.

-

This message informs the owner process that the connection -was lost. Depending on the retry and retry_timeout -options Gun may automatically attempt to reconnect.

-

When the connection goes back up, Gun will not attempt to retry -requests. It will also not upgrade to Websocket automatically -if that was the protocol in use when the connection was lost.

-
-
-
+
{gun_down, ConnPid, Protocol, Reason, KilledStreams, UnprocessedStreams}
+
+ConnPid            :: pid()
+Protocol           :: http | http2 | ws
+Reason             :: any()
+KilledStreams      :: [reference()]
+UnprocessedStreams :: [reference()]
+
+

The connection is down.

+

This message informs the owner process that the connection was lost. Depending on the retry and retry_timeout options Gun may automatically attempt to reconnect.

+

When the connection goes back up, Gun will not attempt to retry requests. It will also not upgrade to Websocket automatically if that was the protocol in use when the connection was lost.

Elements

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-Protocol -
-
-

-The protocol that was selected for this connection -or upgraded to during the course of the connection. -

+
Protocol
+

The protocol that was selected for this connection or upgraded to during the course of the connection.

-
-Reason -
-
-

-The reason for the loss of the connection. -

-

It is present for debugging purposes only. You should not -rely on this value to perform operations programmatically.

+
Reason
+

The reason for the loss of the connection.

+

It is present for debugging purposes only. You should not rely on this value to perform operations programmatically.

-
-KilledStreams -
-
-

-List of streams that have been brutally terminated. -

-

They are active streams that did not complete before the closing -of the connection. Whether they can be retried safely depends -on the protocol used and the idempotence property of the requests.

+
KilledStreams
+

List of streams that have been brutally terminated.

+

They are active streams that did not complete before the closing of the connection. Whether they can be retried safely depends on the protocol used and the idempotence property of the requests.

-
-UnprocessedStreams -
-
-

-List of streams that have not been processed by the server. -

-

They are streams that the server did not start processing yet. -They may be retried safely depending on whether related streams -were killed.

+
UnprocessedStreams
+

List of streams that have not been processed by the server.

+

They are streams that the server did not start processing yet. They may be retried safely depending on whether related streams were killed.

-
-
- -
+

Changelog

-
-
    -
  • -

    -1.0: Message introduced. -

    +
    • 1.0: Message introduced.
    • -
-
-
-
+

Examples

-
-
-
Receive a gun_down message in a gen_server
-
-
handle_info({gun_down, ConnPid, _Protocol,
-             _Reason, _Killed, _Unprocessed},
-            State=#state{conn_pid=ConnPid}) ->
-    %% Do something.
-    {noreply, State}.
-
-
-
+
handle_info({gun_down, ConnPid, _Protocol,
+             _Reason, _Killed, _Unprocessed},
+            State=#state{conn_pid=ConnPid}) ->
+    %% Do something.
+    {noreply, State}.
+

See also

- - +

gun(3), gun:open(3), gun:open_unix(3), gun_up(3), gun_error(3)

+ diff --git a/docs/en/gun/1.0/manual/gun_error/index.html b/docs/en/gun/1.0/manual/gun_error/index.html index 1d8499d3..10e9462c 100644 --- a/docs/en/gun/1.0/manual/gun_error/index.html +++ b/docs/en/gun/1.0/manual/gun_error/index.html @@ -62,106 +62,56 @@

gun_error(3)

-

Name

-
-

gun_error - Stream or connection-wide error

-
-
-
+

gun_error - Stream or connection-wide error

Description

-
-
-
-
{gun_error, ConnPid, StreamRef, Reason}
-{gun_error, ConnPid, Reason}
-
-ConnPid   :: pid()
-StreamRef :: reference()
-Reason    :: any()
-

Stream or connection-wide error.

-

These messages inform the relevant process that an error -occurred. A reference is given when the error pertains -to a specific stream. Connection-wide errors do not -imply that the connection is no longer usable, they are -used for all errors that are not specific to a stream.

-
-
-
+
{gun_error, ConnPid, StreamRef, Reason}
+{gun_error, ConnPid, Reason}
+
+ConnPid   :: pid()
+StreamRef :: reference()
+Reason    :: any()
+
+

Stream or connection-wide error.

+

These messages inform the relevant process that an error occurred. A reference is given when the error pertains to a specific stream. Connection-wide errors do not imply that the connection is no longer usable, they are used for all errors that are not specific to a stream.

Elements

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-StreamRef -
-
-

-Identifier of the stream that resulted in an error. -

+
StreamRef
+

Identifier of the stream that resulted in an error.

-
-Reason -
-
-

-The reason for the error. -

-

It is present for debugging purposes only. You should not -rely on this value to perform operations programmatically.

+
Reason
+

The reason for the error.

+

It is present for debugging purposes only. You should not rely on this value to perform operations programmatically.

-
-
- -
+

Changelog

-
-
    -
  • -

    -1.0: Message introduced. -

    +
    • 1.0: Message introduced.
    • -
-
-
-
+

Examples

-
-
-
Receive a gun_error message in a gen_server
-
-
handle_info({gun_error, ConnPid, _Reason},
-            State=#state{conn_pid=ConnPid}) ->
-    %% Do something.
-    {noreply, State};
-handle_info({gun_error, ConnPid, _StreamRef, _Reason},
-            State=#state{conn_pid=ConnPid}) ->
-    %% Do something.
-    {noreply, State}.
-
-
-
+
handle_info({gun_error, ConnPid, _Reason},
+            State=#state{conn_pid=ConnPid}) ->
+    %% Do something.
+    {noreply, State};
+handle_info({gun_error, ConnPid, _StreamRef, _Reason},
+            State=#state{conn_pid=ConnPid}) ->
+    %% Do something.
+    {noreply, State}.
+

See also

- - +

gun(3), gun_up(3), gun_down(3)

+ diff --git a/docs/en/gun/1.0/manual/gun_inform/index.html b/docs/en/gun/1.0/manual/gun_inform/index.html index 7f04b59b..b2970f53 100644 --- a/docs/en/gun/1.0/manual/gun_inform/index.html +++ b/docs/en/gun/1.0/manual/gun_inform/index.html @@ -62,113 +62,56 @@

gun_inform(3)

-

Name

-
-

gun_inform - Informational response

-
-
-
+

gun_inform - Informational response

Description

-
-
-
-
{gun_inform, ConnPid, StreamRef, Status, Headers}
-
-ConnPid   :: pid()
-StreamRef :: reference()
-Status    :: 100..199
-Headers   :: [{binary(), binary()}]
-

Informational response.

-

This message informs the relevant process that the server -sent an informational response to the original request.

-

Informational responses are only intermediate responses -and provide no guarantees as to what the final response -will be. An informational response always precedes the -response to the original request.

-
-
-
+
{gun_inform, ConnPid, StreamRef, Status, Headers}
+
+ConnPid   :: pid()
+StreamRef :: reference()
+Status    :: 100..199
+Headers   :: [{binary(), binary()}]
+
+

Informational response.

+

This message informs the relevant process that the server sent an informational response to the original request.

+

Informational responses are only intermediate responses and provide no guarantees as to what the final response will be. An informational response always precedes the response to the original request.

Elements

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-StreamRef -
-
-

-Identifier of the stream for the original request. -

+
StreamRef
+

Identifier of the stream for the original request.

-
-Status -
-
-

-Status code for the informational response. -

+
Status
+

Status code for the informational response.

-
-Headers -
-
-

-Headers sent with the informational response. -

+
Headers
+

Headers sent with the informational response.

-
-
- -
+

Changelog

-
-
    -
  • -

    -1.0: Message introduced. -

    +
    • 1.0: Message introduced.
    • -
-
-
-
+

Examples

-
-
-
Receive a gun_inform message in a gen_server
-
-
handle_info({gun_inform, ConnPid, _StreamRef,
-             _Status, _Headers},
-            State=#state{conn_pid=ConnPid}) ->
-    %% Do something.
-    {noreply, State}.
-
-
-
+
handle_info({gun_inform, ConnPid, _StreamRef,
+             _Status, _Headers},
+            State=#state{conn_pid=ConnPid}) ->
+    %% Do something.
+    {noreply, State}.
+

See also

- - +

gun(3), gun:get(3), gun:patch(3), gun:post(3), gun:put(3), gun_response(3)

+ diff --git a/docs/en/gun/1.0/manual/gun_push/index.html b/docs/en/gun/1.0/manual/gun_push/index.html index 86229224..15075e15 100644 --- a/docs/en/gun/1.0/manual/gun_push/index.html +++ b/docs/en/gun/1.0/manual/gun_push/index.html @@ -62,141 +62,76 @@

gun_push(3)

-

Name

-
-

gun_push - Server-initiated push

-
-
-
+

gun_push - Server-initiated push

Description

-
-
-
-
{gun_push, ConnPid, StreamRef, NewStreamRef, Method, URI, Headers}
-
-ConnPid      :: pid()
-StreamRef    :: reference()
-NewStreamRef :: reference()
-Method       :: binary()
-URI          :: binary()
-Headers      :: [{binary(), binary()}]
-

Server-initiated push.

-

This message informs the relevant process that the server -is pushing a resource related to the effective target URI -of the original request.

-

A server-initiated push message always precedes the response -to the original request.

-

This message will not be sent when using the HTTP/1.1 protocol -because it lacks the concept of server-initiated push.

-
-
-
+
{gun_push, ConnPid, StreamRef, NewStreamRef, Method, URI, Headers}
+
+ConnPid      :: pid()
+StreamRef    :: reference()
+NewStreamRef :: reference()
+Method       :: binary()
+URI          :: binary()
+Headers      :: [{binary(), binary()}]
+
+

Server-initiated push.

+

This message informs the relevant process that the server is pushing a resource related to the effective target URI of the original request.

+

A server-initiated push message always precedes the response to the original request.

+

This message will not be sent when using the HTTP/1.1 protocol because it lacks the concept of server-initiated push.

Elements

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-StreamRef -
-
-

-Identifier of the stream for the original request. -

+
StreamRef
+

Identifier of the stream for the original request.

-
-NewStreamRef -
-
-

-Identifier of the stream being pushed. -

+
NewStreamRef
+

Identifier of the stream being pushed.

-
-Method -
-
-

-Method of the equivalent HTTP request. -

+
Method
+

Method of the equivalent HTTP request.

-
-URI -
-
-

-URI of the resource being pushed. -

+
URI
+

URI of the resource being pushed.

-
-Headers -
-
-

-Headers of the equivalent HTTP request. -

+
Headers
+

Headers of the equivalent HTTP request.

-
-
- -
+

Changelog

-
-
    -
  • -

    -1.0: Message introduced. -

    +
    • 1.0: Message introduced.
    • -
-
-
-
+

Examples

-
-
-
Receive a gun_push message in a gen_server
-
-
handle_info({gun_push, ConnPid, _StreamRef,
-             _NewStreamRef, _Method, _URI, _Headers},
-            State=#state{conn_pid=ConnPid}) ->
-    %% Do something.
-    {noreply, State}.
-
-
Cancel an unwanted push
-
-
handle_info({gun_push, ConnPid, _StreamRef,
-             NewStreamRef, _Method, _URI, _Headers},
-            State=#state{conn_pid=ConnPid}) ->
-    gun:cancel(ConnPid, NewStreamRef),
-    {noreply, State}.
-
-
-
+
handle_info({gun_push, ConnPid, _StreamRef,
+             NewStreamRef, _Method, _URI, _Headers},
+            State=#state{conn_pid=ConnPid}) ->
+    gun:cancel(ConnPid, NewStreamRef),
+    {noreply, State}.
+

See also

- - +

gun(3), gun:get(3), gun:cancel(3), gun_response(3)

+ diff --git a/docs/en/gun/1.0/manual/gun_response/index.html b/docs/en/gun/1.0/manual/gun_response/index.html index 379142ba..52a9e5d3 100644 --- a/docs/en/gun/1.0/manual/gun_response/index.html +++ b/docs/en/gun/1.0/manual/gun_response/index.html @@ -62,123 +62,59 @@

gun_response(3)

-

Name

-
-

gun_response - Response

-
-
-
+

gun_response - Response

Description

-
-
-
-
{gun_response, ConnPid, StreamRef, IsFin, Status, Headers}
-
-ConnPid   :: pid()
-StreamRef :: reference()
-IsFin     :: fin | nofin
-Status    :: non_neg_integer()
-Headers   :: [{binary(), binary()}]
-

Response.

-

This message informs the relevant process that the server -sent a response to the original request.

-
-
-
+
{gun_response, ConnPid, StreamRef, IsFin, Status, Headers}
+
+ConnPid   :: pid()
+StreamRef :: reference()
+IsFin     :: fin | nofin
+Status    :: non_neg_integer()
+Headers   :: [{binary(), binary()}]
+
+

Response.

+

This message informs the relevant process that the server sent a response to the original request.

Elements

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-StreamRef -
-
-

-Identifier of the stream for the original request. -

+
StreamRef
+

Identifier of the stream for the original request.

-
-IsFin -
-
-

-Whether this message terminates the response. -

+
IsFin
+

Whether this message terminates the response.

-
-Status -
-
-

-Status code for the response. -

+
Status
+

Status code for the response.

-
-Headers -
-
-

-Headers sent with the response. -

+
Headers
+

Headers sent with the response.

-
-
- -
+

Changelog

-
-
    -
  • -

    -1.0: Message introduced. -

    +
    • 1.0: Message introduced.
    • -
-
-
-
+

Examples

-
-
-
Receive a gun_response message in a gen_server
-
-
handle_info({gun_response, ConnPid, _StreamRef,
-             _IsFin, _Status, _Headers},
-            State=#state{conn_pid=ConnPid}) ->
-    %% Do something.
-    {noreply, State}.
-
-
-
+
handle_info({gun_response, ConnPid, _StreamRef,
+             _IsFin, _Status, _Headers},
+            State=#state{conn_pid=ConnPid}) ->
+    %% Do something.
+    {noreply, State}.
+

See also

- - +

gun(3), gun:get(3), gun:head(3), gun:patch(3), gun:post(3), gun:put(3), gun:delete(3), gun:options(3), gun:request(3), gun_inform(3), gun_push(3)

+ diff --git a/docs/en/gun/1.0/manual/gun_trailers/index.html b/docs/en/gun/1.0/manual/gun_trailers/index.html index e67b0afb..d78678c4 100644 --- a/docs/en/gun/1.0/manual/gun_trailers/index.html +++ b/docs/en/gun/1.0/manual/gun_trailers/index.html @@ -62,106 +62,51 @@

gun_trailers(3)

-

Name

-
-

gun_trailers - Response trailers

-
-
-
+

gun_trailers - Response trailers

Description

-
-
-
-
{gun_trailers, ConnPid, StreamRef, Headers}
-
-ConnPid   :: pid()
-StreamRef :: reference()
-Headers   :: [{binary(), binary()}]
-

Response trailers.

-

This message informs the relevant process that the server -sent response trailers for the response to the original -request.

-

A trailers message terminates the response.

-
-
-
+
{gun_trailers, ConnPid, StreamRef, Headers}
+
+ConnPid   :: pid()
+StreamRef :: reference()
+Headers   :: [{binary(), binary()}]
+
+

Response trailers.

+

This message informs the relevant process that the server sent response trailers for the response to the original request.

+

A trailers message terminates the response.

Elements

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-StreamRef -
-
-

-Identifier of the stream for the original request. -

+
StreamRef
+

Identifier of the stream for the original request.

-
-Headers -
-
-

-Trailing headers sent after the response body. -

+
Headers
+

Trailing headers sent after the response body.

-
-
- -
+

Changelog

-
-
    -
  • -

    -1.0: Message introduced. -

    +
    • 1.0: Message introduced.
    • -
-
-
-
+

Examples

-
-
-
Receive a gun_trailers message in a gen_server
-
-
handle_info({gun_trailers, ConnPid, _StreamRef, _Headers},
-            State=#state{conn_pid=ConnPid}) ->
-    %% Do something.
-    {noreply, State}.
-
-
-
+
handle_info({gun_trailers, ConnPid, _StreamRef, _Headers},
+            State=#state{conn_pid=ConnPid}) ->
+    %% Do something.
+    {noreply, State}.
+

See also

- - +

gun(3), gun:get(3), gun:head(3), gun:patch(3), gun:post(3), gun:put(3), gun:delete(3), gun:options(3), gun:request(3), gun_response(3), gun_data(3)

+ diff --git a/docs/en/gun/1.0/manual/gun_up/index.html b/docs/en/gun/1.0/manual/gun_up/index.html index ea61a339..0d0257ba 100644 --- a/docs/en/gun/1.0/manual/gun_up/index.html +++ b/docs/en/gun/1.0/manual/gun_up/index.html @@ -62,96 +62,47 @@

gun_up(3)

-

Name

-
-

gun_up - The connection is up

-
-
-
+

gun_up - The connection is up

Description

-
-
-
-
{gun_up, ConnPid, Protocol}
-
-ConnPid  :: pid()
-Protocol :: http | http2
-

The connection is up.

-

This message informs the owner process that the connection or -reconnection completed.

-

Gun will now start processing the messages it received while -waiting for the connection to be up. If this is a reconnection, -then this may not be desirable for all requests. Those requests -should be cancelled when the connection goes down, and any -subsequent messages ignored.

-
-
-
+
{gun_up, ConnPid, Protocol}
+
+ConnPid  :: pid()
+Protocol :: http | http2
+
+

The connection is up.

+

This message informs the owner process that the connection or reconnection completed.

+

Gun will now start processing the messages it received while waiting for the connection to be up. If this is a reconnection, then this may not be desirable for all requests. Those requests should be cancelled when the connection goes down, and any subsequent messages ignored.

Elements

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-Protocol -
-
-

-The protocol selected for this connection. It can be used -to determine the capabilities of the server. -

+
Protocol
+

The protocol selected for this connection. It can be used to determine the capabilities of the server.

-
-
- -
+

Changelog

-
-
    -
  • -

    -1.0: Message introduced. -

    +
    • 1.0: Message introduced.
    • -
-
-
-
+

Examples

-
-
-
Receive a gun_up message in a gen_server
-
-
handle_info({gun_up, ConnPid, _Protocol},
-            State=#state{conn_pid=ConnPid}) ->
-    %% Do something.
-    {noreply, State}.
-
-
-
+
handle_info({gun_up, ConnPid, _Protocol},
+            State=#state{conn_pid=ConnPid}) ->
+    %% Do something.
+    {noreply, State}.
+

See also

- - +

gun(3), gun:open(3), gun:open_unix(3), gun:await_up(3), gun_down(3), gun_error(3)

+ diff --git a/docs/en/gun/1.0/manual/gun_upgrade/index.html b/docs/en/gun/1.0/manual/gun_upgrade/index.html index 56e8e569..ec4fdff2 100644 --- a/docs/en/gun/1.0/manual/gun_upgrade/index.html +++ b/docs/en/gun/1.0/manual/gun_upgrade/index.html @@ -62,114 +62,57 @@

gun_upgrade(3)

-

Name

-
-

gun_upgrade - Successful protocol upgrade

-
-
-
+

gun_upgrade - Successful protocol upgrade

Description

-
-
-
-
{gun_upgrade, ConnPid, StreamRef, Protocols, Headers}
-
-ConnPid   :: pid()
-StreamRef :: reference()
-Protocols :: [<<"websocket">>]
-Headers   :: [{binary(), binary()}]
-

Successful protocol upgrade.

-

This message informs the relevant process that the server -accepted to upgrade to one or more protocols given in the -original request.

-

The exact semantics of this message depend on the original -protocol. HTTP/1.1 upgrades apply to the entire connection. -HTTP/2 uses a different mechanism which allows switching -specific streams to a different protocol.

-

Gun currently only supports upgrading HTTP/1.1 connections -to the Websocket protocol.

-
-
-
+
{gun_upgrade, ConnPid, StreamRef, Protocols, Headers}
+
+ConnPid   :: pid()
+StreamRef :: reference()
+Protocols :: [<<"websocket">>]
+Headers   :: [{binary(), binary()}]
+
+

Successful protocol upgrade.

+

This message informs the relevant process that the server accepted to upgrade to one or more protocols given in the original request.

+

The exact semantics of this message depend on the original protocol. HTTP/1.1 upgrades apply to the entire connection. HTTP/2 uses a different mechanism which allows switching specific streams to a different protocol.

+

Gun currently only supports upgrading HTTP/1.1 connections to the Websocket protocol.

Elements

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-StreamRef -
-
-

-Identifier of the stream that resulted in an upgrade. -

+
StreamRef
+

Identifier of the stream that resulted in an upgrade.

-
-Protocols -
-
-

-List of protocols this stream was upgraded to. -

+
Protocols
+

List of protocols this stream was upgraded to.

-
-Headers -
-
-

-Headers sent with the upgrade response. -

+
Headers
+

Headers sent with the upgrade response.

-
-
- -
+

Changelog

-
-
    -
  • -

    -1.0: Message introduced. -

    +
    • 1.0: Message introduced.
    • -
-
-
-
+

Examples

-
-
-
Receive a gun_upgrade message in a gen_server
-
-
handle_info({gun_upgrade, ConnPid, _StreamRef,
-             _Protocols, _Headers},
-            State=#state{conn_pid=ConnPid}) ->
-    %% Do something.
-    {noreply, State}.
-
-
-
+
handle_info({gun_upgrade, ConnPid, _StreamRef,
+             _Protocols, _Headers},
+            State=#state{conn_pid=ConnPid}) ->
+    %% Do something.
+    {noreply, State}.
+

See also

- - +

gun(3), gun:ws_upgrade(3), gun:ws_send(3), gun_ws(3)

+ diff --git a/docs/en/gun/1.0/manual/gun_ws/index.html b/docs/en/gun/1.0/manual/gun_ws/index.html index e7eb4125..447fdc63 100644 --- a/docs/en/gun/1.0/manual/gun_ws/index.html +++ b/docs/en/gun/1.0/manual/gun_ws/index.html @@ -62,101 +62,53 @@

gun_ws(3)

-

Name

-
-

gun_ws - Websocket frame

-
-
-
+

gun_ws - Websocket frame

Description

-
-
-
-
{gun_ws, ConnPid, StreamRef, Frame}
-
-ConnPid   :: pid()
-StreamRef :: reference()
-Frame     :: close
-           | {text | binary | close, binary()}
-           | {close, non_neg_integer(), binary()}
-

Websocket frame.

-

This message informs the relevant process that the server -sent the enclosed frame.

-

This message can only be sent on streams that were upgraded -to the Websocket protocol.

-
-
-
+
{gun_ws, ConnPid, StreamRef, Frame}
+
+ConnPid   :: pid()
+StreamRef :: reference()
+Frame     :: close
+           | {text | binary | close, binary()}
+           | {close, non_neg_integer(), binary()}
+
+

Websocket frame.

+

This message informs the relevant process that the server sent the enclosed frame.

+

This message can only be sent on streams that were upgraded to the Websocket protocol.

Elements

-
-
-
-ConnPid -
-
-

-The pid of the Gun connection process. -

+
ConnPid
+

The pid of the Gun connection process.

-
-StreamRef -
-
-

-Identifier of the stream that was upgraded to Websocket. -

+
StreamRef
+

Identifier of the stream that was upgraded to Websocket.

-
-Frame -
-
-

-The Websocket frame in question. -

+
Frame
+

The Websocket frame in question.

-
-
- -
+

Changelog

-
-
    -
  • -

    -1.0: Message introduced. -

    +
    • 1.0: Message introduced.
    • -
-
-
-
+

Examples

-
-
-
Receive a gun_ws message in a gen_server
-
-
handle_info({gun_ws, ConnPid, _StreamRef, _Frame},
-            State=#state{conn_pid=ConnPid}) ->
-    %% Do something.
-    {noreply, State}.
-
-
-
+
handle_info({gun_ws, ConnPid, _StreamRef, _Frame},
+            State=#state{conn_pid=ConnPid}) ->
+    %% Do something.
+    {noreply, State}.
+

See also

- - +

gun(3), gun:ws_upgrade(3), gun:ws_send(3), gun_upgrade(3)

+ diff --git a/docs/en/gun/1.0/manual/index.html b/docs/en/gun/1.0/manual/index.html index 241ed25e..96bf8528 100644 --- a/docs/en/gun/1.0/manual/index.html +++ b/docs/en/gun/1.0/manual/index.html @@ -62,72 +62,33 @@

Gun Function Reference

-

Name

-
-

gun - HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP

-
-
-
+

gun - HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP

Description

-
-

Gun is an HTTP client for Erlang/OTP with support for the -HTTP/1.1, HTTP/2 and Websocket protocols.

-

Gun aims to provide an easy to use, asynchronous and -always-connected client. It maintains a permanent connection -to the server and reconnects automatically when necessary.

-
-
-
+

Gun is an HTTP client for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols.

+

Gun aims to provide an easy to use, asynchronous and always-connected client. It maintains a permanent connection to the server and reconnects automatically when necessary.

Modules

-
-
    -
  • -

    -gun(3) - Asynchronous HTTP client -

    +
    • gun(3) - Asynchronous HTTP client
    • -
-
-
-
+

Dependencies

-
-
    -
  • -

    -cowlib(7) - Support library for manipulating Web protocols -

    +
    • cowlib(7) - Support library for manipulating Web protocols
    • -
    • -

      -ssl - Secure communication over sockets -

      +
    • ssl - Secure communication over sockets
    • -
-

All these applications must be started before the gun -application. To start Gun and all dependencies at once:

-
-
-
{ok, _} = application:ensure_all_started(gun).
-
-
-
+
{ok, _} = application:ensure_all_started(gun).
+

Environment

-
-

The gun application does not define any application -environment configuration parameters.

-
- -
+

The gun application does not define any application environment configuration parameters.

See also

- -
+

cowlib(7)

+ diff --git a/docs/en/ranch/1.2/guide/embedded/index.html b/docs/en/ranch/1.2/guide/embedded/index.html index 39350a45..141bad1e 100644 --- a/docs/en/ranch/1.2/guide/embedded/index.html +++ b/docs/en/ranch/1.2/guide/embedded/index.html @@ -62,48 +62,30 @@

Embedded mode

-

Embedded mode allows you to insert Ranch listeners directly -in your supervision tree. This allows for greater fault tolerance -control by permitting the shutdown of a listener due to the -failure of another part of the application and vice versa.

-
+

Embedded mode allows you to insert Ranch listeners directly in your supervision tree. This allows for greater fault tolerance control by permitting the shutdown of a listener due to the failure of another part of the application and vice versa.

Embedding

-
-

To embed Ranch in your application you can simply add the child specs -to your supervision tree. This can all be done in the init/1 function -of one of your application supervisors.

-

Ranch requires at the minimum two kinds of child specs for embedding. -First, you need to add ranch_sup to your supervision tree, only once, -regardless of the number of listeners you will use. Then you need to -add the child specs for each listener.

-

Ranch has a convenience function for getting the listeners child specs -called ranch:child_spec/6, that works like ranch:start_listener/6, -except that it doesn’t start anything, it only returns child specs.

-

As for ranch_sup, the child spec is simple enough to not require a -convenience function.

-

The following example adds both ranch_sup and one listener to another -application’s supervision tree.

-
-
Embed Ranch directly in your supervision tree
-
-
init([]) ->
-        RanchSupSpec = {ranch_sup, {ranch_sup, start_link, []},
-                permanent, 5000, supervisor, [ranch_sup]},
-        ListenerSpec = ranch:child_spec(echo, 100,
-                ranch_tcp, [{port, 5555}],
-                echo_protocol, []
-        ),
-        {ok, {{one_for_one, 10, 10}, [RanchSupSpec, ListenerSpec]}}.
-

Remember, you can add as many listener child specs as needed, but only -one ranch_sup spec!

-

It is recommended that your architecture makes sure that all listeners -are restarted if ranch_sup fails. See the Ranch internals chapter for -more details on how Ranch does it.

-
-
+
init([]) ->
+	RanchSupSpec = {ranch_sup, {ranch_sup, start_link, []},
+		permanent, 5000, supervisor, [ranch_sup]},
+	ListenerSpec = ranch:child_spec(echo, 100,
+		ranch_tcp, [{port, 5555}],
+		echo_protocol, []
+	),
+	{ok, {{one_for_one, 10, 10}, [RanchSupSpec, ListenerSpec]}}.
+ +

Remember, you can add as many listener child specs as needed, but only one ranch_sup spec!

+

It is recommended that your architecture makes sure that all listeners are restarted if ranch_sup fails. See the Ranch internals chapter for more details on how Ranch does it.

+ @@ -160,6 +142,8 @@ more details on how Ranch does it.

+
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.2/guide/index.html b/docs/en/ranch/1.2/guide/index.html index 7c1cf9ed..8c91582e 100644 --- a/docs/en/ranch/1.2/guide/index.html +++ b/docs/en/ranch/1.2/guide/index.html @@ -62,48 +62,24 @@

    Ranch User Guide

    - + + @@ -138,6 +114,8 @@ +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.2/guide/internals/index.html b/docs/en/ranch/1.2/guide/internals/index.html index 5794c4bc..c5926f1e 100644 --- a/docs/en/ranch/1.2/guide/internals/index.html +++ b/docs/en/ranch/1.2/guide/internals/index.html @@ -62,93 +62,34 @@

    Internals

    -

    This chapter may not apply to embedded Ranch as embedding allows you -to use an architecture specific to your application, which may or may -not be compatible with the description of the Ranch application.

    -

    Note that for everything related to efficiency and performance, -you should perform the benchmarks yourself to get the numbers that -matter to you. Generic benchmarks found on the web may or may not -be of use to you, you can never know until you benchmark your own -system.

    -
    +

    This chapter may not apply to embedded Ranch as embedding allows you to use an architecture specific to your application, which may or may not be compatible with the description of the Ranch application.

    +

    Note that for everything related to efficiency and performance, you should perform the benchmarks yourself to get the numbers that matter to you. Generic benchmarks found on the web may or may not be of use to you, you can never know until you benchmark your own system.

    Architecture

    -
    -

    Ranch is an OTP application.

    -

    Like all OTP applications, Ranch has a top supervisor. It is responsible -for supervising the ranch_server process and all the listeners that -will be started.

    -

    The ranch_server gen_server is a central process keeping track of the -listeners and their acceptors. It does so through the use of a public ets -table called ranch_server. The table is owned by the top supervisor -to improve fault tolerance. This way if the ranch_server gen_server -fails, it doesn’t lose any information and the restarted process can -continue as if nothing happened.

    -

    Ranch uses a custom supervisor for managing connections. This supervisor -keeps track of the number of connections and handles connection limits -directly. While it is heavily optimized to perform the task of creating -connection processes for accepted connections, it is still following the -OTP principles and the usual sys and supervisor calls will work on -it as expected.

    -

    Listeners are grouped into the ranch_listener_sup supervisor and -consist of three kinds of processes: the listener gen_server, the -acceptor processes and the connection processes, both grouped under -their own supervisor. All of these processes are registered to the -ranch_server gen_server with varying amount of information.

    -

    All socket operations, including listening for connections, go through -transport handlers. Accepted connections are given to the protocol handler. -Transport handlers are simple callback modules for performing operations on -sockets. Protocol handlers start a new process, which receives socket -ownership, with no requirements on how the code should be written inside -that new process.

    -
    -
    -
    +

    Ranch is an OTP application.

    +

    Like all OTP applications, Ranch has a top supervisor. It is responsible for supervising the ranch_server process and all the listeners that will be started.

    +

    The ranch_server gen_server is a central process keeping track of the listeners and their acceptors. It does so through the use of a public ets table called ranch_server. The table is owned by the top supervisor to improve fault tolerance. This way if the ranch_server gen_server fails, it doesn't lose any information and the restarted process can continue as if nothing happened.

    +

    Ranch uses a custom supervisor for managing connections. This supervisor keeps track of the number of connections and handles connection limits directly. While it is heavily optimized to perform the task of creating connection processes for accepted connections, it is still following the OTP principles and the usual sys and supervisor calls will work on it as expected.

    +

    Listeners are grouped into the ranch_listener_sup supervisor and consist of three kinds of processes: the listener gen_server, the acceptor processes and the connection processes, both grouped under their own supervisor. All of these processes are registered to the ranch_server gen_server with varying amount of information.

    +

    All socket operations, including listening for connections, go through transport handlers. Accepted connections are given to the protocol handler. Transport handlers are simple callback modules for performing operations on sockets. Protocol handlers start a new process, which receives socket ownership, with no requirements on how the code should be written inside that new process.

    Number of acceptors

    -
    -

    The second argument to ranch:start_listener/6 is the number of -processes that will be accepting connections. Care should be taken -when choosing this number.

    -

    First of all, it should not be confused with the maximum number -of connections. Acceptor processes are only used for accepting and -have nothing else in common with connection processes. Therefore -there is nothing to be gained from setting this number too high, -in fact it can slow everything else down.

    -

    Second, this number should be high enough to allow Ranch to accept -connections concurrently. But the number of cores available doesn’t -seem to be the only factor for choosing this number, as we can -observe faster accepts if we have more acceptors than cores. It -might be entirely dependent on the protocol, however.

    -

    Our observations suggest that using 100 acceptors on modern hardware -is a good solution, as it’s big enough to always have acceptors ready -and it’s low enough that it doesn’t have a negative impact on the -system’s performances.

    -
    -
    -
    +

    The second argument to ranch:start_listener/6 is the number of processes that will be accepting connections. Care should be taken when choosing this number.

    +

    First of all, it should not be confused with the maximum number of connections. Acceptor processes are only used for accepting and have nothing else in common with connection processes. Therefore there is nothing to be gained from setting this number too high, in fact it can slow everything else down.

    +

    Second, this number should be high enough to allow Ranch to accept connections concurrently. But the number of cores available doesn't seem to be the only factor for choosing this number, as we can observe faster accepts if we have more acceptors than cores. It might be entirely dependent on the protocol, however.

    +

    Our observations suggest that using 100 acceptors on modern hardware is a good solution, as it's big enough to always have acceptors ready and it's low enough that it doesn't have a negative impact on the system's performances.

    Platform-specific TCP features

    -
    -

    Some socket options are platform-specific and not supported by inet. -They can be of interest because they generally are related to -optimizations provided by the underlying OS. They can still be enabled -thanks to the raw option, for which we will see an example.

    -

    One of these features is TCP_DEFER_ACCEPT on Linux. It is a simplified -accept mechanism which will wait for application data to come in before -handing out the connection to the Erlang process.

    -

    This is especially useful if you expect many connections to be mostly -idle, perhaps part of a connection pool. They can be handled by the -kernel directly until they send any real data, instead of allocating -resources to idle connections.

    -

    To enable this mechanism, the following option can be used.

    -
    -
    Using raw transport options
    -
    -
    {raw, 6, 9, << 30:32/native >>}
    -

    It means go on layer 6, turn on option 9 with the given integer parameter.

    -
    -
    +
    {raw, 6, 9, << 30:32/native >>}
    + +

    It means go on layer 6, turn on option 9 with the given integer parameter.

    + @@ -201,6 +142,8 @@ http://www.gnu.org/software/src-highlite --> +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.2/guide/introduction/index.html b/docs/en/ranch/1.2/guide/introduction/index.html index e2e8b3b6..64859ee0 100644 --- a/docs/en/ranch/1.2/guide/introduction/index.html +++ b/docs/en/ranch/1.2/guide/introduction/index.html @@ -62,32 +62,17 @@

    Introduction

    -

    Ranch is a socket acceptor pool for TCP protocols.

    -

    Ranch aims to provide everything you need to accept TCP connections -with a small code base and low latency while being easy to use directly -as an application or to embed into your own.

    -
    +

    Ranch is a socket acceptor pool for TCP protocols.

    +

    Ranch aims to provide everything you need to accept TCP connections with a small code base and low latency while being easy to use directly as an application or to embed into your own.

    Prerequisites

    -
    -

    It is assumed the developer already knows Erlang and has some experience -with socket programming and TCP protocols.

    -
    -
    -
    +

    It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols.

    Supported platforms

    -
    -

    Ranch is tested and supported on Linux.

    -

    Ranch is developed for Erlang R15B01+.

    -

    Ranch may be compiled on earlier Erlang versions with small source code -modifications but there is no guarantee that it will work as expected.

    -
    -
    -
    +

    Ranch is tested and supported on Linux.

    +

    Ranch is developed for Erlang R15B01+.

    +

    Ranch may be compiled on earlier Erlang versions with small source code modifications but there is no guarantee that it will work as expected.

    Versioning

    - -
    +

    Ranch uses Semantic Versioning 2.0.0

    + @@ -140,6 +125,8 @@ modifications but there is no guarantee that it will work as expected.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.2/guide/listeners/index.html b/docs/en/ranch/1.2/guide/listeners/index.html index f8c24289..5d7bb697 100644 --- a/docs/en/ranch/1.2/guide/listeners/index.html +++ b/docs/en/ranch/1.2/guide/listeners/index.html @@ -62,287 +62,168 @@

    Listeners

    -

    A listener is a set of processes whose role is to listen on a port -for new connections. It manages a pool of acceptor processes, each -of them indefinitely accepting connections. When it does, it starts -a new process executing the protocol handler code. All the socket -programming is abstracted through the user of transport handlers.

    -

    The listener takes care of supervising all the acceptor and connection -processes, allowing developers to focus on building their application.

    -
    +

    A listener is a set of processes whose role is to listen on a port for new connections. It manages a pool of acceptor processes, each of them indefinitely accepting connections. When it does, it starts a new process executing the protocol handler code. All the socket programming is abstracted through the user of transport handlers.

    +

    The listener takes care of supervising all the acceptor and connection processes, allowing developers to focus on building their application.

    Starting a listener

    -
    -

    Ranch does nothing by default. It is up to the application developer -to request that Ranch listens for connections.

    -

    A listener can be started and stopped at will.

    -

    When starting a listener, a number of different settings are required:

    -
      -
    • -

      -A name to identify it locally and be able to interact with it. -

      +

      Ranch does nothing by default. It is up to the application developer to request that Ranch listens for connections.

      +

      A listener can be started and stopped at will.

      +

      When starting a listener, a number of different settings are required:

      +
      • A name to identify it locally and be able to interact with it.
      • -
      • -

        -The number of acceptors in the pool. -

        +
      • The number of acceptors in the pool.
      • -
      • -

        -A transport handler and its associated options. -

        +
      • A transport handler and its associated options.
      • -
      • -

        -A protocol handler and its associated options. -

        +
      • A protocol handler and its associated options.
      • -
    -

    Ranch includes both TCP and SSL transport handlers, respectively -ranch_tcp and ranch_ssl.

    -

    A listener can be started by calling the ranch:start_listener/6 -function. Before doing so however, you must ensure that the ranch -application is started.

    -
    -
    Starting the Ranch application
    -
    -
    ok = application:start(ranch).
    -

    You are then ready to start a listener. Let’s call it tcp_echo. It will -have a pool of 100 acceptors, use a TCP transport and forward connections -to the echo_protocol handler.

    -
    -
    Starting a listener for TCP connections on port 5555
    -
    -
    {ok, _} = ranch:start_listener(tcp_echo, 100,
    -        ranch_tcp, [{port, 5555}],
    -        echo_protocol, []
    -).
    -

    You can try this out by compiling and running the tcp_echo example in the -examples directory. To do so, open a shell in the examples/tcp_echo/ -directory and run the following command:

    -
    -
    Building and starting a Ranch example
    -
    -
    $ make run
    -

    You can then connect to it using telnet and see the echo server reply -everything you send to it. Then when you’re done testing, you can use -the Ctrl+] key to escape to the telnet command line and type -quit to exit.

    -
    -
    Connecting to the example listener with telnet
    -
    -
    $ telnet localhost 5555
    -Trying 127.0.0.1...
    -Connected to localhost.
    -Escape character is '^]'.
    -Hello!
    -Hello!
    -It works!
    -It works!
    -^]
    -
    -telnet> quit
    -Connection closed.
    -
    -
    -
    +
    $ telnet localhost 5555
    +Trying 127.0.0.1...
    +Connected to localhost.
    +Escape character is '^]'.
    +Hello!
    +Hello!
    +It works!
    +It works!
    +^]
    +
    +telnet> quit
    +Connection closed.
    +

    Stopping a listener

    -
    -

    All you need to stop a Ranch listener is to call the -ranch:stop_listener/1 function with the listener’s name -as argument. In the previous section we started the listener -named tcp_echo. We can now stop it.

    -
    -
    Stopping a listener
    -
    -
    ranch:stop_listener(tcp_echo).
    -
    - -
    +
    ranch:stop_listener(tcp_echo).
    +

    Default transport options

    -
    -

    By default the socket will be set to return binary data, with the -options {active, false}, {packet, raw}, {reuseaddr, true} set. -These values can’t be overriden when starting the listener, but -they can be overriden using Transport:setopts/2 in the protocol.

    -

    It will also set {backlog, 1024} and {nodelay, true}, which -can be overriden at listener startup.

    -
    - -
    +

    By default the socket will be set to return binary data, with the options {active, false}, {packet, raw}, {reuseaddr, true} set. These values can't be overriden when starting the listener, but they can be overriden using Transport:setopts/2 in the protocol.

    +

    It will also set {backlog, 1024} and {nodelay, true}, which can be overriden at listener startup.

    Listening on a random port

    -
    -

    You do not have to specify a specific port to listen on. If you give -the port number 0, or if you omit the port number entirely, Ranch will -start listening on a random port.

    -

    You can retrieve this port number by calling ranch:get_port/1. The -argument is the name of the listener you gave in ranch:start_listener/6.

    -
    -
    Starting a listener for TCP connections on a random port
    -
    -
    {ok, _} = ranch:start_listener(tcp_echo, 100,
    -        ranch_tcp, [{port, 0}],
    -        echo_protocol, []
    -).
    -Port = ranch:get_port(tcp_echo).
    -
    -
    -
    +
    {ok, _} = ranch:start_listener(tcp_echo, 100,
    +	ranch_tcp, [{port, 0}],
    +	echo_protocol, []
    +).
    +Port = ranch:get_port(tcp_echo).
    +

    Listening on privileged ports

    -
    -

    Some systems limit access to ports below 1024 for security reasons. -This can easily be identified by an {error, eacces} error when trying -to open a listening socket on such a port.

    -

    The methods for listening on privileged ports vary between systems, -please refer to your system’s documentation for more information.

    -

    We recommend the use of port rewriting for systems with a single server, -and load balancing for systems with multiple servers. Documenting these -solutions is however out of the scope of this guide.

    -
    - -
    +

    Some systems limit access to ports below 1024 for security reasons. This can easily be identified by an {error, eacces} error when trying to open a listening socket on such a port.

    +

    The methods for listening on privileged ports vary between systems, please refer to your system's documentation for more information.

    +

    We recommend the use of port rewriting for systems with a single server, and load balancing for systems with multiple servers. Documenting these solutions is however out of the scope of this guide.

    Accepting connections on an existing socket

    -
    -

    If you want to accept connections on an existing socket, you can use the -socket transport option, which should just be the relevant data returned -from the connect function for the transport or the underlying socket library -(gen_tcp:connect, ssl:connect). The accept function will then be -called on the passed in socket. You should connect the socket in -{active, false} mode, as well.

    -

    Note, however, that because of a bug in SSL, you cannot change ownership of an -SSL listen socket prior to R16. Ranch will catch the error thrown, but the -owner of the SSL socket will remain as whatever process created the socket. -However, this will not affect accept behaviour unless the owner process dies, -in which case the socket is closed. Therefore, to use this feature with SSL -with an erlang release prior to R16, ensure that the SSL socket is opened in a -persistant process.

    -
    -
    -
    +

    If you want to accept connections on an existing socket, you can use the socket transport option, which should just be the relevant data returned from the connect function for the transport or the underlying socket library (gen_tcp:connect, ssl:connect). The accept function will then be called on the passed in socket. You should connect the socket in {active, false} mode, as well.

    +

    Note, however, that because of a bug in SSL, you cannot change ownership of an SSL listen socket prior to R16. Ranch will catch the error thrown, but the owner of the SSL socket will remain as whatever process created the socket. However, this will not affect accept behaviour unless the owner process dies, in which case the socket is closed. Therefore, to use this feature with SSL with an erlang release prior to R16, ensure that the SSL socket is opened in a persistant process.

    Limiting the number of concurrent connections

    -
    -

    The max_connections transport option allows you to limit the number -of concurrent connections. It defaults to 1024. Its purpose is to -prevent your system from being overloaded and ensuring all the -connections are handled optimally.

    -
    -
    Customizing the maximum number of concurrent connections
    -
    -
    {ok, _} = ranch:start_listener(tcp_echo, 100,
    -        ranch_tcp, [{port, 5555}, {max_connections, 100}],
    -        echo_protocol, []
    -).
    -

    You can disable this limit by setting its value to the atom infinity.

    -
    -
    Disabling the limit for the number of connections
    -
    -
    {ok, _} = ranch:start_listener(tcp_echo, 100,
    -        ranch_tcp, [{port, 5555}, {max_connections, infinity}],
    -        echo_protocol, []
    -).
    -

    You may not always want connections to be counted when checking for -max_connections. For example you might have a protocol where both -short-lived and long-lived connections are possible. If the long-lived -connections are mostly waiting for messages, then they don’t consume -much resources and can safely be removed from the count.

    -

    To remove the connection from the count, you must call the -ranch:remove_connection/1 from within the connection process, -with the name of the listener as the only argument.

    -
    -
    Removing a connection from the count of connections
    -
    -
    ranch:remove_connection(Ref).
    -

    As seen in the chapter covering protocols, this pid is received as the -first argument of the protocol’s start_link/4 callback.

    -

    You can modify the max_connections value on a running listener by -using the ranch:set_max_connections/2 function, with the name of the -listener as first argument and the new value as the second.

    -
    -
    Upgrading the maximum number of connections
    -
    -
    ranch:set_max_connections(tcp_echo, MaxConns).
    -

    The change will occur immediately.

    -
    -
    -
    +
    ranch:set_max_connections(tcp_echo, MaxConns).
    +
    +

    The change will occur immediately.

    Using a supervisor for connection processes

    -
    -

    Ranch allows you to define the type of process that will be used -for the connection processes. By default it expects a worker. -When the connection_type configuration value is set to supervisor, -Ranch will consider that the connection process it manages is a -supervisor and will reflect that in its supervision tree.

    -

    Connection processes of type supervisor can either handle the -socket directly or through one of their children. In the latter -case the start function for the connection process must return -two pids: the pid of the supervisor you created (that will be -supervised) and the pid of the protocol handling process (that -will receive the socket).

    -

    Instead of returning {ok, ConnPid}, simply return -{ok, SupPid, ConnPid}.

    -

    It is very important that the connection process be created -under the supervisor process so that everything works as intended. -If not, you will most likely experience issues when the supervised -process is stopped.

    -
    - -
    +

    Ranch allows you to define the type of process that will be used for the connection processes. By default it expects a worker. When the connection_type configuration value is set to supervisor, Ranch will consider that the connection process it manages is a supervisor and will reflect that in its supervision tree.

    +

    Connection processes of type supervisor can either handle the socket directly or through one of their children. In the latter case the start function for the connection process must return two pids: the pid of the supervisor you created (that will be supervised) and the pid of the protocol handling process (that will receive the socket).

    +

    Instead of returning {ok, ConnPid}, simply return {ok, SupPid, ConnPid}.

    +

    It is very important that the connection process be created under the supervisor process so that everything works as intended. If not, you will most likely experience issues when the supervised process is stopped.

    Upgrading

    -
    -

    Ranch allows you to upgrade the protocol options. This takes effect -immediately and for all subsequent connections.

    -

    To upgrade the protocol options, call ranch:set_protocol_options/2 -with the name of the listener as first argument and the new options -as the second.

    -
    -
    Upgrading the protocol options
    -
    -
    ranch:set_protocol_options(tcp_echo, NewOpts).
    -

    All future connections will use the new options.

    -

    You can also retrieve the current options similarly by -calling ranch:get_protocol_options/1.

    -
    -
    Retrieving the current protocol options
    -
    -
    Opts = ranch:get_protocol_options(tcp_echo).
    -
    -
    +
    Opts = ranch:get_protocol_options(tcp_echo).
    + + @@ -399,6 +280,8 @@ http://www.gnu.org/software/src-highlite --> +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.2/guide/parsers/index.html b/docs/en/ranch/1.2/guide/parsers/index.html index f9f1ac5e..9891fde2 100644 --- a/docs/en/ranch/1.2/guide/parsers/index.html +++ b/docs/en/ranch/1.2/guide/parsers/index.html @@ -62,109 +62,69 @@

    Writing parsers

    -

    There are three kinds of protocols:

    -
      -
    • -

      -Text protocols -

      +

      There are three kinds of protocols:

      +
      • Text protocols
      • -
      • -

        -Schema-less binary protocols -

        +
      • Schema-less binary protocols
      • -
      • -

        -Schema-based binary protocols -

        +
      • Schema-based binary protocols
      • -
    -

    This chapter introduces the first two kinds. It will not cover -more advanced topics such as continuations or parser generators.

    -

    This chapter isn’t specifically about Ranch, we assume here that -you know how to read data from the socket. The data you read and -the data that hasn’t been parsed is saved in a buffer. Every -time you read from the socket, the data read is appended to the -buffer. What happens next depends on the kind of protocol. We -will only cover the first two.

    -
    + +

    This chapter introduces the first two kinds. It will not cover more advanced topics such as continuations or parser generators.

    +

    This chapter isn't specifically about Ranch, we assume here that you know how to read data from the socket. The data you read and the data that hasn't been parsed is saved in a buffer. Every time you read from the socket, the data read is appended to the buffer. What happens next depends on the kind of protocol. We will only cover the first two.

    Parsing text

    -
    -

    Text protocols are generally line based. This means that we can’t -do anything with them until we receive the full line.

    -

    A simple way to get a full line is to use binary:split/{2,3}.

    -
    -
    Using binary:split/2 to get a line of input
    -
    -
    case binary:split(Buffer, <<"\n">>) of
    -        [_] ->
    -                get_more_data(Buffer);
    -        [Line, Rest] ->
    -                handle_line(Line, Rest)
    -end.
    -

    In the above example, we can have two results. Either there was -a line break in the buffer and we get it split into two parts, -the line and the rest of the buffer; or there was no line break -in the buffer and we need to get more data from the socket.

    -

    Next, we need to parse the line. The simplest way is to again -split, here on space. The difference is that we want to split -on all spaces character, as we want to tokenize the whole string.

    -
    -
    Using binary:split/3 to split text
    -
    -
    case binary:split(Line, <<" ">>, [global]) of
    -        [<<"HELLO">>] ->
    -                be_polite();
    -        [<<"AUTH">>, User, Password] ->
    -                authenticate_user(User, Password);
    -        [<<"QUIT">>, Reason] ->
    -                quit(Reason)
    -        %% ...
    -end.
    -

    Pretty simple, right? Match on the command name, get the rest -of the tokens in variables and call the respective functions.

    -

    After doing this, you will want to check if there is another -line in the buffer, and handle it immediately if any. -Otherwise wait for more data.

    -
    -
    -
    +
    case binary:split(Line, <<" ">>, [global]) of
    +	[<<"HELLO">>] ->
    +		be_polite();
    +	[<<"AUTH">>, User, Password] ->
    +		authenticate_user(User, Password);
    +	[<<"QUIT">>, Reason] ->
    +		quit(Reason)
    +	%% ...
    +end.
    +
    +

    Pretty simple, right? Match on the command name, get the rest of the tokens in variables and call the respective functions.

    +

    After doing this, you will want to check if there is another line in the buffer, and handle it immediately if any. Otherwise wait for more data.

    Parsing binary

    -
    -

    Binary protocols can be more varied, although most of them are -pretty similar. The first four bytes of a frame tend to be -the size of the frame, which is followed by a certain number -of bytes for the type of frame and then various parameters.

    -

    Sometimes the size of the frame includes the first four bytes, -sometimes not. Other times this size is encoded over two bytes. -And even other times little-endian is used instead of big-endian.

    -

    The general idea stays the same though.

    -
    -
    Using binary pattern matching to split frames
    -
    -
    << Size:32, _/bits >> = Buffer,
    -case Buffer of
    -        << Frame:Size/binary, Rest/bits >> ->
    -                handle_frame(Frame, Rest);
    -        _ ->
    -                get_more_data(Buffer)
    -end.
    -

    You will then need to parse this frame using binary pattern -matching, and handle it. Then you will want to check if there -is another frame fully received in the buffer, and handle it -immediately if any. Otherwise wait for more data.

    -
    - +
    << Size:32, _/bits >> = Buffer,
    +case Buffer of
    +	<< Frame:Size/binary, Rest/bits >> ->
    +		handle_frame(Frame, Rest);
    +	_ ->
    +		get_more_data(Buffer)
    +end.
    + +

    You will then need to parse this frame using binary pattern matching, and handle it. Then you will want to check if there is another frame fully received in the buffer, and handle it immediately if any. Otherwise wait for more data.

    + @@ -221,6 +181,8 @@ immediately if any. Otherwise wait for more data.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.2/guide/protocols/index.html b/docs/en/ranch/1.2/guide/protocols/index.html index 950615b5..901a0770 100644 --- a/docs/en/ranch/1.2/guide/protocols/index.html +++ b/docs/en/ranch/1.2/guide/protocols/index.html @@ -62,129 +62,98 @@

    Protocols

    -

    A protocol handler starts a connection process and defines the -protocol logic executed in this process.

    -
    +

    A protocol handler starts a connection process and defines the protocol logic executed in this process.

    Writing a protocol handler

    -
    -

    All protocol handlers must implement the ranch_protocol behavior -which defines a single callback, start_link/4. This callback is -responsible for spawning a new process for handling the connection. -It receives four arguments: the name of the listener, the socket, the -transport handler being used and the protocol options defined in -the call to ranch:start_listener/6. This callback must -return {ok, Pid}, with Pid the pid of the new process.

    -

    The newly started process can then freely initialize itself. However, -it must call ranch:accept_ack/1 before doing any socket operation. -This will ensure the connection process is the owner of the socket. -It expects the listener’s name as argument.

    -
    -
    Acknowledge accepting the socket
    -
    -
    ok = ranch:accept_ack(Ref).
    -

    If your protocol code requires specific socket options, you should -set them while initializing your connection process, after -calling ranch:accept_ack/1. You can use Transport:setopts/2 -for that purpose.

    -

    Following is the complete protocol code for the example found -in examples/tcp_echo/.

    -
    -
    Protocol module that echoes everything it receives
    -
    -
    -module(echo_protocol).
    --behaviour(ranch_protocol).
    -
    --export([start_link/4]).
    --export([init/4]).
    -
    -start_link(Ref, Socket, Transport, Opts) ->
    -        Pid = spawn_link(?MODULE, init, [Ref, Socket, Transport, Opts]),
    -        {ok, Pid}.
    -
    -init(Ref, Socket, Transport, _Opts = []) ->
    -        ok = ranch:accept_ack(Ref),
    -        loop(Socket, Transport).
    -
    -loop(Socket, Transport) ->
    -        case Transport:recv(Socket, 0, 5000) of
    -                {ok, Data} ->
    -                        Transport:send(Socket, Data),
    -                        loop(Socket, Transport);
    -                _ ->
    -                        ok = Transport:close(Socket)
    -        end.
    -
    -
    -
    +
    -module(echo_protocol).
    +-behaviour(ranch_protocol).
    +
    +-export([start_link/4]).
    +-export([init/4]).
    +
    +start_link(Ref, Socket, Transport, Opts) ->
    +	Pid = spawn_link(?MODULE, init, [Ref, Socket, Transport, Opts]),
    +	{ok, Pid}.
    +
    +init(Ref, Socket, Transport, _Opts = []) ->
    +	ok = ranch:accept_ack(Ref),
    +	loop(Socket, Transport).
    +
    +loop(Socket, Transport) ->
    +	case Transport:recv(Socket, 0, 5000) of
    +		{ok, Data} ->
    +			Transport:send(Socket, Data),
    +			loop(Socket, Transport);
    +		_ ->
    +			ok = Transport:close(Socket)
    +	end.
    +

    Using gen_server

    -
    -

    Special processes like the ones that use the gen_server or gen_fsm -behaviours have the particularity of having their start_link call not -return until the init function returns. This is problematic, because -you won’t be able to call ranch:accept_ack/1 from the init callback -as this would cause a deadlock to happen.

    -

    There are two ways of solving this problem.

    -

    The first, and probably the most elegant one, is to make use of the -gen_server:enter_loop/3 function. It allows you to start your process -normally (although it must be started with proc_lib like all special -processes), then perform any needed operations before falling back into -the normal gen_server execution loop.

    -
    -
    Use a gen_server for protocol handling
    -
    -
    -module(my_protocol).
    --behaviour(gen_server).
    --behaviour(ranch_protocol).
    -
    --export([start_link/4]).
    --export([init/4]).
    -%% Exports of other gen_server callbacks here.
    -
    -start_link(Ref, Socket, Transport, Opts) ->
    -        proc_lib:start_link(?MODULE, init, [Ref, Socket, Transport, Opts]).
    -
    -init(Ref, Socket, Transport, _Opts = []) ->
    -        ok = proc_lib:init_ack({ok, self()}),
    -        %% Perform any required state initialization here.
    -        ok = ranch:accept_ack(Ref),
    -        ok = Transport:setopts(Socket, [{active, once}]),
    -        gen_server:enter_loop(?MODULE, [], {state, Socket, Transport}).
    -
    -%% Other gen_server callbacks here.
    -

    The second method involves triggering a timeout just after gen_server:init -ends. If you return a timeout value of 0 then the gen_server will call -handle_info(timeout, _, _) right away.

    -
    -
    Use a gen_server for protocol handling, method 2
    -
    -
    -module(my_protocol).
    --behaviour(gen_server).
    --behaviour(ranch_protocol).
    +
    -module(my_protocol).
    +-behaviour(gen_server).
    +-behaviour(ranch_protocol).
     
    -%% Exports go here.
    +%% Exports go here.
     
    -init([Ref, Socket, Transport]) ->
    -        {ok, {state, Ref, Socket, Transport}, 0}.
    +init([Ref, Socket, Transport]) ->
    +	{ok, {state, Ref, Socket, Transport}, 0}.
    +
    +handle_info(timeout, State={state, Ref, Socket, Transport}) ->
    +	ok = ranch:accept_ack(Ref),
    +	ok = Transport:setopts(Socket, [{active, once}]),
    +	{noreply, State};
    +%% ...
    +
    -handle_info(timeout, State={state, Ref, Socket, Transport}) -> - ok = ranch:accept_ack(Ref), - ok = Transport:setopts(Socket, [{active, once}]), - {noreply, State}; -%% ...
    - - @@ -241,6 +210,8 @@ http://www.gnu.org/software/src-highlite --> +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.2/guide/ssl_auth/index.html b/docs/en/ranch/1.2/guide/ssl_auth/index.html index 498c719a..2a0d3b35 100644 --- a/docs/en/ranch/1.2/guide/ssl_auth/index.html +++ b/docs/en/ranch/1.2/guide/ssl_auth/index.html @@ -62,158 +62,82 @@

    SSL client authentication

    -

    Purpose

    -
    -

    SSL client authentication is a mechanism allowing applications to -identify certificates. This allows your application to make sure that -the client is an authorized certificate, but makes no claim about -whether the user can be trusted. This can be combined with a password -based authentication to attain greater security.

    -

    The server only needs to retain the certificate serial number and -the certificate issuer to authenticate the certificate. Together, -they can be used to uniquely identify a certicate.

    -

    As Ranch allows the same protocol code to be used for both SSL and -non-SSL transports, you need to make sure you are in an SSL context -before attempting to perform an SSL client authentication. This -can be done by checking the return value of Transport:name/0.

    -
    -
    -
    +

    SSL client authentication is a mechanism allowing applications to identify certificates. This allows your application to make sure that the client is an authorized certificate, but makes no claim about whether the user can be trusted. This can be combined with a password based authentication to attain greater security.

    +

    The server only needs to retain the certificate serial number and the certificate issuer to authenticate the certificate. Together, they can be used to uniquely identify a certicate.

    +

    As Ranch allows the same protocol code to be used for both SSL and non-SSL transports, you need to make sure you are in an SSL context before attempting to perform an SSL client authentication. This can be done by checking the return value of Transport:name/0.

    Obtaining client certificates

    -
    -

    You can obtain client certificates from various sources. You can -generate them yourself, or you can use a service like CAcert.org -which allows you to generate client and server certificates for -free.

    -

    Following are the steps you need to take to create a CAcert.org -account, generate a certificate and install it in your favorite -browser.

    -
      -
    • -

      -Open [CAcert.org](http://cacert.org) in your favorite browser -

      +

      You can obtain client certificates from various sources. You can generate them yourself, or you can use a service like CAcert.org which allows you to generate client and server certificates for free.

      +

      Following are the steps you need to take to create a CAcert.org account, generate a certificate and install it in your favorite browser.

      +
      • Open [CAcert.org](http://cacert.org) in your favorite browser
      • -
      • -

        -Root Certificate link: install both certificates -

        +
      • Root Certificate link: install both certificates
      • -
      • -

        -Join (Register an account) -

        +
      • Join (Register an account)
      • -
      • -

        -Verify your account (check your email inbox!) -

        +
      • Verify your account (check your email inbox!)
      • -
      • -

        -Log in -

        +
      • Log in
      • -
      • -

        -Client Certificates: New -

        +
      • Client Certificates: New
      • -
      • -

        -Follow instructions to create the certificate -

        +
      • Follow instructions to create the certificate
      • -
      • -

        -Install the certificate in your browser -

        +
      • Install the certificate in your browser
      • -
    -

    You can optionally save the certificate for later use, for example -to extract the IssuerID information as will be detailed later on.

    -
    -
    -
    + +

    You can optionally save the certificate for later use, for example to extract the IssuerID information as will be detailed later on.

    Transport configuration

    -
    -

    The SSL transport does not request a client certificate by default. -You need to specify the {verify, verify_peer} option when starting -the listener to enable this behavior.

    -
    -
    Configure a listener for SSL authentication
    -
    -
    {ok, _} = ranch:start_listener(my_ssl, 100,
    -        ranch_ssl, [
    -                {port, SSLPort},
    -                {certfile, PathToCertfile},
    -                {cacertfile, PathToCACertfile},
    -                {verify, verify_peer}
    -        ],
    -        my_protocol, []
    -).
    -

    In this example we set the required port and certfile, but also -the cacertfile containing the CACert.org root certificate, and -the option to request the client certificate.

    -

    If you enable the {verify, verify_peer} option and the client does -not have a client certificate configured for your domain, then no -certificate will be sent. This allows you to use SSL for more than -just authenticated clients.

    -
    -
    -
    +
    {ok, _} = ranch:start_listener(my_ssl, 100,
    +	ranch_ssl, [
    +		{port, SSLPort},
    +		{certfile, PathToCertfile},
    +		{cacertfile, PathToCACertfile},
    +		{verify, verify_peer}
    +	],
    +	my_protocol, []
    +).
    +
    +

    In this example we set the required port and certfile, but also the cacertfile containing the CACert.org root certificate, and the option to request the client certificate.

    +

    If you enable the {verify, verify_peer} option and the client does not have a client certificate configured for your domain, then no certificate will be sent. This allows you to use SSL for more than just authenticated clients.

    Authentication

    -
    -

    To authenticate users, you must first save the certificate information -required. If you have your users' certificate files, you can simply -load the certificate and retrieve the information directly.

    -
    -
    Retrieve the issuer ID from a certificate
    -
    -
    certfile_to_issuer_id(Filename) ->
    -        {ok, Data} = file:read_file(Filename),
    -        [{'Certificate', Cert, not_encrypted}] = public_key:pem_decode(Data),
    -        {ok, IssuerID} = public_key:pkix_issuer_id(Cert, self),
    -        IssuerID.
    -

    The IssuerID variable contains both the certificate serial number -and the certificate issuer stored in a tuple, so this value alone can -be used to uniquely identify the user certificate. You can save this -value in a database, a configuration file or any other place where an -Erlang term can be stored and retrieved.

    -

    To retrieve the IssuerID from a running connection, you need to first -retrieve the client certificate and then extract this information from -it. Ranch does not provide a function to retrieve the client certificate. -Instead you can use the ssl:peercert/1 function. Once you have the -certificate, you can again use the public_key:pkix_issuer_id/2 to -extract the IssuerID value.

    -

    The following function returns the IssuerID or false if no client -certificate was found. This snippet is intended to be used from your -protocol code.

    -
    -
    Retrieve the issuer ID from the certificate for the current connection
    -
    -
    socket_to_issuer_id(Socket) ->
    -        case ssl:peercert(Socket) of
    -                {error, no_peercert} ->
    -                        false;
    -                {ok, Cert} ->
    -                        {ok, IssuerID} = public_key:pkix_issuer_id(Cert, self),
    -                        IssuerID
    -        end.
    -

    You then only need to match the IssuerID value to authenticate the -user.

    -
    - +
    socket_to_issuer_id(Socket) ->
    +	case ssl:peercert(Socket) of
    +		{error, no_peercert} ->
    +			false;
    +		{ok, Cert} ->
    +			{ok, IssuerID} = public_key:pkix_issuer_id(Cert, self),
    +			IssuerID
    +	end.
    + +

    You then only need to match the IssuerID value to authenticate the user.

    + @@ -270,6 +194,8 @@ user.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.2/guide/transports/index.html b/docs/en/ranch/1.2/guide/transports/index.html index 91e2d4d6..3ced83c7 100644 --- a/docs/en/ranch/1.2/guide/transports/index.html +++ b/docs/en/ranch/1.2/guide/transports/index.html @@ -62,189 +62,114 @@

    Transports

    -

    A transport defines the interface to interact with a socket.

    -

    Transports can be used for connecting, listening and accepting -connections, but also for receiving and sending data. Both -passive and active mode are supported, although all sockets -are initialized as passive.

    -
    +

    A transport defines the interface to interact with a socket.

    +

    Transports can be used for connecting, listening and accepting connections, but also for receiving and sending data. Both passive and active mode are supported, although all sockets are initialized as passive.

    TCP transport

    -
    -

    The TCP transport is a thin wrapper around gen_tcp.

    -
    -
    -
    +

    The TCP transport is a thin wrapper around gen_tcp.

    SSL transport

    -
    -

    The SSL transport is a thin wrapper around ssl. It requires -the crypto, asn1, public_key and ssl applications -to be started. When starting an SSL listener, Ranch will attempt -to automatically start them. It will not try to stop them when -the listener is removed, however.

    -
    -
    Starting the SSL application
    -
    -
    ssl:start().
    -

    In a proper OTP setting, you will need to make your application -depend on the crypto, public_key and ssl applications. -They will be started automatically when starting your release.

    -

    The SSL transport accept/2 function performs both transport -and SSL accepts. Errors occurring during the SSL accept phase -are returned as {error, {ssl_accept, atom()}} to differentiate -on which socket the problem occurred.

    -
    -
    -
    +
    ssl:start().
    +
    +

    In a proper OTP setting, you will need to make your application depend on the crypto, public_key and ssl applications. They will be started automatically when starting your release.

    +

    The SSL transport accept/2 function performs both transport and SSL accepts. Errors occurring during the SSL accept phase are returned as {error, {ssl_accept, atom()}} to differentiate on which socket the problem occurred.

    Sending and receiving data

    -
    -

    This section assumes that Transport is a valid transport handler -(like ranch_tcp or ranch_ssl) and Socket is a connected -socket obtained through the listener.

    -

    You can send data to a socket by calling the Transport:send/2 -function. The data can be given as iodata(), which is defined as -binary() | iolist(). All the following calls will work:

    -
    -
    Sending data to the socket
    -
    -
    Transport:send(Socket, <<"Ranch is cool!">>).
    -Transport:send(Socket, "Ranch is cool!").
    -Transport:send(Socket, ["Ranch", ["is", "cool!"]]).
    -Transport:send(Socket, ["Ranch", [<<"is">>, "cool!"]]).
    -

    You can receive data either in passive or in active mode. Passive mode -means that you will perform a blocking Transport:recv/3 call, while -active mode means that you will receive the data as a message.

    -

    By default, all data will be received as binary. It is possible to -receive data as strings, although this is not recommended as binaries -are a more efficient construct, especially for binary protocols.

    -

    Receiving data using passive mode requires a single function call. The -first argument is the socket, and the third argument is a timeout duration -before the call returns with {error, timeout}.

    -

    The second argument is the amount of data in bytes that we want to receive. -The function will wait for data until it has received exactly this amount. -If you are not expecting a precise size, you can specify 0 which will make -this call return as soon as data was read, regardless of its size.

    -
    -
    Receiving data from the socket in passive mode
    -
    -
    {ok, Data} = Transport:recv(Socket, 0, 5000).
    -

    Active mode requires you to inform the socket that you want to receive -data as a message and to write the code to actually receive it.

    -

    There are two kinds of active modes: {active, once} and -{active, true}. The first will send a single message before going -back to passive mode; the second will send messages indefinitely. -We recommend not using the {active, true} mode as it could quickly -flood your process mailbox. It’s better to keep the data in the socket -and read it only when required.

    -

    Three different messages can be received:

    -
      -
    • -

      -{OK, Socket, Data} -

      +
      {ok, Data} = Transport:recv(Socket, 0, 5000).
      +
    +

    Active mode requires you to inform the socket that you want to receive data as a message and to write the code to actually receive it.

    +

    There are two kinds of active modes: {active, once} and {active, true}. The first will send a single message before going back to passive mode; the second will send messages indefinitely. We recommend not using the {active, true} mode as it could quickly flood your process mailbox. It's better to keep the data in the socket and read it only when required.

    +

    Three different messages can be received:

    +
    • {OK, Socket, Data}
    • -
    • -

      -{Closed, Socket} -

      +
    • {Closed, Socket}
    • -
    • -

      -{Error, Socket, Reason} -

      +
    • {Error, Socket, Reason}
    • -
    -

    The value of OK, Closed and Error can be different -depending on the transport being used. To be able to properly match -on them you must first call the Transport:messages/0 function.

    -
    -
    Retrieving the transport’s active message identifiers
    -
    -
    {OK, Closed, Error} = Transport:messages().
    -

    To start receiving messages you will need to call the Transport:setopts/2 -function, and do so every time you want to receive data.

    -
    -
    Receiving messages from the socket in active mode
    -
    -
    {OK, Closed, Error} = Transport:messages(),
    -Transport:setopts(Socket, [{active, once}]),
    -receive
    -        {OK, Socket, Data} ->
    -                io:format("data received: ~p~n", [Data]);
    -        {Closed, Socket} ->
    -                io:format("socket got closed!~n");
    -        {Error, Socket, Reason} ->
    -                io:format("error happened: ~p~n", [Reason])
    -end.
    -

    You can easily integrate active sockets with existing Erlang code as all -you really need is just a few more clauses when receiving messages.

    - - -
    +
    {OK, Closed, Error} = Transport:messages(),
    +Transport:setopts(Socket, [{active, once}]),
    +receive
    +	{OK, Socket, Data} ->
    +		io:format("data received: ~p~n", [Data]);
    +	{Closed, Socket} ->
    +		io:format("socket got closed!~n");
    +	{Error, Socket, Reason} ->
    +		io:format("error happened: ~p~n", [Reason])
    +end.
    +
    +

    You can easily integrate active sockets with existing Erlang code as all you really need is just a few more clauses when receiving messages.

    Sending files

    -
    -

    As in the previous section it is assumed Transport is a valid transport -handler and Socket is a connected socket obtained through the listener.

    -

    To send a whole file, with name Filename, over a socket:

    -
    -
    Sending a file by filename
    -
    -
    {ok, SentBytes} = Transport:sendfile(Socket, Filename).
    -

    Or part of a file, with Offset greater than or equal to 0, Bytes number of -bytes and chunks of size ChunkSize:

    -
    -
    Sending part of a file by filename in chunks
    -
    -
    Opts = [{chunk_size, ChunkSize}],
    -{ok, SentBytes} = Transport:sendfile(Socket, Filename, Offset, Bytes, Opts).
    -

    To improve efficiency when sending multiple parts of the same file it is also -possible to use a file descriptor opened in raw mode:

    -
    -
    Sending a file opened in raw mode
    -
    -
    {ok, RawFile} = file:open(Filename, [raw, read, binary]),
    -{ok, SentBytes} = Transport:sendfile(Socket, RawFile, Offset, Bytes, Opts).
    -
    - -
    +
    {ok, RawFile} = file:open(Filename, [raw, read, binary]),
    +{ok, SentBytes} = Transport:sendfile(Socket, RawFile, Offset, Bytes, Opts).
    +

    Writing a transport handler

    -
    -

    A transport handler is a module implementing the ranch_transport behavior. -It defines a certain number of callbacks that must be written in order to -allow transparent usage of the transport handler.

    -

    The behavior doesn’t define the socket options available when opening a -socket. These do not need to be common to all transports as it’s easy enough -to write different initialization functions for the different transports that -will be used. With one exception though. The setopts/2 function must -implement the {active, once} and the {active, true} options.

    -

    If the transport handler doesn’t have a native implementation of sendfile/5 a -fallback is available, ranch_transport:sendfile/6. The extra first argument -is the transport’s module. See ranch_ssl for an example.

    -
    - +

    A transport handler is a module implementing the ranch_transport behavior. It defines a certain number of callbacks that must be written in order to allow transparent usage of the transport handler.

    +

    The behavior doesn't define the socket options available when opening a socket. These do not need to be common to all transports as it's easy enough to write different initialization functions for the different transports that will be used. With one exception though. The setopts/2 function must implement the {active, once} and the {active, true} options.

    +

    If the transport handler doesn't have a native implementation of sendfile/5 a fallback is available, ranch_transport:sendfile/6. The extra first argument is the transport's module. See ranch_ssl for an example.

    + @@ -301,6 +226,8 @@ is the transport’s module. See ranch_ssl for an example.

    < +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.2/manual/index.html b/docs/en/ranch/1.2/manual/index.html index 4d379ce7..91c0a3c5 100644 --- a/docs/en/ranch/1.2/manual/index.html +++ b/docs/en/ranch/1.2/manual/index.html @@ -62,38 +62,20 @@

    Ranch Function Reference

    - + + @@ -128,6 +110,8 @@ +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.2/manual/ranch/index.html b/docs/en/ranch/1.2/manual/ranch/index.html index 3c45e2f2..edbdb353 100644 --- a/docs/en/ranch/1.2/manual/ranch/index.html +++ b/docs/en/ranch/1.2/manual/ranch/index.html @@ -62,423 +62,175 @@

    ranch(3)

    -

    Name

    -
    -

    ranch - socket acceptor pool

    -
    -
    -
    +

    ranch - socket acceptor pool

    Description

    -
    -

    The ranch module provides functions for starting and -manipulating Ranch listeners.

    -
    -
    -
    +

    The ranch module provides functions for starting and manipulating Ranch listeners.

    Types

    -
    -
    -

    max_conns() = non_neg_integer() | infinity

    -

    Maximum number of connections allowed on this listener.

    -

    This is a soft limit. The actual number of connections -might be slightly above the limit due to concurrency -when accepting new connections. Some connections may -also be removed from this count explicitly by the user -code.

    -
    -
    +

    max_conns() = non_neg_integer() | infinity

    +

    Maximum number of connections allowed on this listener.

    +

    This is a soft limit. The actual number of connections might be slightly above the limit due to concurrency when accepting new connections. Some connections may also be removed from this count explicitly by the user code.

    opt()

    -
    -
    -
    opt() = {ack_timeout, timeout()}
    -        | {connection_type, worker | supervisor}
    -        | {max_connections, max_conns()}
    -        | {shutdown, timeout() | brutal_kill}
    -        | {socket, any()}
    -

    Ranch-specific transport options.

    -

    These options are not passed on to the transports. -They are used by Ranch while setting up the listeners.

    -
    -
    -

    ref() = any()

    -

    Unique name used to refer to a listener.

    -
    -
    -
    -
    +
    opt() = {ack_timeout, timeout()}
    +	| {connection_type, worker | supervisor}
    +	| {max_connections, max_conns()}
    +	| {shutdown, timeout() | brutal_kill}
    +	| {socket, any()}
    +
    +

    Ranch-specific transport options.

    +

    These options are not passed on to the transports. They are used by Ranch while setting up the listeners.

    +

    ref() = any()

    +

    Unique name used to refer to a listener.

    Option descriptions

    -
    -

    None of the options are required.

    -
    -
    -ack_timeout (5000) -
    -
    -

    - Maximum allowed time for the ranch:accept_ack/1 call to finish. -

    -
    -
    -connection_type (worker) -
    -
    -

    - Type of process that will handle the connection. -

    -
    -
    -max_connections (1024) -
    -
    -

    - Maximum number of active connections. Soft limit. Using infinity will disable the limit entirely. -

    -
    -
    -shutdown (5000) -
    -
    -

    - Maximum allowed time for children to stop on listener shutdown. -

    -
    -
    -socket -
    -
    -

    - Listening socket opened externally to be used instead of calling Transport:listen/1. -

    -
    -
    -
    - -
    +

    None of the options are required.

    +
    ack_timeout (5000)
    +

    Maximum allowed time for the ranch:accept_ack/1 call to finish.

    +
    +
    connection_type (worker)
    +

    Type of process that will handle the connection.

    +
    +
    max_connections (1024)
    +

    Maximum number of active connections. Soft limit. Using infinity will disable the limit entirely.

    +
    +
    shutdown (5000)
    +

    Maximum allowed time for children to stop on listener shutdown.

    +
    +
    socket
    +

    Listening socket opened externally to be used instead of calling Transport:listen/1.

    +
    +

    Exports

    -
    -
    -

    accept_ack(Ref) → ok

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -

    Acknowledge that the connection is accepted.

    -

    This function MUST be used by a connection process to inform -Ranch that it initialized properly and let it perform any -additional operations before the socket can be safely used.

    -
    -
    -

    child_spec(Ref, NbAcceptors, Transport, TransOpts, Protocol, ProtoOpts) → supervisor:child_spec()

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -NbAcceptors = non_neg_integer() -
    -
    -

    -Number of acceptor processes. -

    -
    -
    -Transport = module() -
    -
    -

    -Transport module. -

    -
    -
    -TransOpts = any() -
    -
    -

    -Transport options. -

    -
    -
    -Protocol = module() -
    -
    -

    -Protocol module. -

    -
    -
    -ProtoOpts = any() -
    -
    -

    -Protocol options. -

    -
    -
    -

    Return child specifications for a new listener.

    -

    This function can be used to embed a listener directly -in an application instead of letting Ranch handle it.

    -
    -
    -

    get_addr(Ref) → {IP, Port}

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -IP = inet:ip_address() -
    -
    -

    -IP of the interface used by this listener. -

    -
    -
    -Port = inet:port_number() -
    -
    -

    -Port number used by this listener. -

    -
    -
    -

    Return the IP address and port for the given listener.

    -
    -
    -

    get_max_connections(Ref) → MaxConns

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -MaxConns = max_conns() -
    -
    -

    -Current maximum number of connections. -

    -
    -
    -

    Return the max number of connections allowed for the given listener.

    -
    -
    -

    get_port(Ref) → Port

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -Port = inet:port_number() -
    -
    -

    -Port number used by this listener. -

    -
    -
    -

    Return the port for the given listener.

    -
    -
    -

    get_protocol_options(Ref) → ProtoOpts

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -ProtoOpts = any() -
    -
    -

    -Current protocol options. -

    -
    -
    -

    Return the protocol options set for the given listener.

    -
    -
    -

    remove_connection(Ref) → ok

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -

    Do not count this connection when limiting the number of connections.

    -

    You can use this function for long-running connection processes -which spend most of their time idling rather than consuming -resources. This allows Ranch to accept a lot more connections -without sacrificing the latency of the system.

    -

    This function may only be called from a connection process.

    -
    -
    -

    set_max_connections(Ref, MaxConns) → ok

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -MaxConns = max_conns() -
    -
    -

    -New maximum number of connections. -

    -
    -
    -

    Set the max number of connections for the given listener.

    -

    The change will be applied immediately. If the new value is -smaller than the previous one, Ranch will not kill the extra -connections, but will wait for them to terminate properly.

    -
    -
    -

    set_protocol_options(Ref, ProtoOpts) → ok

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -ProtoOpts = any() -
    -
    -

    -New protocol options. -

    -
    -
    -

    Set the protocol options for the given listener.

    -

    The change will be applied immediately for all new connections. -Old connections will not receive the new options.

    -
    -
    -

    start_listener(Ref, NbAcceptors, Transport, TransOpts, Protocol, ProtoOpts) → {ok, pid()} | {error, badarg}

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -NbAcceptors = non_neg_integer() -
    -
    -

    -Number of acceptor processes. -

    -
    -
    -Transport = module() -
    -
    -

    -Transport module. -

    -
    -
    -TransOpts = any() -
    -
    -

    -Transport options. -

    -
    -
    -Protocol = module() -
    -
    -

    -Protocol module. -

    -
    -
    -ProtoOpts = any() -
    -
    -

    -Protocol options. -

    -
    -
    -

    Start listening for connections using the given transport -and protocol. Returns the pid for this listener’s supervisor.

    -

    There are additional transport options that apply -regardless of transport. They allow configuring how the -connections are supervised, rate limited and more. Please -consult the previous section for more details.

    -
    -
    -

    stop_listener(Ref) → ok | {error, not_found}

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -

    Stop the given listener.

    -

    The listener is stopped gracefully, first by closing the -listening port, then by stopping the connection processes. -These processes are stopped according to the shutdown -transport option, which may be set to brutally kill all -connection processes or give them some time to stop properly.

    -

    This function does not return until the listener is -completely stopped.

    -
    -
    -
    +

    accept_ack(Ref) -> ok

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    +

    Acknowledge that the connection is accepted.

    +

    This function MUST be used by a connection process to inform Ranch that it initialized properly and let it perform any additional operations before the socket can be safely used.

    +

    child_spec(Ref, NbAcceptors, Transport, TransOpts, Protocol, ProtoOpts) -> supervisor:child_spec()

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    NbAcceptors = non_neg_integer()
    +

    Number of acceptor processes.

    +
    +
    Transport = module()
    +

    Transport module.

    +
    +
    TransOpts = any()
    +

    Transport options.

    +
    +
    Protocol = module()
    +

    Protocol module.

    +
    +
    ProtoOpts = any()
    +

    Protocol options.

    +
    +
    +

    Return child specifications for a new listener.

    +

    This function can be used to embed a listener directly in an application instead of letting Ranch handle it.

    +

    get_addr(Ref) -> {IP, Port}

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    IP = inet:ip_address()
    +

    IP of the interface used by this listener.

    +
    +
    Port = inet:port_number()
    +

    Port number used by this listener.

    +
    +
    +

    Return the IP address and port for the given listener.

    +

    get_max_connections(Ref) -> MaxConns

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    MaxConns = max_conns()
    +

    Current maximum number of connections.

    +
    +
    +

    Return the max number of connections allowed for the given listener.

    +

    get_port(Ref) -> Port

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    Port = inet:port_number()
    +

    Port number used by this listener.

    +
    +
    +

    Return the port for the given listener.

    +

    get_protocol_options(Ref) -> ProtoOpts

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    ProtoOpts = any()
    +

    Current protocol options.

    +
    +
    +

    Return the protocol options set for the given listener.

    +

    remove_connection(Ref) -> ok

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    +

    Do not count this connection when limiting the number of connections.

    +

    You can use this function for long-running connection processes which spend most of their time idling rather than consuming resources. This allows Ranch to accept a lot more connections without sacrificing the latency of the system.

    +

    This function may only be called from a connection process.

    +

    set_max_connections(Ref, MaxConns) -> ok

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    MaxConns = max_conns()
    +

    New maximum number of connections.

    +
    +
    +

    Set the max number of connections for the given listener.

    +

    The change will be applied immediately. If the new value is smaller than the previous one, Ranch will not kill the extra connections, but will wait for them to terminate properly.

    +

    set_protocol_options(Ref, ProtoOpts) -> ok

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    ProtoOpts = any()
    +

    New protocol options.

    +
    +
    +

    Set the protocol options for the given listener.

    +

    The change will be applied immediately for all new connections. Old connections will not receive the new options.

    +

    start_listener(Ref, NbAcceptors, Transport, TransOpts, Protocol, ProtoOpts) -> {ok, pid()} | {error, badarg}

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    NbAcceptors = non_neg_integer()
    +

    Number of acceptor processes.

    +
    +
    Transport = module()
    +

    Transport module.

    +
    +
    TransOpts = any()
    +

    Transport options.

    +
    +
    Protocol = module()
    +

    Protocol module.

    +
    +
    ProtoOpts = any()
    +

    Protocol options.

    +
    +
    +

    Start listening for connections using the given transport and protocol. Returns the pid for this listener's supervisor.

    +

    There are additional transport options that apply regardless of transport. They allow configuring how the connections are supervised, rate limited and more. Please consult the previous section for more details.

    +

    stop_listener(Ref) -> ok | {error, not_found}

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    +

    Stop the given listener.

    +

    The listener is stopped gracefully, first by closing the listening port, then by stopping the connection processes. These processes are stopped according to the shutdown transport option, which may be set to brutally kill all connection processes or give them some time to stop properly.

    +

    This function does not return until the listener is completely stopped.

    + @@ -513,6 +265,8 @@ completely stopped.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.2/manual/ranch_app/index.html b/docs/en/ranch/1.2/manual/ranch_app/index.html index 4e5e609c..fc27d096 100644 --- a/docs/en/ranch/1.2/manual/ranch_app/index.html +++ b/docs/en/ranch/1.2/manual/ranch_app/index.html @@ -62,43 +62,19 @@

    ranch(7)

    -

    Name

    -
    -

    ranch - Socket acceptor pool for TCP protocols.

    -
    -
    -
    +

    ranch - Socket acceptor pool for TCP protocols.

    Dependencies

    -
    -

    The ranch application has no particular dependency required -to start.

    -

    It has optional dependencies that are only required when -listening for SSL connections. The dependencies are crypto, -asn1, public_key and ssl. They are started automatically -if they weren’t before.

    -
    -
    -
    +

    The ranch application has no particular dependency required to start.

    +

    It has optional dependencies that are only required when listening for SSL connections. The dependencies are crypto, asn1, public_key and ssl. They are started automatically if they weren't before.

    Environment

    -
    -

    The ranch application defines one application environment -configuration parameter.

    -
    -
    -profile (false) -
    -
    -

    - When enabled, Ranch will start eprof profiling automatically. -

    +

    The ranch application defines one application environment configuration parameter.

    +
    profile (false)
    +

    When enabled, Ranch will start eprof profiling automatically.

    -
    -

    You can use the ranch_app:profile_output/0 function to stop -profiling and output the results to the files procs.profile -and total.profile. Do not use in production.

    -
    -
    + +

    You can use the ranch_app:profile_output/0 function to stop profiling and output the results to the files procs.profile and total.profile. Do not use in production.

    + @@ -133,6 +109,8 @@ and total.profile. Do not use in production.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.2/manual/ranch_protocol/index.html b/docs/en/ranch/1.2/manual/ranch_protocol/index.html index 1b145f30..d548e5ca 100644 --- a/docs/en/ranch/1.2/manual/ranch_protocol/index.html +++ b/docs/en/ranch/1.2/manual/ranch_protocol/index.html @@ -62,83 +62,33 @@

    ranch_protocol(3)

    -

    Name

    -
    -

    ranch_protocol - behaviour for protocol modules

    -
    -
    -
    +

    ranch_protocol - behaviour for protocol modules

    Description

    -
    -

    The ranch_protocol behaviour defines the interface used -by Ranch protocols.

    -
    -
    -
    +

    The ranch_protocol behaviour defines the interface used by Ranch protocols.

    Types

    -
    -

    None.

    -
    -
    -
    +

    None.

    Callbacks

    -
    -
    - -
    -
    -Ref = ranch:ref() -
    -
    -

    -Listener name. -

    + +
    Ref = ranch:ref()
    +

    Listener name.

    -
    -Socket = any() -
    -
    -

    -Socket for this connection. -

    +
    Socket = any()
    +

    Socket for this connection.

    -
    -Transport = module() -
    -
    -

    -Transport module for this socket. -

    +
    Transport = module()
    +

    Transport module for this socket.

    -
    -ProtoOpts = any() -
    -
    -

    -Protocol options. -

    +
    ProtoOpts = any()
    +

    Protocol options.

    -
    -

    Start a new connection process for the given socket.

    -

    The only purpose of this callback is to start a process that -will handle the socket. It must spawn the process, link and -then return the new pid. This function will always be called -from inside a supervisor.

    -

    This callback can also return two pids. The first pid is the -pid of the process that will be supervised. The second pid is -the pid of the process that will receive ownership of the -socket. This second process must be a child of the first. This -form is only available when connection_type is set to -supervisor.

    -

    If any other value is returned, the supervisor will close the -socket and assume no process has been started.

    -

    Do not perform any operations in this callback, as this would -block the supervisor responsible for starting connection -processes and degrade performance severely.

    -
    -
    -
    + +

    Start a new connection process for the given socket.

    +

    The only purpose of this callback is to start a process that will handle the socket. It must spawn the process, link and then return the new pid. This function will always be called from inside a supervisor.

    +

    This callback can also return two pids. The first pid is the pid of the process that will be supervised. The second pid is the pid of the process that will receive ownership of the socket. This second process must be a child of the first. This form is only available when connection_type is set to supervisor.

    +

    If any other value is returned, the supervisor will close the socket and assume no process has been started.

    +

    Do not perform any operations in this callback, as this would block the supervisor responsible for starting connection processes and degrade performance severely.

    + @@ -173,6 +123,8 @@ processes and degrade performance severely.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.2/manual/ranch_ssl/index.html b/docs/en/ranch/1.2/manual/ranch_ssl/index.html index f310db81..7ea56fa3 100644 --- a/docs/en/ranch/1.2/manual/ranch_ssl/index.html +++ b/docs/en/ranch/1.2/manual/ranch_ssl/index.html @@ -62,349 +62,158 @@

    ranch_ssl(3)

    -

    Name

    -
    -

    ranch_ssl - SSL transport module

    -
    -
    -
    +

    ranch_ssl - SSL transport module

    Description

    -
    -

    The ranch_ssl module implements an SSL Ranch transport.

    -
    -
    -
    +

    The ranch_ssl module implements an SSL Ranch transport.

    Types

    -
    -

    ssl_opt()

    -
    -
    -
    ssl_opt() = {alpn_preferred_protocols, [binary()]}
    -        | {cacertfile, string()}
    -        | {cacerts, [public_key:der_encoded()]}
    -        | {cert, public_key:der_encoded()}
    -        | {certfile, string()}
    -        | {ciphers, [ssl:erl_cipher_suite()] | string()}
    -        | {client_renegotiation, boolean()}
    -        | {crl_cache, {module(), {internal | any(), list()}}}
    -        | {crl_check, boolean() | peer | best_effort}
    -        | {depth, 0..255}
    -        | {dh, public_key:der_encoded()}
    -        | {dhfile, string()}
    -        | {fail_if_no_peer_cert, boolean()}
    -        | {hibernate_after, integer() | undefined}
    -        | {honor_cipher_order, boolean()}
    -        | {key, {'RSAPrivateKey' | 'DSAPrivateKey' | 'PrivateKeyInfo', public_key:der_encoded()}}
    -        | {keyfile, string()}
    -        | {log_alert, boolean()}
    -        | {next_protocols_advertised, [binary()]}
    -        | {partial_chain, fun(([public_key:der_encoded()]) -> {trusted_ca, public_key:der_encoded()} | unknown_ca)}
    -        | {password, string()}
    -        | {psk_identity, string()}
    -        | {reuse_session, fun()}
    -        | {reuse_sessions, boolean()}
    -        | {secure_renegotiate, boolean()}
    -        | {sni_fun, fun()}
    -        | {sni_hosts, [{string(), ssl_opt()}]}
    -        | {user_lookup_fun, {fun(), any()}}
    -        | {verify, ssl:verify_type()}
    -        | {verify_fun, {fun(), any()}}
    -        | {versions, [atom()]}.
    -

    SSL-specific listen options.

    -
    -
    -

    opt() = ranch_tcp:opt() | ssl_opt()

    -

    Listen options.

    -
    -
    -

    opts() = [opt()]

    -

    List of listen options.

    -
    -
    -
    -
    +
    ssl_opt() = {alpn_preferred_protocols, [binary()]}
    +	| {cacertfile, string()}
    +	| {cacerts, [public_key:der_encoded()]}
    +	| {cert, public_key:der_encoded()}
    +	| {certfile, string()}
    +	| {ciphers, [ssl:erl_cipher_suite()] | string()}
    +	| {client_renegotiation, boolean()}
    +	| {crl_cache, {module(), {internal | any(), list()}}}
    +	| {crl_check, boolean() | peer | best_effort}
    +	| {depth, 0..255}
    +	| {dh, public_key:der_encoded()}
    +	| {dhfile, string()}
    +	| {fail_if_no_peer_cert, boolean()}
    +	| {hibernate_after, integer() | undefined}
    +	| {honor_cipher_order, boolean()}
    +	| {key, {'RSAPrivateKey' | 'DSAPrivateKey' | 'PrivateKeyInfo', public_key:der_encoded()}}
    +	| {keyfile, string()}
    +	| {log_alert, boolean()}
    +	| {next_protocols_advertised, [binary()]}
    +	| {partial_chain, fun(([public_key:der_encoded()]) -> {trusted_ca, public_key:der_encoded()} | unknown_ca)}
    +	| {password, string()}
    +	| {psk_identity, string()}
    +	| {reuse_session, fun()}
    +	| {reuse_sessions, boolean()}
    +	| {secure_renegotiate, boolean()}
    +	| {sni_fun, fun()}
    +	| {sni_hosts, [{string(), ssl_opt()}]}
    +	| {user_lookup_fun, {fun(), any()}}
    +	| {verify, ssl:verify_type()}
    +	| {verify_fun, {fun(), any()}}
    +	| {versions, [atom()]}.
    +
    +

    SSL-specific listen options.

    +

    opt() = ranch_tcp:opt() | ssl_opt()

    +

    Listen options.

    +

    opts() = [opt()]

    +

    List of listen options.

    Option descriptions

    -
    -

    Specifying a certificate is mandatory, either through the cert -or the certfile option. None of the other options are required.

    -

    The default value is given next to the option name.

    -
    -
    -alpn_preferred_protocols -
    -
    -

    - Perform Application-Layer Protocol Negotiation with the given list of preferred protocols. -

    -
    -
    -cacertfile -
    -
    -

    - Path to PEM encoded trusted certificates file used to verify peer certificates. -

    -
    -
    -cacerts -
    -
    -

    - List of DER encoded trusted certificates. -

    -
    -
    -cert -
    -
    -

    - DER encoded user certificate. -

    -
    -
    -certfile -
    -
    -

    - Path to the PEM encoded user certificate file. May also contain the private key. -

    -
    -
    -ciphers -
    -
    -

    - List of ciphers that clients are allowed to use. -

    -
    -
    -client_renegotiation (true) -
    -
    -

    - Whether to allow client-initiated renegotiation. -

    -
    -
    -crl_cache ({ssl_crl_cache, {internal, []}}) -
    -
    -

    - Customize the module used to cache Certificate Revocation Lists. -

    -
    -
    -crl_check (false) -
    -
    -

    - Whether to perform CRL check on all certificates in the chain during validation. -

    -
    -
    -depth (1) -
    -
    -

    - Maximum of intermediate certificates allowed in the certification path. -

    -
    -
    -dh -
    -
    -

    - DER encoded Diffie-Hellman parameters. -

    -
    -
    -dhfile -
    -
    -

    - Path to the PEM encoded Diffie-Hellman parameters file. -

    -
    -
    -fail_if_no_peer_cert (false) -
    -
    -

    - Whether to refuse the connection if the client sends an empty certificate. -

    -
    -
    -hibernate_after (undefined) -
    -
    -

    - Time in ms after which SSL socket processes go into hibernation to reduce memory usage. -

    -
    -
    -honor_cipher_order (false) -
    -
    -

    - If true, use the server’s preference for cipher selection. If false, use the client’s preference. -

    -
    -
    -key -
    -
    -

    - DER encoded user private key. -

    -
    -
    -keyfile -
    -
    -

    - Path to the PEM encoded private key file, if different than the certfile. -

    -
    -
    -log_alert (true) -
    -
    -

    - If false, error reports will not be displayed. -

    -
    -
    -next_protocols_advertised -
    -
    -

    - List of protocols to send to the client if it supports the Next Protocol extension. -

    -
    -
    -nodelay (true) -
    -
    -

    - Whether to enable TCP_NODELAY. -

    -
    -
    -partial_chain -
    -
    -

    - Claim an intermediate CA in the chain as trusted. -

    -
    -
    -password -
    -
    -

    - Password to the private key file, if password protected. -

    -
    -
    -psk_identity -
    -
    -

    - Provide the given PSK identity hint to the client during the handshake. -

    -
    -
    -reuse_session -
    -
    -

    - Custom policy to decide whether a session should be reused. -

    -
    -
    -reuse_sessions (false) -
    -
    -

    - Whether to allow session reuse. -

    -
    -
    -secure_renegotiate (false) -
    -
    -

    - Whether to reject renegotiation attempts that do not conform to RFC5746. -

    -
    -
    -sni_fun -
    -
    -

    - Function called when the client requests a host using Server Name Indication. Returns options to apply. -

    -
    -
    -sni_hosts -
    -
    -

    - Options to apply for the host that matches what the client requested with Server Name Indication. -

    -
    -
    -user_lookup_fun -
    -
    -

    - Function called to determine the shared secret when using PSK, or provide parameters when using SRP. -

    -
    -
    -verify (verify_none) -
    -
    -

    - Use verify_peer to request a certificate from the client. -

    -
    -
    -verify_fun -
    -
    -

    - Custom policy to decide whether a client certificate is valid. -

    -
    -
    -versions -
    -
    -

    - TLS protocol versions that will be supported. -

    -
    -
    -

    Note that the client will not send a certificate unless the -value for the verify option is set to verify_peer. This -means that the fail_if_no_peer_cert only apply when combined -with the verify option. The verify_fun option allows -greater control over the client certificate validation.

    -

    The options sni_fun and sni_hosts are mutually exclusive.

    -
    - -
    +

    Specifying a certificate is mandatory, either through the cert or the certfile option. None of the other options are required.

    +

    The default value is given next to the option name.

    +
    alpn_preferred_protocols
    +

    Perform Application-Layer Protocol Negotiation with the given list of preferred protocols.

    +
    +
    cacertfile
    +

    Path to PEM encoded trusted certificates file used to verify peer certificates.

    +
    +
    cacerts
    +

    List of DER encoded trusted certificates.

    +
    +
    cert
    +

    DER encoded user certificate.

    +
    +
    certfile
    +

    Path to the PEM encoded user certificate file. May also contain the private key.

    +
    +
    ciphers
    +

    List of ciphers that clients are allowed to use.

    +
    +
    client_renegotiation (true)
    +

    Whether to allow client-initiated renegotiation.

    +
    +
    crl_cache ({ssl_crl_cache, {internal, []}})
    +

    Customize the module used to cache Certificate Revocation Lists.

    +
    +
    crl_check (false)
    +

    Whether to perform CRL check on all certificates in the chain during validation.

    +
    +
    depth (1)
    +

    Maximum of intermediate certificates allowed in the certification path.

    +
    +
    dh
    +

    DER encoded Diffie-Hellman parameters.

    +
    +
    dhfile
    +

    Path to the PEM encoded Diffie-Hellman parameters file.

    +
    +
    fail_if_no_peer_cert (false)
    +

    Whether to refuse the connection if the client sends an empty certificate.

    +
    +
    hibernate_after (undefined)
    +

    Time in ms after which SSL socket processes go into hibernation to reduce memory usage.

    +
    +
    honor_cipher_order (false)
    +

    If true, use the server's preference for cipher selection. If false, use the client's preference.

    +
    +
    key
    +

    DER encoded user private key.

    +
    +
    keyfile
    +

    Path to the PEM encoded private key file, if different than the certfile.

    +
    +
    log_alert (true)
    +

    If false, error reports will not be displayed.

    +
    +
    next_protocols_advertised
    +

    List of protocols to send to the client if it supports the Next Protocol extension.

    +
    +
    nodelay (true)
    +

    Whether to enable TCP_NODELAY.

    +
    +
    partial_chain
    +

    Claim an intermediate CA in the chain as trusted.

    +
    +
    password
    +

    Password to the private key file, if password protected.

    +
    +
    psk_identity
    +

    Provide the given PSK identity hint to the client during the handshake.

    +
    +
    reuse_session
    +

    Custom policy to decide whether a session should be reused.

    +
    +
    reuse_sessions (false)
    +

    Whether to allow session reuse.

    +
    +
    secure_renegotiate (false)
    +

    Whether to reject renegotiation attempts that do not conform to RFC5746.

    +
    +
    sni_fun
    +

    Function called when the client requests a host using Server Name Indication. Returns options to apply.

    +
    +
    sni_hosts
    +

    Options to apply for the host that matches what the client requested with Server Name Indication.

    +
    +
    user_lookup_fun
    +

    Function called to determine the shared secret when using PSK, or provide parameters when using SRP.

    +
    +
    verify (verify_none)
    +

    Use verify_peer to request a certificate from the client.

    +
    +
    verify_fun
    +

    Custom policy to decide whether a client certificate is valid.

    +
    +
    versions
    +

    TLS protocol versions that will be supported.

    +
    +
    +

    Note that the client will not send a certificate unless the value for the verify option is set to verify_peer. This means that the fail_if_no_peer_cert only apply when combined with the verify option. The verify_fun option allows greater control over the client certificate validation.

    +

    The options sni_fun and sni_hosts are mutually exclusive.

    Exports

    -
    -

    None.

    -
    -
    +

    None.

    + @@ -439,6 +248,8 @@ greater control over the client certificate validation.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.2/manual/ranch_tcp/index.html b/docs/en/ranch/1.2/manual/ranch_tcp/index.html index 6e3f7c64..2218c203 100644 --- a/docs/en/ranch/1.2/manual/ranch_tcp/index.html +++ b/docs/en/ranch/1.2/manual/ranch_tcp/index.html @@ -62,274 +62,123 @@

    ranch_tcp(3)

    -

    Name

    -
    -

    ranch_tcp - TCP transport module

    -
    -
    -
    +

    ranch_tcp - TCP transport module

    Description

    -
    -

    The ranch_tcp module implements a TCP Ranch transport.

    -

    Note that due to bugs in OTP up to at least R16B02, it is -recommended to disable async threads when using the -sendfile function of this transport, as it can make -the threads stuck indefinitely.

    -
    -
    -
    +

    The ranch_tcp module implements a TCP Ranch transport.

    +

    Note that due to bugs in OTP up to at least R16B02, it is recommended to disable async threads when using the sendfile function of this transport, as it can make the threads stuck indefinitely.

    Types

    -
    -

    opt()

    -
    -
    -
    opt() = {backlog, non_neg_integer()}
    -        | {buffer, non_neg_integer()}
    -        | {delay_send, boolean()}
    -        | {dontroute, boolean()}
    -        | {exit_on_close, boolean()}
    -        | {fd, non_neg_integer()}
    -        | {high_msgq_watermark, non_neg_integer()}
    -        | {high_watermark, non_neg_integer()}
    -        | inet
    -        | inet6
    -        | {ip, inet:ip_address()}
    -        | {keepalive, boolean()}
    -        | {linger, {boolean(), non_neg_integer()}}
    -        | {low_msgq_watermark, non_neg_integer()}
    -        | {low_watermark, non_neg_integer()}
    -        | {nodelay, boolean()}
    -        | {port, inet:port_number()}
    -        | {priority, integer()}
    -        | {raw, non_neg_integer(), non_neg_integer(), binary()}
    -        | {recbuf, non_neg_integer()}
    -        | {send_timeout, timeout()}
    -        | {send_timeout_close, boolean()}
    -        | {sndbuf, non_neg_integer()}
    -        | {tos, integer()}
    -

    Listen options.

    -

    This does not represent the entirety of the options that can -be set on the socket, but only the options that may be -set independently of protocol implementation.

    -
    -
    -

    opts() = [opt()]

    -

    List of listen options.

    -
    -
    -
    -
    +
    opt() = {backlog, non_neg_integer()}
    +	| {buffer, non_neg_integer()}
    +	| {delay_send, boolean()}
    +	| {dontroute, boolean()}
    +	| {exit_on_close, boolean()}
    +	| {fd, non_neg_integer()}
    +	| {high_msgq_watermark, non_neg_integer()}
    +	| {high_watermark, non_neg_integer()}
    +	| inet
    +	| inet6
    +	| {ip, inet:ip_address()}
    +	| {keepalive, boolean()}
    +	| {linger, {boolean(), non_neg_integer()}}
    +	| {low_msgq_watermark, non_neg_integer()}
    +	| {low_watermark, non_neg_integer()}
    +	| {nodelay, boolean()}
    +	| {port, inet:port_number()}
    +	| {priority, integer()}
    +	| {raw, non_neg_integer(), non_neg_integer(), binary()}
    +	| {recbuf, non_neg_integer()}
    +	| {send_timeout, timeout()}
    +	| {send_timeout_close, boolean()}
    +	| {sndbuf, non_neg_integer()}
    +	| {tos, integer()}
    +
    +

    Listen options.

    +

    This does not represent the entirety of the options that can be set on the socket, but only the options that may be set independently of protocol implementation.

    +

    opts() = [opt()]

    +

    List of listen options.

    Option descriptions

    -
    -

    None of the options are required.

    -

    Please consult the gen_tcp and inet manuals for a more -thorough description of these options. This manual only aims -to provide a short description along with what the defaults -are. Defaults may be different in Ranch compared to gen_tcp. -Defaults are given next to the option name.

    -
    -
    -backlog (1024) -
    -
    -

    - Max length of the queue of pending connections. -

    +

    None of the options are required.

    +

    Please consult the gen_tcp and inet manuals for a more thorough description of these options. This manual only aims to provide a short description along with what the defaults are. Defaults may be different in Ranch compared to gen_tcp. Defaults are given next to the option name.

    +
    backlog (1024)
    +

    Max length of the queue of pending connections.

    -
    -buffer -
    -
    -

    - Size of the buffer used by the Erlang driver. Default is system-dependent. -

    +
    buffer
    +

    Size of the buffer used by the Erlang driver. Default is system-dependent.

    -
    -delay_send (false) -
    -
    -

    - Always queue packets before sending, to send fewer, larger packets over the network. -

    +
    delay_send (false)
    +

    Always queue packets before sending, to send fewer, larger packets over the network.

    -
    -dontroute (false) -
    -
    -

    - Don’t send via a gateway, only send to directly connected hosts. -

    +
    dontroute (false)
    +

    Don't send via a gateway, only send to directly connected hosts.

    -
    -exit_on_close (true) -
    -
    -

    - Disable to allow sending data after a close has been detected. -

    +
    exit_on_close (true)
    +

    Disable to allow sending data after a close has been detected.

    -
    -fd -
    -
    -

    - File descriptor of the socket, if it was opened externally. -

    +
    fd
    +

    File descriptor of the socket, if it was opened externally.

    -
    -high_msgq_watermark (8192) -
    -
    -

    - Limit in the amount of data in the socket message queue before the socket queue becomes busy. -

    +
    high_msgq_watermark (8192)
    +

    Limit in the amount of data in the socket message queue before the socket queue becomes busy.

    -
    -high_watermark (8192) -
    -
    -

    - Limit in the amount of data in the ERTS socket implementation’s queue before the socket becomes busy. -

    +
    high_watermark (8192)
    +

    Limit in the amount of data in the ERTS socket implementation's queue before the socket becomes busy.

    -
    -inet -
    -
    -

    - Set up the socket for IPv4. -

    +
    inet
    +

    Set up the socket for IPv4.

    -
    -inet6 -
    -
    -

    - Set up the socket for IPv6. -

    +
    inet6
    +

    Set up the socket for IPv6.

    -
    -ip -
    -
    -

    - Interface to listen on. Listen on all interfaces by default. -

    +
    ip
    +

    Interface to listen on. Listen on all interfaces by default.

    -
    -keepalive (false) -
    -
    -

    - Enable sending of keep-alive messages. -

    +
    keepalive (false)
    +

    Enable sending of keep-alive messages.

    -
    -linger ({false, 0}) -
    -
    -

    - Whether to wait and how long to flush data sent before closing the socket. -

    +
    linger ({false, 0})
    +

    Whether to wait and how long to flush data sent before closing the socket.

    -
    -low_msgq_watermark (4096) -
    -
    -

    - Amount of data in the socket message queue before the socket queue leaves busy state. -

    +
    low_msgq_watermark (4096)
    +

    Amount of data in the socket message queue before the socket queue leaves busy state.

    -
    -low_watermark (4096) -
    -
    -

    - Amount of data in the ERTS socket implementation’s queue before the socket leaves busy state. -

    +
    low_watermark (4096)
    +

    Amount of data in the ERTS socket implementation's queue before the socket leaves busy state.

    -
    -nodelay (true) -
    -
    -

    - Whether to enable TCP_NODELAY. -

    +
    nodelay (true)
    +

    Whether to enable TCP_NODELAY.

    -
    -port (0) -
    -
    -

    - TCP port number to listen on. 0 means a random port will be used. -

    +
    port (0)
    +

    TCP port number to listen on. 0 means a random port will be used.

    -
    -priority (0) -
    -
    -

    - Priority value for all packets to be sent by this socket. -

    +
    priority (0)
    +

    Priority value for all packets to be sent by this socket.

    -
    -recbuf -
    -
    -

    - Minimum size of the socket’s receive buffer. Default is system-dependent. -

    +
    recbuf
    +

    Minimum size of the socket's receive buffer. Default is system-dependent.

    -
    -send_timeout (30000) -
    -
    -

    - How long the send call may wait for confirmation before returning. -

    +
    send_timeout (30000)
    +

    How long the send call may wait for confirmation before returning.

    -
    -send_timeout_close (true) -
    -
    -

    - Whether to close the socket when the confirmation wasn’t received. -

    +
    send_timeout_close (true)
    +

    Whether to close the socket when the confirmation wasn't received.

    -
    -sndbuf -
    -
    -

    - Minimum size of the socket’s send buffer. Default is system-dependent. -

    +
    sndbuf
    +

    Minimum size of the socket's send buffer. Default is system-dependent.

    -
    -tos -
    -
    -

    - Value for the IP_TOS IP level option. Use with caution. -

    +
    tos
    +

    Value for the IP_TOS IP level option. Use with caution.

    -
    -

    In addition, the raw option can be used to set system-specific -options by specifying the protocol level, the option number and -the actual option value specified as a binary. This option is not -portable. Use with caution.

    -
    - -
    + +

    In addition, the raw option can be used to set system-specific options by specifying the protocol level, the option number and the actual option value specified as a binary. This option is not portable. Use with caution.

    Exports

    -
    -

    None.

    -
    -
    +

    None.

    + @@ -364,6 +213,8 @@ portable. Use with caution.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.2/manual/ranch_transport/index.html b/docs/en/ranch/1.2/manual/ranch_transport/index.html index c0c08417..f276197e 100644 --- a/docs/en/ranch/1.2/manual/ranch_transport/index.html +++ b/docs/en/ranch/1.2/manual/ranch_transport/index.html @@ -62,494 +62,198 @@

    ranch_transport(3)

    -

    Name

    -
    -

    ranch_transport - behaviour for transport modules

    -
    -
    -
    +

    ranch_transport - behaviour for transport modules

    Description

    -
    -

    The ranch_transport behaviour defines the interface used -by Ranch transports.

    -
    -
    -
    +

    The ranch_transport behaviour defines the interface used by Ranch transports.

    Types

    -
    -
    -

    sendfile_opts() = [{chunk_size, non_neg_integer()}]

    -

    Options used by the sendfile function and callbacks.

    -

    Allows configuring the chunk size, in bytes. Defaults to 8191 bytes.

    -
    -
    -
    -
    +

    sendfile_opts() = [{chunk_size, non_neg_integer()}]

    +

    Options used by the sendfile function and callbacks.

    +

    Allows configuring the chunk size, in bytes. Defaults to 8191 bytes.

    Callbacks

    -
    -
    -

    accept(LSocket, Timeout) → {ok, CSocket} | {error, closed | timeout | atom()}

    -
    -
    -LSocket = CSocket = any() -
    -
    -

    -Listening socket. -

    -
    -
    -Timeout = timeout() -
    -
    -

    -Accept timeout. -

    -
    -
    -

    Accept a connection on the given listening socket.

    -

    The accept_ack callback will be used to initialize the socket -after accepting the connection. This is most useful when the -transport is not raw TCP, like with SSL for example.

    -
    -
    -

    accept_ack(CSocket, Timeout) → ok

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -Timeout = timeout() -
    -
    -

    -Ack timeout. -

    -
    -
    -

    Perform post-accept initialization of the connection.

    -

    This function will be called by connection processes -before performing any socket operation. It allows -transports that require extra initialization to perform -their task and make the socket ready to use.

    -
    -
    -

    close(Socket) → ok

    -
    -
    -Socket = any() -
    -
    -

    -Socket opened with listen/1 or accept/2. -

    -
    -
    -

    Close the given socket.

    -
    -
    -

    controlling_process(Socket, Pid) → ok | {error, closed | not_owner | atom()}

    -
    -
    -Socket = any() -
    -
    -

    -Socket opened with listen/1 or accept/2. -

    -
    -
    -Pid = pid() -
    -
    -

    -Pid of the new owner of the socket. -

    -
    -
    -

    Change the controlling process for the given socket.

    -

    The controlling process is the process that is allowed to -perform operations on the socket, and that will receive -messages from the socket when active mode is used. When -the controlling process dies, the socket is closed.

    -
    -
    -

    listen(TransOpts) → {ok, LSocket} | {error, atom()}

    -
    -
    -TransOpts = any() -
    -
    -

    -Transport options. -

    -
    -
    -LSocket = any() -
    -
    -

    -Listening socket. -

    -
    -
    -

    Listen for connections on the given port.

    -

    The port is given as part of the transport options under -the key port. Any other option is transport dependent.

    -

    The socket returned by this call can then be used to -accept connections. It is not possible to send or receive -data from the listening socket.

    -
    -
    -

    messages() → {OK, Closed, Error}

    -
    -
    -OK = Closed = Error = atom() -
    -
    -

    -Tuple names. -

    -
    -
    -

    Return the atoms used to identify messages sent in active mode.

    -
    -
    -

    name() → Name

    -
    -
    -Name = atom() -
    -
    -

    -Transport module name. -

    -
    -
    -

    Return the name of the transport.

    -
    -
    -

    peername(CSocket) → {ok, {IP, Port}} | {error, atom()}

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -IP = inet:ip_address() -
    -
    -

    -IP of the remote endpoint. -

    -
    -
    -Port = inet:port_number() -
    -
    -

    -Port of the remote endpoint. -

    -
    -
    -

    Return the IP and port of the remote endpoint.

    -
    -
    -

    recv(CSocket, Length, Timeout) → {ok, Packet} | {error, closed | timeout | atom()}

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -Length = non_neg_integer() -
    -
    -

    -Requested length. -

    -
    -
    -Timeout = timeout() -
    -
    -

    -Receive timeout. -

    -
    -
    -Packet = iodata() | any() -
    -
    -

    -Data received. -

    -
    -
    -

    Receive data from the given socket when in passive mode.

    -

    Trying to receive data from a socket that is in active mode -will return an error.

    -

    A length of 0 will return any data available on the socket.

    -

    While it is possible to use the timeout value infinity, -this is highly discouraged as this could cause your process -to get stuck waiting for data that will never come. This may -happen when a socket becomes half-open due to a crash of the -remote endpoint. Wi-Fi going down is another common culprit -of this issue.

    -
    -
    -

    send(CSocket, Packet) → ok | {error, atom()}

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -Packet = iodata() -
    -
    -

    -Data to be sent. -

    -
    -
    -

    Send data to the given socket.

    -
    -
    -

    sendfile(CSocket, File) → sendfile(CSocket, File, 0, 0, [])

    -

    Alias of ranch_transport:sendfile/5.

    -
    -
    -

    sendfile(CSocket, File, Offset, Bytes) → sendfile(CSocket, File, Offset, Bytes, [])

    -

    Alias of ranch_transport:sendfile/5.

    -
    -
    -

    sendfile(CSocket, File, Offset, Bytes, SfOpts) → {ok, SentBytes} | {error, atom()}

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -File = file:filename_all() | file:fd() -
    -
    -

    -Filename or file descriptor for the file to be sent. -

    -
    -
    -Offset = non_neg_integer() -
    -
    -

    -Begin sending at this position in the file. -

    -
    -
    -Bytes = non_neg_integer() -
    -
    -

    -Send this many bytes. -

    -
    -
    -SentBytes = non_neg_integer() -
    -
    -

    -This many bytes were sent. -

    -
    -
    -SfOpts = sendfile_opts() -
    -
    -

    -Sendfile options. -

    -
    -
    -

    Send data from a file to the given socket.

    -

    The file may be sent full or in parts, and may be specified -by its filename or by an already open file descriptor.

    -

    Transports that manipulate TCP directly may use the -file:sendfile/{2,4,5} function, which calls the sendfile -syscall where applicable (on Linux, for example). Other -transports can use the sendfile/6 function exported from -this module.

    -
    -
    -

    setopts(CSocket, SockOpts) → ok | {error, atom()}

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -SockOpts = any() -
    -
    -

    -Socket options. -

    -
    -
    -

    Change options for the given socket.

    -

    This is mainly useful for switching to active or passive mode -or to set protocol-specific options.

    -
    -
    -

    shutdown(CSocket, How) → ok | {error, atom()}

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -How = read | write | read_write -
    -
    -

    -Which side(s) of the socket to close. -

    -
    -
    -

    Immediately close the socket in one or two directions.

    -
    -
    -

    sockname(Socket) → {ok, {IP, Port}} | {error, atom()}

    -
    -
    -Socket = any() -
    -
    -

    -Socket opened with listen/1 or accept/2. -

    -
    -
    -IP = inet:ip_address() -
    -
    -

    -IP of the local endpoint. -

    -
    -
    -Port = inet:port_number() -
    -
    -

    -Port of the local endpoint. -

    -
    -
    -

    Return the IP and port of the local endpoint.

    -
    -
    -
    -
    +

    accept(LSocket, Timeout) -> {ok, CSocket} | {error, closed | timeout | atom()}

    +
    LSocket = CSocket = any()
    +

    Listening socket.

    +
    +
    Timeout = timeout()
    +

    Accept timeout.

    +
    +
    +

    Accept a connection on the given listening socket.

    +

    The accept_ack callback will be used to initialize the socket after accepting the connection. This is most useful when the transport is not raw TCP, like with SSL for example.

    +

    accept_ack(CSocket, Timeout) -> ok

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    Timeout = timeout()
    +

    Ack timeout.

    +
    +
    +

    Perform post-accept initialization of the connection.

    +

    This function will be called by connection processes before performing any socket operation. It allows transports that require extra initialization to perform their task and make the socket ready to use.

    +

    close(Socket) -> ok

    +
    Socket = any()
    +

    Socket opened with listen/1 or accept/2.

    +
    +
    +

    Close the given socket.

    +

    controlling_process(Socket, Pid) -> ok | {error, closed | not_owner | atom()}

    +
    Socket = any()
    +

    Socket opened with listen/1 or accept/2.

    +
    +
    Pid = pid()
    +

    Pid of the new owner of the socket.

    +
    +
    +

    Change the controlling process for the given socket.

    +

    The controlling process is the process that is allowed to perform operations on the socket, and that will receive messages from the socket when active mode is used. When the controlling process dies, the socket is closed.

    +

    listen(TransOpts) -> {ok, LSocket} | {error, atom()}

    +
    TransOpts = any()
    +

    Transport options.

    +
    +
    LSocket = any()
    +

    Listening socket.

    +
    +
    +

    Listen for connections on the given port.

    +

    The port is given as part of the transport options under the key port. Any other option is transport dependent.

    +

    The socket returned by this call can then be used to accept connections. It is not possible to send or receive data from the listening socket.

    +

    messages() -> {OK, Closed, Error}

    +
    OK = Closed = Error = atom()
    +

    Tuple names.

    +
    +
    +

    Return the atoms used to identify messages sent in active mode.

    +

    name() -> Name

    +
    Name = atom()
    +

    Transport module name.

    +
    +
    +

    Return the name of the transport.

    +

    peername(CSocket) -> {ok, {IP, Port}} | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    IP = inet:ip_address()
    +

    IP of the remote endpoint.

    +
    +
    Port = inet:port_number()
    +

    Port of the remote endpoint.

    +
    +
    +

    Return the IP and port of the remote endpoint.

    +

    recv(CSocket, Length, Timeout) -> {ok, Packet} | {error, closed | timeout | atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    Length = non_neg_integer()
    +

    Requested length.

    +
    +
    Timeout = timeout()
    +

    Receive timeout.

    +
    +
    Packet = iodata() | any()
    +

    Data received.

    +
    +
    +

    Receive data from the given socket when in passive mode.

    +

    Trying to receive data from a socket that is in active mode will return an error.

    +

    A length of 0 will return any data available on the socket.

    +

    While it is possible to use the timeout value infinity, this is highly discouraged as this could cause your process to get stuck waiting for data that will never come. This may happen when a socket becomes half-open due to a crash of the remote endpoint. Wi-Fi going down is another common culprit of this issue.

    +

    send(CSocket, Packet) -> ok | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    Packet = iodata()
    +

    Data to be sent.

    +
    +
    +

    Send data to the given socket.

    +

    sendfile(CSocket, File) -> sendfile(CSocket, File, 0, 0, [])

    +

    Alias of ranch_transport:sendfile/5.

    +

    sendfile(CSocket, File, Offset, Bytes) -> sendfile(CSocket, File, Offset, Bytes, [])

    +

    Alias of ranch_transport:sendfile/5.

    +

    sendfile(CSocket, File, Offset, Bytes, SfOpts) -> {ok, SentBytes} | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    File = file:filename_all() | file:fd()
    +

    Filename or file descriptor for the file to be sent.

    +
    +
    Offset = non_neg_integer()
    +

    Begin sending at this position in the file.

    +
    +
    Bytes = non_neg_integer()
    +

    Send this many bytes.

    +
    +
    SentBytes = non_neg_integer()
    +

    This many bytes were sent.

    +
    +
    SfOpts = sendfile_opts()
    +

    Sendfile options.

    +
    +
    +

    Send data from a file to the given socket.

    +

    The file may be sent full or in parts, and may be specified by its filename or by an already open file descriptor.

    +

    Transports that manipulate TCP directly may use the file:sendfile/{2,4,5} function, which calls the sendfile syscall where applicable (on Linux, for example). Other transports can use the sendfile/6 function exported from this module.

    +

    setopts(CSocket, SockOpts) -> ok | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    SockOpts = any()
    +

    Socket options.

    +
    +
    +

    Change options for the given socket.

    +

    This is mainly useful for switching to active or passive mode or to set protocol-specific options.

    +

    shutdown(CSocket, How) -> ok | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    How = read | write | read_write
    +

    Which side(s) of the socket to close.

    +
    +
    +

    Immediately close the socket in one or two directions.

    +

    sockname(Socket) -> {ok, {IP, Port}} | {error, atom()}

    +
    Socket = any()
    +

    Socket opened with listen/1 or accept/2.

    +
    +
    IP = inet:ip_address()
    +

    IP of the local endpoint.

    +
    +
    Port = inet:port_number()
    +

    Port of the local endpoint.

    +
    +
    +

    Return the IP and port of the local endpoint.

    Exports

    -
    -
    -

    sendfile(Transport, CSocket, File, Offset, Bytes, SfOpts) → {ok, SentBytes} | {error, atom()}

    -
    -
    -Transport = module() -
    -
    -

    -Transport module for this socket. -

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -File = file:filename_all() | file:fd() -
    -
    -

    -Filename or file descriptor for the file to be sent. -

    -
    -
    -Offset = non_neg_integer() -
    -
    -

    -Begin sending at this position in the file. -

    -
    -
    -Bytes = non_neg_integer() -
    -
    -

    -Send this many bytes. -

    -
    -
    -SentBytes = non_neg_integer() -
    -
    -

    -This many bytes were sent. -

    -
    -
    -SfOpts = sendfile_opts() -
    -
    -

    -Sendfile options. -

    -
    -
    -

    Send data from a file to the given socket.

    -

    This function emulates the function file:sendfile/{2,4,5} -and may be used when transports are not manipulating TCP -directly.

    -
    -
    -
    +

    sendfile(Transport, CSocket, File, Offset, Bytes, SfOpts) -> {ok, SentBytes} | {error, atom()}

    +
    Transport = module()
    +

    Transport module for this socket.

    +
    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    File = file:filename_all() | file:fd()
    +

    Filename or file descriptor for the file to be sent.

    +
    +
    Offset = non_neg_integer()
    +

    Begin sending at this position in the file.

    +
    +
    Bytes = non_neg_integer()
    +

    Send this many bytes.

    +
    +
    SentBytes = non_neg_integer()
    +

    This many bytes were sent.

    +
    +
    SfOpts = sendfile_opts()
    +

    Sendfile options.

    +
    +
    +

    Send data from a file to the given socket.

    +

    This function emulates the function file:sendfile/{2,4,5} and may be used when transports are not manipulating TCP directly.

    + @@ -584,6 +288,8 @@ directly.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.3/guide/embedded/index.html b/docs/en/ranch/1.3/guide/embedded/index.html index 48adad24..a3b31404 100644 --- a/docs/en/ranch/1.3/guide/embedded/index.html +++ b/docs/en/ranch/1.3/guide/embedded/index.html @@ -62,48 +62,30 @@

    Embedded mode

    -

    Embedded mode allows you to insert Ranch listeners directly -in your supervision tree. This allows for greater fault tolerance -control by permitting the shutdown of a listener due to the -failure of another part of the application and vice versa.

    -
    +

    Embedded mode allows you to insert Ranch listeners directly in your supervision tree. This allows for greater fault tolerance control by permitting the shutdown of a listener due to the failure of another part of the application and vice versa.

    Embedding

    -
    -

    To embed Ranch in your application you can simply add the child specs -to your supervision tree. This can all be done in the init/1 function -of one of your application supervisors.

    -

    Ranch requires at the minimum two kinds of child specs for embedding. -First, you need to add ranch_sup to your supervision tree, only once, -regardless of the number of listeners you will use. Then you need to -add the child specs for each listener.

    -

    Ranch has a convenience function for getting the listeners child specs -called ranch:child_spec/6, that works like ranch:start_listener/6, -except that it doesn’t start anything, it only returns child specs.

    -

    As for ranch_sup, the child spec is simple enough to not require a -convenience function.

    -

    The following example adds both ranch_sup and one listener to another -application’s supervision tree.

    -
    -
    Embed Ranch directly in your supervision tree
    -
    -
    init([]) ->
    -        RanchSupSpec = {ranch_sup, {ranch_sup, start_link, []},
    -                permanent, 5000, supervisor, [ranch_sup]},
    -        ListenerSpec = ranch:child_spec(echo, 100,
    -                ranch_tcp, [{port, 5555}],
    -                echo_protocol, []
    -        ),
    -        {ok, {{one_for_one, 10, 10}, [RanchSupSpec, ListenerSpec]}}.
    -

    Remember, you can add as many listener child specs as needed, but only -one ranch_sup spec!

    -

    It is recommended that your architecture makes sure that all listeners -are restarted if ranch_sup fails. See the Ranch internals chapter for -more details on how Ranch does it.

    -
    -
    +
    init([]) ->
    +	RanchSupSpec = {ranch_sup, {ranch_sup, start_link, []},
    +		permanent, 5000, supervisor, [ranch_sup]},
    +	ListenerSpec = ranch:child_spec(echo, 100,
    +		ranch_tcp, [{port, 5555}],
    +		echo_protocol, []
    +	),
    +	{ok, {{one_for_one, 10, 10}, [RanchSupSpec, ListenerSpec]}}.
    + +

    Remember, you can add as many listener child specs as needed, but only one ranch_sup spec!

    +

    It is recommended that your architecture makes sure that all listeners are restarted if ranch_sup fails. See the Ranch internals chapter for more details on how Ranch does it.

    + @@ -160,6 +142,8 @@ more details on how Ranch does it.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.3/guide/index.html b/docs/en/ranch/1.3/guide/index.html index 20ecfab5..02ac7fe7 100644 --- a/docs/en/ranch/1.3/guide/index.html +++ b/docs/en/ranch/1.3/guide/index.html @@ -62,48 +62,24 @@

    Ranch User Guide

    - + + @@ -138,6 +114,8 @@ +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.3/guide/internals/index.html b/docs/en/ranch/1.3/guide/internals/index.html index 89ae1e28..ecb5f90d 100644 --- a/docs/en/ranch/1.3/guide/internals/index.html +++ b/docs/en/ranch/1.3/guide/internals/index.html @@ -62,93 +62,34 @@

    Internals

    -

    This chapter may not apply to embedded Ranch as embedding allows you -to use an architecture specific to your application, which may or may -not be compatible with the description of the Ranch application.

    -

    Note that for everything related to efficiency and performance, -you should perform the benchmarks yourself to get the numbers that -matter to you. Generic benchmarks found on the web may or may not -be of use to you, you can never know until you benchmark your own -system.

    -
    +

    This chapter may not apply to embedded Ranch as embedding allows you to use an architecture specific to your application, which may or may not be compatible with the description of the Ranch application.

    +

    Note that for everything related to efficiency and performance, you should perform the benchmarks yourself to get the numbers that matter to you. Generic benchmarks found on the web may or may not be of use to you, you can never know until you benchmark your own system.

    Architecture

    -
    -

    Ranch is an OTP application.

    -

    Like all OTP applications, Ranch has a top supervisor. It is responsible -for supervising the ranch_server process and all the listeners that -will be started.

    -

    The ranch_server gen_server is a central process keeping track of the -listeners and their acceptors. It does so through the use of a public ets -table called ranch_server. The table is owned by the top supervisor -to improve fault tolerance. This way if the ranch_server gen_server -fails, it doesn’t lose any information and the restarted process can -continue as if nothing happened.

    -

    Ranch uses a custom supervisor for managing connections. This supervisor -keeps track of the number of connections and handles connection limits -directly. While it is heavily optimized to perform the task of creating -connection processes for accepted connections, it is still following the -OTP principles and the usual sys and supervisor calls will work on -it as expected.

    -

    Listeners are grouped into the ranch_listener_sup supervisor and -consist of three kinds of processes: the listener gen_server, the -acceptor processes and the connection processes, both grouped under -their own supervisor. All of these processes are registered to the -ranch_server gen_server with varying amount of information.

    -

    All socket operations, including listening for connections, go through -transport handlers. Accepted connections are given to the protocol handler. -Transport handlers are simple callback modules for performing operations on -sockets. Protocol handlers start a new process, which receives socket -ownership, with no requirements on how the code should be written inside -that new process.

    -
    -
    -
    +

    Ranch is an OTP application.

    +

    Like all OTP applications, Ranch has a top supervisor. It is responsible for supervising the ranch_server process and all the listeners that will be started.

    +

    The ranch_server gen_server is a central process keeping track of the listeners and their acceptors. It does so through the use of a public ets table called ranch_server. The table is owned by the top supervisor to improve fault tolerance. This way if the ranch_server gen_server fails, it doesn't lose any information and the restarted process can continue as if nothing happened.

    +

    Ranch uses a custom supervisor for managing connections. This supervisor keeps track of the number of connections and handles connection limits directly. While it is heavily optimized to perform the task of creating connection processes for accepted connections, it is still following the OTP principles and the usual sys and supervisor calls will work on it as expected.

    +

    Listeners are grouped into the ranch_listener_sup supervisor and consist of three kinds of processes: the listener gen_server, the acceptor processes and the connection processes, both grouped under their own supervisor. All of these processes are registered to the ranch_server gen_server with varying amount of information.

    +

    All socket operations, including listening for connections, go through transport handlers. Accepted connections are given to the protocol handler. Transport handlers are simple callback modules for performing operations on sockets. Protocol handlers start a new process, which receives socket ownership, with no requirements on how the code should be written inside that new process.

    Number of acceptors

    -
    -

    The second argument to ranch:start_listener/6 is the number of -processes that will be accepting connections. Care should be taken -when choosing this number.

    -

    First of all, it should not be confused with the maximum number -of connections. Acceptor processes are only used for accepting and -have nothing else in common with connection processes. Therefore -there is nothing to be gained from setting this number too high, -in fact it can slow everything else down.

    -

    Second, this number should be high enough to allow Ranch to accept -connections concurrently. But the number of cores available doesn’t -seem to be the only factor for choosing this number, as we can -observe faster accepts if we have more acceptors than cores. It -might be entirely dependent on the protocol, however.

    -

    Our observations suggest that using 100 acceptors on modern hardware -is a good solution, as it’s big enough to always have acceptors ready -and it’s low enough that it doesn’t have a negative impact on the -system’s performances.

    -
    -
    -
    +

    The second argument to ranch:start_listener/6 is the number of processes that will be accepting connections. Care should be taken when choosing this number.

    +

    First of all, it should not be confused with the maximum number of connections. Acceptor processes are only used for accepting and have nothing else in common with connection processes. Therefore there is nothing to be gained from setting this number too high, in fact it can slow everything else down.

    +

    Second, this number should be high enough to allow Ranch to accept connections concurrently. But the number of cores available doesn't seem to be the only factor for choosing this number, as we can observe faster accepts if we have more acceptors than cores. It might be entirely dependent on the protocol, however.

    +

    Our observations suggest that using 100 acceptors on modern hardware is a good solution, as it's big enough to always have acceptors ready and it's low enough that it doesn't have a negative impact on the system's performances.

    Platform-specific TCP features

    -
    -

    Some socket options are platform-specific and not supported by inet. -They can be of interest because they generally are related to -optimizations provided by the underlying OS. They can still be enabled -thanks to the raw option, for which we will see an example.

    -

    One of these features is TCP_DEFER_ACCEPT on Linux. It is a simplified -accept mechanism which will wait for application data to come in before -handing out the connection to the Erlang process.

    -

    This is especially useful if you expect many connections to be mostly -idle, perhaps part of a connection pool. They can be handled by the -kernel directly until they send any real data, instead of allocating -resources to idle connections.

    -

    To enable this mechanism, the following option can be used.

    -
    -
    Using raw transport options
    -
    -
    {raw, 6, 9, << 30:32/native >>}
    -

    It means go on layer 6, turn on option 9 with the given integer parameter.

    -
    -
    +
    {raw, 6, 9, << 30:32/native >>}
    + +

    It means go on layer 6, turn on option 9 with the given integer parameter.

    + @@ -201,6 +142,8 @@ http://www.gnu.org/software/src-highlite --> +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.3/guide/introduction/index.html b/docs/en/ranch/1.3/guide/introduction/index.html index f361ce69..e2868f41 100644 --- a/docs/en/ranch/1.3/guide/introduction/index.html +++ b/docs/en/ranch/1.3/guide/introduction/index.html @@ -62,34 +62,18 @@

    Introduction

    -

    Ranch is a socket acceptor pool for TCP protocols.

    -

    Ranch aims to provide everything you need to accept TCP connections -with a small code base and low latency while being easy to use directly -as an application or to embed into your own.

    -
    +

    Ranch is a socket acceptor pool for TCP protocols.

    +

    Ranch aims to provide everything you need to accept TCP connections with a small code base and low latency while being easy to use directly as an application or to embed into your own.

    Prerequisites

    -
    -

    It is assumed the developer already knows Erlang and has some experience -with socket programming and TCP protocols.

    -
    -
    -
    +

    It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols.

    Supported platforms

    -
    -

    Ranch is tested and supported on Linux, FreeBSD, OSX and Windows.

    -

    Ranch is developed for Erlang/OTP R16B+.

    -

    There are known issues with the SSL application found in Erlang/OTP -18.3.2 and 18.3.3. These versions are therefore not supported.

    -

    Ranch may be compiled on earlier Erlang versions with small source code -modifications but there is no guarantee that it will work as expected.

    -
    -
    -
    +

    Ranch is tested and supported on Linux, FreeBSD, OSX and Windows.

    +

    Ranch is developed for Erlang/OTP R16B+.

    +

    There are known issues with the SSL application found in Erlang/OTP 18.3.2 and 18.3.3. These versions are therefore not supported.

    +

    Ranch may be compiled on earlier Erlang versions with small source code modifications but there is no guarantee that it will work as expected.

    Versioning

    - -
    +

    Ranch uses Semantic Versioning 2.0.0

    + @@ -142,6 +126,8 @@ modifications but there is no guarantee that it will work as expected.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.3/guide/listeners/index.html b/docs/en/ranch/1.3/guide/listeners/index.html index 1195d3ca..b1c30867 100644 --- a/docs/en/ranch/1.3/guide/listeners/index.html +++ b/docs/en/ranch/1.3/guide/listeners/index.html @@ -62,346 +62,200 @@

    Listeners

    -

    A listener is a set of processes whose role is to listen on a port -for new connections. It manages a pool of acceptor processes, each -of them indefinitely accepting connections. When it does, it starts -a new process executing the protocol handler code. All the socket -programming is abstracted through the use of transport handlers.

    -

    The listener takes care of supervising all the acceptor and connection -processes, allowing developers to focus on building their application.

    -
    +

    A listener is a set of processes whose role is to listen on a port for new connections. It manages a pool of acceptor processes, each of them indefinitely accepting connections. When it does, it starts a new process executing the protocol handler code. All the socket programming is abstracted through the use of transport handlers.

    +

    The listener takes care of supervising all the acceptor and connection processes, allowing developers to focus on building their application.

    Starting a listener

    -
    -

    Ranch does nothing by default. It is up to the application developer -to request that Ranch listens for connections.

    -

    A listener can be started and stopped at will.

    -

    When starting a listener, a number of different settings are required:

    -
      -
    • -

      -A name to identify it locally and be able to interact with it. -

      +

      Ranch does nothing by default. It is up to the application developer to request that Ranch listens for connections.

      +

      A listener can be started and stopped at will.

      +

      When starting a listener, a number of different settings are required:

      +
      • A name to identify it locally and be able to interact with it.
      • -
      • -

        -The number of acceptors in the pool. -

        +
      • The number of acceptors in the pool.
      • -
      • -

        -A transport handler and its associated options. -

        +
      • A transport handler and its associated options.
      • -
      • -

        -A protocol handler and its associated options. -

        +
      • A protocol handler and its associated options.
      • -
    -

    Ranch includes both TCP and SSL transport handlers, respectively -ranch_tcp and ranch_ssl.

    -

    A listener can be started by calling the ranch:start_listener/6 -function. Before doing so however, you must ensure that the ranch -application is started.

    -
    -
    Starting the Ranch application
    -
    -
    ok = application:start(ranch).
    -

    You are then ready to start a listener. Let’s call it tcp_echo. It will -have a pool of 100 acceptors, use a TCP transport and forward connections -to the echo_protocol handler.

    -
    -
    Starting a listener for TCP connections on port 5555
    -
    -
    {ok, _} = ranch:start_listener(tcp_echo, 100,
    -        ranch_tcp, [{port, 5555}],
    -        echo_protocol, []
    -).
    -

    You can try this out by compiling and running the tcp_echo example in the -examples directory. To do so, open a shell in the examples/tcp_echo/ -directory and run the following command:

    -
    -
    Building and starting a Ranch example
    -
    -
    $ make run
    -

    You can then connect to it using telnet and see the echo server reply -everything you send to it. Then when you’re done testing, you can use -the Ctrl+] key to escape to the telnet command line and type -quit to exit.

    -
    -
    Connecting to the example listener with telnet
    -
    -
    $ telnet localhost 5555
    -Trying 127.0.0.1...
    -Connected to localhost.
    -Escape character is '^]'.
    -Hello!
    -Hello!
    -It works!
    -It works!
    -^]
    -
    -telnet> quit
    -Connection closed.
    -
    -
    -
    +
    $ telnet localhost 5555
    +Trying 127.0.0.1...
    +Connected to localhost.
    +Escape character is '^]'.
    +Hello!
    +Hello!
    +It works!
    +It works!
    +^]
    +
    +telnet> quit
    +Connection closed.
    +

    Stopping a listener

    -
    -

    All you need to stop a Ranch listener is to call the -ranch:stop_listener/1 function with the listener’s name -as argument. In the previous section we started the listener -named tcp_echo. We can now stop it.

    -
    -
    Stopping a listener
    -
    -
    ranch:stop_listener(tcp_echo).
    -
    - -
    +
    ranch:stop_listener(tcp_echo).
    +

    Default transport options

    -
    -

    By default the socket will be set to return binary data, with the -options {active, false}, {packet, raw}, {reuseaddr, true} set. -These values can’t be overriden when starting the listener, but -they can be overriden using Transport:setopts/2 in the protocol.

    -

    It will also set {backlog, 1024} and {nodelay, true}, which -can be overriden at listener startup.

    -
    - -
    +

    By default the socket will be set to return binary data, with the options {active, false}, {packet, raw}, {reuseaddr, true} set. These values can't be overriden when starting the listener, but they can be overriden using Transport:setopts/2 in the protocol.

    +

    It will also set {backlog, 1024} and {nodelay, true}, which can be overriden at listener startup.

    Listening on a random port

    -
    -

    You do not have to specify a specific port to listen on. If you give -the port number 0, or if you omit the port number entirely, Ranch will -start listening on a random port.

    -

    You can retrieve this port number by calling ranch:get_port/1. The -argument is the name of the listener you gave in ranch:start_listener/6.

    -
    -
    Starting a listener for TCP connections on a random port
    -
    -
    {ok, _} = ranch:start_listener(tcp_echo, 100,
    -        ranch_tcp, [{port, 0}],
    -        echo_protocol, []
    -).
    -Port = ranch:get_port(tcp_echo).
    -
    -
    -
    +
    {ok, _} = ranch:start_listener(tcp_echo, 100,
    +	ranch_tcp, [{port, 0}],
    +	echo_protocol, []
    +).
    +Port = ranch:get_port(tcp_echo).
    +

    Listening on privileged ports

    -
    -

    Some systems limit access to ports below 1024 for security reasons. -This can easily be identified by an {error, eacces} error when trying -to open a listening socket on such a port.

    -

    The methods for listening on privileged ports vary between systems, -please refer to your system’s documentation for more information.

    -

    We recommend the use of port rewriting for systems with a single server, -and load balancing for systems with multiple servers. Documenting these -solutions is however out of the scope of this guide.

    -
    - -
    +

    Some systems limit access to ports below 1024 for security reasons. This can easily be identified by an {error, eacces} error when trying to open a listening socket on such a port.

    +

    The methods for listening on privileged ports vary between systems, please refer to your system's documentation for more information.

    +

    We recommend the use of port rewriting for systems with a single server, and load balancing for systems with multiple servers. Documenting these solutions is however out of the scope of this guide.

    Accepting connections on an existing socket

    -
    -

    If you want to accept connections on an existing socket, you can use the -socket transport option, which should just be the relevant data returned -from the connect function for the transport or the underlying socket library -(gen_tcp:connect, ssl:connect). The accept function will then be -called on the passed in socket. You should connect the socket in -{active, false} mode, as well.

    -

    Note, however, that because of a bug in SSL, you cannot change ownership of an -SSL listen socket prior to R16. Ranch will catch the error thrown, but the -owner of the SSL socket will remain as whatever process created the socket. -However, this will not affect accept behaviour unless the owner process dies, -in which case the socket is closed. Therefore, to use this feature with SSL -with an erlang release prior to R16, ensure that the SSL socket is opened in a -persistant process.

    -
    -
    -
    +

    If you want to accept connections on an existing socket, you can use the socket transport option, which should just be the relevant data returned from the connect function for the transport or the underlying socket library (gen_tcp:connect, ssl:connect). The accept function will then be called on the passed in socket. You should connect the socket in {active, false} mode, as well.

    +

    Note, however, that because of a bug in SSL, you cannot change ownership of an SSL listen socket prior to R16. Ranch will catch the error thrown, but the owner of the SSL socket will remain as whatever process created the socket. However, this will not affect accept behaviour unless the owner process dies, in which case the socket is closed. Therefore, to use this feature with SSL with an erlang release prior to R16, ensure that the SSL socket is opened in a persistant process.

    Limiting the number of concurrent connections

    -
    -

    The max_connections transport option allows you to limit the number -of concurrent connections. It defaults to 1024. Its purpose is to -prevent your system from being overloaded and ensuring all the -connections are handled optimally.

    -
    -
    Customizing the maximum number of concurrent connections
    -
    -
    {ok, _} = ranch:start_listener(tcp_echo, 100,
    -        ranch_tcp, [{port, 5555}, {max_connections, 100}],
    -        echo_protocol, []
    -).
    -

    You can disable this limit by setting its value to the atom infinity.

    -
    -
    Disabling the limit for the number of connections
    -
    -
    {ok, _} = ranch:start_listener(tcp_echo, 100,
    -        ranch_tcp, [{port, 5555}, {max_connections, infinity}],
    -        echo_protocol, []
    -).
    -

    The maximum number of connections is a soft limit. In practice, it -can reach max_connections + the number of acceptors.

    -

    When the maximum number of connections is reached, Ranch will stop -accepting connections. This will not result in further connections -being rejected, as the kernel option allows queueing incoming -connections. The size of this queue is determined by the backlog -option and defaults to 1024. Ranch does not know about the number -of connections that are in the backlog.

    -

    You may not always want connections to be counted when checking for -max_connections. For example you might have a protocol where both -short-lived and long-lived connections are possible. If the long-lived -connections are mostly waiting for messages, then they don’t consume -much resources and can safely be removed from the count.

    -

    To remove the connection from the count, you must call the -ranch:remove_connection/1 from within the connection process, -with the name of the listener as the only argument.

    -
    -
    Removing a connection from the count of connections
    -
    -
    ranch:remove_connection(Ref).
    -

    As seen in the chapter covering protocols, this pid is received as the -first argument of the protocol’s start_link/4 callback.

    -

    You can modify the max_connections value on a running listener by -using the ranch:set_max_connections/2 function, with the name of the -listener as first argument and the new value as the second.

    -
    -
    Upgrading the maximum number of connections
    -
    -
    ranch:set_max_connections(tcp_echo, MaxConns).
    -

    The change will occur immediately.

    -
    -
    -
    -

    When running out of file descriptors

    -
    -

    Operating systems have limits on the number of sockets -which can be opened by applications. When this maximum is -reached the listener can no longer accept new connections. The -accept rate of the listener will be automatically reduced, and a -warning message will be logged.

    -
    -
    -
    =ERROR REPORT==== 13-Jan-2016::12:24:38 ===
    -Ranch acceptor reducing accept rate: out of file descriptors
    +
    ranch:set_max_connections(tcp_echo, MaxConns).
    -

    If you notice messages like this you should increase the number -of file-descriptors which can be opened by your application. How -this should be done is operating-system dependent. Please consult -the documentation of your operating system.

    -
    -
    -
    +

    The change will occur immediately.

    +

    When running out of file descriptors

    +

    Operating systems have limits on the number of sockets which can be opened by applications. When this maximum is reached the listener can no longer accept new connections. The accept rate of the listener will be automatically reduced, and a warning message will be logged.

    +
    =ERROR REPORT==== 13-Jan-2016::12:24:38 ===
    +Ranch acceptor reducing accept rate: out of file descriptors
    +

    If you notice messages like this you should increase the number of file-descriptors which can be opened by your application. How this should be done is operating-system dependent. Please consult the documentation of your operating system.

    Using a supervisor for connection processes

    -
    -

    Ranch allows you to define the type of process that will be used -for the connection processes. By default it expects a worker. -When the connection_type configuration value is set to supervisor, -Ranch will consider that the connection process it manages is a -supervisor and will reflect that in its supervision tree.

    -

    Connection processes of type supervisor can either handle the -socket directly or through one of their children. In the latter -case the start function for the connection process must return -two pids: the pid of the supervisor you created (that will be -supervised) and the pid of the protocol handling process (that -will receive the socket).

    -

    Instead of returning {ok, ConnPid}, simply return -{ok, SupPid, ConnPid}.

    -

    It is very important that the connection process be created -under the supervisor process so that everything works as intended. -If not, you will most likely experience issues when the supervised -process is stopped.

    -
    -
    -
    +

    Ranch allows you to define the type of process that will be used for the connection processes. By default it expects a worker. When the connection_type configuration value is set to supervisor, Ranch will consider that the connection process it manages is a supervisor and will reflect that in its supervision tree.

    +

    Connection processes of type supervisor can either handle the socket directly or through one of their children. In the latter case the start function for the connection process must return two pids: the pid of the supervisor you created (that will be supervised) and the pid of the protocol handling process (that will receive the socket).

    +

    Instead of returning {ok, ConnPid}, simply return {ok, SupPid, ConnPid}.

    +

    It is very important that the connection process be created under the supervisor process so that everything works as intended. If not, you will most likely experience issues when the supervised process is stopped.

    Upgrading

    -
    -

    Ranch allows you to upgrade the protocol options. This takes effect -immediately and for all subsequent connections.

    -

    To upgrade the protocol options, call ranch:set_protocol_options/2 -with the name of the listener as first argument and the new options -as the second.

    -
    -
    Upgrading the protocol options
    -
    -
    ranch:set_protocol_options(tcp_echo, NewOpts).
    -

    All future connections will use the new options.

    -

    You can also retrieve the current options similarly by -calling ranch:get_protocol_options/1.

    -
    -
    Retrieving the current protocol options
    -
    -
    Opts = ranch:get_protocol_options(tcp_echo).
    -
    -
    -
    +
    Opts = ranch:get_protocol_options(tcp_echo).
    +

    Obtain information about listeners

    -
    -

    Ranch provides two functions for retrieving information about the -listeners, for reporting and diagnostic purposes.

    -

    The ranch:info/0 function will return detailed information -about all listeners.

    -
    -
    Retrieving detailed information
    -
    -
    ranch:info().
    -

    The ranch:procs/2 function will return all acceptor or listener -processes for a given listener.

    -
    -
    Get all acceptor processes
    -
    -
    ranch:procs(tcp_echo, acceptors).
    -
    -
    Get all connection processes
    -
    -
    ranch:procs(tcp_echo, connections).
    -
    - +
    ranch:procs(tcp_echo, connections).
    + + @@ -458,6 +312,8 @@ http://www.gnu.org/software/src-highlite --> +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.3/guide/parsers/index.html b/docs/en/ranch/1.3/guide/parsers/index.html index fb089bde..eb1a7f85 100644 --- a/docs/en/ranch/1.3/guide/parsers/index.html +++ b/docs/en/ranch/1.3/guide/parsers/index.html @@ -62,109 +62,69 @@

    Writing parsers

    -

    There are three kinds of protocols:

    -
      -
    • -

      -Text protocols -

      +

      There are three kinds of protocols:

      +
      • Text protocols
      • -
      • -

        -Schema-less binary protocols -

        +
      • Schema-less binary protocols
      • -
      • -

        -Schema-based binary protocols -

        +
      • Schema-based binary protocols
      • -
    -

    This chapter introduces the first two kinds. It will not cover -more advanced topics such as continuations or parser generators.

    -

    This chapter isn’t specifically about Ranch, we assume here that -you know how to read data from the socket. The data you read and -the data that hasn’t been parsed is saved in a buffer. Every -time you read from the socket, the data read is appended to the -buffer. What happens next depends on the kind of protocol. We -will only cover the first two.

    -
    + +

    This chapter introduces the first two kinds. It will not cover more advanced topics such as continuations or parser generators.

    +

    This chapter isn't specifically about Ranch, we assume here that you know how to read data from the socket. The data you read and the data that hasn't been parsed is saved in a buffer. Every time you read from the socket, the data read is appended to the buffer. What happens next depends on the kind of protocol. We will only cover the first two.

    Parsing text

    -
    -

    Text protocols are generally line based. This means that we can’t -do anything with them until we receive the full line.

    -

    A simple way to get a full line is to use binary:split/{2,3}.

    -
    -
    Using binary:split/2 to get a line of input
    -
    -
    case binary:split(Buffer, <<"\n">>) of
    -        [_] ->
    -                get_more_data(Buffer);
    -        [Line, Rest] ->
    -                handle_line(Line, Rest)
    -end.
    -

    In the above example, we can have two results. Either there was -a line break in the buffer and we get it split into two parts, -the line and the rest of the buffer; or there was no line break -in the buffer and we need to get more data from the socket.

    -

    Next, we need to parse the line. The simplest way is to again -split, here on space. The difference is that we want to split -on all spaces character, as we want to tokenize the whole string.

    -
    -
    Using binary:split/3 to split text
    -
    -
    case binary:split(Line, <<" ">>, [global]) of
    -        [<<"HELLO">>] ->
    -                be_polite();
    -        [<<"AUTH">>, User, Password] ->
    -                authenticate_user(User, Password);
    -        [<<"QUIT">>, Reason] ->
    -                quit(Reason)
    -        %% ...
    -end.
    -

    Pretty simple, right? Match on the command name, get the rest -of the tokens in variables and call the respective functions.

    -

    After doing this, you will want to check if there is another -line in the buffer, and handle it immediately if any. -Otherwise wait for more data.

    -
    -
    -
    +
    case binary:split(Line, <<" ">>, [global]) of
    +	[<<"HELLO">>] ->
    +		be_polite();
    +	[<<"AUTH">>, User, Password] ->
    +		authenticate_user(User, Password);
    +	[<<"QUIT">>, Reason] ->
    +		quit(Reason)
    +	%% ...
    +end.
    +
    +

    Pretty simple, right? Match on the command name, get the rest of the tokens in variables and call the respective functions.

    +

    After doing this, you will want to check if there is another line in the buffer, and handle it immediately if any. Otherwise wait for more data.

    Parsing binary

    -
    -

    Binary protocols can be more varied, although most of them are -pretty similar. The first four bytes of a frame tend to be -the size of the frame, which is followed by a certain number -of bytes for the type of frame and then various parameters.

    -

    Sometimes the size of the frame includes the first four bytes, -sometimes not. Other times this size is encoded over two bytes. -And even other times little-endian is used instead of big-endian.

    -

    The general idea stays the same though.

    -
    -
    Using binary pattern matching to split frames
    -
    -
    << Size:32, _/bits >> = Buffer,
    -case Buffer of
    -        << Frame:Size/binary, Rest/bits >> ->
    -                handle_frame(Frame, Rest);
    -        _ ->
    -                get_more_data(Buffer)
    -end.
    -

    You will then need to parse this frame using binary pattern -matching, and handle it. Then you will want to check if there -is another frame fully received in the buffer, and handle it -immediately if any. Otherwise wait for more data.

    -
    - +
    << Size:32, _/bits >> = Buffer,
    +case Buffer of
    +	<< Frame:Size/binary, Rest/bits >> ->
    +		handle_frame(Frame, Rest);
    +	_ ->
    +		get_more_data(Buffer)
    +end.
    + +

    You will then need to parse this frame using binary pattern matching, and handle it. Then you will want to check if there is another frame fully received in the buffer, and handle it immediately if any. Otherwise wait for more data.

    + @@ -221,6 +181,8 @@ immediately if any. Otherwise wait for more data.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.3/guide/protocols/index.html b/docs/en/ranch/1.3/guide/protocols/index.html index ad099507..b14a22b3 100644 --- a/docs/en/ranch/1.3/guide/protocols/index.html +++ b/docs/en/ranch/1.3/guide/protocols/index.html @@ -62,104 +62,76 @@

    Protocols

    -

    A protocol handler starts a connection process and defines the -protocol logic executed in this process.

    -
    +

    A protocol handler starts a connection process and defines the protocol logic executed in this process.

    Writing a protocol handler

    -
    -

    All protocol handlers must implement the ranch_protocol behavior -which defines a single callback, start_link/4. This callback is -responsible for spawning a new process for handling the connection. -It receives four arguments: the name of the listener, the socket, the -transport handler being used and the protocol options defined in -the call to ranch:start_listener/6. This callback must -return {ok, Pid}, with Pid the pid of the new process.

    -

    The newly started process can then freely initialize itself. However, -it must call ranch:accept_ack/1 before doing any socket operation. -This will ensure the connection process is the owner of the socket. -It expects the listener’s name as argument.

    -
    -
    Acknowledge accepting the socket
    -
    -
    ok = ranch:accept_ack(Ref).
    -

    If your protocol code requires specific socket options, you should -set them while initializing your connection process, after -calling ranch:accept_ack/1. You can use Transport:setopts/2 -for that purpose.

    -

    Following is the complete protocol code for the example found -in examples/tcp_echo/.

    -
    -
    Protocol module that echoes everything it receives
    -
    -
    -module(echo_protocol).
    --behaviour(ranch_protocol).
    -
    --export([start_link/4]).
    --export([init/4]).
    -
    -start_link(Ref, Socket, Transport, Opts) ->
    -        Pid = spawn_link(?MODULE, init, [Ref, Socket, Transport, Opts]),
    -        {ok, Pid}.
    -
    -init(Ref, Socket, Transport, _Opts = []) ->
    -        ok = ranch:accept_ack(Ref),
    -        loop(Socket, Transport).
    -
    -loop(Socket, Transport) ->
    -        case Transport:recv(Socket, 0, 5000) of
    -                {ok, Data} ->
    -                        Transport:send(Socket, Data),
    -                        loop(Socket, Transport);
    -                _ ->
    -                        ok = Transport:close(Socket)
    -        end.
    -
    -
    -
    +
    -module(echo_protocol).
    +-behaviour(ranch_protocol).
    +
    +-export([start_link/4]).
    +-export([init/4]).
    +
    +start_link(Ref, Socket, Transport, Opts) ->
    +	Pid = spawn_link(?MODULE, init, [Ref, Socket, Transport, Opts]),
    +	{ok, Pid}.
    +
    +init(Ref, Socket, Transport, _Opts = []) ->
    +	ok = ranch:accept_ack(Ref),
    +	loop(Socket, Transport).
    +
    +loop(Socket, Transport) ->
    +	case Transport:recv(Socket, 0, 5000) of
    +		{ok, Data} ->
    +			Transport:send(Socket, Data),
    +			loop(Socket, Transport);
    +		_ ->
    +			ok = Transport:close(Socket)
    +	end.
    +

    Using gen_server

    -
    -

    Special processes like the ones that use the gen_server or gen_fsm -behaviours have the particularity of having their start_link call not -return until the init function returns. This is problematic, because -you won’t be able to call ranch:accept_ack/1 from the init callback -as this would cause a deadlock to happen.

    -

    Use the gen_server:enter_loop/3 function. It allows you to start your process -normally (although it must be started with proc_lib like all special -processes), then perform any needed operations before falling back into -the normal gen_server execution loop.

    -
    -
    Use a gen_server for protocol handling
    -
    -
    -module(my_protocol).
    --behaviour(gen_server).
    --behaviour(ranch_protocol).
    +
    -module(my_protocol).
    +-behaviour(gen_server).
    +-behaviour(ranch_protocol).
     
    --export([start_link/4]).
    --export([init/1]).
    -%% Exports of other gen_server callbacks here.
    +-export([start_link/4]).
    +-export([init/1]).
    +%% Exports of other gen_server callbacks here.
     
    -start_link(Ref, Socket, Transport, Opts) ->
    -        {ok, proc_lib:spawn_link(?MODULE, init, [{Ref, Socket, Transport, Opts}])}.
    +start_link(Ref, Socket, Transport, Opts) ->
    +	{ok, proc_lib:spawn_link(?MODULE, init, [{Ref, Socket, Transport, Opts}])}.
     
    -init({Ref, Socket, Transport, _Opts = []}) ->
    -        %% Perform any required state initialization here.
    -        ok = ranch:accept_ack(Ref),
    -        ok = Transport:setopts(Socket, [{active, once}]),
    -        gen_server:enter_loop(?MODULE, [], {state, Socket, Transport}).
    +init({Ref, Socket, Transport, _Opts = []}) ->
    +	%% Perform any required state initialization here.
    +	ok = ranch:accept_ack(Ref),
    +	ok = Transport:setopts(Socket, [{active, once}]),
    +	gen_server:enter_loop(?MODULE, [], {state, Socket, Transport}).
    +
    +%% Other gen_server callbacks here.
    +
    +

    Check the tcp_reverse example for a complete example.

    -%% Other gen_server callbacks here.
    -

    Check the tcp_reverse example for a complete example.

    - - @@ -216,6 +188,8 @@ http://www.gnu.org/software/src-highlite --> +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.3/guide/ssl_auth/index.html b/docs/en/ranch/1.3/guide/ssl_auth/index.html index 6f4f93dc..4018790d 100644 --- a/docs/en/ranch/1.3/guide/ssl_auth/index.html +++ b/docs/en/ranch/1.3/guide/ssl_auth/index.html @@ -62,158 +62,82 @@

    SSL client authentication

    -

    Purpose

    -
    -

    SSL client authentication is a mechanism allowing applications to -identify certificates. This allows your application to make sure that -the client is an authorized certificate, but makes no claim about -whether the user can be trusted. This can be combined with a password -based authentication to attain greater security.

    -

    The server only needs to retain the certificate serial number and -the certificate issuer to authenticate the certificate. Together, -they can be used to uniquely identify a certicate.

    -

    As Ranch allows the same protocol code to be used for both SSL and -non-SSL transports, you need to make sure you are in an SSL context -before attempting to perform an SSL client authentication. This -can be done by checking the return value of Transport:name/0.

    -
    -
    -
    +

    SSL client authentication is a mechanism allowing applications to identify certificates. This allows your application to make sure that the client is an authorized certificate, but makes no claim about whether the user can be trusted. This can be combined with a password based authentication to attain greater security.

    +

    The server only needs to retain the certificate serial number and the certificate issuer to authenticate the certificate. Together, they can be used to uniquely identify a certicate.

    +

    As Ranch allows the same protocol code to be used for both SSL and non-SSL transports, you need to make sure you are in an SSL context before attempting to perform an SSL client authentication. This can be done by checking the return value of Transport:name/0.

    Obtaining client certificates

    -
    -

    You can obtain client certificates from various sources. You can -generate them yourself, or you can use a service like CAcert.org -which allows you to generate client and server certificates for -free.

    -

    Following are the steps you need to take to create a CAcert.org -account, generate a certificate and install it in your favorite -browser.

    -
      -
    • -

      -Open http://cacert.org in your favorite browser -

      +

      You can obtain client certificates from various sources. You can generate them yourself, or you can use a service like CAcert.org which allows you to generate client and server certificates for free.

      +

      Following are the steps you need to take to create a CAcert.org account, generate a certificate and install it in your favorite browser.

      +
      • Open http://cacert.org in your favorite browser
      • -
      • -

        -Root Certificate link: install both certificates -

        +
      • Root Certificate link: install both certificates
      • -
      • -

        -Join (Register an account) -

        +
      • Join (Register an account)
      • -
      • -

        -Verify your account (check your email inbox!) -

        +
      • Verify your account (check your email inbox!)
      • -
      • -

        -Log in -

        +
      • Log in
      • -
      • -

        -Client Certificates: New -

        +
      • Client Certificates: New
      • -
      • -

        -Follow instructions to create the certificate -

        +
      • Follow instructions to create the certificate
      • -
      • -

        -Install the certificate in your browser -

        +
      • Install the certificate in your browser
      • -
    -

    You can optionally save the certificate for later use, for example -to extract the IssuerID information as will be detailed later on.

    -
    -
    -
    + +

    You can optionally save the certificate for later use, for example to extract the IssuerID information as will be detailed later on.

    Transport configuration

    -
    -

    The SSL transport does not request a client certificate by default. -You need to specify the {verify, verify_peer} option when starting -the listener to enable this behavior.

    -
    -
    Configure a listener for SSL authentication
    -
    -
    {ok, _} = ranch:start_listener(my_ssl, 100,
    -        ranch_ssl, [
    -                {port, SSLPort},
    -                {certfile, PathToCertfile},
    -                {cacertfile, PathToCACertfile},
    -                {verify, verify_peer}
    -        ],
    -        my_protocol, []
    -).
    -

    In this example we set the required port and certfile, but also -the cacertfile containing the CACert.org root certificate, and -the option to request the client certificate.

    -

    If you enable the {verify, verify_peer} option and the client does -not have a client certificate configured for your domain, then no -certificate will be sent. This allows you to use SSL for more than -just authenticated clients.

    -
    -
    -
    +
    {ok, _} = ranch:start_listener(my_ssl, 100,
    +	ranch_ssl, [
    +		{port, SSLPort},
    +		{certfile, PathToCertfile},
    +		{cacertfile, PathToCACertfile},
    +		{verify, verify_peer}
    +	],
    +	my_protocol, []
    +).
    +
    +

    In this example we set the required port and certfile, but also the cacertfile containing the CACert.org root certificate, and the option to request the client certificate.

    +

    If you enable the {verify, verify_peer} option and the client does not have a client certificate configured for your domain, then no certificate will be sent. This allows you to use SSL for more than just authenticated clients.

    Authentication

    -
    -

    To authenticate users, you must first save the certificate information -required. If you have your users' certificate files, you can simply -load the certificate and retrieve the information directly.

    -
    -
    Retrieve the issuer ID from a certificate
    -
    -
    certfile_to_issuer_id(Filename) ->
    -        {ok, Data} = file:read_file(Filename),
    -        [{'Certificate', Cert, not_encrypted}] = public_key:pem_decode(Data),
    -        {ok, IssuerID} = public_key:pkix_issuer_id(Cert, self),
    -        IssuerID.
    -

    The IssuerID variable contains both the certificate serial number -and the certificate issuer stored in a tuple, so this value alone can -be used to uniquely identify the user certificate. You can save this -value in a database, a configuration file or any other place where an -Erlang term can be stored and retrieved.

    -

    To retrieve the IssuerID from a running connection, you need to first -retrieve the client certificate and then extract this information from -it. Ranch does not provide a function to retrieve the client certificate. -Instead you can use the ssl:peercert/1 function. Once you have the -certificate, you can again use the public_key:pkix_issuer_id/2 to -extract the IssuerID value.

    -

    The following function returns the IssuerID or false if no client -certificate was found. This snippet is intended to be used from your -protocol code.

    -
    -
    Retrieve the issuer ID from the certificate for the current connection
    -
    -
    socket_to_issuer_id(Socket) ->
    -        case ssl:peercert(Socket) of
    -                {error, no_peercert} ->
    -                        false;
    -                {ok, Cert} ->
    -                        {ok, IssuerID} = public_key:pkix_issuer_id(Cert, self),
    -                        IssuerID
    -        end.
    -

    You then only need to match the IssuerID value to authenticate the -user.

    -
    - +
    socket_to_issuer_id(Socket) ->
    +	case ssl:peercert(Socket) of
    +		{error, no_peercert} ->
    +			false;
    +		{ok, Cert} ->
    +			{ok, IssuerID} = public_key:pkix_issuer_id(Cert, self),
    +			IssuerID
    +	end.
    + +

    You then only need to match the IssuerID value to authenticate the user.

    + @@ -270,6 +194,8 @@ user.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.3/guide/transports/index.html b/docs/en/ranch/1.3/guide/transports/index.html index 103ae423..09bf93b3 100644 --- a/docs/en/ranch/1.3/guide/transports/index.html +++ b/docs/en/ranch/1.3/guide/transports/index.html @@ -62,179 +62,107 @@

    Transports

    -

    A transport defines the interface to interact with a socket.

    -

    Transports can be used for connecting, listening and accepting -connections, but also for receiving and sending data. Both -passive and active mode are supported, although all sockets -are initialized as passive.

    -
    +

    A transport defines the interface to interact with a socket.

    +

    Transports can be used for connecting, listening and accepting connections, but also for receiving and sending data. Both passive and active mode are supported, although all sockets are initialized as passive.

    TCP transport

    -
    -

    The TCP transport is a thin wrapper around gen_tcp.

    -
    -
    -
    +

    The TCP transport is a thin wrapper around gen_tcp.

    SSL transport

    -
    -

    The SSL transport is a thin wrapper around ssl.

    -

    Ranch depends on ssl by default so any necessary -dependencies will start when Ranch is started. It is -possible to remove the dependency when the SSL transport -will not be used. Refer to your release build tool’s -documentation for more information.

    -

    When embedding Ranch listeners that have an SSL transport, -your application must depend on the ssl application for -proper behavior.

    -
    -
    -
    +

    The SSL transport is a thin wrapper around ssl.

    +

    Ranch depends on ssl by default so any necessary dependencies will start when Ranch is started. It is possible to remove the dependency when the SSL transport will not be used. Refer to your release build tool's documentation for more information.

    +

    When embedding Ranch listeners that have an SSL transport, your application must depend on the ssl application for proper behavior.

    Sending and receiving data

    -
    -

    This section assumes that Transport is a valid transport handler -(like ranch_tcp or ranch_ssl) and Socket is a connected -socket obtained through the listener.

    -

    You can send data to a socket by calling the Transport:send/2 -function. The data can be given as iodata(), which is defined as -binary() | iolist(). All the following calls will work:

    -
    -
    Sending data to the socket
    -
    -
    Transport:send(Socket, <<"Ranch is cool!">>).
    -Transport:send(Socket, "Ranch is cool!").
    -Transport:send(Socket, ["Ranch", ["is", "cool!"]]).
    -Transport:send(Socket, ["Ranch", [<<"is">>, "cool!"]]).
    -

    You can receive data either in passive or in active mode. Passive mode -means that you will perform a blocking Transport:recv/3 call, while -active mode means that you will receive the data as a message.

    -

    By default, all data will be received as binary. It is possible to -receive data as strings, although this is not recommended as binaries -are a more efficient construct, especially for binary protocols.

    -

    Receiving data using passive mode requires a single function call. The -first argument is the socket, and the third argument is a timeout duration -before the call returns with {error, timeout}.

    -

    The second argument is the amount of data in bytes that we want to receive. -The function will wait for data until it has received exactly this amount. -If you are not expecting a precise size, you can specify 0 which will make -this call return as soon as data was read, regardless of its size.

    -
    -
    Receiving data from the socket in passive mode
    -
    -
    {ok, Data} = Transport:recv(Socket, 0, 5000).
    -

    Active mode requires you to inform the socket that you want to receive -data as a message and to write the code to actually receive it.

    -

    There are two kinds of active modes: {active, once} and -{active, true}. The first will send a single message before going -back to passive mode; the second will send messages indefinitely. -We recommend not using the {active, true} mode as it could quickly -flood your process mailbox. It’s better to keep the data in the socket -and read it only when required.

    -

    Three different messages can be received:

    -
      -
    • -

      -{OK, Socket, Data} -

      +
      {ok, Data} = Transport:recv(Socket, 0, 5000).
      +
    +

    Active mode requires you to inform the socket that you want to receive data as a message and to write the code to actually receive it.

    +

    There are two kinds of active modes: {active, once} and {active, true}. The first will send a single message before going back to passive mode; the second will send messages indefinitely. We recommend not using the {active, true} mode as it could quickly flood your process mailbox. It's better to keep the data in the socket and read it only when required.

    +

    Three different messages can be received:

    +
    • {OK, Socket, Data}
    • -
    • -

      -{Closed, Socket} -

      +
    • {Closed, Socket}
    • -
    • -

      -{Error, Socket, Reason} -

      +
    • {Error, Socket, Reason}
    • -
    -

    The value of OK, Closed and Error can be different -depending on the transport being used. To be able to properly match -on them you must first call the Transport:messages/0 function.

    -
    -
    Retrieving the transport’s active message identifiers
    -
    -
    {OK, Closed, Error} = Transport:messages().
    -

    To start receiving messages you will need to call the Transport:setopts/2 -function, and do so every time you want to receive data.

    -
    -
    Receiving messages from the socket in active mode
    -
    -
    {OK, Closed, Error} = Transport:messages(),
    -Transport:setopts(Socket, [{active, once}]),
    -receive
    -        {OK, Socket, Data} ->
    -                io:format("data received: ~p~n", [Data]);
    -        {Closed, Socket} ->
    -                io:format("socket got closed!~n");
    -        {Error, Socket, Reason} ->
    -                io:format("error happened: ~p~n", [Reason])
    -end.
    -

    You can easily integrate active sockets with existing Erlang code as all -you really need is just a few more clauses when receiving messages.

    - - -
    +
    {OK, Closed, Error} = Transport:messages(),
    +Transport:setopts(Socket, [{active, once}]),
    +receive
    +	{OK, Socket, Data} ->
    +		io:format("data received: ~p~n", [Data]);
    +	{Closed, Socket} ->
    +		io:format("socket got closed!~n");
    +	{Error, Socket, Reason} ->
    +		io:format("error happened: ~p~n", [Reason])
    +end.
    +
    +

    You can easily integrate active sockets with existing Erlang code as all you really need is just a few more clauses when receiving messages.

    Sending files

    -
    -

    As in the previous section it is assumed Transport is a valid transport -handler and Socket is a connected socket obtained through the listener.

    -

    To send a whole file, with name Filename, over a socket:

    -
    -
    Sending a file by filename
    -
    -
    {ok, SentBytes} = Transport:sendfile(Socket, Filename).
    -

    Or part of a file, with Offset greater than or equal to 0, Bytes number of -bytes and chunks of size ChunkSize:

    -
    -
    Sending part of a file by filename in chunks
    -
    -
    Opts = [{chunk_size, ChunkSize}],
    -{ok, SentBytes} = Transport:sendfile(Socket, Filename, Offset, Bytes, Opts).
    -

    To improve efficiency when sending multiple parts of the same file it is also -possible to use a file descriptor opened in raw mode:

    -
    -
    Sending a file opened in raw mode
    -
    -
    {ok, RawFile} = file:open(Filename, [raw, read, binary]),
    -{ok, SentBytes} = Transport:sendfile(Socket, RawFile, Offset, Bytes, Opts).
    -
    - -
    +
    {ok, RawFile} = file:open(Filename, [raw, read, binary]),
    +{ok, SentBytes} = Transport:sendfile(Socket, RawFile, Offset, Bytes, Opts).
    +

    Writing a transport handler

    -
    -

    A transport handler is a module implementing the ranch_transport behavior. -It defines a certain number of callbacks that must be written in order to -allow transparent usage of the transport handler.

    -

    The behavior doesn’t define the socket options available when opening a -socket. These do not need to be common to all transports as it’s easy enough -to write different initialization functions for the different transports that -will be used. With one exception though. The setopts/2 function must -implement the {active, once} and the {active, true} options.

    -

    If the transport handler doesn’t have a native implementation of sendfile/5 a -fallback is available, ranch_transport:sendfile/6. The extra first argument -is the transport’s module. See ranch_ssl for an example.

    -
    - +

    A transport handler is a module implementing the ranch_transport behavior. It defines a certain number of callbacks that must be written in order to allow transparent usage of the transport handler.

    +

    The behavior doesn't define the socket options available when opening a socket. These do not need to be common to all transports as it's easy enough to write different initialization functions for the different transports that will be used. With one exception though. The setopts/2 function must implement the {active, once} and the {active, true} options.

    +

    If the transport handler doesn't have a native implementation of sendfile/5 a fallback is available, ranch_transport:sendfile/6. The extra first argument is the transport's module. See ranch_ssl for an example.

    + @@ -291,6 +219,8 @@ is the transport’s module. See ranch_ssl for an example.

    < +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.3/manual/index.html b/docs/en/ranch/1.3/manual/index.html index 3e9ec4eb..a3d157c5 100644 --- a/docs/en/ranch/1.3/manual/index.html +++ b/docs/en/ranch/1.3/manual/index.html @@ -62,38 +62,20 @@

    Ranch Function Reference

    - + + @@ -128,6 +110,8 @@ +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.3/manual/ranch/index.html b/docs/en/ranch/1.3/manual/ranch/index.html index d1897b1d..d4c74209 100644 --- a/docs/en/ranch/1.3/manual/ranch/index.html +++ b/docs/en/ranch/1.3/manual/ranch/index.html @@ -62,558 +62,228 @@

    ranch(3)

    -

    Name

    -
    -

    ranch - socket acceptor pool

    -
    -
    -
    +

    ranch - socket acceptor pool

    Description

    -
    -

    The ranch module provides functions for starting and -manipulating Ranch listeners.

    -
    -
    -
    +

    The ranch module provides functions for starting and manipulating Ranch listeners.

    Types

    -
    -
    -

    max_conns() = non_neg_integer() | infinity

    -

    Maximum number of connections allowed on this listener.

    -

    This is a soft limit. The actual number of connections -might be slightly above the limit due to concurrency -when accepting new connections. Some connections may -also be removed from this count explicitly by the user -code.

    -
    -
    +

    max_conns() = non_neg_integer() | infinity

    +

    Maximum number of connections allowed on this listener.

    +

    This is a soft limit. The actual number of connections might be slightly above the limit due to concurrency when accepting new connections. Some connections may also be removed from this count explicitly by the user code.

    opt()

    -
    -
    -
    opt() = {ack_timeout, timeout()}
    -        | {connection_type, worker | supervisor}
    -        | {max_connections, max_conns()}
    -        | {shutdown, timeout() | brutal_kill}
    -        | {socket, any()}
    -

    Ranch-specific transport options.

    -

    These options are not passed on to the transports. -They are used by Ranch while setting up the listeners.

    -
    -
    -

    ref() = any()

    -

    Unique name used to refer to a listener.

    -
    -
    -
    -
    +
    opt() = {ack_timeout, timeout()}
    +	| {connection_type, worker | supervisor}
    +	| {max_connections, max_conns()}
    +	| {shutdown, timeout() | brutal_kill}
    +	| {socket, any()}
    +
    +

    Ranch-specific transport options.

    +

    These options are not passed on to the transports. They are used by Ranch while setting up the listeners.

    +

    ref() = any()

    +

    Unique name used to refer to a listener.

    Option descriptions

    -
    -

    None of the options are required.

    -
    -
    -ack_timeout (5000) -
    -
    -

    - Maximum allowed time for the ranch:accept_ack/1 call to finish. -

    -
    -
    -connection_type (worker) -
    -
    -

    - Type of process that will handle the connection. -

    -
    -
    -max_connections (1024) -
    -
    -

    - Maximum number of active connections. Soft limit. Using infinity will disable the limit entirely. -

    -
    -
    -shutdown (5000) -
    -
    -

    - Maximum allowed time for children to stop on listener shutdown. -

    -
    -
    -socket -
    -
    -

    - Listening socket opened externally to be used instead of calling Transport:listen/1. -

    -
    -
    -
    - -
    +

    None of the options are required.

    +
    ack_timeout (5000)
    +

    Maximum allowed time for the ranch:accept_ack/1 call to finish.

    +
    +
    connection_type (worker)
    +

    Type of process that will handle the connection.

    +
    +
    max_connections (1024)
    +

    Maximum number of active connections. Soft limit. Using infinity will disable the limit entirely.

    +
    +
    shutdown (5000)
    +

    Maximum allowed time for children to stop on listener shutdown.

    +
    +
    socket
    +

    Listening socket opened externally to be used instead of calling Transport:listen/1.

    +
    +

    Exports

    -
    -
    -

    accept_ack(Ref) → ok

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -

    Acknowledge that the connection is accepted.

    -

    This function MUST be used by a connection process to inform -Ranch that it initialized properly and let it perform any -additional operations before the socket can be safely used.

    -
    -
    -

    child_spec(Ref, NumAcceptors, Transport, TransOpts, Protocol, ProtoOpts) → supervisor:child_spec()

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -NumAcceptors = non_neg_integer() -
    -
    -

    -Number of acceptor processes. -

    -
    -
    -Transport = module() -
    -
    -

    -Transport module. -

    -
    -
    -TransOpts = any() -
    -
    -

    -Transport options. -

    -
    -
    -Protocol = module() -
    -
    -

    -Protocol module. -

    -
    -
    -ProtoOpts = any() -
    -
    -

    -Protocol options. -

    -
    -
    -

    Return child specifications for a new listener.

    -

    This function can be used to embed a listener directly -in an application instead of letting Ranch handle it.

    -
    -
    -

    get_addr(Ref) → {IP, Port}

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -IP = inet:ip_address() -
    -
    -

    -IP of the interface used by this listener. -

    -
    -
    -Port = inet:port_number() -
    -
    -

    -Port number used by this listener. -

    -
    -
    -

    Return the IP address and port for the given listener.

    -
    -
    -

    get_max_connections(Ref) → MaxConns

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -MaxConns = max_conns() -
    -
    -

    -Current maximum number of connections. -

    -
    -
    -

    Return the max number of connections allowed for the given listener.

    -
    -
    -

    get_port(Ref) → Port

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -Port = inet:port_number() -
    -
    -

    -Port number used by this listener. -

    -
    -
    -

    Return the port for the given listener.

    -
    -
    -

    get_protocol_options(Ref) → ProtoOpts

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -ProtoOpts = any() -
    -
    -

    -Current protocol options. -

    -
    -
    -

    Return the protocol options set for the given listener.

    -
    -
    -

    info() → [{Ref, [{Key, Value}]}]

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -Key = atom() -
    -
    -

    -Information key. -

    -
    -
    -Value = any() -
    -
    -

    -Information value. -

    -
    -
    -

    Return detailed information about all Ranch listeners.

    -

    The following keys are defined:

    -
    -
    -pid -
    -
    -

    -Pid of the listener’s top-level supervisor. -

    -
    -
    -ip -
    -
    -

    -Interface Ranch listens on. -

    -
    -
    -port -
    -
    -

    -Port number Ranch listens on. -

    -
    -
    -num_acceptors -
    -
    -

    -Number of acceptor processes. -

    -
    -
    -max_connections -
    -
    -

    -Maximum number of connections. -

    -
    -
    -active_connections -
    -
    -

    -Number of active connections. -

    -
    -
    -all_connections -
    -
    -

    -Number of connections, including those removed from the count. -

    -
    -
    -transport -
    -
    -

    -Transport module. -

    -
    -
    -transport_options -
    -
    -

    -Transport options. -

    -
    -
    -protocol -
    -
    -

    -Protocol module. -

    -
    -
    -protocol_options -
    -
    -

    -Protocol options. -

    -
    -
    -
    -
    -

    procs(Ref, acceptors | connections) → [pid()]

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -

    Return all acceptor or connection processes for one listener.

    -
    -
    -

    remove_connection(Ref) → ok

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -

    Do not count this connection when limiting the number of connections.

    -

    You can use this function for long-running connection processes -which spend most of their time idling rather than consuming -resources. This allows Ranch to accept a lot more connections -without sacrificing the latency of the system.

    -

    This function may only be called from a connection process.

    -
    -
    -

    set_max_connections(Ref, MaxConns) → ok

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -MaxConns = max_conns() -
    -
    -

    -New maximum number of connections. -

    -
    -
    -

    Set the max number of connections for the given listener.

    -

    The change will be applied immediately. If the new value is -smaller than the previous one, Ranch will not kill the extra -connections, but will wait for them to terminate properly.

    -
    -
    -

    set_protocol_options(Ref, ProtoOpts) → ok

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -ProtoOpts = any() -
    -
    -

    -New protocol options. -

    -
    -
    -

    Set the protocol options for the given listener.

    -

    The change will be applied immediately for all new connections. -Old connections will not receive the new options.

    -
    -
    -

    start_listener(Ref, NumAcceptors, Transport, TransOpts, Protocol, ProtoOpts) → {ok, pid()} | {error, badarg}

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -NumAcceptors = non_neg_integer() -
    -
    -

    -Number of acceptor processes. -

    -
    -
    -Transport = module() -
    -
    -

    -Transport module. -

    -
    -
    -TransOpts = any() -
    -
    -

    -Transport options. -

    -
    -
    -Protocol = module() -
    -
    -

    -Protocol module. -

    -
    -
    -ProtoOpts = any() -
    -
    -

    -Protocol options. -

    -
    -
    -

    Start listening for connections using the given transport -and protocol. Returns the pid for this listener’s supervisor.

    -

    There are additional transport options that apply -regardless of transport. They allow configuring how the -connections are supervised, rate limited and more. Please -consult the previous section for more details.

    -
    -
    -

    stop_listener(Ref) → ok | {error, not_found}

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -

    Stop the given listener.

    -

    The listener is stopped gracefully, first by closing the -listening port, then by stopping the connection processes. -These processes are stopped according to the shutdown -transport option, which may be set to brutally kill all -connection processes or give them some time to stop properly.

    -

    This function does not return until the listener is -completely stopped.

    -
    -
    -
    +

    accept_ack(Ref) -> ok

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    +

    Acknowledge that the connection is accepted.

    +

    This function MUST be used by a connection process to inform Ranch that it initialized properly and let it perform any additional operations before the socket can be safely used.

    +

    child_spec(Ref, NumAcceptors, Transport, TransOpts, Protocol, ProtoOpts) -> supervisor:child_spec()

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    NumAcceptors = non_neg_integer()
    +

    Number of acceptor processes.

    +
    +
    Transport = module()
    +

    Transport module.

    +
    +
    TransOpts = any()
    +

    Transport options.

    +
    +
    Protocol = module()
    +

    Protocol module.

    +
    +
    ProtoOpts = any()
    +

    Protocol options.

    +
    +
    +

    Return child specifications for a new listener.

    +

    This function can be used to embed a listener directly in an application instead of letting Ranch handle it.

    +

    get_addr(Ref) -> {IP, Port}

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    IP = inet:ip_address()
    +

    IP of the interface used by this listener.

    +
    +
    Port = inet:port_number()
    +

    Port number used by this listener.

    +
    +
    +

    Return the IP address and port for the given listener.

    +

    get_max_connections(Ref) -> MaxConns

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    MaxConns = max_conns()
    +

    Current maximum number of connections.

    +
    +
    +

    Return the max number of connections allowed for the given listener.

    +

    get_port(Ref) -> Port

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    Port = inet:port_number()
    +

    Port number used by this listener.

    +
    +
    +

    Return the port for the given listener.

    +

    get_protocol_options(Ref) -> ProtoOpts

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    ProtoOpts = any()
    +

    Current protocol options.

    +
    +
    +

    Return the protocol options set for the given listener.

    +

    info() -> [{Ref, [{Key, Value}]}]

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    Key = atom()
    +

    Information key.

    +
    +
    Value = any()
    +

    Information value.

    +
    +
    +

    Return detailed information about all Ranch listeners.

    +

    The following keys are defined:

    +
    pid
    +

    Pid of the listener's top-level supervisor.

    +
    +
    ip
    +

    Interface Ranch listens on.

    +
    +
    port
    +

    Port number Ranch listens on.

    +
    +
    num_acceptors
    +

    Number of acceptor processes.

    +
    +
    max_connections
    +

    Maximum number of connections.

    +
    +
    active_connections
    +

    Number of active connections.

    +
    +
    all_connections
    +

    Number of connections, including those removed from the count.

    +
    +
    transport
    +

    Transport module.

    +
    +
    transport_options
    +

    Transport options.

    +
    +
    protocol
    +

    Protocol module.

    +
    +
    protocol_options
    +

    Protocol options.

    +
    +
    +

    procs(Ref, acceptors | connections) -> [pid()]

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    +

    Return all acceptor or connection processes for one listener.

    +

    remove_connection(Ref) -> ok

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    +

    Do not count this connection when limiting the number of connections.

    +

    You can use this function for long-running connection processes which spend most of their time idling rather than consuming resources. This allows Ranch to accept a lot more connections without sacrificing the latency of the system.

    +

    This function may only be called from a connection process.

    +

    set_max_connections(Ref, MaxConns) -> ok

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    MaxConns = max_conns()
    +

    New maximum number of connections.

    +
    +
    +

    Set the max number of connections for the given listener.

    +

    The change will be applied immediately. If the new value is smaller than the previous one, Ranch will not kill the extra connections, but will wait for them to terminate properly.

    +

    set_protocol_options(Ref, ProtoOpts) -> ok

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    ProtoOpts = any()
    +

    New protocol options.

    +
    +
    +

    Set the protocol options for the given listener.

    +

    The change will be applied immediately for all new connections. Old connections will not receive the new options.

    +

    start_listener(Ref, NumAcceptors, Transport, TransOpts, Protocol, ProtoOpts) -> {ok, pid()} | {error, badarg}

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    NumAcceptors = non_neg_integer()
    +

    Number of acceptor processes.

    +
    +
    Transport = module()
    +

    Transport module.

    +
    +
    TransOpts = any()
    +

    Transport options.

    +
    +
    Protocol = module()
    +

    Protocol module.

    +
    +
    ProtoOpts = any()
    +

    Protocol options.

    +
    +
    +

    Start listening for connections using the given transport and protocol. Returns the pid for this listener's supervisor.

    +

    There are additional transport options that apply regardless of transport. They allow configuring how the connections are supervised, rate limited and more. Please consult the previous section for more details.

    +

    stop_listener(Ref) -> ok | {error, not_found}

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    +

    Stop the given listener.

    +

    The listener is stopped gracefully, first by closing the listening port, then by stopping the connection processes. These processes are stopped according to the shutdown transport option, which may be set to brutally kill all connection processes or give them some time to stop properly.

    +

    This function does not return until the listener is completely stopped.

    + @@ -648,6 +318,8 @@ completely stopped.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.3/manual/ranch_app/index.html b/docs/en/ranch/1.3/manual/ranch_app/index.html index a63f6056..8ae52cde 100644 --- a/docs/en/ranch/1.3/manual/ranch_app/index.html +++ b/docs/en/ranch/1.3/manual/ranch_app/index.html @@ -62,41 +62,18 @@

    ranch(7)

    -

    Name

    -
    -

    ranch - Socket acceptor pool for TCP protocols.

    -
    -
    -
    +

    ranch - Socket acceptor pool for TCP protocols.

    Dependencies

    -
    -

    The ranch application depends on the ssl application to -start. It is used for handling secure connections, when the -transport is ranch_ssl. It can be disabled if SSL is not -used.

    -
    -
    -
    +

    The ranch application depends on the ssl application to start. It is used for handling secure connections, when the transport is ranch_ssl. It can be disabled if SSL is not used.

    Environment

    -
    -

    The ranch application defines one application environment -configuration parameter.

    -
    -
    -profile (false) -
    -
    -

    - When enabled, Ranch will start eprof profiling automatically. -

    +

    The ranch application defines one application environment configuration parameter.

    +
    profile (false)
    +

    When enabled, Ranch will start eprof profiling automatically.

    -
    -

    You can use the ranch_app:profile_output/0 function to stop -profiling and output the results to the files procs.profile -and total.profile. Do not use in production.

    -
    -
    + +

    You can use the ranch_app:profile_output/0 function to stop profiling and output the results to the files procs.profile and total.profile. Do not use in production.

    + @@ -131,6 +108,8 @@ and total.profile. Do not use in production.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.3/manual/ranch_protocol/index.html b/docs/en/ranch/1.3/manual/ranch_protocol/index.html index 0d9124cf..dde2746d 100644 --- a/docs/en/ranch/1.3/manual/ranch_protocol/index.html +++ b/docs/en/ranch/1.3/manual/ranch_protocol/index.html @@ -62,83 +62,33 @@

    ranch_protocol(3)

    -

    Name

    -
    -

    ranch_protocol - behaviour for protocol modules

    -
    -
    -
    +

    ranch_protocol - behaviour for protocol modules

    Description

    -
    -

    The ranch_protocol behaviour defines the interface used -by Ranch protocols.

    -
    -
    -
    +

    The ranch_protocol behaviour defines the interface used by Ranch protocols.

    Types

    -
    -

    None.

    -
    -
    -
    +

    None.

    Callbacks

    -
    -
    - -
    -
    -Ref = ranch:ref() -
    -
    -

    -Listener name. -

    + +
    Ref = ranch:ref()
    +

    Listener name.

    -
    -Socket = any() -
    -
    -

    -Socket for this connection. -

    +
    Socket = any()
    +

    Socket for this connection.

    -
    -Transport = module() -
    -
    -

    -Transport module for this socket. -

    +
    Transport = module()
    +

    Transport module for this socket.

    -
    -ProtoOpts = any() -
    -
    -

    -Protocol options. -

    +
    ProtoOpts = any()
    +

    Protocol options.

    -
    -

    Start a new connection process for the given socket.

    -

    The only purpose of this callback is to start a process that -will handle the socket. It must spawn the process, link and -then return the new pid. This function will always be called -from inside a supervisor.

    -

    This callback can also return two pids. The first pid is the -pid of the process that will be supervised. The second pid is -the pid of the process that will receive ownership of the -socket. This second process must be a child of the first. This -form is only available when connection_type is set to -supervisor.

    -

    If any other value is returned, the supervisor will close the -socket and assume no process has been started.

    -

    Do not perform any operations in this callback, as this would -block the supervisor responsible for starting connection -processes and degrade performance severely.

    -
    -
    -
    + +

    Start a new connection process for the given socket.

    +

    The only purpose of this callback is to start a process that will handle the socket. It must spawn the process, link and then return the new pid. This function will always be called from inside a supervisor.

    +

    This callback can also return two pids. The first pid is the pid of the process that will be supervised. The second pid is the pid of the process that will receive ownership of the socket. This second process must be a child of the first. This form is only available when connection_type is set to supervisor.

    +

    If any other value is returned, the supervisor will close the socket and assume no process has been started.

    +

    Do not perform any operations in this callback, as this would block the supervisor responsible for starting connection processes and degrade performance severely.

    + @@ -173,6 +123,8 @@ processes and degrade performance severely.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.3/manual/ranch_ssl/index.html b/docs/en/ranch/1.3/manual/ranch_ssl/index.html index 1367b965..2132ad99 100644 --- a/docs/en/ranch/1.3/manual/ranch_ssl/index.html +++ b/docs/en/ranch/1.3/manual/ranch_ssl/index.html @@ -62,385 +62,174 @@

    ranch_ssl(3)

    -

    Name

    -
    -

    ranch_ssl - SSL transport module

    -
    -
    -
    +

    ranch_ssl - SSL transport module

    Description

    -
    -

    The ranch_ssl module implements an SSL Ranch transport.

    -
    -
    -
    +

    The ranch_ssl module implements an SSL Ranch transport.

    Types

    -
    -

    ssl_opt()

    -
    -
    -
    ssl_opt() = {alpn_preferred_protocols, [binary()]}
    -        | {beast_mitigation, one_n_minus_one | zero_n | disabled}
    -        | {cacertfile, string()}
    -        | {cacerts, [public_key:der_encoded()]}
    -        | {cert, public_key:der_encoded()}
    -        | {certfile, string()}
    -        | {ciphers, [ssl:erl_cipher_suite()] | string()}
    -        | {client_renegotiation, boolean()}
    -        | {crl_cache, {module(), {internal | any(), list()}}}
    -        | {crl_check, boolean() | peer | best_effort}
    -        | {depth, 0..255}
    -        | {dh, public_key:der_encoded()}
    -        | {dhfile, string()}
    -        | {fail_if_no_peer_cert, boolean()}
    -        | {hibernate_after, integer() | undefined}
    -        | {honor_cipher_order, boolean()}
    -        | {key, {'RSAPrivateKey' | 'DSAPrivateKey' | 'PrivateKeyInfo', public_key:der_encoded()}}
    -        | {keyfile, string()}
    -        | {log_alert, boolean()}
    -        | {next_protocols_advertised, [binary()]}
    -        | {padding_check, boolean()}
    -        | {partial_chain, fun(([public_key:der_encoded()]) -> {trusted_ca, public_key:der_encoded()} | unknown_ca)}
    -        | {password, string()}
    -        | {psk_identity, string()}
    -        | {reuse_session, fun()}
    -        | {reuse_sessions, boolean()}
    -        | {secure_renegotiate, boolean()}
    -        | {signature_algs, [{atom(), atom()}]}
    -        | {sni_fun, fun()}
    -        | {sni_hosts, [{string(), ssl_opt()}]}
    -        | {user_lookup_fun, {fun(), any()}}
    -        | {v2_hello_compatible, boolean()}
    -        | {verify, ssl:verify_type()}
    -        | {verify_fun, {fun(), any()}}
    -        | {versions, [atom()]}.
    -

    SSL-specific listen options.

    -
    -
    -

    opt() = ranch_tcp:opt() | ssl_opt()

    -

    Listen options.

    -
    -
    -

    opts() = [opt()]

    -

    List of listen options.

    -
    -
    -
    -
    +
    ssl_opt() = {alpn_preferred_protocols, [binary()]}
    +	| {beast_mitigation, one_n_minus_one | zero_n | disabled}
    +	| {cacertfile, string()}
    +	| {cacerts, [public_key:der_encoded()]}
    +	| {cert, public_key:der_encoded()}
    +	| {certfile, string()}
    +	| {ciphers, [ssl:erl_cipher_suite()] | string()}
    +	| {client_renegotiation, boolean()}
    +	| {crl_cache, {module(), {internal | any(), list()}}}
    +	| {crl_check, boolean() | peer | best_effort}
    +	| {depth, 0..255}
    +	| {dh, public_key:der_encoded()}
    +	| {dhfile, string()}
    +	| {fail_if_no_peer_cert, boolean()}
    +	| {hibernate_after, integer() | undefined}
    +	| {honor_cipher_order, boolean()}
    +	| {key, {'RSAPrivateKey' | 'DSAPrivateKey' | 'PrivateKeyInfo', public_key:der_encoded()}}
    +	| {keyfile, string()}
    +	| {log_alert, boolean()}
    +	| {next_protocols_advertised, [binary()]}
    +	| {padding_check, boolean()}
    +	| {partial_chain, fun(([public_key:der_encoded()]) -> {trusted_ca, public_key:der_encoded()} | unknown_ca)}
    +	| {password, string()}
    +	| {psk_identity, string()}
    +	| {reuse_session, fun()}
    +	| {reuse_sessions, boolean()}
    +	| {secure_renegotiate, boolean()}
    +	| {signature_algs, [{atom(), atom()}]}
    +	| {sni_fun, fun()}
    +	| {sni_hosts, [{string(), ssl_opt()}]}
    +	| {user_lookup_fun, {fun(), any()}}
    +	| {v2_hello_compatible, boolean()}
    +	| {verify, ssl:verify_type()}
    +	| {verify_fun, {fun(), any()}}
    +	| {versions, [atom()]}.
    +
    +

    SSL-specific listen options.

    +

    opt() = ranch_tcp:opt() | ssl_opt()

    +

    Listen options.

    +

    opts() = [opt()]

    +

    List of listen options.

    Option descriptions

    -
    -

    Specifying a certificate is mandatory, either through the cert -or the certfile option. None of the other options are required.

    -

    The default value is given next to the option name.

    -
    -
    -alpn_preferred_protocols -
    -
    -

    - Perform Application-Layer Protocol Negotiation with the given list of preferred protocols. -

    -
    -
    -beast_mitigation -
    -
    -

    - Change the BEAST mitigation strategy for SSL-3.0 and TLS-1.0 to interoperate with legacy software. -

    -
    -
    -cacertfile -
    -
    -

    - Path to PEM encoded trusted certificates file used to verify peer certificates. -

    -
    -
    -cacerts -
    -
    -

    - List of DER encoded trusted certificates. -

    -
    -
    -cert -
    -
    -

    - DER encoded user certificate. -

    -
    -
    -certfile -
    -
    -

    - Path to the PEM encoded user certificate file. May also contain the private key. -

    -
    -
    -ciphers -
    -
    -

    - List of ciphers that clients are allowed to use. -

    -
    -
    -client_renegotiation (true) -
    -
    -

    - Whether to allow client-initiated renegotiation. -

    -
    -
    -crl_cache ({ssl_crl_cache, {internal, []}}) -
    -
    -

    - Customize the module used to cache Certificate Revocation Lists. -

    -
    -
    -crl_check (false) -
    -
    -

    - Whether to perform CRL check on all certificates in the chain during validation. -

    -
    -
    -depth (1) -
    -
    -

    - Maximum of intermediate certificates allowed in the certification path. -

    -
    -
    -dh -
    -
    -

    - DER encoded Diffie-Hellman parameters. -

    -
    -
    -dhfile -
    -
    -

    - Path to the PEM encoded Diffie-Hellman parameters file. -

    -
    -
    -fail_if_no_peer_cert (false) -
    -
    -

    - Whether to refuse the connection if the client sends an empty certificate. -

    -
    -
    -hibernate_after (undefined) -
    -
    -

    - Time in ms after which SSL socket processes go into hibernation to reduce memory usage. -

    -
    -
    -honor_cipher_order (false) -
    -
    -

    - If true, use the server’s preference for cipher selection. If false, use the client’s preference. -

    -
    -
    -key -
    -
    -

    - DER encoded user private key. -

    -
    -
    -keyfile -
    -
    -

    - Path to the PEM encoded private key file, if different than the certfile. -

    -
    -
    -log_alert (true) -
    -
    -

    - If false, error reports will not be displayed. -

    -
    -
    -next_protocols_advertised -
    -
    -

    - List of protocols to send to the client if it supports the Next Protocol extension. -

    -
    -
    -nodelay (true) -
    -
    -

    - Whether to enable TCP_NODELAY. -

    -
    -
    -padding_check -
    -
    -

    - Allow disabling the block cipher padding check for TLS-1.0 to be able to interoperate with legacy software. -

    -
    -
    -partial_chain -
    -
    -

    - Claim an intermediate CA in the chain as trusted. -

    -
    -
    -password -
    -
    -

    - Password to the private key file, if password protected. -

    -
    -
    -psk_identity -
    -
    -

    - Provide the given PSK identity hint to the client during the handshake. -

    -
    -
    -reuse_session -
    -
    -

    - Custom policy to decide whether a session should be reused. -

    -
    -
    -reuse_sessions (false) -
    -
    -

    - Whether to allow session reuse. -

    -
    -
    -secure_renegotiate (false) -
    -
    -

    - Whether to reject renegotiation attempts that do not conform to RFC5746. -

    -
    -
    -signature_algs -
    -
    -

    - The TLS signature algorithm extension may be used, from TLS 1.2, to negotiate which signature algorithm to use during the TLS handshake. -

    -
    -
    -sni_fun -
    -
    -

    - Function called when the client requests a host using Server Name Indication. Returns options to apply. -

    -
    -
    -sni_hosts -
    -
    -

    - Options to apply for the host that matches what the client requested with Server Name Indication. -

    -
    -
    -user_lookup_fun -
    -
    -

    - Function called to determine the shared secret when using PSK, or provide parameters when using SRP. -

    -
    -
    -v2_hello_compatible -
    -
    -

    - Accept clients that send hello messages in SSL-2.0 format while offering supported SSL/TLS versions. -

    -
    -
    -verify (verify_none) -
    -
    -

    - Use verify_peer to request a certificate from the client. -

    -
    -
    -verify_fun -
    -
    -

    - Custom policy to decide whether a client certificate is valid. -

    -
    -
    -versions -
    -
    -

    - TLS protocol versions that will be supported. -

    -
    -
    -

    Note that the client will not send a certificate unless the -value for the verify option is set to verify_peer. This -means that the fail_if_no_peer_cert only apply when combined -with the verify option. The verify_fun option allows -greater control over the client certificate validation.

    -

    The options sni_fun and sni_hosts are mutually exclusive.

    -
    - -
    +

    Specifying a certificate is mandatory, either through the cert or the certfile option. None of the other options are required.

    +

    The default value is given next to the option name.

    +
    alpn_preferred_protocols
    +

    Perform Application-Layer Protocol Negotiation with the given list of preferred protocols.

    +
    +
    beast_mitigation
    +

    Change the BEAST mitigation strategy for SSL-3.0 and TLS-1.0 to interoperate with legacy software.

    +
    +
    cacertfile
    +

    Path to PEM encoded trusted certificates file used to verify peer certificates.

    +
    +
    cacerts
    +

    List of DER encoded trusted certificates.

    +
    +
    cert
    +

    DER encoded user certificate.

    +
    +
    certfile
    +

    Path to the PEM encoded user certificate file. May also contain the private key.

    +
    +
    ciphers
    +

    List of ciphers that clients are allowed to use.

    +
    +
    client_renegotiation (true)
    +

    Whether to allow client-initiated renegotiation.

    +
    +
    crl_cache ({ssl_crl_cache, {internal, []}})
    +

    Customize the module used to cache Certificate Revocation Lists.

    +
    +
    crl_check (false)
    +

    Whether to perform CRL check on all certificates in the chain during validation.

    +
    +
    depth (1)
    +

    Maximum of intermediate certificates allowed in the certification path.

    +
    +
    dh
    +

    DER encoded Diffie-Hellman parameters.

    +
    +
    dhfile
    +

    Path to the PEM encoded Diffie-Hellman parameters file.

    +
    +
    fail_if_no_peer_cert (false)
    +

    Whether to refuse the connection if the client sends an empty certificate.

    +
    +
    hibernate_after (undefined)
    +

    Time in ms after which SSL socket processes go into hibernation to reduce memory usage.

    +
    +
    honor_cipher_order (false)
    +

    If true, use the server's preference for cipher selection. If false, use the client's preference.

    +
    +
    key
    +

    DER encoded user private key.

    +
    +
    keyfile
    +

    Path to the PEM encoded private key file, if different than the certfile.

    +
    +
    log_alert (true)
    +

    If false, error reports will not be displayed.

    +
    +
    next_protocols_advertised
    +

    List of protocols to send to the client if it supports the Next Protocol extension.

    +
    +
    nodelay (true)
    +

    Whether to enable TCP_NODELAY.

    +
    +
    padding_check
    +

    Allow disabling the block cipher padding check for TLS-1.0 to be able to interoperate with legacy software.

    +
    +
    partial_chain
    +

    Claim an intermediate CA in the chain as trusted.

    +
    +
    password
    +

    Password to the private key file, if password protected.

    +
    +
    psk_identity
    +

    Provide the given PSK identity hint to the client during the handshake.

    +
    +
    reuse_session
    +

    Custom policy to decide whether a session should be reused.

    +
    +
    reuse_sessions (false)
    +

    Whether to allow session reuse.

    +
    +
    secure_renegotiate (false)
    +

    Whether to reject renegotiation attempts that do not conform to RFC5746.

    +
    +
    signature_algs
    +

    The TLS signature algorithm extension may be used, from TLS 1.2, to negotiate which signature algorithm to use during the TLS handshake.

    +
    +
    sni_fun
    +

    Function called when the client requests a host using Server Name Indication. Returns options to apply.

    +
    +
    sni_hosts
    +

    Options to apply for the host that matches what the client requested with Server Name Indication.

    +
    +
    user_lookup_fun
    +

    Function called to determine the shared secret when using PSK, or provide parameters when using SRP.

    +
    +
    v2_hello_compatible
    +

    Accept clients that send hello messages in SSL-2.0 format while offering supported SSL/TLS versions.

    +
    +
    verify (verify_none)
    +

    Use verify_peer to request a certificate from the client.

    +
    +
    verify_fun
    +

    Custom policy to decide whether a client certificate is valid.

    +
    +
    versions
    +

    TLS protocol versions that will be supported.

    +
    +
    +

    Note that the client will not send a certificate unless the value for the verify option is set to verify_peer. This means that the fail_if_no_peer_cert only apply when combined with the verify option. The verify_fun option allows greater control over the client certificate validation.

    +

    The options sni_fun and sni_hosts are mutually exclusive.

    Exports

    -
    -

    None.

    -
    -
    +

    None.

    + @@ -475,6 +264,8 @@ greater control over the client certificate validation.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.3/manual/ranch_tcp/index.html b/docs/en/ranch/1.3/manual/ranch_tcp/index.html index 89c3b36a..157371ae 100644 --- a/docs/en/ranch/1.3/manual/ranch_tcp/index.html +++ b/docs/en/ranch/1.3/manual/ranch_tcp/index.html @@ -62,283 +62,127 @@

    ranch_tcp(3)

    -

    Name

    -
    -

    ranch_tcp - TCP transport module

    -
    -
    -
    +

    ranch_tcp - TCP transport module

    Description

    -
    -

    The ranch_tcp module implements a TCP Ranch transport.

    -

    Note that due to bugs in OTP up to at least R16B02, it is -recommended to disable async threads when using the -sendfile function of this transport, as it can make -the threads stuck indefinitely.

    -
    -
    -
    +

    The ranch_tcp module implements a TCP Ranch transport.

    +

    Note that due to bugs in OTP up to at least R16B02, it is recommended to disable async threads when using the sendfile function of this transport, as it can make the threads stuck indefinitely.

    Types

    -
    -

    opt()

    -
    -
    -
    opt() = {backlog, non_neg_integer()}
    -        | {buffer, non_neg_integer()}
    -        | {delay_send, boolean()}
    -        | {dontroute, boolean()}
    -        | {exit_on_close, boolean()}
    -        | {fd, non_neg_integer()}
    -        | {high_msgq_watermark, non_neg_integer()}
    -        | {high_watermark, non_neg_integer()}
    -        | inet
    -        | inet6
    -        | {ip, inet:ip_address()}
    -        | {ipv6_v6only, boolean()}
    -        | {keepalive, boolean()}
    -        | {linger, {boolean(), non_neg_integer()}}
    -        | {low_msgq_watermark, non_neg_integer()}
    -        | {low_watermark, non_neg_integer()}
    -        | {nodelay, boolean()}
    -        | {port, inet:port_number()}
    -        | {priority, integer()}
    -        | {raw, non_neg_integer(), non_neg_integer(), binary()}
    -        | {recbuf, non_neg_integer()}
    -        | {send_timeout, timeout()}
    -        | {send_timeout_close, boolean()}
    -        | {sndbuf, non_neg_integer()}
    -        | {tos, integer()}
    -

    Listen options.

    -

    This does not represent the entirety of the options that can -be set on the socket, but only the options that may be -set independently of protocol implementation.

    -
    -
    -

    opts() = [opt()]

    -

    List of listen options.

    -
    -
    -
    -
    +
    opt() = {backlog, non_neg_integer()}
    +	| {buffer, non_neg_integer()}
    +	| {delay_send, boolean()}
    +	| {dontroute, boolean()}
    +	| {exit_on_close, boolean()}
    +	| {fd, non_neg_integer()}
    +	| {high_msgq_watermark, non_neg_integer()}
    +	| {high_watermark, non_neg_integer()}
    +	| inet
    +	| inet6
    +	| {ip, inet:ip_address()}
    +	| {ipv6_v6only, boolean()}
    +	| {keepalive, boolean()}
    +	| {linger, {boolean(), non_neg_integer()}}
    +	| {low_msgq_watermark, non_neg_integer()}
    +	| {low_watermark, non_neg_integer()}
    +	| {nodelay, boolean()}
    +	| {port, inet:port_number()}
    +	| {priority, integer()}
    +	| {raw, non_neg_integer(), non_neg_integer(), binary()}
    +	| {recbuf, non_neg_integer()}
    +	| {send_timeout, timeout()}
    +	| {send_timeout_close, boolean()}
    +	| {sndbuf, non_neg_integer()}
    +	| {tos, integer()}
    +
    +

    Listen options.

    +

    This does not represent the entirety of the options that can be set on the socket, but only the options that may be set independently of protocol implementation.

    +

    opts() = [opt()]

    +

    List of listen options.

    Option descriptions

    -
    -

    None of the options are required.

    -

    Please consult the gen_tcp and inet manuals for a more -thorough description of these options. This manual only aims -to provide a short description along with what the defaults -are. Defaults may be different in Ranch compared to gen_tcp. -Defaults are given next to the option name.

    -
    -
    -backlog (1024) -
    -
    -

    - Max length of the queue of pending connections. -

    +

    None of the options are required.

    +

    Please consult the gen_tcp and inet manuals for a more thorough description of these options. This manual only aims to provide a short description along with what the defaults are. Defaults may be different in Ranch compared to gen_tcp. Defaults are given next to the option name.

    +
    backlog (1024)
    +

    Max length of the queue of pending connections.

    -
    -buffer -
    -
    -

    - Size of the buffer used by the Erlang driver. Default is system-dependent. -

    +
    buffer
    +

    Size of the buffer used by the Erlang driver. Default is system-dependent.

    -
    -delay_send (false) -
    -
    -

    - Always queue packets before sending, to send fewer, larger packets over the network. -

    +
    delay_send (false)
    +

    Always queue packets before sending, to send fewer, larger packets over the network.

    -
    -dontroute (false) -
    -
    -

    - Don’t send via a gateway, only send to directly connected hosts. -

    +
    dontroute (false)
    +

    Don't send via a gateway, only send to directly connected hosts.

    -
    -exit_on_close (true) -
    -
    -

    - Disable to allow sending data after a close has been detected. -

    +
    exit_on_close (true)
    +

    Disable to allow sending data after a close has been detected.

    -
    -fd -
    -
    -

    - File descriptor of the socket, if it was opened externally. -

    +
    fd
    +

    File descriptor of the socket, if it was opened externally.

    -
    -high_msgq_watermark (8192) -
    -
    -

    - Limit in the amount of data in the socket message queue before the socket queue becomes busy. -

    +
    high_msgq_watermark (8192)
    +

    Limit in the amount of data in the socket message queue before the socket queue becomes busy.

    -
    -high_watermark (8192) -
    -
    -

    - Limit in the amount of data in the ERTS socket implementation’s queue before the socket becomes busy. -

    +
    high_watermark (8192)
    +

    Limit in the amount of data in the ERTS socket implementation's queue before the socket becomes busy.

    -
    -inet -
    -
    -

    - Set up the socket for IPv4. -

    +
    inet
    +

    Set up the socket for IPv4.

    -
    -inet6 -
    -
    -

    - Set up the socket for IPv6. -

    +
    inet6
    +

    Set up the socket for IPv6.

    -
    -ip -
    -
    -

    - Interface to listen on. Listen on all interfaces by default. -

    +
    ip
    +

    Interface to listen on. Listen on all interfaces by default.

    -
    -ipv6_v6only (false) -
    -
    -

    - Listen on IPv4 and IPv6 (false) or only on IPv6 (true). Use with inet6. -

    +
    ipv6_v6only (false)
    +

    Listen on IPv4 and IPv6 (false) or only on IPv6 (true). Use with inet6.

    -
    -keepalive (false) -
    -
    -

    - Enable sending of keep-alive messages. -

    +
    keepalive (false)
    +

    Enable sending of keep-alive messages.

    -
    -linger ({false, 0}) -
    -
    -

    - Whether to wait and how long to flush data sent before closing the socket. -

    +
    linger ({false, 0})
    +

    Whether to wait and how long to flush data sent before closing the socket.

    -
    -low_msgq_watermark (4096) -
    -
    -

    - Amount of data in the socket message queue before the socket queue leaves busy state. -

    +
    low_msgq_watermark (4096)
    +

    Amount of data in the socket message queue before the socket queue leaves busy state.

    -
    -low_watermark (4096) -
    -
    -

    - Amount of data in the ERTS socket implementation’s queue before the socket leaves busy state. -

    +
    low_watermark (4096)
    +

    Amount of data in the ERTS socket implementation's queue before the socket leaves busy state.

    -
    -nodelay (true) -
    -
    -

    - Whether to enable TCP_NODELAY. -

    +
    nodelay (true)
    +

    Whether to enable TCP_NODELAY.

    -
    -port (0) -
    -
    -

    - TCP port number to listen on. 0 means a random port will be used. -

    +
    port (0)
    +

    TCP port number to listen on. 0 means a random port will be used.

    -
    -priority (0) -
    -
    -

    - Priority value for all packets to be sent by this socket. -

    +
    priority (0)
    +

    Priority value for all packets to be sent by this socket.

    -
    -recbuf -
    -
    -

    - Minimum size of the socket’s receive buffer. Default is system-dependent. -

    +
    recbuf
    +

    Minimum size of the socket's receive buffer. Default is system-dependent.

    -
    -send_timeout (30000) -
    -
    -

    - How long the send call may wait for confirmation before returning. -

    +
    send_timeout (30000)
    +

    How long the send call may wait for confirmation before returning.

    -
    -send_timeout_close (true) -
    -
    -

    - Whether to close the socket when the confirmation wasn’t received. -

    +
    send_timeout_close (true)
    +

    Whether to close the socket when the confirmation wasn't received.

    -
    -sndbuf -
    -
    -

    - Minimum size of the socket’s send buffer. Default is system-dependent. -

    +
    sndbuf
    +

    Minimum size of the socket's send buffer. Default is system-dependent.

    -
    -tos -
    -
    -

    - Value for the IP_TOS IP level option. Use with caution. -

    +
    tos
    +

    Value for the IP_TOS IP level option. Use with caution.

    -
    -

    In addition, the raw option can be used to set system-specific -options by specifying the protocol level, the option number and -the actual option value specified as a binary. This option is not -portable. Use with caution.

    -
    - -
    + +

    In addition, the raw option can be used to set system-specific options by specifying the protocol level, the option number and the actual option value specified as a binary. This option is not portable. Use with caution.

    Exports

    -
    -

    None.

    -
    -
    +

    None.

    + @@ -373,6 +217,8 @@ portable. Use with caution.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.3/manual/ranch_transport/index.html b/docs/en/ranch/1.3/manual/ranch_transport/index.html index 700559b6..ddce05ce 100644 --- a/docs/en/ranch/1.3/manual/ranch_transport/index.html +++ b/docs/en/ranch/1.3/manual/ranch_transport/index.html @@ -62,494 +62,198 @@

    ranch_transport(3)

    -

    Name

    -
    -

    ranch_transport - behaviour for transport modules

    -
    -
    -
    +

    ranch_transport - behaviour for transport modules

    Description

    -
    -

    The ranch_transport behaviour defines the interface used -by Ranch transports.

    -
    -
    -
    +

    The ranch_transport behaviour defines the interface used by Ranch transports.

    Types

    -
    -
    -

    sendfile_opts() = [{chunk_size, non_neg_integer()}]

    -

    Options used by the sendfile function and callbacks.

    -

    Allows configuring the chunk size, in bytes. Defaults to 8191 bytes.

    -
    -
    -
    -
    +

    sendfile_opts() = [{chunk_size, non_neg_integer()}]

    +

    Options used by the sendfile function and callbacks.

    +

    Allows configuring the chunk size, in bytes. Defaults to 8191 bytes.

    Callbacks

    -
    -
    -

    accept(LSocket, Timeout) → {ok, CSocket} | {error, closed | timeout | atom()}

    -
    -
    -LSocket = CSocket = any() -
    -
    -

    -Listening socket. -

    -
    -
    -Timeout = timeout() -
    -
    -

    -Accept timeout. -

    -
    -
    -

    Accept a connection on the given listening socket.

    -

    The accept_ack callback will be used to initialize the socket -after accepting the connection. This is most useful when the -transport is not raw TCP, like with SSL for example.

    -
    -
    -

    accept_ack(CSocket, Timeout) → ok

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -Timeout = timeout() -
    -
    -

    -Ack timeout. -

    -
    -
    -

    Perform post-accept initialization of the connection.

    -

    This function will be called by connection processes -before performing any socket operation. It allows -transports that require extra initialization to perform -their task and make the socket ready to use.

    -
    -
    -

    close(Socket) → ok

    -
    -
    -Socket = any() -
    -
    -

    -Socket opened with listen/1 or accept/2. -

    -
    -
    -

    Close the given socket.

    -
    -
    -

    controlling_process(Socket, Pid) → ok | {error, closed | not_owner | atom()}

    -
    -
    -Socket = any() -
    -
    -

    -Socket opened with listen/1 or accept/2. -

    -
    -
    -Pid = pid() -
    -
    -

    -Pid of the new owner of the socket. -

    -
    -
    -

    Change the controlling process for the given socket.

    -

    The controlling process is the process that is allowed to -perform operations on the socket, and that will receive -messages from the socket when active mode is used. When -the controlling process dies, the socket is closed.

    -
    -
    -

    listen(TransOpts) → {ok, LSocket} | {error, atom()}

    -
    -
    -TransOpts = any() -
    -
    -

    -Transport options. -

    -
    -
    -LSocket = any() -
    -
    -

    -Listening socket. -

    -
    -
    -

    Listen for connections on the given port.

    -

    The port is given as part of the transport options under -the key port. Any other option is transport dependent.

    -

    The socket returned by this call can then be used to -accept connections. It is not possible to send or receive -data from the listening socket.

    -
    -
    -

    messages() → {OK, Closed, Error}

    -
    -
    -OK = Closed = Error = atom() -
    -
    -

    -Tuple names. -

    -
    -
    -

    Return the atoms used to identify messages sent in active mode.

    -
    -
    -

    name() → Name

    -
    -
    -Name = atom() -
    -
    -

    -Transport module name. -

    -
    -
    -

    Return the name of the transport.

    -
    -
    -

    peername(CSocket) → {ok, {IP, Port}} | {error, atom()}

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -IP = inet:ip_address() -
    -
    -

    -IP of the remote endpoint. -

    -
    -
    -Port = inet:port_number() -
    -
    -

    -Port of the remote endpoint. -

    -
    -
    -

    Return the IP and port of the remote endpoint.

    -
    -
    -

    recv(CSocket, Length, Timeout) → {ok, Packet} | {error, closed | timeout | atom()}

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -Length = non_neg_integer() -
    -
    -

    -Requested length. -

    -
    -
    -Timeout = timeout() -
    -
    -

    -Receive timeout. -

    -
    -
    -Packet = iodata() | any() -
    -
    -

    -Data received. -

    -
    -
    -

    Receive data from the given socket when in passive mode.

    -

    Trying to receive data from a socket that is in active mode -will return an error.

    -

    A length of 0 will return any data available on the socket.

    -

    While it is possible to use the timeout value infinity, -this is highly discouraged as this could cause your process -to get stuck waiting for data that will never come. This may -happen when a socket becomes half-open due to a crash of the -remote endpoint. Wi-Fi going down is another common culprit -of this issue.

    -
    -
    -

    send(CSocket, Packet) → ok | {error, atom()}

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -Packet = iodata() -
    -
    -

    -Data to be sent. -

    -
    -
    -

    Send data to the given socket.

    -
    -
    -

    sendfile(CSocket, File) → sendfile(CSocket, File, 0, 0, [])

    -

    Alias of ranch_transport:sendfile/5.

    -
    -
    -

    sendfile(CSocket, File, Offset, Bytes) → sendfile(CSocket, File, Offset, Bytes, [])

    -

    Alias of ranch_transport:sendfile/5.

    -
    -
    -

    sendfile(CSocket, File, Offset, Bytes, SfOpts) → {ok, SentBytes} | {error, atom()}

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -File = file:filename_all() | file:fd() -
    -
    -

    -Filename or file descriptor for the file to be sent. -

    -
    -
    -Offset = non_neg_integer() -
    -
    -

    -Begin sending at this position in the file. -

    -
    -
    -Bytes = non_neg_integer() -
    -
    -

    -Send this many bytes. -

    -
    -
    -SentBytes = non_neg_integer() -
    -
    -

    -This many bytes were sent. -

    -
    -
    -SfOpts = sendfile_opts() -
    -
    -

    -Sendfile options. -

    -
    -
    -

    Send data from a file to the given socket.

    -

    The file may be sent full or in parts, and may be specified -by its filename or by an already open file descriptor.

    -

    Transports that manipulate TCP directly may use the -file:sendfile/{2,4,5} function, which calls the sendfile -syscall where applicable (on Linux, for example). Other -transports can use the sendfile/6 function exported from -this module.

    -
    -
    -

    setopts(CSocket, SockOpts) → ok | {error, atom()}

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -SockOpts = any() -
    -
    -

    -Socket options. -

    -
    -
    -

    Change options for the given socket.

    -

    This is mainly useful for switching to active or passive mode -or to set protocol-specific options.

    -
    -
    -

    shutdown(CSocket, How) → ok | {error, atom()}

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -How = read | write | read_write -
    -
    -

    -Which side(s) of the socket to close. -

    -
    -
    -

    Immediately close the socket in one or two directions.

    -
    -
    -

    sockname(Socket) → {ok, {IP, Port}} | {error, atom()}

    -
    -
    -Socket = any() -
    -
    -

    -Socket opened with listen/1 or accept/2. -

    -
    -
    -IP = inet:ip_address() -
    -
    -

    -IP of the local endpoint. -

    -
    -
    -Port = inet:port_number() -
    -
    -

    -Port of the local endpoint. -

    -
    -
    -

    Return the IP and port of the local endpoint.

    -
    -
    -
    -
    +

    accept(LSocket, Timeout) -> {ok, CSocket} | {error, closed | timeout | atom()}

    +
    LSocket = CSocket = any()
    +

    Listening socket.

    +
    +
    Timeout = timeout()
    +

    Accept timeout.

    +
    +
    +

    Accept a connection on the given listening socket.

    +

    The accept_ack callback will be used to initialize the socket after accepting the connection. This is most useful when the transport is not raw TCP, like with SSL for example.

    +

    accept_ack(CSocket, Timeout) -> ok

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    Timeout = timeout()
    +

    Ack timeout.

    +
    +
    +

    Perform post-accept initialization of the connection.

    +

    This function will be called by connection processes before performing any socket operation. It allows transports that require extra initialization to perform their task and make the socket ready to use.

    +

    close(Socket) -> ok

    +
    Socket = any()
    +

    Socket opened with listen/1 or accept/2.

    +
    +
    +

    Close the given socket.

    +

    controlling_process(Socket, Pid) -> ok | {error, closed | not_owner | atom()}

    +
    Socket = any()
    +

    Socket opened with listen/1 or accept/2.

    +
    +
    Pid = pid()
    +

    Pid of the new owner of the socket.

    +
    +
    +

    Change the controlling process for the given socket.

    +

    The controlling process is the process that is allowed to perform operations on the socket, and that will receive messages from the socket when active mode is used. When the controlling process dies, the socket is closed.

    +

    listen(TransOpts) -> {ok, LSocket} | {error, atom()}

    +
    TransOpts = any()
    +

    Transport options.

    +
    +
    LSocket = any()
    +

    Listening socket.

    +
    +
    +

    Listen for connections on the given port.

    +

    The port is given as part of the transport options under the key port. Any other option is transport dependent.

    +

    The socket returned by this call can then be used to accept connections. It is not possible to send or receive data from the listening socket.

    +

    messages() -> {OK, Closed, Error}

    +
    OK = Closed = Error = atom()
    +

    Tuple names.

    +
    +
    +

    Return the atoms used to identify messages sent in active mode.

    +

    name() -> Name

    +
    Name = atom()
    +

    Transport module name.

    +
    +
    +

    Return the name of the transport.

    +

    peername(CSocket) -> {ok, {IP, Port}} | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    IP = inet:ip_address()
    +

    IP of the remote endpoint.

    +
    +
    Port = inet:port_number()
    +

    Port of the remote endpoint.

    +
    +
    +

    Return the IP and port of the remote endpoint.

    +

    recv(CSocket, Length, Timeout) -> {ok, Packet} | {error, closed | timeout | atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    Length = non_neg_integer()
    +

    Requested length.

    +
    +
    Timeout = timeout()
    +

    Receive timeout.

    +
    +
    Packet = iodata() | any()
    +

    Data received.

    +
    +
    +

    Receive data from the given socket when in passive mode.

    +

    Trying to receive data from a socket that is in active mode will return an error.

    +

    A length of 0 will return any data available on the socket.

    +

    While it is possible to use the timeout value infinity, this is highly discouraged as this could cause your process to get stuck waiting for data that will never come. This may happen when a socket becomes half-open due to a crash of the remote endpoint. Wi-Fi going down is another common culprit of this issue.

    +

    send(CSocket, Packet) -> ok | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    Packet = iodata()
    +

    Data to be sent.

    +
    +
    +

    Send data to the given socket.

    +

    sendfile(CSocket, File) -> sendfile(CSocket, File, 0, 0, [])

    +

    Alias of ranch_transport:sendfile/5.

    +

    sendfile(CSocket, File, Offset, Bytes) -> sendfile(CSocket, File, Offset, Bytes, [])

    +

    Alias of ranch_transport:sendfile/5.

    +

    sendfile(CSocket, File, Offset, Bytes, SfOpts) -> {ok, SentBytes} | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    File = file:filename_all() | file:fd()
    +

    Filename or file descriptor for the file to be sent.

    +
    +
    Offset = non_neg_integer()
    +

    Begin sending at this position in the file.

    +
    +
    Bytes = non_neg_integer()
    +

    Send this many bytes.

    +
    +
    SentBytes = non_neg_integer()
    +

    This many bytes were sent.

    +
    +
    SfOpts = sendfile_opts()
    +

    Sendfile options.

    +
    +
    +

    Send data from a file to the given socket.

    +

    The file may be sent full or in parts, and may be specified by its filename or by an already open file descriptor.

    +

    Transports that manipulate TCP directly may use the file:sendfile/{2,4,5} function, which calls the sendfile syscall where applicable (on Linux, for example). Other transports can use the sendfile/6 function exported from this module.

    +

    setopts(CSocket, SockOpts) -> ok | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    SockOpts = any()
    +

    Socket options.

    +
    +
    +

    Change options for the given socket.

    +

    This is mainly useful for switching to active or passive mode or to set protocol-specific options.

    +

    shutdown(CSocket, How) -> ok | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    How = read | write | read_write
    +

    Which side(s) of the socket to close.

    +
    +
    +

    Immediately close the socket in one or two directions.

    +

    sockname(Socket) -> {ok, {IP, Port}} | {error, atom()}

    +
    Socket = any()
    +

    Socket opened with listen/1 or accept/2.

    +
    +
    IP = inet:ip_address()
    +

    IP of the local endpoint.

    +
    +
    Port = inet:port_number()
    +

    Port of the local endpoint.

    +
    +
    +

    Return the IP and port of the local endpoint.

    Exports

    -
    -
    -

    sendfile(Transport, CSocket, File, Offset, Bytes, SfOpts) → {ok, SentBytes} | {error, atom()}

    -
    -
    -Transport = module() -
    -
    -

    -Transport module for this socket. -

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -File = file:filename_all() | file:fd() -
    -
    -

    -Filename or file descriptor for the file to be sent. -

    -
    -
    -Offset = non_neg_integer() -
    -
    -

    -Begin sending at this position in the file. -

    -
    -
    -Bytes = non_neg_integer() -
    -
    -

    -Send this many bytes. -

    -
    -
    -SentBytes = non_neg_integer() -
    -
    -

    -This many bytes were sent. -

    -
    -
    -SfOpts = sendfile_opts() -
    -
    -

    -Sendfile options. -

    -
    -
    -

    Send data from a file to the given socket.

    -

    This function emulates the function file:sendfile/{2,4,5} -and may be used when transports are not manipulating TCP -directly.

    -
    -
    -
    +

    sendfile(Transport, CSocket, File, Offset, Bytes, SfOpts) -> {ok, SentBytes} | {error, atom()}

    +
    Transport = module()
    +

    Transport module for this socket.

    +
    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    File = file:filename_all() | file:fd()
    +

    Filename or file descriptor for the file to be sent.

    +
    +
    Offset = non_neg_integer()
    +

    Begin sending at this position in the file.

    +
    +
    Bytes = non_neg_integer()
    +

    Send this many bytes.

    +
    +
    SentBytes = non_neg_integer()
    +

    This many bytes were sent.

    +
    +
    SfOpts = sendfile_opts()
    +

    Sendfile options.

    +
    +
    +

    Send data from a file to the given socket.

    +

    This function emulates the function file:sendfile/{2,4,5} and may be used when transports are not manipulating TCP directly.

    + @@ -584,6 +288,8 @@ directly.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.4/guide/embedded/index.html b/docs/en/ranch/1.4/guide/embedded/index.html index fdad24c2..533d353d 100644 --- a/docs/en/ranch/1.4/guide/embedded/index.html +++ b/docs/en/ranch/1.4/guide/embedded/index.html @@ -62,48 +62,30 @@

    Embedded mode

    -

    Embedded mode allows you to insert Ranch listeners directly -in your supervision tree. This allows for greater fault tolerance -control by permitting the shutdown of a listener due to the -failure of another part of the application and vice versa.

    -
    +

    Embedded mode allows you to insert Ranch listeners directly in your supervision tree. This allows for greater fault tolerance control by permitting the shutdown of a listener due to the failure of another part of the application and vice versa.

    Embedding

    -
    -

    To embed Ranch in your application you can simply add the child specs -to your supervision tree. This can all be done in the init/1 function -of one of your application supervisors.

    -

    Ranch requires at the minimum two kinds of child specs for embedding. -First, you need to add ranch_sup to your supervision tree, only once, -regardless of the number of listeners you will use. Then you need to -add the child specs for each listener.

    -

    Ranch has a convenience function for getting the listeners child specs -called ranch:child_spec/5, that works like ranch:start_listener/5, -except that it doesn’t start anything, it only returns child specs.

    -

    As for ranch_sup, the child spec is simple enough to not require a -convenience function.

    -

    The following example adds both ranch_sup and one listener to another -application’s supervision tree.

    -
    -
    Embed Ranch directly in your supervision tree
    -
    -
    init([]) ->
    -        RanchSupSpec = {ranch_sup, {ranch_sup, start_link, []},
    -                permanent, 5000, supervisor, [ranch_sup]},
    -        ListenerSpec = ranch:child_spec(echo, 100,
    -                ranch_tcp, [{port, 5555}],
    -                echo_protocol, []
    -        ),
    -        {ok, {{one_for_one, 10, 10}, [RanchSupSpec, ListenerSpec]}}.
    -

    Remember, you can add as many listener child specs as needed, but only -one ranch_sup spec!

    -

    It is recommended that your architecture makes sure that all listeners -are restarted if ranch_sup fails. See the Ranch internals chapter for -more details on how Ranch does it.

    -
    -
    +
    init([]) ->
    +	RanchSupSpec = {ranch_sup, {ranch_sup, start_link, []},
    +		permanent, 5000, supervisor, [ranch_sup]},
    +	ListenerSpec = ranch:child_spec(echo, 100,
    +		ranch_tcp, [{port, 5555}],
    +		echo_protocol, []
    +	),
    +	{ok, {{one_for_one, 10, 10}, [RanchSupSpec, ListenerSpec]}}.
    + +

    Remember, you can add as many listener child specs as needed, but only one ranch_sup spec!

    +

    It is recommended that your architecture makes sure that all listeners are restarted if ranch_sup fails. See the Ranch internals chapter for more details on how Ranch does it.

    + @@ -160,6 +142,8 @@ more details on how Ranch does it.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.4/guide/index.html b/docs/en/ranch/1.4/guide/index.html index c5ce61a2..5b381706 100644 --- a/docs/en/ranch/1.4/guide/index.html +++ b/docs/en/ranch/1.4/guide/index.html @@ -62,48 +62,24 @@

    Ranch User Guide

    - + + @@ -138,6 +114,8 @@ +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.4/guide/internals/index.html b/docs/en/ranch/1.4/guide/internals/index.html index 721e7324..120d0291 100644 --- a/docs/en/ranch/1.4/guide/internals/index.html +++ b/docs/en/ranch/1.4/guide/internals/index.html @@ -62,93 +62,34 @@

    Internals

    -

    This chapter may not apply to embedded Ranch as embedding allows you -to use an architecture specific to your application, which may or may -not be compatible with the description of the Ranch application.

    -

    Note that for everything related to efficiency and performance, -you should perform the benchmarks yourself to get the numbers that -matter to you. Generic benchmarks found on the web may or may not -be of use to you, you can never know until you benchmark your own -system.

    -
    +

    This chapter may not apply to embedded Ranch as embedding allows you to use an architecture specific to your application, which may or may not be compatible with the description of the Ranch application.

    +

    Note that for everything related to efficiency and performance, you should perform the benchmarks yourself to get the numbers that matter to you. Generic benchmarks found on the web may or may not be of use to you, you can never know until you benchmark your own system.

    Architecture

    -
    -

    Ranch is an OTP application.

    -

    Like all OTP applications, Ranch has a top supervisor. It is responsible -for supervising the ranch_server process and all the listeners that -will be started.

    -

    The ranch_server gen_server is a central process keeping track of the -listeners and their acceptors. It does so through the use of a public ets -table called ranch_server. The table is owned by the top supervisor -to improve fault tolerance. This way if the ranch_server gen_server -fails, it doesn’t lose any information and the restarted process can -continue as if nothing happened.

    -

    Ranch uses a custom supervisor for managing connections. This supervisor -keeps track of the number of connections and handles connection limits -directly. While it is heavily optimized to perform the task of creating -connection processes for accepted connections, it is still following the -OTP principles and the usual sys and supervisor calls will work on -it as expected.

    -

    Listeners are grouped into the ranch_listener_sup supervisor and -consist of three kinds of processes: the listener gen_server, the -acceptor processes and the connection processes, both grouped under -their own supervisor. All of these processes are registered to the -ranch_server gen_server with varying amount of information.

    -

    All socket operations, including listening for connections, go through -transport handlers. Accepted connections are given to the protocol handler. -Transport handlers are simple callback modules for performing operations on -sockets. Protocol handlers start a new process, which receives socket -ownership, with no requirements on how the code should be written inside -that new process.

    -
    -
    -
    +

    Ranch is an OTP application.

    +

    Like all OTP applications, Ranch has a top supervisor. It is responsible for supervising the ranch_server process and all the listeners that will be started.

    +

    The ranch_server gen_server is a central process keeping track of the listeners and their acceptors. It does so through the use of a public ets table called ranch_server. The table is owned by the top supervisor to improve fault tolerance. This way if the ranch_server gen_server fails, it doesn't lose any information and the restarted process can continue as if nothing happened.

    +

    Ranch uses a custom supervisor for managing connections. This supervisor keeps track of the number of connections and handles connection limits directly. While it is heavily optimized to perform the task of creating connection processes for accepted connections, it is still following the OTP principles and the usual sys and supervisor calls will work on it as expected.

    +

    Listeners are grouped into the ranch_listener_sup supervisor and consist of three kinds of processes: the listener gen_server, the acceptor processes and the connection processes, both grouped under their own supervisor. All of these processes are registered to the ranch_server gen_server with varying amount of information.

    +

    All socket operations, including listening for connections, go through transport handlers. Accepted connections are given to the protocol handler. Transport handlers are simple callback modules for performing operations on sockets. Protocol handlers start a new process, which receives socket ownership, with no requirements on how the code should be written inside that new process.

    Number of acceptors

    -
    -

    The second argument to ranch:start_listener/5 is the number of -processes that will be accepting connections. Care should be taken -when choosing this number.

    -

    First of all, it should not be confused with the maximum number -of connections. Acceptor processes are only used for accepting and -have nothing else in common with connection processes. Therefore -there is nothing to be gained from setting this number too high, -in fact it can slow everything else down.

    -

    Second, this number should be high enough to allow Ranch to accept -connections concurrently. But the number of cores available doesn’t -seem to be the only factor for choosing this number, as we can -observe faster accepts if we have more acceptors than cores. It -might be entirely dependent on the protocol, however.

    -

    Our observations suggest that using 100 acceptors on modern hardware -is a good solution, as it’s big enough to always have acceptors ready -and it’s low enough that it doesn’t have a negative impact on the -system’s performances.

    -
    -
    -
    +

    The second argument to ranch:start_listener/5 is the number of processes that will be accepting connections. Care should be taken when choosing this number.

    +

    First of all, it should not be confused with the maximum number of connections. Acceptor processes are only used for accepting and have nothing else in common with connection processes. Therefore there is nothing to be gained from setting this number too high, in fact it can slow everything else down.

    +

    Second, this number should be high enough to allow Ranch to accept connections concurrently. But the number of cores available doesn't seem to be the only factor for choosing this number, as we can observe faster accepts if we have more acceptors than cores. It might be entirely dependent on the protocol, however.

    +

    Our observations suggest that using 100 acceptors on modern hardware is a good solution, as it's big enough to always have acceptors ready and it's low enough that it doesn't have a negative impact on the system's performances.

    Platform-specific TCP features

    -
    -

    Some socket options are platform-specific and not supported by inet. -They can be of interest because they generally are related to -optimizations provided by the underlying OS. They can still be enabled -thanks to the raw option, for which we will see an example.

    -

    One of these features is TCP_DEFER_ACCEPT on Linux. It is a simplified -accept mechanism which will wait for application data to come in before -handing out the connection to the Erlang process.

    -

    This is especially useful if you expect many connections to be mostly -idle, perhaps part of a connection pool. They can be handled by the -kernel directly until they send any real data, instead of allocating -resources to idle connections.

    -

    To enable this mechanism, the following option can be used.

    -
    -
    Using raw transport options
    -
    -
    {raw, 6, 9, << 30:32/native >>}
    -

    It means go on layer 6, turn on option 9 with the given integer parameter.

    -
    -
    +
    {raw, 6, 9, << 30:32/native >>}
    + +

    It means go on layer 6, turn on option 9 with the given integer parameter.

    + @@ -201,6 +142,8 @@ http://www.gnu.org/software/src-highlite --> +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.4/guide/introduction/index.html b/docs/en/ranch/1.4/guide/introduction/index.html index aac9305e..897bdebd 100644 --- a/docs/en/ranch/1.4/guide/introduction/index.html +++ b/docs/en/ranch/1.4/guide/introduction/index.html @@ -62,34 +62,18 @@

    Introduction

    -

    Ranch is a socket acceptor pool for TCP protocols.

    -

    Ranch aims to provide everything you need to accept TCP connections -with a small code base and low latency while being easy to use directly -as an application or to embed into your own.

    -
    +

    Ranch is a socket acceptor pool for TCP protocols.

    +

    Ranch aims to provide everything you need to accept TCP connections with a small code base and low latency while being easy to use directly as an application or to embed into your own.

    Prerequisites

    -
    -

    It is assumed the developer already knows Erlang and has some experience -with socket programming and TCP protocols.

    -
    -
    -
    +

    It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols.

    Supported platforms

    -
    -

    Ranch is tested and supported on Linux, FreeBSD, OSX and Windows.

    -

    Ranch is developed for Erlang/OTP R16B+.

    -

    There are known issues with the SSL application found in Erlang/OTP -18.3.2 and 18.3.3. These versions are therefore not supported.

    -

    Ranch may be compiled on earlier Erlang versions with small source code -modifications but there is no guarantee that it will work as expected.

    -
    -
    -
    +

    Ranch is tested and supported on Linux, FreeBSD, OSX and Windows.

    +

    Ranch is developed for Erlang/OTP R16B+.

    +

    There are known issues with the SSL application found in Erlang/OTP 18.3.2 and 18.3.3. These versions are therefore not supported.

    +

    Ranch may be compiled on earlier Erlang versions with small source code modifications but there is no guarantee that it will work as expected.

    Versioning

    - -
    +

    Ranch uses Semantic Versioning 2.0.0

    + @@ -142,6 +126,8 @@ modifications but there is no guarantee that it will work as expected.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.4/guide/listeners/index.html b/docs/en/ranch/1.4/guide/listeners/index.html index 3a0af22a..633c942c 100644 --- a/docs/en/ranch/1.4/guide/listeners/index.html +++ b/docs/en/ranch/1.4/guide/listeners/index.html @@ -62,367 +62,213 @@

    Listeners

    -

    A listener is a set of processes whose role is to listen on a port -for new connections. It manages a pool of acceptor processes, each -of them indefinitely accepting connections. When it does, it starts -a new process executing the protocol handler code. All the socket -programming is abstracted through the use of transport handlers.

    -

    The listener takes care of supervising all the acceptor and connection -processes, allowing developers to focus on building their application.

    -
    +

    A listener is a set of processes whose role is to listen on a port for new connections. It manages a pool of acceptor processes, each of them indefinitely accepting connections. When it does, it starts a new process executing the protocol handler code. All the socket programming is abstracted through the use of transport handlers.

    +

    The listener takes care of supervising all the acceptor and connection processes, allowing developers to focus on building their application.

    Starting a listener

    -
    -

    Ranch does nothing by default. It is up to the application developer -to request that Ranch listens for connections.

    -

    A listener can be started and stopped at will.

    -

    When starting a listener, a number of different settings are required:

    -
      -
    • -

      -A name to identify it locally and be able to interact with it. -

      +

      Ranch does nothing by default. It is up to the application developer to request that Ranch listens for connections.

      +

      A listener can be started and stopped at will.

      +

      When starting a listener, a number of different settings are required:

      +
      • A name to identify it locally and be able to interact with it.
      • -
      • -

        -The number of acceptors in the pool. -

        +
      • The number of acceptors in the pool.
      • -
      • -

        -A transport handler and its associated options. -

        +
      • A transport handler and its associated options.
      • -
      • -

        -A protocol handler and its associated options. -

        +
      • A protocol handler and its associated options.
      • -
    -

    Ranch includes both TCP and SSL transport handlers, respectively -ranch_tcp and ranch_ssl.

    -

    A listener can be started by calling the ranch:start_listener/5 -function. Before doing so however, you must ensure that the ranch -application is started.

    -
    -
    Starting the Ranch application
    -
    -
    ok = application:start(ranch).
    -

    You are then ready to start a listener. Let’s call it tcp_echo. It will -have a pool of 100 acceptors, use a TCP transport and forward connections -to the echo_protocol handler.

    -
    -
    Starting a listener for TCP connections on port 5555
    -
    -
    {ok, _} = ranch:start_listener(tcp_echo,
    -        ranch_tcp, [{port, 5555}],
    -        echo_protocol, []
    -).
    -

    You can try this out by compiling and running the tcp_echo example in the -examples directory. To do so, open a shell in the examples/tcp_echo/ -directory and run the following command:

    -
    -
    Building and starting a Ranch example
    -
    -
    $ make run
    -

    You can then connect to it using telnet and see the echo server reply -everything you send to it. Then when you’re done testing, you can use -the Ctrl+] key to escape to the telnet command line and type -quit to exit.

    -
    -
    Connecting to the example listener with telnet
    -
    -
    $ telnet localhost 5555
    -Trying 127.0.0.1...
    -Connected to localhost.
    -Escape character is '^]'.
    -Hello!
    -Hello!
    -It works!
    -It works!
    -^]
    -
    -telnet> quit
    -Connection closed.
    -
    -
    -
    +
    $ telnet localhost 5555
    +Trying 127.0.0.1...
    +Connected to localhost.
    +Escape character is '^]'.
    +Hello!
    +Hello!
    +It works!
    +It works!
    +^]
    +
    +telnet> quit
    +Connection closed.
    +

    Stopping a listener

    -
    -

    All you need to stop a Ranch listener is to call the -ranch:stop_listener/1 function with the listener’s name -as argument. In the previous section we started the listener -named tcp_echo. We can now stop it.

    -
    -
    Stopping a listener
    -
    -
    ranch:stop_listener(tcp_echo).
    -
    - -
    +
    ranch:stop_listener(tcp_echo).
    +

    Default transport options

    -
    -

    By default the socket will be set to return binary data, with the -options {active, false}, {packet, raw}, {reuseaddr, true} set. -These values can’t be overriden when starting the listener, but -they can be overriden using Transport:setopts/2 in the protocol.

    -

    It will also set {backlog, 1024} and {nodelay, true}, which -can be overriden at listener startup.

    -
    - -
    +

    By default the socket will be set to return binary data, with the options {active, false}, {packet, raw}, {reuseaddr, true} set. These values can't be overriden when starting the listener, but they can be overriden using Transport:setopts/2 in the protocol.

    +

    It will also set {backlog, 1024} and {nodelay, true}, which can be overriden at listener startup.

    Listening on a random port

    -
    -

    You do not have to specify a specific port to listen on. If you give -the port number 0, or if you omit the port number entirely, Ranch will -start listening on a random port.

    -

    You can retrieve this port number by calling ranch:get_port/1. The -argument is the name of the listener you gave in ranch:start_listener/5.

    -
    -
    Starting a listener for TCP connections on a random port
    -
    -
    {ok, _} = ranch:start_listener(tcp_echo,
    -        ranch_tcp, [{port, 0}],
    -        echo_protocol, []
    -).
    -Port = ranch:get_port(tcp_echo).
    -
    -
    -
    +
    {ok, _} = ranch:start_listener(tcp_echo,
    +	ranch_tcp, [{port, 0}],
    +	echo_protocol, []
    +).
    +Port = ranch:get_port(tcp_echo).
    +

    Listening on privileged ports

    -
    -

    Some systems limit access to ports below 1024 for security reasons. -This can easily be identified by an {error, eacces} error when trying -to open a listening socket on such a port.

    -

    The methods for listening on privileged ports vary between systems, -please refer to your system’s documentation for more information.

    -

    We recommend the use of port rewriting for systems with a single server, -and load balancing for systems with multiple servers. Documenting these -solutions is however out of the scope of this guide.

    -
    - -
    +

    Some systems limit access to ports below 1024 for security reasons. This can easily be identified by an {error, eacces} error when trying to open a listening socket on such a port.

    +

    The methods for listening on privileged ports vary between systems, please refer to your system's documentation for more information.

    +

    We recommend the use of port rewriting for systems with a single server, and load balancing for systems with multiple servers. Documenting these solutions is however out of the scope of this guide.

    Accepting connections on an existing socket

    -
    -

    If you want to accept connections on an existing socket, you can use the -socket transport option, which should just be the relevant data returned -from the connect function for the transport or the underlying socket library -(gen_tcp:connect, ssl:connect). The accept function will then be -called on the passed in socket. You should connect the socket in -{active, false} mode, as well.

    -

    Note, however, that because of a bug in SSL, you cannot change ownership of an -SSL listen socket prior to R16. Ranch will catch the error thrown, but the -owner of the SSL socket will remain as whatever process created the socket. -However, this will not affect accept behaviour unless the owner process dies, -in which case the socket is closed. Therefore, to use this feature with SSL -with an erlang release prior to R16, ensure that the SSL socket is opened in a -persistant process.

    -
    -
    -
    +

    If you want to accept connections on an existing socket, you can use the socket transport option, which should just be the relevant data returned from the connect function for the transport or the underlying socket library (gen_tcp:connect, ssl:connect). The accept function will then be called on the passed in socket. You should connect the socket in {active, false} mode, as well.

    +

    Note, however, that because of a bug in SSL, you cannot change ownership of an SSL listen socket prior to R16. Ranch will catch the error thrown, but the owner of the SSL socket will remain as whatever process created the socket. However, this will not affect accept behaviour unless the owner process dies, in which case the socket is closed. Therefore, to use this feature with SSL with an erlang release prior to R16, ensure that the SSL socket is opened in a persistant process.

    Limiting the number of concurrent connections

    -
    -

    The max_connections transport option allows you to limit the number -of concurrent connections. It defaults to 1024. Its purpose is to -prevent your system from being overloaded and ensuring all the -connections are handled optimally.

    -
    -
    Customizing the maximum number of concurrent connections
    -
    -
    {ok, _} = ranch:start_listener(tcp_echo,
    -        ranch_tcp, [{port, 5555}, {max_connections, 100}],
    -        echo_protocol, []
    -).
    -

    You can disable this limit by setting its value to the atom infinity.

    -
    -
    Disabling the limit for the number of connections
    -
    -
    {ok, _} = ranch:start_listener(tcp_echo,
    -        ranch_tcp, [{port, 5555}, {max_connections, infinity}],
    -        echo_protocol, []
    -).
    -

    The maximum number of connections is a soft limit. In practice, it -can reach max_connections + the number of acceptors.

    -

    When the maximum number of connections is reached, Ranch will stop -accepting connections. This will not result in further connections -being rejected, as the kernel option allows queueing incoming -connections. The size of this queue is determined by the backlog -option and defaults to 1024. Ranch does not know about the number -of connections that are in the backlog.

    -

    You may not always want connections to be counted when checking for -max_connections. For example you might have a protocol where both -short-lived and long-lived connections are possible. If the long-lived -connections are mostly waiting for messages, then they don’t consume -much resources and can safely be removed from the count.

    -

    To remove the connection from the count, you must call the -ranch:remove_connection/1 from within the connection process, -with the name of the listener as the only argument.

    -
    -
    Removing a connection from the count of connections
    -
    -
    ranch:remove_connection(Ref).
    -

    As seen in the chapter covering protocols, this pid is received as the -first argument of the protocol’s start_link/4 callback.

    -

    You can modify the max_connections value on a running listener by -using the ranch:set_max_connections/2 function, with the name of the -listener as first argument and the new value as the second.

    -
    -
    Upgrading the maximum number of connections
    -
    -
    ranch:set_max_connections(tcp_echo, MaxConns).
    -

    The change will occur immediately.

    -
    -
    -
    +
    ranch:set_max_connections(tcp_echo, MaxConns).
    +
    +

    The change will occur immediately.

    Customizing the number of acceptor processes

    -
    -

    By default Ranch will use 10 acceptor processes. Their role is -to accept connections and spawn a connection process for every -new connection.

    -

    This number can be tweaked to improve performance. A good -number is typically between 10 or 100 acceptors. You must -measure to find the best value for your application.

    -
    -
    Specifying a custom number of acceptor processes
    -
    -
    {ok, _} = ranch:start_listener(tcp_echo,
    -        ranch_tcp, [{port, 5555}, {num_acceptors, 42}],
    -        echo_protocol, []
    -).
    -
    - -
    -

    When running out of file descriptors

    -
    -

    Operating systems have limits on the number of sockets -which can be opened by applications. When this maximum is -reached the listener can no longer accept new connections. The -accept rate of the listener will be automatically reduced, and a -warning message will be logged.

    -
    -
    -
    =ERROR REPORT==== 13-Jan-2016::12:24:38 ===
    -Ranch acceptor reducing accept rate: out of file descriptors
    +
    {ok, _} = ranch:start_listener(tcp_echo,
    +	ranch_tcp, [{port, 5555}, {num_acceptors, 42}],
    +	echo_protocol, []
    +).
    -

    If you notice messages like this you should increase the number -of file-descriptors which can be opened by your application. How -this should be done is operating-system dependent. Please consult -the documentation of your operating system.

    -
    -
    -
    +

    When running out of file descriptors

    +

    Operating systems have limits on the number of sockets which can be opened by applications. When this maximum is reached the listener can no longer accept new connections. The accept rate of the listener will be automatically reduced, and a warning message will be logged.

    +
    =ERROR REPORT==== 13-Jan-2016::12:24:38 ===
    +Ranch acceptor reducing accept rate: out of file descriptors
    +

    If you notice messages like this you should increase the number of file-descriptors which can be opened by your application. How this should be done is operating-system dependent. Please consult the documentation of your operating system.

    Using a supervisor for connection processes

    -
    -

    Ranch allows you to define the type of process that will be used -for the connection processes. By default it expects a worker. -When the connection_type configuration value is set to supervisor, -Ranch will consider that the connection process it manages is a -supervisor and will reflect that in its supervision tree.

    -

    Connection processes of type supervisor can either handle the -socket directly or through one of their children. In the latter -case the start function for the connection process must return -two pids: the pid of the supervisor you created (that will be -supervised) and the pid of the protocol handling process (that -will receive the socket).

    -

    Instead of returning {ok, ConnPid}, simply return -{ok, SupPid, ConnPid}.

    -

    It is very important that the connection process be created -under the supervisor process so that everything works as intended. -If not, you will most likely experience issues when the supervised -process is stopped.

    -
    -
    -
    +

    Ranch allows you to define the type of process that will be used for the connection processes. By default it expects a worker. When the connection_type configuration value is set to supervisor, Ranch will consider that the connection process it manages is a supervisor and will reflect that in its supervision tree.

    +

    Connection processes of type supervisor can either handle the socket directly or through one of their children. In the latter case the start function for the connection process must return two pids: the pid of the supervisor you created (that will be supervised) and the pid of the protocol handling process (that will receive the socket).

    +

    Instead of returning {ok, ConnPid}, simply return {ok, SupPid, ConnPid}.

    +

    It is very important that the connection process be created under the supervisor process so that everything works as intended. If not, you will most likely experience issues when the supervised process is stopped.

    Upgrading

    -
    -

    Ranch allows you to upgrade the protocol options. This takes effect -immediately and for all subsequent connections.

    -

    To upgrade the protocol options, call ranch:set_protocol_options/2 -with the name of the listener as first argument and the new options -as the second.

    -
    -
    Upgrading the protocol options
    -
    -
    ranch:set_protocol_options(tcp_echo, NewOpts).
    -

    All future connections will use the new options.

    -

    You can also retrieve the current options similarly by -calling ranch:get_protocol_options/1.

    -
    -
    Retrieving the current protocol options
    -
    -
    Opts = ranch:get_protocol_options(tcp_echo).
    -
    -
    -
    +
    Opts = ranch:get_protocol_options(tcp_echo).
    +

    Obtaining information about listeners

    -
    -

    Ranch provides two functions for retrieving information about the -listeners, for reporting and diagnostic purposes.

    -

    The ranch:info/0 function will return detailed information -about all listeners.

    -
    -
    Retrieving detailed information
    -
    -
    ranch:info().
    -

    The ranch:procs/2 function will return all acceptor or listener -processes for a given listener.

    -
    -
    Get all acceptor processes
    -
    -
    ranch:procs(tcp_echo, acceptors).
    -
    -
    Get all connection processes
    -
    -
    ranch:procs(tcp_echo, connections).
    -
    - +
    ranch:procs(tcp_echo, connections).
    + + @@ -479,6 +325,8 @@ http://www.gnu.org/software/src-highlite --> +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.4/guide/parsers/index.html b/docs/en/ranch/1.4/guide/parsers/index.html index 4b2aa2b8..065d4914 100644 --- a/docs/en/ranch/1.4/guide/parsers/index.html +++ b/docs/en/ranch/1.4/guide/parsers/index.html @@ -62,109 +62,69 @@

    Writing parsers

    -

    There are three kinds of protocols:

    -
      -
    • -

      -Text protocols -

      +

      There are three kinds of protocols:

      +
      • Text protocols
      • -
      • -

        -Schema-less binary protocols -

        +
      • Schema-less binary protocols
      • -
      • -

        -Schema-based binary protocols -

        +
      • Schema-based binary protocols
      • -
    -

    This chapter introduces the first two kinds. It will not cover -more advanced topics such as continuations or parser generators.

    -

    This chapter isn’t specifically about Ranch, we assume here that -you know how to read data from the socket. The data you read and -the data that hasn’t been parsed is saved in a buffer. Every -time you read from the socket, the data read is appended to the -buffer. What happens next depends on the kind of protocol. We -will only cover the first two.

    -
    + +

    This chapter introduces the first two kinds. It will not cover more advanced topics such as continuations or parser generators.

    +

    This chapter isn't specifically about Ranch, we assume here that you know how to read data from the socket. The data you read and the data that hasn't been parsed is saved in a buffer. Every time you read from the socket, the data read is appended to the buffer. What happens next depends on the kind of protocol. We will only cover the first two.

    Parsing text

    -
    -

    Text protocols are generally line based. This means that we can’t -do anything with them until we receive the full line.

    -

    A simple way to get a full line is to use binary:split/{2,3}.

    -
    -
    Using binary:split/2 to get a line of input
    -
    -
    case binary:split(Buffer, <<"\n">>) of
    -        [_] ->
    -                get_more_data(Buffer);
    -        [Line, Rest] ->
    -                handle_line(Line, Rest)
    -end.
    -

    In the above example, we can have two results. Either there was -a line break in the buffer and we get it split into two parts, -the line and the rest of the buffer; or there was no line break -in the buffer and we need to get more data from the socket.

    -

    Next, we need to parse the line. The simplest way is to again -split, here on space. The difference is that we want to split -on all spaces character, as we want to tokenize the whole string.

    -
    -
    Using binary:split/3 to split text
    -
    -
    case binary:split(Line, <<" ">>, [global]) of
    -        [<<"HELLO">>] ->
    -                be_polite();
    -        [<<"AUTH">>, User, Password] ->
    -                authenticate_user(User, Password);
    -        [<<"QUIT">>, Reason] ->
    -                quit(Reason)
    -        %% ...
    -end.
    -

    Pretty simple, right? Match on the command name, get the rest -of the tokens in variables and call the respective functions.

    -

    After doing this, you will want to check if there is another -line in the buffer, and handle it immediately if any. -Otherwise wait for more data.

    -
    -
    -
    +
    case binary:split(Line, <<" ">>, [global]) of
    +	[<<"HELLO">>] ->
    +		be_polite();
    +	[<<"AUTH">>, User, Password] ->
    +		authenticate_user(User, Password);
    +	[<<"QUIT">>, Reason] ->
    +		quit(Reason)
    +	%% ...
    +end.
    +
    +

    Pretty simple, right? Match on the command name, get the rest of the tokens in variables and call the respective functions.

    +

    After doing this, you will want to check if there is another line in the buffer, and handle it immediately if any. Otherwise wait for more data.

    Parsing binary

    -
    -

    Binary protocols can be more varied, although most of them are -pretty similar. The first four bytes of a frame tend to be -the size of the frame, which is followed by a certain number -of bytes for the type of frame and then various parameters.

    -

    Sometimes the size of the frame includes the first four bytes, -sometimes not. Other times this size is encoded over two bytes. -And even other times little-endian is used instead of big-endian.

    -

    The general idea stays the same though.

    -
    -
    Using binary pattern matching to split frames
    -
    -
    << Size:32, _/bits >> = Buffer,
    -case Buffer of
    -        << Frame:Size/binary, Rest/bits >> ->
    -                handle_frame(Frame, Rest);
    -        _ ->
    -                get_more_data(Buffer)
    -end.
    -

    You will then need to parse this frame using binary pattern -matching, and handle it. Then you will want to check if there -is another frame fully received in the buffer, and handle it -immediately if any. Otherwise wait for more data.

    -
    - +
    << Size:32, _/bits >> = Buffer,
    +case Buffer of
    +	<< Frame:Size/binary, Rest/bits >> ->
    +		handle_frame(Frame, Rest);
    +	_ ->
    +		get_more_data(Buffer)
    +end.
    + +

    You will then need to parse this frame using binary pattern matching, and handle it. Then you will want to check if there is another frame fully received in the buffer, and handle it immediately if any. Otherwise wait for more data.

    + @@ -221,6 +181,8 @@ immediately if any. Otherwise wait for more data.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.4/guide/protocols/index.html b/docs/en/ranch/1.4/guide/protocols/index.html index 579faf62..c2d019a4 100644 --- a/docs/en/ranch/1.4/guide/protocols/index.html +++ b/docs/en/ranch/1.4/guide/protocols/index.html @@ -62,104 +62,76 @@

    Protocols

    -

    A protocol handler starts a connection process and defines the -protocol logic executed in this process.

    -
    +

    A protocol handler starts a connection process and defines the protocol logic executed in this process.

    Writing a protocol handler

    -
    -

    All protocol handlers must implement the ranch_protocol behavior -which defines a single callback, start_link/4. This callback is -responsible for spawning a new process for handling the connection. -It receives four arguments: the name of the listener, the socket, the -transport handler being used and the protocol options defined in -the call to ranch:start_listener/5. This callback must -return {ok, Pid}, with Pid the pid of the new process.

    -

    The newly started process can then freely initialize itself. However, -it must call ranch:accept_ack/1 before doing any socket operation. -This will ensure the connection process is the owner of the socket. -It expects the listener’s name as argument.

    -
    -
    Acknowledge accepting the socket
    -
    -
    ok = ranch:accept_ack(Ref).
    -

    If your protocol code requires specific socket options, you should -set them while initializing your connection process, after -calling ranch:accept_ack/1. You can use Transport:setopts/2 -for that purpose.

    -

    Following is the complete protocol code for the example found -in examples/tcp_echo/.

    -
    -
    Protocol module that echoes everything it receives
    -
    -
    -module(echo_protocol).
    --behaviour(ranch_protocol).
    -
    --export([start_link/4]).
    --export([init/4]).
    -
    -start_link(Ref, Socket, Transport, Opts) ->
    -        Pid = spawn_link(?MODULE, init, [Ref, Socket, Transport, Opts]),
    -        {ok, Pid}.
    -
    -init(Ref, Socket, Transport, _Opts = []) ->
    -        ok = ranch:accept_ack(Ref),
    -        loop(Socket, Transport).
    -
    -loop(Socket, Transport) ->
    -        case Transport:recv(Socket, 0, 5000) of
    -                {ok, Data} ->
    -                        Transport:send(Socket, Data),
    -                        loop(Socket, Transport);
    -                _ ->
    -                        ok = Transport:close(Socket)
    -        end.
    -
    -
    -
    +
    -module(echo_protocol).
    +-behaviour(ranch_protocol).
    +
    +-export([start_link/4]).
    +-export([init/4]).
    +
    +start_link(Ref, Socket, Transport, Opts) ->
    +	Pid = spawn_link(?MODULE, init, [Ref, Socket, Transport, Opts]),
    +	{ok, Pid}.
    +
    +init(Ref, Socket, Transport, _Opts = []) ->
    +	ok = ranch:accept_ack(Ref),
    +	loop(Socket, Transport).
    +
    +loop(Socket, Transport) ->
    +	case Transport:recv(Socket, 0, 5000) of
    +		{ok, Data} ->
    +			Transport:send(Socket, Data),
    +			loop(Socket, Transport);
    +		_ ->
    +			ok = Transport:close(Socket)
    +	end.
    +

    Using gen_server

    -
    -

    Special processes like the ones that use the gen_server or gen_fsm -behaviours have the particularity of having their start_link call not -return until the init function returns. This is problematic, because -you won’t be able to call ranch:accept_ack/1 from the init callback -as this would cause a deadlock to happen.

    -

    Use the gen_server:enter_loop/3 function. It allows you to start your process -normally (although it must be started with proc_lib like all special -processes), then perform any needed operations before falling back into -the normal gen_server execution loop.

    -
    -
    Use a gen_server for protocol handling
    -
    -
    -module(my_protocol).
    --behaviour(gen_server).
    --behaviour(ranch_protocol).
    +
    -module(my_protocol).
    +-behaviour(gen_server).
    +-behaviour(ranch_protocol).
     
    --export([start_link/4]).
    --export([init/1]).
    -%% Exports of other gen_server callbacks here.
    +-export([start_link/4]).
    +-export([init/1]).
    +%% Exports of other gen_server callbacks here.
     
    -start_link(Ref, Socket, Transport, Opts) ->
    -        {ok, proc_lib:spawn_link(?MODULE, init, [{Ref, Socket, Transport, Opts}])}.
    +start_link(Ref, Socket, Transport, Opts) ->
    +	{ok, proc_lib:spawn_link(?MODULE, init, [{Ref, Socket, Transport, Opts}])}.
     
    -init({Ref, Socket, Transport, _Opts = []}) ->
    -        %% Perform any required state initialization here.
    -        ok = ranch:accept_ack(Ref),
    -        ok = Transport:setopts(Socket, [{active, once}]),
    -        gen_server:enter_loop(?MODULE, [], {state, Socket, Transport}).
    +init({Ref, Socket, Transport, _Opts = []}) ->
    +	%% Perform any required state initialization here.
    +	ok = ranch:accept_ack(Ref),
    +	ok = Transport:setopts(Socket, [{active, once}]),
    +	gen_server:enter_loop(?MODULE, [], {state, Socket, Transport}).
    +
    +%% Other gen_server callbacks here.
    +
    +

    Check the tcp_reverse example for a complete example.

    -%% Other gen_server callbacks here.
    -

    Check the tcp_reverse example for a complete example.

    - - @@ -216,6 +188,8 @@ http://www.gnu.org/software/src-highlite --> +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.4/guide/ssl_auth/index.html b/docs/en/ranch/1.4/guide/ssl_auth/index.html index 821199d8..54209966 100644 --- a/docs/en/ranch/1.4/guide/ssl_auth/index.html +++ b/docs/en/ranch/1.4/guide/ssl_auth/index.html @@ -62,158 +62,82 @@

    SSL client authentication

    -

    Purpose

    -
    -

    SSL client authentication is a mechanism allowing applications to -identify certificates. This allows your application to make sure that -the client is an authorized certificate, but makes no claim about -whether the user can be trusted. This can be combined with a password -based authentication to attain greater security.

    -

    The server only needs to retain the certificate serial number and -the certificate issuer to authenticate the certificate. Together, -they can be used to uniquely identify a certicate.

    -

    As Ranch allows the same protocol code to be used for both SSL and -non-SSL transports, you need to make sure you are in an SSL context -before attempting to perform an SSL client authentication. This -can be done by checking the return value of Transport:name/0.

    -
    -
    -
    +

    SSL client authentication is a mechanism allowing applications to identify certificates. This allows your application to make sure that the client is an authorized certificate, but makes no claim about whether the user can be trusted. This can be combined with a password based authentication to attain greater security.

    +

    The server only needs to retain the certificate serial number and the certificate issuer to authenticate the certificate. Together, they can be used to uniquely identify a certicate.

    +

    As Ranch allows the same protocol code to be used for both SSL and non-SSL transports, you need to make sure you are in an SSL context before attempting to perform an SSL client authentication. This can be done by checking the return value of Transport:name/0.

    Obtaining client certificates

    -
    -

    You can obtain client certificates from various sources. You can -generate them yourself, or you can use a service like CAcert.org -which allows you to generate client and server certificates for -free.

    -

    Following are the steps you need to take to create a CAcert.org -account, generate a certificate and install it in your favorite -browser.

    -
      -
    • -

      -Open http://cacert.org in your favorite browser -

      +

      You can obtain client certificates from various sources. You can generate them yourself, or you can use a service like CAcert.org which allows you to generate client and server certificates for free.

      +

      Following are the steps you need to take to create a CAcert.org account, generate a certificate and install it in your favorite browser.

      +
      • Open http://cacert.org in your favorite browser
      • -
      • -

        -Root Certificate link: install both certificates -

        +
      • Root Certificate link: install both certificates
      • -
      • -

        -Join (Register an account) -

        +
      • Join (Register an account)
      • -
      • -

        -Verify your account (check your email inbox!) -

        +
      • Verify your account (check your email inbox!)
      • -
      • -

        -Log in -

        +
      • Log in
      • -
      • -

        -Client Certificates: New -

        +
      • Client Certificates: New
      • -
      • -

        -Follow instructions to create the certificate -

        +
      • Follow instructions to create the certificate
      • -
      • -

        -Install the certificate in your browser -

        +
      • Install the certificate in your browser
      • -
    -

    You can optionally save the certificate for later use, for example -to extract the IssuerID information as will be detailed later on.

    -
    -
    -
    + +

    You can optionally save the certificate for later use, for example to extract the IssuerID information as will be detailed later on.

    Transport configuration

    -
    -

    The SSL transport does not request a client certificate by default. -You need to specify the {verify, verify_peer} option when starting -the listener to enable this behavior.

    -
    -
    Configure a listener for SSL authentication
    -
    -
    {ok, _} = ranch:start_listener(my_ssl,
    -        ranch_ssl, [
    -                {port, SSLPort},
    -                {certfile, PathToCertfile},
    -                {cacertfile, PathToCACertfile},
    -                {verify, verify_peer}
    -        ],
    -        my_protocol, []
    -).
    -

    In this example we set the required port and certfile, but also -the cacertfile containing the CACert.org root certificate, and -the option to request the client certificate.

    -

    If you enable the {verify, verify_peer} option and the client does -not have a client certificate configured for your domain, then no -certificate will be sent. This allows you to use SSL for more than -just authenticated clients.

    -
    -
    -
    +
    {ok, _} = ranch:start_listener(my_ssl,
    +	ranch_ssl, [
    +		{port, SSLPort},
    +		{certfile, PathToCertfile},
    +		{cacertfile, PathToCACertfile},
    +		{verify, verify_peer}
    +	],
    +	my_protocol, []
    +).
    +
    +

    In this example we set the required port and certfile, but also the cacertfile containing the CACert.org root certificate, and the option to request the client certificate.

    +

    If you enable the {verify, verify_peer} option and the client does not have a client certificate configured for your domain, then no certificate will be sent. This allows you to use SSL for more than just authenticated clients.

    Authentication

    -
    -

    To authenticate users, you must first save the certificate information -required. If you have your users' certificate files, you can simply -load the certificate and retrieve the information directly.

    -
    -
    Retrieve the issuer ID from a certificate
    -
    -
    certfile_to_issuer_id(Filename) ->
    -        {ok, Data} = file:read_file(Filename),
    -        [{'Certificate', Cert, not_encrypted}] = public_key:pem_decode(Data),
    -        {ok, IssuerID} = public_key:pkix_issuer_id(Cert, self),
    -        IssuerID.
    -

    The IssuerID variable contains both the certificate serial number -and the certificate issuer stored in a tuple, so this value alone can -be used to uniquely identify the user certificate. You can save this -value in a database, a configuration file or any other place where an -Erlang term can be stored and retrieved.

    -

    To retrieve the IssuerID from a running connection, you need to first -retrieve the client certificate and then extract this information from -it. Ranch does not provide a function to retrieve the client certificate. -Instead you can use the ssl:peercert/1 function. Once you have the -certificate, you can again use the public_key:pkix_issuer_id/2 to -extract the IssuerID value.

    -

    The following function returns the IssuerID or false if no client -certificate was found. This snippet is intended to be used from your -protocol code.

    -
    -
    Retrieve the issuer ID from the certificate for the current connection
    -
    -
    socket_to_issuer_id(Socket) ->
    -        case ssl:peercert(Socket) of
    -                {error, no_peercert} ->
    -                        false;
    -                {ok, Cert} ->
    -                        {ok, IssuerID} = public_key:pkix_issuer_id(Cert, self),
    -                        IssuerID
    -        end.
    -

    You then only need to match the IssuerID value to authenticate the -user.

    -
    - +
    socket_to_issuer_id(Socket) ->
    +	case ssl:peercert(Socket) of
    +		{error, no_peercert} ->
    +			false;
    +		{ok, Cert} ->
    +			{ok, IssuerID} = public_key:pkix_issuer_id(Cert, self),
    +			IssuerID
    +	end.
    + +

    You then only need to match the IssuerID value to authenticate the user.

    + @@ -270,6 +194,8 @@ user.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.4/guide/transports/index.html b/docs/en/ranch/1.4/guide/transports/index.html index 6c803fb3..dd96e531 100644 --- a/docs/en/ranch/1.4/guide/transports/index.html +++ b/docs/en/ranch/1.4/guide/transports/index.html @@ -62,179 +62,107 @@

    Transports

    -

    A transport defines the interface to interact with a socket.

    -

    Transports can be used for connecting, listening and accepting -connections, but also for receiving and sending data. Both -passive and active mode are supported, although all sockets -are initialized as passive.

    -
    +

    A transport defines the interface to interact with a socket.

    +

    Transports can be used for connecting, listening and accepting connections, but also for receiving and sending data. Both passive and active mode are supported, although all sockets are initialized as passive.

    TCP transport

    -
    -

    The TCP transport is a thin wrapper around gen_tcp.

    -
    -
    -
    +

    The TCP transport is a thin wrapper around gen_tcp.

    SSL transport

    -
    -

    The SSL transport is a thin wrapper around ssl.

    -

    Ranch depends on ssl by default so any necessary -dependencies will start when Ranch is started. It is -possible to remove the dependency when the SSL transport -will not be used. Refer to your release build tool’s -documentation for more information.

    -

    When embedding Ranch listeners that have an SSL transport, -your application must depend on the ssl application for -proper behavior.

    -
    -
    -
    +

    The SSL transport is a thin wrapper around ssl.

    +

    Ranch depends on ssl by default so any necessary dependencies will start when Ranch is started. It is possible to remove the dependency when the SSL transport will not be used. Refer to your release build tool's documentation for more information.

    +

    When embedding Ranch listeners that have an SSL transport, your application must depend on the ssl application for proper behavior.

    Sending and receiving data

    -
    -

    This section assumes that Transport is a valid transport handler -(like ranch_tcp or ranch_ssl) and Socket is a connected -socket obtained through the listener.

    -

    You can send data to a socket by calling the Transport:send/2 -function. The data can be given as iodata(), which is defined as -binary() | iolist(). All the following calls will work:

    -
    -
    Sending data to the socket
    -
    -
    Transport:send(Socket, <<"Ranch is cool!">>).
    -Transport:send(Socket, "Ranch is cool!").
    -Transport:send(Socket, ["Ranch", ["is", "cool!"]]).
    -Transport:send(Socket, ["Ranch", [<<"is">>, "cool!"]]).
    -

    You can receive data either in passive or in active mode. Passive mode -means that you will perform a blocking Transport:recv/3 call, while -active mode means that you will receive the data as a message.

    -

    By default, all data will be received as binary. It is possible to -receive data as strings, although this is not recommended as binaries -are a more efficient construct, especially for binary protocols.

    -

    Receiving data using passive mode requires a single function call. The -first argument is the socket, and the third argument is a timeout duration -before the call returns with {error, timeout}.

    -

    The second argument is the amount of data in bytes that we want to receive. -The function will wait for data until it has received exactly this amount. -If you are not expecting a precise size, you can specify 0 which will make -this call return as soon as data was read, regardless of its size.

    -
    -
    Receiving data from the socket in passive mode
    -
    -
    {ok, Data} = Transport:recv(Socket, 0, 5000).
    -

    Active mode requires you to inform the socket that you want to receive -data as a message and to write the code to actually receive it.

    -

    There are two kinds of active modes: {active, once} and -{active, true}. The first will send a single message before going -back to passive mode; the second will send messages indefinitely. -We recommend not using the {active, true} mode as it could quickly -flood your process mailbox. It’s better to keep the data in the socket -and read it only when required.

    -

    Three different messages can be received:

    -
      -
    • -

      -{OK, Socket, Data} -

      +
      {ok, Data} = Transport:recv(Socket, 0, 5000).
      +
    +

    Active mode requires you to inform the socket that you want to receive data as a message and to write the code to actually receive it.

    +

    There are two kinds of active modes: {active, once} and {active, true}. The first will send a single message before going back to passive mode; the second will send messages indefinitely. We recommend not using the {active, true} mode as it could quickly flood your process mailbox. It's better to keep the data in the socket and read it only when required.

    +

    Three different messages can be received:

    +
    • {OK, Socket, Data}
    • -
    • -

      -{Closed, Socket} -

      +
    • {Closed, Socket}
    • -
    • -

      -{Error, Socket, Reason} -

      +
    • {Error, Socket, Reason}
    • -
    -

    The value of OK, Closed and Error can be different -depending on the transport being used. To be able to properly match -on them you must first call the Transport:messages/0 function.

    -
    -
    Retrieving the transport’s active message identifiers
    -
    -
    {OK, Closed, Error} = Transport:messages().
    -

    To start receiving messages you will need to call the Transport:setopts/2 -function, and do so every time you want to receive data.

    -
    -
    Receiving messages from the socket in active mode
    -
    -
    {OK, Closed, Error} = Transport:messages(),
    -Transport:setopts(Socket, [{active, once}]),
    -receive
    -        {OK, Socket, Data} ->
    -                io:format("data received: ~p~n", [Data]);
    -        {Closed, Socket} ->
    -                io:format("socket got closed!~n");
    -        {Error, Socket, Reason} ->
    -                io:format("error happened: ~p~n", [Reason])
    -end.
    -

    You can easily integrate active sockets with existing Erlang code as all -you really need is just a few more clauses when receiving messages.

    - - -
    +
    {OK, Closed, Error} = Transport:messages(),
    +Transport:setopts(Socket, [{active, once}]),
    +receive
    +	{OK, Socket, Data} ->
    +		io:format("data received: ~p~n", [Data]);
    +	{Closed, Socket} ->
    +		io:format("socket got closed!~n");
    +	{Error, Socket, Reason} ->
    +		io:format("error happened: ~p~n", [Reason])
    +end.
    +
    +

    You can easily integrate active sockets with existing Erlang code as all you really need is just a few more clauses when receiving messages.

    Sending files

    -
    -

    As in the previous section it is assumed Transport is a valid transport -handler and Socket is a connected socket obtained through the listener.

    -

    To send a whole file, with name Filename, over a socket:

    -
    -
    Sending a file by filename
    -
    -
    {ok, SentBytes} = Transport:sendfile(Socket, Filename).
    -

    Or part of a file, with Offset greater than or equal to 0, Bytes number of -bytes and chunks of size ChunkSize:

    -
    -
    Sending part of a file by filename in chunks
    -
    -
    Opts = [{chunk_size, ChunkSize}],
    -{ok, SentBytes} = Transport:sendfile(Socket, Filename, Offset, Bytes, Opts).
    -

    To improve efficiency when sending multiple parts of the same file it is also -possible to use a file descriptor opened in raw mode:

    -
    -
    Sending a file opened in raw mode
    -
    -
    {ok, RawFile} = file:open(Filename, [raw, read, binary]),
    -{ok, SentBytes} = Transport:sendfile(Socket, RawFile, Offset, Bytes, Opts).
    -
    - -
    +
    {ok, RawFile} = file:open(Filename, [raw, read, binary]),
    +{ok, SentBytes} = Transport:sendfile(Socket, RawFile, Offset, Bytes, Opts).
    +

    Writing a transport handler

    -
    -

    A transport handler is a module implementing the ranch_transport behavior. -It defines a certain number of callbacks that must be written in order to -allow transparent usage of the transport handler.

    -

    The behavior doesn’t define the socket options available when opening a -socket. These do not need to be common to all transports as it’s easy enough -to write different initialization functions for the different transports that -will be used. With one exception though. The setopts/2 function must -implement the {active, once} and the {active, true} options.

    -

    If the transport handler doesn’t have a native implementation of sendfile/5 a -fallback is available, ranch_transport:sendfile/6. The extra first argument -is the transport’s module. See ranch_ssl for an example.

    -
    - +

    A transport handler is a module implementing the ranch_transport behavior. It defines a certain number of callbacks that must be written in order to allow transparent usage of the transport handler.

    +

    The behavior doesn't define the socket options available when opening a socket. These do not need to be common to all transports as it's easy enough to write different initialization functions for the different transports that will be used. With one exception though. The setopts/2 function must implement the {active, once} and the {active, true} options.

    +

    If the transport handler doesn't have a native implementation of sendfile/5 a fallback is available, ranch_transport:sendfile/6. The extra first argument is the transport's module. See ranch_ssl for an example.

    + @@ -291,6 +219,8 @@ is the transport’s module. See ranch_ssl for an example.

    < +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.4/manual/index.html b/docs/en/ranch/1.4/manual/index.html index a8c6943c..4f300b68 100644 --- a/docs/en/ranch/1.4/manual/index.html +++ b/docs/en/ranch/1.4/manual/index.html @@ -62,38 +62,20 @@

    Ranch Function Reference

    - + + @@ -128,6 +110,8 @@ +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.4/manual/ranch/index.html b/docs/en/ranch/1.4/manual/ranch/index.html index b77d7548..2dfdd506 100644 --- a/docs/en/ranch/1.4/manual/ranch/index.html +++ b/docs/en/ranch/1.4/manual/ranch/index.html @@ -62,567 +62,232 @@

    ranch(3)

    -

    Name

    -
    -

    ranch - socket acceptor pool

    -
    -
    -
    +

    ranch - socket acceptor pool

    Description

    -
    -

    The ranch module provides functions for starting and -manipulating Ranch listeners.

    -
    -
    -
    +

    The ranch module provides functions for starting and manipulating Ranch listeners.

    Types

    -
    -
    -

    max_conns() = non_neg_integer() | infinity

    -

    Maximum number of connections allowed on this listener.

    -

    This is a soft limit. The actual number of connections -might be slightly above the limit due to concurrency -when accepting new connections. Some connections may -also be removed from this count explicitly by the user -code.

    -
    -
    +

    max_conns() = non_neg_integer() | infinity

    +

    Maximum number of connections allowed on this listener.

    +

    This is a soft limit. The actual number of connections might be slightly above the limit due to concurrency when accepting new connections. Some connections may also be removed from this count explicitly by the user code.

    opt()

    -
    -
    -
    opt() = {ack_timeout, timeout()}
    -        | {connection_type, worker | supervisor}
    -        | {max_connections, max_conns()}
    -        | {num_acceptors, pos_integer()}
    -        | {shutdown, timeout() | brutal_kill}
    -        | {socket, any()}
    -

    Ranch-specific transport options.

    -

    These options are not passed on to the transports. -They are used by Ranch while setting up the listeners.

    -
    -
    -

    ref() = any()

    -

    Unique name used to refer to a listener.

    -
    -
    -
    -
    +
    opt() = {ack_timeout, timeout()}
    +	| {connection_type, worker | supervisor}
    +	| {max_connections, max_conns()}
    +	| {num_acceptors, pos_integer()}
    +	| {shutdown, timeout() | brutal_kill}
    +	| {socket, any()}
    +
    +

    Ranch-specific transport options.

    +

    These options are not passed on to the transports. They are used by Ranch while setting up the listeners.

    +

    ref() = any()

    +

    Unique name used to refer to a listener.

    Option descriptions

    -
    -

    None of the options are required.

    -
    -
    -ack_timeout (5000) -
    -
    -

    - Maximum allowed time for the ranch:accept_ack/1 call to finish. -

    -
    -
    -connection_type (worker) -
    -
    -

    - Type of process that will handle the connection. -

    -
    -
    -max_connections (1024) -
    -
    -

    - Maximum number of active connections. Soft limit. Using infinity will disable the limit entirely. -

    -
    -
    -num_acceptors (10) -
    -
    -

    - Number of processes that accept connections. -

    -
    -
    -shutdown (5000) -
    -
    -

    - Maximum allowed time for children to stop on listener shutdown. -

    -
    -
    -socket -
    -
    -

    - Listening socket opened externally to be used instead of calling Transport:listen/1. -

    -
    -
    -
    - -
    +

    None of the options are required.

    +
    ack_timeout (5000)
    +

    Maximum allowed time for the ranch:accept_ack/1 call to finish.

    +
    +
    connection_type (worker)
    +

    Type of process that will handle the connection.

    +
    +
    max_connections (1024)
    +

    Maximum number of active connections. Soft limit. Using infinity will disable the limit entirely.

    +
    +
    num_acceptors (10)
    +

    Number of processes that accept connections.

    +
    +
    shutdown (5000)
    +

    Maximum allowed time for children to stop on listener shutdown.

    +
    +
    socket
    +

    Listening socket opened externally to be used instead of calling Transport:listen/1.

    +
    +

    Exports

    -
    -
    -

    accept_ack(Ref) → ok

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -

    Acknowledge that the connection is accepted.

    -

    This function MUST be used by a connection process to inform -Ranch that it initialized properly and let it perform any -additional operations before the socket can be safely used.

    -
    -
    -

    child_spec(Ref, NumAcceptors, Transport, TransOpts, Protocol, ProtoOpts) → supervisor:child_spec()

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -NumAcceptors = non_neg_integer() -
    -
    -

    -Number of acceptor processes. -

    -
    -
    -Transport = module() -
    -
    -

    -Transport module. -

    -
    -
    -TransOpts = any() -
    -
    -

    -Transport options. -

    -
    -
    -Protocol = module() -
    -
    -

    -Protocol module. -

    -
    -
    -ProtoOpts = any() -
    -
    -

    -Protocol options. -

    -
    -
    -

    Return child specifications for a new listener.

    -

    This function can be used to embed a listener directly -in an application instead of letting Ranch handle it.

    -
    -
    -

    get_addr(Ref) → {IP, Port}

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -IP = inet:ip_address() -
    -
    -

    -IP of the interface used by this listener. -

    -
    -
    -Port = inet:port_number() -
    -
    -

    -Port number used by this listener. -

    -
    -
    -

    Return the IP address and port for the given listener.

    -
    -
    -

    get_max_connections(Ref) → MaxConns

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -MaxConns = max_conns() -
    -
    -

    -Current maximum number of connections. -

    -
    -
    -

    Return the max number of connections allowed for the given listener.

    -
    -
    -

    get_port(Ref) → Port

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -Port = inet:port_number() -
    -
    -

    -Port number used by this listener. -

    -
    -
    -

    Return the port for the given listener.

    -
    -
    -

    get_protocol_options(Ref) → ProtoOpts

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -ProtoOpts = any() -
    -
    -

    -Current protocol options. -

    -
    -
    -

    Return the protocol options set for the given listener.

    -
    -
    -

    info() → [{Ref, [{Key, Value}]}]

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -Key = atom() -
    -
    -

    -Information key. -

    -
    -
    -Value = any() -
    -
    -

    -Information value. -

    -
    -
    -

    Return detailed information about all Ranch listeners.

    -

    The following keys are defined:

    -
    -
    -pid -
    -
    -

    -Pid of the listener’s top-level supervisor. -

    -
    -
    -ip -
    -
    -

    -Interface Ranch listens on. -

    -
    -
    -port -
    -
    -

    -Port number Ranch listens on. -

    -
    -
    -num_acceptors -
    -
    -

    -Number of acceptor processes. -

    -
    -
    -max_connections -
    -
    -

    -Maximum number of connections. -

    -
    -
    -active_connections -
    -
    -

    -Number of active connections. -

    -
    -
    -all_connections -
    -
    -

    -Number of connections, including those removed from the count. -

    -
    -
    -transport -
    -
    -

    -Transport module. -

    -
    -
    -transport_options -
    -
    -

    -Transport options. -

    -
    -
    -protocol -
    -
    -

    -Protocol module. -

    -
    -
    -protocol_options -
    -
    -

    -Protocol options. -

    -
    -
    -
    -
    -

    procs(Ref, acceptors | connections) → [pid()]

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -

    Return all acceptor or connection processes for one listener.

    -
    -
    -

    remove_connection(Ref) → ok

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -

    Do not count this connection when limiting the number of connections.

    -

    You can use this function for long-running connection processes -which spend most of their time idling rather than consuming -resources. This allows Ranch to accept a lot more connections -without sacrificing the latency of the system.

    -

    This function may only be called from a connection process.

    -
    -
    -

    set_max_connections(Ref, MaxConns) → ok

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -MaxConns = max_conns() -
    -
    -

    -New maximum number of connections. -

    -
    -
    -

    Set the max number of connections for the given listener.

    -

    The change will be applied immediately. If the new value is -smaller than the previous one, Ranch will not kill the extra -connections, but will wait for them to terminate properly.

    -
    -
    -

    set_protocol_options(Ref, ProtoOpts) → ok

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -ProtoOpts = any() -
    -
    -

    -New protocol options. -

    -
    -
    -

    Set the protocol options for the given listener.

    -

    The change will be applied immediately for all new connections. -Old connections will not receive the new options.

    -
    -
    -

    start_listener(Ref, NumAcceptors, Transport, TransOpts, Protocol, ProtoOpts) → {ok, pid()} | {error, badarg}

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -NumAcceptors = non_neg_integer() -
    -
    -

    -Number of acceptor processes. -

    -
    -
    -Transport = module() -
    -
    -

    -Transport module. -

    -
    -
    -TransOpts = any() -
    -
    -

    -Transport options. -

    -
    -
    -Protocol = module() -
    -
    -

    -Protocol module. -

    -
    -
    -ProtoOpts = any() -
    -
    -

    -Protocol options. -

    -
    -
    -

    Start listening for connections using the given transport -and protocol. Returns the pid for this listener’s supervisor.

    -

    There are additional transport options that apply -regardless of transport. They allow configuring how the -connections are supervised, rate limited and more. Please -consult the previous section for more details.

    -
    -
    -

    stop_listener(Ref) → ok | {error, not_found}

    -
    -
    -Ref = ref() -
    -
    -

    -Listener name. -

    -
    -
    -

    Stop the given listener.

    -

    The listener is stopped gracefully, first by closing the -listening port, then by stopping the connection processes. -These processes are stopped according to the shutdown -transport option, which may be set to brutally kill all -connection processes or give them some time to stop properly.

    -

    This function does not return until the listener is -completely stopped.

    -
    -
    -
    +

    accept_ack(Ref) -> ok

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    +

    Acknowledge that the connection is accepted.

    +

    This function MUST be used by a connection process to inform Ranch that it initialized properly and let it perform any additional operations before the socket can be safely used.

    +

    child_spec(Ref, NumAcceptors, Transport, TransOpts, Protocol, ProtoOpts) -> supervisor:child_spec()

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    NumAcceptors = non_neg_integer()
    +

    Number of acceptor processes.

    +
    +
    Transport = module()
    +

    Transport module.

    +
    +
    TransOpts = any()
    +

    Transport options.

    +
    +
    Protocol = module()
    +

    Protocol module.

    +
    +
    ProtoOpts = any()
    +

    Protocol options.

    +
    +
    +

    Return child specifications for a new listener.

    +

    This function can be used to embed a listener directly in an application instead of letting Ranch handle it.

    +

    get_addr(Ref) -> {IP, Port}

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    IP = inet:ip_address()
    +

    IP of the interface used by this listener.

    +
    +
    Port = inet:port_number()
    +

    Port number used by this listener.

    +
    +
    +

    Return the IP address and port for the given listener.

    +

    get_max_connections(Ref) -> MaxConns

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    MaxConns = max_conns()
    +

    Current maximum number of connections.

    +
    +
    +

    Return the max number of connections allowed for the given listener.

    +

    get_port(Ref) -> Port

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    Port = inet:port_number()
    +

    Port number used by this listener.

    +
    +
    +

    Return the port for the given listener.

    +

    get_protocol_options(Ref) -> ProtoOpts

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    ProtoOpts = any()
    +

    Current protocol options.

    +
    +
    +

    Return the protocol options set for the given listener.

    +

    info() -> [{Ref, [{Key, Value}]}]

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    Key = atom()
    +

    Information key.

    +
    +
    Value = any()
    +

    Information value.

    +
    +
    +

    Return detailed information about all Ranch listeners.

    +

    The following keys are defined:

    +
    pid
    +

    Pid of the listener's top-level supervisor.

    +
    +
    ip
    +

    Interface Ranch listens on.

    +
    +
    port
    +

    Port number Ranch listens on.

    +
    +
    num_acceptors
    +

    Number of acceptor processes.

    +
    +
    max_connections
    +

    Maximum number of connections.

    +
    +
    active_connections
    +

    Number of active connections.

    +
    +
    all_connections
    +

    Number of connections, including those removed from the count.

    +
    +
    transport
    +

    Transport module.

    +
    +
    transport_options
    +

    Transport options.

    +
    +
    protocol
    +

    Protocol module.

    +
    +
    protocol_options
    +

    Protocol options.

    +
    +
    +

    procs(Ref, acceptors | connections) -> [pid()]

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    +

    Return all acceptor or connection processes for one listener.

    +

    remove_connection(Ref) -> ok

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    +

    Do not count this connection when limiting the number of connections.

    +

    You can use this function for long-running connection processes which spend most of their time idling rather than consuming resources. This allows Ranch to accept a lot more connections without sacrificing the latency of the system.

    +

    This function may only be called from a connection process.

    +

    set_max_connections(Ref, MaxConns) -> ok

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    MaxConns = max_conns()
    +

    New maximum number of connections.

    +
    +
    +

    Set the max number of connections for the given listener.

    +

    The change will be applied immediately. If the new value is smaller than the previous one, Ranch will not kill the extra connections, but will wait for them to terminate properly.

    +

    set_protocol_options(Ref, ProtoOpts) -> ok

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    ProtoOpts = any()
    +

    New protocol options.

    +
    +
    +

    Set the protocol options for the given listener.

    +

    The change will be applied immediately for all new connections. Old connections will not receive the new options.

    +

    start_listener(Ref, NumAcceptors, Transport, TransOpts, Protocol, ProtoOpts) -> {ok, pid()} | {error, badarg}

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    NumAcceptors = non_neg_integer()
    +

    Number of acceptor processes.

    +
    +
    Transport = module()
    +

    Transport module.

    +
    +
    TransOpts = any()
    +

    Transport options.

    +
    +
    Protocol = module()
    +

    Protocol module.

    +
    +
    ProtoOpts = any()
    +

    Protocol options.

    +
    +
    +

    Start listening for connections using the given transport and protocol. Returns the pid for this listener's supervisor.

    +

    There are additional transport options that apply regardless of transport. They allow configuring how the connections are supervised, rate limited and more. Please consult the previous section for more details.

    +

    stop_listener(Ref) -> ok | {error, not_found}

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    +

    Stop the given listener.

    +

    The listener is stopped gracefully, first by closing the listening port, then by stopping the connection processes. These processes are stopped according to the shutdown transport option, which may be set to brutally kill all connection processes or give them some time to stop properly.

    +

    This function does not return until the listener is completely stopped.

    + @@ -657,6 +322,8 @@ completely stopped.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.4/manual/ranch_app/index.html b/docs/en/ranch/1.4/manual/ranch_app/index.html index 0457f868..bdda66af 100644 --- a/docs/en/ranch/1.4/manual/ranch_app/index.html +++ b/docs/en/ranch/1.4/manual/ranch_app/index.html @@ -62,41 +62,18 @@

    ranch(7)

    -

    Name

    -
    -

    ranch - Socket acceptor pool for TCP protocols.

    -
    -
    -
    +

    ranch - Socket acceptor pool for TCP protocols.

    Dependencies

    -
    -

    The ranch application depends on the ssl application to -start. It is used for handling secure connections, when the -transport is ranch_ssl. It can be disabled if SSL is not -used.

    -
    -
    -
    +

    The ranch application depends on the ssl application to start. It is used for handling secure connections, when the transport is ranch_ssl. It can be disabled if SSL is not used.

    Environment

    -
    -

    The ranch application defines one application environment -configuration parameter.

    -
    -
    -profile (false) -
    -
    -

    - When enabled, Ranch will start eprof profiling automatically. -

    +

    The ranch application defines one application environment configuration parameter.

    +
    profile (false)
    +

    When enabled, Ranch will start eprof profiling automatically.

    -
    -

    You can use the ranch_app:profile_output/0 function to stop -profiling and output the results to the files procs.profile -and total.profile. Do not use in production.

    -
    -
    + +

    You can use the ranch_app:profile_output/0 function to stop profiling and output the results to the files procs.profile and total.profile. Do not use in production.

    + @@ -131,6 +108,8 @@ and total.profile. Do not use in production.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.4/manual/ranch_protocol/index.html b/docs/en/ranch/1.4/manual/ranch_protocol/index.html index 333d8fe8..a54db606 100644 --- a/docs/en/ranch/1.4/manual/ranch_protocol/index.html +++ b/docs/en/ranch/1.4/manual/ranch_protocol/index.html @@ -62,83 +62,33 @@

    ranch_protocol(3)

    -

    Name

    -
    -

    ranch_protocol - behaviour for protocol modules

    -
    -
    -
    +

    ranch_protocol - behaviour for protocol modules

    Description

    -
    -

    The ranch_protocol behaviour defines the interface used -by Ranch protocols.

    -
    -
    -
    +

    The ranch_protocol behaviour defines the interface used by Ranch protocols.

    Types

    -
    -

    None.

    -
    -
    -
    +

    None.

    Callbacks

    -
    -
    - -
    -
    -Ref = ranch:ref() -
    -
    -

    -Listener name. -

    + +
    Ref = ranch:ref()
    +

    Listener name.

    -
    -Socket = any() -
    -
    -

    -Socket for this connection. -

    +
    Socket = any()
    +

    Socket for this connection.

    -
    -Transport = module() -
    -
    -

    -Transport module for this socket. -

    +
    Transport = module()
    +

    Transport module for this socket.

    -
    -ProtoOpts = any() -
    -
    -

    -Protocol options. -

    +
    ProtoOpts = any()
    +

    Protocol options.

    -
    -

    Start a new connection process for the given socket.

    -

    The only purpose of this callback is to start a process that -will handle the socket. It must spawn the process, link and -then return the new pid. This function will always be called -from inside a supervisor.

    -

    This callback can also return two pids. The first pid is the -pid of the process that will be supervised. The second pid is -the pid of the process that will receive ownership of the -socket. This second process must be a child of the first. This -form is only available when connection_type is set to -supervisor.

    -

    If any other value is returned, the supervisor will close the -socket and assume no process has been started.

    -

    Do not perform any operations in this callback, as this would -block the supervisor responsible for starting connection -processes and degrade performance severely.

    -
    -
    -
    + +

    Start a new connection process for the given socket.

    +

    The only purpose of this callback is to start a process that will handle the socket. It must spawn the process, link and then return the new pid. This function will always be called from inside a supervisor.

    +

    This callback can also return two pids. The first pid is the pid of the process that will be supervised. The second pid is the pid of the process that will receive ownership of the socket. This second process must be a child of the first. This form is only available when connection_type is set to supervisor.

    +

    If any other value is returned, the supervisor will close the socket and assume no process has been started.

    +

    Do not perform any operations in this callback, as this would block the supervisor responsible for starting connection processes and degrade performance severely.

    + @@ -173,6 +123,8 @@ processes and degrade performance severely.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.4/manual/ranch_ssl/index.html b/docs/en/ranch/1.4/manual/ranch_ssl/index.html index c6f5221e..6701e689 100644 --- a/docs/en/ranch/1.4/manual/ranch_ssl/index.html +++ b/docs/en/ranch/1.4/manual/ranch_ssl/index.html @@ -62,385 +62,174 @@

    ranch_ssl(3)

    -

    Name

    -
    -

    ranch_ssl - SSL transport module

    -
    -
    -
    +

    ranch_ssl - SSL transport module

    Description

    -
    -

    The ranch_ssl module implements an SSL Ranch transport.

    -
    -
    -
    +

    The ranch_ssl module implements an SSL Ranch transport.

    Types

    -
    -

    ssl_opt()

    -
    -
    -
    ssl_opt() = {alpn_preferred_protocols, [binary()]}
    -        | {beast_mitigation, one_n_minus_one | zero_n | disabled}
    -        | {cacertfile, string()}
    -        | {cacerts, [public_key:der_encoded()]}
    -        | {cert, public_key:der_encoded()}
    -        | {certfile, string()}
    -        | {ciphers, [ssl:erl_cipher_suite()] | string()}
    -        | {client_renegotiation, boolean()}
    -        | {crl_cache, {module(), {internal | any(), list()}}}
    -        | {crl_check, boolean() | peer | best_effort}
    -        | {depth, 0..255}
    -        | {dh, public_key:der_encoded()}
    -        | {dhfile, string()}
    -        | {fail_if_no_peer_cert, boolean()}
    -        | {hibernate_after, integer() | undefined}
    -        | {honor_cipher_order, boolean()}
    -        | {key, {'RSAPrivateKey' | 'DSAPrivateKey' | 'PrivateKeyInfo', public_key:der_encoded()}}
    -        | {keyfile, string()}
    -        | {log_alert, boolean()}
    -        | {next_protocols_advertised, [binary()]}
    -        | {padding_check, boolean()}
    -        | {partial_chain, fun(([public_key:der_encoded()]) -> {trusted_ca, public_key:der_encoded()} | unknown_ca)}
    -        | {password, string()}
    -        | {psk_identity, string()}
    -        | {reuse_session, fun()}
    -        | {reuse_sessions, boolean()}
    -        | {secure_renegotiate, boolean()}
    -        | {signature_algs, [{atom(), atom()}]}
    -        | {sni_fun, fun()}
    -        | {sni_hosts, [{string(), ssl_opt()}]}
    -        | {user_lookup_fun, {fun(), any()}}
    -        | {v2_hello_compatible, boolean()}
    -        | {verify, ssl:verify_type()}
    -        | {verify_fun, {fun(), any()}}
    -        | {versions, [atom()]}.
    -

    SSL-specific listen options.

    -
    -
    -

    opt() = ranch_tcp:opt() | ssl_opt()

    -

    Listen options.

    -
    -
    -

    opts() = [opt()]

    -

    List of listen options.

    -
    -
    -
    -
    +
    ssl_opt() = {alpn_preferred_protocols, [binary()]}
    +	| {beast_mitigation, one_n_minus_one | zero_n | disabled}
    +	| {cacertfile, string()}
    +	| {cacerts, [public_key:der_encoded()]}
    +	| {cert, public_key:der_encoded()}
    +	| {certfile, string()}
    +	| {ciphers, [ssl:erl_cipher_suite()] | string()}
    +	| {client_renegotiation, boolean()}
    +	| {crl_cache, {module(), {internal | any(), list()}}}
    +	| {crl_check, boolean() | peer | best_effort}
    +	| {depth, 0..255}
    +	| {dh, public_key:der_encoded()}
    +	| {dhfile, string()}
    +	| {fail_if_no_peer_cert, boolean()}
    +	| {hibernate_after, integer() | undefined}
    +	| {honor_cipher_order, boolean()}
    +	| {key, {'RSAPrivateKey' | 'DSAPrivateKey' | 'PrivateKeyInfo', public_key:der_encoded()}}
    +	| {keyfile, string()}
    +	| {log_alert, boolean()}
    +	| {next_protocols_advertised, [binary()]}
    +	| {padding_check, boolean()}
    +	| {partial_chain, fun(([public_key:der_encoded()]) -> {trusted_ca, public_key:der_encoded()} | unknown_ca)}
    +	| {password, string()}
    +	| {psk_identity, string()}
    +	| {reuse_session, fun()}
    +	| {reuse_sessions, boolean()}
    +	| {secure_renegotiate, boolean()}
    +	| {signature_algs, [{atom(), atom()}]}
    +	| {sni_fun, fun()}
    +	| {sni_hosts, [{string(), ssl_opt()}]}
    +	| {user_lookup_fun, {fun(), any()}}
    +	| {v2_hello_compatible, boolean()}
    +	| {verify, ssl:verify_type()}
    +	| {verify_fun, {fun(), any()}}
    +	| {versions, [atom()]}.
    +
    +

    SSL-specific listen options.

    +

    opt() = ranch_tcp:opt() | ssl_opt()

    +

    Listen options.

    +

    opts() = [opt()]

    +

    List of listen options.

    Option descriptions

    -
    -

    Specifying a certificate is mandatory, either through the cert -or the certfile option. None of the other options are required.

    -

    The default value is given next to the option name.

    -
    -
    -alpn_preferred_protocols -
    -
    -

    - Perform Application-Layer Protocol Negotiation with the given list of preferred protocols. -

    -
    -
    -beast_mitigation -
    -
    -

    - Change the BEAST mitigation strategy for SSL-3.0 and TLS-1.0 to interoperate with legacy software. -

    -
    -
    -cacertfile -
    -
    -

    - Path to PEM encoded trusted certificates file used to verify peer certificates. -

    -
    -
    -cacerts -
    -
    -

    - List of DER encoded trusted certificates. -

    -
    -
    -cert -
    -
    -

    - DER encoded user certificate. -

    -
    -
    -certfile -
    -
    -

    - Path to the PEM encoded user certificate file. May also contain the private key. -

    -
    -
    -ciphers -
    -
    -

    - List of ciphers that clients are allowed to use. -

    -
    -
    -client_renegotiation (true) -
    -
    -

    - Whether to allow client-initiated renegotiation. -

    -
    -
    -crl_cache ({ssl_crl_cache, {internal, []}}) -
    -
    -

    - Customize the module used to cache Certificate Revocation Lists. -

    -
    -
    -crl_check (false) -
    -
    -

    - Whether to perform CRL check on all certificates in the chain during validation. -

    -
    -
    -depth (1) -
    -
    -

    - Maximum of intermediate certificates allowed in the certification path. -

    -
    -
    -dh -
    -
    -

    - DER encoded Diffie-Hellman parameters. -

    -
    -
    -dhfile -
    -
    -

    - Path to the PEM encoded Diffie-Hellman parameters file. -

    -
    -
    -fail_if_no_peer_cert (false) -
    -
    -

    - Whether to refuse the connection if the client sends an empty certificate. -

    -
    -
    -hibernate_after (undefined) -
    -
    -

    - Time in ms after which SSL socket processes go into hibernation to reduce memory usage. -

    -
    -
    -honor_cipher_order (false) -
    -
    -

    - If true, use the server’s preference for cipher selection. If false, use the client’s preference. -

    -
    -
    -key -
    -
    -

    - DER encoded user private key. -

    -
    -
    -keyfile -
    -
    -

    - Path to the PEM encoded private key file, if different than the certfile. -

    -
    -
    -log_alert (true) -
    -
    -

    - If false, error reports will not be displayed. -

    -
    -
    -next_protocols_advertised -
    -
    -

    - List of protocols to send to the client if it supports the Next Protocol extension. -

    -
    -
    -nodelay (true) -
    -
    -

    - Whether to enable TCP_NODELAY. -

    -
    -
    -padding_check -
    -
    -

    - Allow disabling the block cipher padding check for TLS-1.0 to be able to interoperate with legacy software. -

    -
    -
    -partial_chain -
    -
    -

    - Claim an intermediate CA in the chain as trusted. -

    -
    -
    -password -
    -
    -

    - Password to the private key file, if password protected. -

    -
    -
    -psk_identity -
    -
    -

    - Provide the given PSK identity hint to the client during the handshake. -

    -
    -
    -reuse_session -
    -
    -

    - Custom policy to decide whether a session should be reused. -

    -
    -
    -reuse_sessions (false) -
    -
    -

    - Whether to allow session reuse. -

    -
    -
    -secure_renegotiate (false) -
    -
    -

    - Whether to reject renegotiation attempts that do not conform to RFC5746. -

    -
    -
    -signature_algs -
    -
    -

    - The TLS signature algorithm extension may be used, from TLS 1.2, to negotiate which signature algorithm to use during the TLS handshake. -

    -
    -
    -sni_fun -
    -
    -

    - Function called when the client requests a host using Server Name Indication. Returns options to apply. -

    -
    -
    -sni_hosts -
    -
    -

    - Options to apply for the host that matches what the client requested with Server Name Indication. -

    -
    -
    -user_lookup_fun -
    -
    -

    - Function called to determine the shared secret when using PSK, or provide parameters when using SRP. -

    -
    -
    -v2_hello_compatible -
    -
    -

    - Accept clients that send hello messages in SSL-2.0 format while offering supported SSL/TLS versions. -

    -
    -
    -verify (verify_none) -
    -
    -

    - Use verify_peer to request a certificate from the client. -

    -
    -
    -verify_fun -
    -
    -

    - Custom policy to decide whether a client certificate is valid. -

    -
    -
    -versions -
    -
    -

    - TLS protocol versions that will be supported. -

    -
    -
    -

    Note that the client will not send a certificate unless the -value for the verify option is set to verify_peer. This -means that the fail_if_no_peer_cert only apply when combined -with the verify option. The verify_fun option allows -greater control over the client certificate validation.

    -

    The options sni_fun and sni_hosts are mutually exclusive.

    -
    - -
    +

    Specifying a certificate is mandatory, either through the cert or the certfile option. None of the other options are required.

    +

    The default value is given next to the option name.

    +
    alpn_preferred_protocols
    +

    Perform Application-Layer Protocol Negotiation with the given list of preferred protocols.

    +
    +
    beast_mitigation
    +

    Change the BEAST mitigation strategy for SSL-3.0 and TLS-1.0 to interoperate with legacy software.

    +
    +
    cacertfile
    +

    Path to PEM encoded trusted certificates file used to verify peer certificates.

    +
    +
    cacerts
    +

    List of DER encoded trusted certificates.

    +
    +
    cert
    +

    DER encoded user certificate.

    +
    +
    certfile
    +

    Path to the PEM encoded user certificate file. May also contain the private key.

    +
    +
    ciphers
    +

    List of ciphers that clients are allowed to use.

    +
    +
    client_renegotiation (true)
    +

    Whether to allow client-initiated renegotiation.

    +
    +
    crl_cache ({ssl_crl_cache, {internal, []}})
    +

    Customize the module used to cache Certificate Revocation Lists.

    +
    +
    crl_check (false)
    +

    Whether to perform CRL check on all certificates in the chain during validation.

    +
    +
    depth (1)
    +

    Maximum of intermediate certificates allowed in the certification path.

    +
    +
    dh
    +

    DER encoded Diffie-Hellman parameters.

    +
    +
    dhfile
    +

    Path to the PEM encoded Diffie-Hellman parameters file.

    +
    +
    fail_if_no_peer_cert (false)
    +

    Whether to refuse the connection if the client sends an empty certificate.

    +
    +
    hibernate_after (undefined)
    +

    Time in ms after which SSL socket processes go into hibernation to reduce memory usage.

    +
    +
    honor_cipher_order (false)
    +

    If true, use the server's preference for cipher selection. If false, use the client's preference.

    +
    +
    key
    +

    DER encoded user private key.

    +
    +
    keyfile
    +

    Path to the PEM encoded private key file, if different than the certfile.

    +
    +
    log_alert (true)
    +

    If false, error reports will not be displayed.

    +
    +
    next_protocols_advertised
    +

    List of protocols to send to the client if it supports the Next Protocol extension.

    +
    +
    nodelay (true)
    +

    Whether to enable TCP_NODELAY.

    +
    +
    padding_check
    +

    Allow disabling the block cipher padding check for TLS-1.0 to be able to interoperate with legacy software.

    +
    +
    partial_chain
    +

    Claim an intermediate CA in the chain as trusted.

    +
    +
    password
    +

    Password to the private key file, if password protected.

    +
    +
    psk_identity
    +

    Provide the given PSK identity hint to the client during the handshake.

    +
    +
    reuse_session
    +

    Custom policy to decide whether a session should be reused.

    +
    +
    reuse_sessions (false)
    +

    Whether to allow session reuse.

    +
    +
    secure_renegotiate (false)
    +

    Whether to reject renegotiation attempts that do not conform to RFC5746.

    +
    +
    signature_algs
    +

    The TLS signature algorithm extension may be used, from TLS 1.2, to negotiate which signature algorithm to use during the TLS handshake.

    +
    +
    sni_fun
    +

    Function called when the client requests a host using Server Name Indication. Returns options to apply.

    +
    +
    sni_hosts
    +

    Options to apply for the host that matches what the client requested with Server Name Indication.

    +
    +
    user_lookup_fun
    +

    Function called to determine the shared secret when using PSK, or provide parameters when using SRP.

    +
    +
    v2_hello_compatible
    +

    Accept clients that send hello messages in SSL-2.0 format while offering supported SSL/TLS versions.

    +
    +
    verify (verify_none)
    +

    Use verify_peer to request a certificate from the client.

    +
    +
    verify_fun
    +

    Custom policy to decide whether a client certificate is valid.

    +
    +
    versions
    +

    TLS protocol versions that will be supported.

    +
    +
    +

    Note that the client will not send a certificate unless the value for the verify option is set to verify_peer. This means that the fail_if_no_peer_cert only apply when combined with the verify option. The verify_fun option allows greater control over the client certificate validation.

    +

    The options sni_fun and sni_hosts are mutually exclusive.

    Exports

    -
    -

    None.

    -
    -
    +

    None.

    + @@ -475,6 +264,8 @@ greater control over the client certificate validation.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.4/manual/ranch_tcp/index.html b/docs/en/ranch/1.4/manual/ranch_tcp/index.html index 8f2120e3..9fa98c07 100644 --- a/docs/en/ranch/1.4/manual/ranch_tcp/index.html +++ b/docs/en/ranch/1.4/manual/ranch_tcp/index.html @@ -62,283 +62,127 @@

    ranch_tcp(3)

    -

    Name

    -
    -

    ranch_tcp - TCP transport module

    -
    -
    -
    +

    ranch_tcp - TCP transport module

    Description

    -
    -

    The ranch_tcp module implements a TCP Ranch transport.

    -

    Note that due to bugs in OTP up to at least R16B02, it is -recommended to disable async threads when using the -sendfile function of this transport, as it can make -the threads stuck indefinitely.

    -
    -
    -
    +

    The ranch_tcp module implements a TCP Ranch transport.

    +

    Note that due to bugs in OTP up to at least R16B02, it is recommended to disable async threads when using the sendfile function of this transport, as it can make the threads stuck indefinitely.

    Types

    -
    -

    opt()

    -
    -
    -
    opt() = {backlog, non_neg_integer()}
    -        | {buffer, non_neg_integer()}
    -        | {delay_send, boolean()}
    -        | {dontroute, boolean()}
    -        | {exit_on_close, boolean()}
    -        | {fd, non_neg_integer()}
    -        | {high_msgq_watermark, non_neg_integer()}
    -        | {high_watermark, non_neg_integer()}
    -        | inet
    -        | inet6
    -        | {ip, inet:ip_address()}
    -        | {ipv6_v6only, boolean()}
    -        | {keepalive, boolean()}
    -        | {linger, {boolean(), non_neg_integer()}}
    -        | {low_msgq_watermark, non_neg_integer()}
    -        | {low_watermark, non_neg_integer()}
    -        | {nodelay, boolean()}
    -        | {port, inet:port_number()}
    -        | {priority, integer()}
    -        | {raw, non_neg_integer(), non_neg_integer(), binary()}
    -        | {recbuf, non_neg_integer()}
    -        | {send_timeout, timeout()}
    -        | {send_timeout_close, boolean()}
    -        | {sndbuf, non_neg_integer()}
    -        | {tos, integer()}
    -

    Listen options.

    -

    This does not represent the entirety of the options that can -be set on the socket, but only the options that may be -set independently of protocol implementation.

    -
    -
    -

    opts() = [opt()]

    -

    List of listen options.

    -
    -
    -
    -
    +
    opt() = {backlog, non_neg_integer()}
    +	| {buffer, non_neg_integer()}
    +	| {delay_send, boolean()}
    +	| {dontroute, boolean()}
    +	| {exit_on_close, boolean()}
    +	| {fd, non_neg_integer()}
    +	| {high_msgq_watermark, non_neg_integer()}
    +	| {high_watermark, non_neg_integer()}
    +	| inet
    +	| inet6
    +	| {ip, inet:ip_address()}
    +	| {ipv6_v6only, boolean()}
    +	| {keepalive, boolean()}
    +	| {linger, {boolean(), non_neg_integer()}}
    +	| {low_msgq_watermark, non_neg_integer()}
    +	| {low_watermark, non_neg_integer()}
    +	| {nodelay, boolean()}
    +	| {port, inet:port_number()}
    +	| {priority, integer()}
    +	| {raw, non_neg_integer(), non_neg_integer(), binary()}
    +	| {recbuf, non_neg_integer()}
    +	| {send_timeout, timeout()}
    +	| {send_timeout_close, boolean()}
    +	| {sndbuf, non_neg_integer()}
    +	| {tos, integer()}
    +
    +

    Listen options.

    +

    This does not represent the entirety of the options that can be set on the socket, but only the options that may be set independently of protocol implementation.

    +

    opts() = [opt()]

    +

    List of listen options.

    Option descriptions

    -
    -

    None of the options are required.

    -

    Please consult the gen_tcp and inet manuals for a more -thorough description of these options. This manual only aims -to provide a short description along with what the defaults -are. Defaults may be different in Ranch compared to gen_tcp. -Defaults are given next to the option name.

    -
    -
    -backlog (1024) -
    -
    -

    - Max length of the queue of pending connections. -

    +

    None of the options are required.

    +

    Please consult the gen_tcp and inet manuals for a more thorough description of these options. This manual only aims to provide a short description along with what the defaults are. Defaults may be different in Ranch compared to gen_tcp. Defaults are given next to the option name.

    +
    backlog (1024)
    +

    Max length of the queue of pending connections.

    -
    -buffer -
    -
    -

    - Size of the buffer used by the Erlang driver. Default is system-dependent. -

    +
    buffer
    +

    Size of the buffer used by the Erlang driver. Default is system-dependent.

    -
    -delay_send (false) -
    -
    -

    - Always queue packets before sending, to send fewer, larger packets over the network. -

    +
    delay_send (false)
    +

    Always queue packets before sending, to send fewer, larger packets over the network.

    -
    -dontroute (false) -
    -
    -

    - Don’t send via a gateway, only send to directly connected hosts. -

    +
    dontroute (false)
    +

    Don't send via a gateway, only send to directly connected hosts.

    -
    -exit_on_close (true) -
    -
    -

    - Disable to allow sending data after a close has been detected. -

    +
    exit_on_close (true)
    +

    Disable to allow sending data after a close has been detected.

    -
    -fd -
    -
    -

    - File descriptor of the socket, if it was opened externally. -

    +
    fd
    +

    File descriptor of the socket, if it was opened externally.

    -
    -high_msgq_watermark (8192) -
    -
    -

    - Limit in the amount of data in the socket message queue before the socket queue becomes busy. -

    +
    high_msgq_watermark (8192)
    +

    Limit in the amount of data in the socket message queue before the socket queue becomes busy.

    -
    -high_watermark (8192) -
    -
    -

    - Limit in the amount of data in the ERTS socket implementation’s queue before the socket becomes busy. -

    +
    high_watermark (8192)
    +

    Limit in the amount of data in the ERTS socket implementation's queue before the socket becomes busy.

    -
    -inet -
    -
    -

    - Set up the socket for IPv4. -

    +
    inet
    +

    Set up the socket for IPv4.

    -
    -inet6 -
    -
    -

    - Set up the socket for IPv6. -

    +
    inet6
    +

    Set up the socket for IPv6.

    -
    -ip -
    -
    -

    - Interface to listen on. Listen on all interfaces by default. -

    +
    ip
    +

    Interface to listen on. Listen on all interfaces by default.

    -
    -ipv6_v6only (false) -
    -
    -

    - Listen on IPv4 and IPv6 (false) or only on IPv6 (true). Use with inet6. -

    +
    ipv6_v6only (false)
    +

    Listen on IPv4 and IPv6 (false) or only on IPv6 (true). Use with inet6.

    -
    -keepalive (false) -
    -
    -

    - Enable sending of keep-alive messages. -

    +
    keepalive (false)
    +

    Enable sending of keep-alive messages.

    -
    -linger ({false, 0}) -
    -
    -

    - Whether to wait and how long to flush data sent before closing the socket. -

    +
    linger ({false, 0})
    +

    Whether to wait and how long to flush data sent before closing the socket.

    -
    -low_msgq_watermark (4096) -
    -
    -

    - Amount of data in the socket message queue before the socket queue leaves busy state. -

    +
    low_msgq_watermark (4096)
    +

    Amount of data in the socket message queue before the socket queue leaves busy state.

    -
    -low_watermark (4096) -
    -
    -

    - Amount of data in the ERTS socket implementation’s queue before the socket leaves busy state. -

    +
    low_watermark (4096)
    +

    Amount of data in the ERTS socket implementation's queue before the socket leaves busy state.

    -
    -nodelay (true) -
    -
    -

    - Whether to enable TCP_NODELAY. -

    +
    nodelay (true)
    +

    Whether to enable TCP_NODELAY.

    -
    -port (0) -
    -
    -

    - TCP port number to listen on. 0 means a random port will be used. -

    +
    port (0)
    +

    TCP port number to listen on. 0 means a random port will be used.

    -
    -priority (0) -
    -
    -

    - Priority value for all packets to be sent by this socket. -

    +
    priority (0)
    +

    Priority value for all packets to be sent by this socket.

    -
    -recbuf -
    -
    -

    - Minimum size of the socket’s receive buffer. Default is system-dependent. -

    +
    recbuf
    +

    Minimum size of the socket's receive buffer. Default is system-dependent.

    -
    -send_timeout (30000) -
    -
    -

    - How long the send call may wait for confirmation before returning. -

    +
    send_timeout (30000)
    +

    How long the send call may wait for confirmation before returning.

    -
    -send_timeout_close (true) -
    -
    -

    - Whether to close the socket when the confirmation wasn’t received. -

    +
    send_timeout_close (true)
    +

    Whether to close the socket when the confirmation wasn't received.

    -
    -sndbuf -
    -
    -

    - Minimum size of the socket’s send buffer. Default is system-dependent. -

    +
    sndbuf
    +

    Minimum size of the socket's send buffer. Default is system-dependent.

    -
    -tos -
    -
    -

    - Value for the IP_TOS IP level option. Use with caution. -

    +
    tos
    +

    Value for the IP_TOS IP level option. Use with caution.

    -
    -

    In addition, the raw option can be used to set system-specific -options by specifying the protocol level, the option number and -the actual option value specified as a binary. This option is not -portable. Use with caution.

    -
    - -
    + +

    In addition, the raw option can be used to set system-specific options by specifying the protocol level, the option number and the actual option value specified as a binary. This option is not portable. Use with caution.

    Exports

    -
    -

    None.

    -
    -
    +

    None.

    + @@ -373,6 +217,8 @@ portable. Use with caution.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.4/manual/ranch_transport/index.html b/docs/en/ranch/1.4/manual/ranch_transport/index.html index e0ee8844..5b275cda 100644 --- a/docs/en/ranch/1.4/manual/ranch_transport/index.html +++ b/docs/en/ranch/1.4/manual/ranch_transport/index.html @@ -62,494 +62,198 @@

    ranch_transport(3)

    -

    Name

    -
    -

    ranch_transport - behaviour for transport modules

    -
    -
    -
    +

    ranch_transport - behaviour for transport modules

    Description

    -
    -

    The ranch_transport behaviour defines the interface used -by Ranch transports.

    -
    -
    -
    +

    The ranch_transport behaviour defines the interface used by Ranch transports.

    Types

    -
    -
    -

    sendfile_opts() = [{chunk_size, non_neg_integer()}]

    -

    Options used by the sendfile function and callbacks.

    -

    Allows configuring the chunk size, in bytes. Defaults to 8191 bytes.

    -
    -
    -
    -
    +

    sendfile_opts() = [{chunk_size, non_neg_integer()}]

    +

    Options used by the sendfile function and callbacks.

    +

    Allows configuring the chunk size, in bytes. Defaults to 8191 bytes.

    Callbacks

    -
    -
    -

    accept(LSocket, Timeout) → {ok, CSocket} | {error, closed | timeout | atom()}

    -
    -
    -LSocket = CSocket = any() -
    -
    -

    -Listening socket. -

    -
    -
    -Timeout = timeout() -
    -
    -

    -Accept timeout. -

    -
    -
    -

    Accept a connection on the given listening socket.

    -

    The accept_ack callback will be used to initialize the socket -after accepting the connection. This is most useful when the -transport is not raw TCP, like with SSL for example.

    -
    -
    -

    accept_ack(CSocket, Timeout) → ok

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -Timeout = timeout() -
    -
    -

    -Ack timeout. -

    -
    -
    -

    Perform post-accept initialization of the connection.

    -

    This function will be called by connection processes -before performing any socket operation. It allows -transports that require extra initialization to perform -their task and make the socket ready to use.

    -
    -
    -

    close(Socket) → ok

    -
    -
    -Socket = any() -
    -
    -

    -Socket opened with listen/1 or accept/2. -

    -
    -
    -

    Close the given socket.

    -
    -
    -

    controlling_process(Socket, Pid) → ok | {error, closed | not_owner | atom()}

    -
    -
    -Socket = any() -
    -
    -

    -Socket opened with listen/1 or accept/2. -

    -
    -
    -Pid = pid() -
    -
    -

    -Pid of the new owner of the socket. -

    -
    -
    -

    Change the controlling process for the given socket.

    -

    The controlling process is the process that is allowed to -perform operations on the socket, and that will receive -messages from the socket when active mode is used. When -the controlling process dies, the socket is closed.

    -
    -
    -

    listen(TransOpts) → {ok, LSocket} | {error, atom()}

    -
    -
    -TransOpts = any() -
    -
    -

    -Transport options. -

    -
    -
    -LSocket = any() -
    -
    -

    -Listening socket. -

    -
    -
    -

    Listen for connections on the given port.

    -

    The port is given as part of the transport options under -the key port. Any other option is transport dependent.

    -

    The socket returned by this call can then be used to -accept connections. It is not possible to send or receive -data from the listening socket.

    -
    -
    -

    messages() → {OK, Closed, Error}

    -
    -
    -OK = Closed = Error = atom() -
    -
    -

    -Tuple names. -

    -
    -
    -

    Return the atoms used to identify messages sent in active mode.

    -
    -
    -

    name() → Name

    -
    -
    -Name = atom() -
    -
    -

    -Transport module name. -

    -
    -
    -

    Return the name of the transport.

    -
    -
    -

    peername(CSocket) → {ok, {IP, Port}} | {error, atom()}

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -IP = inet:ip_address() -
    -
    -

    -IP of the remote endpoint. -

    -
    -
    -Port = inet:port_number() -
    -
    -

    -Port of the remote endpoint. -

    -
    -
    -

    Return the IP and port of the remote endpoint.

    -
    -
    -

    recv(CSocket, Length, Timeout) → {ok, Packet} | {error, closed | timeout | atom()}

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -Length = non_neg_integer() -
    -
    -

    -Requested length. -

    -
    -
    -Timeout = timeout() -
    -
    -

    -Receive timeout. -

    -
    -
    -Packet = iodata() | any() -
    -
    -

    -Data received. -

    -
    -
    -

    Receive data from the given socket when in passive mode.

    -

    Trying to receive data from a socket that is in active mode -will return an error.

    -

    A length of 0 will return any data available on the socket.

    -

    While it is possible to use the timeout value infinity, -this is highly discouraged as this could cause your process -to get stuck waiting for data that will never come. This may -happen when a socket becomes half-open due to a crash of the -remote endpoint. Wi-Fi going down is another common culprit -of this issue.

    -
    -
    -

    send(CSocket, Packet) → ok | {error, atom()}

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -Packet = iodata() -
    -
    -

    -Data to be sent. -

    -
    -
    -

    Send data to the given socket.

    -
    -
    -

    sendfile(CSocket, File) → sendfile(CSocket, File, 0, 0, [])

    -

    Alias of ranch_transport:sendfile/5.

    -
    -
    -

    sendfile(CSocket, File, Offset, Bytes) → sendfile(CSocket, File, Offset, Bytes, [])

    -

    Alias of ranch_transport:sendfile/5.

    -
    -
    -

    sendfile(CSocket, File, Offset, Bytes, SfOpts) → {ok, SentBytes} | {error, atom()}

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -File = file:filename_all() | file:fd() -
    -
    -

    -Filename or file descriptor for the file to be sent. -

    -
    -
    -Offset = non_neg_integer() -
    -
    -

    -Begin sending at this position in the file. -

    -
    -
    -Bytes = non_neg_integer() -
    -
    -

    -Send this many bytes. -

    -
    -
    -SentBytes = non_neg_integer() -
    -
    -

    -This many bytes were sent. -

    -
    -
    -SfOpts = sendfile_opts() -
    -
    -

    -Sendfile options. -

    -
    -
    -

    Send data from a file to the given socket.

    -

    The file may be sent full or in parts, and may be specified -by its filename or by an already open file descriptor.

    -

    Transports that manipulate TCP directly may use the -file:sendfile/{2,4,5} function, which calls the sendfile -syscall where applicable (on Linux, for example). Other -transports can use the sendfile/6 function exported from -this module.

    -
    -
    -

    setopts(CSocket, SockOpts) → ok | {error, atom()}

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -SockOpts = any() -
    -
    -

    -Socket options. -

    -
    -
    -

    Change options for the given socket.

    -

    This is mainly useful for switching to active or passive mode -or to set protocol-specific options.

    -
    -
    -

    shutdown(CSocket, How) → ok | {error, atom()}

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -How = read | write | read_write -
    -
    -

    -Which side(s) of the socket to close. -

    -
    -
    -

    Immediately close the socket in one or two directions.

    -
    -
    -

    sockname(Socket) → {ok, {IP, Port}} | {error, atom()}

    -
    -
    -Socket = any() -
    -
    -

    -Socket opened with listen/1 or accept/2. -

    -
    -
    -IP = inet:ip_address() -
    -
    -

    -IP of the local endpoint. -

    -
    -
    -Port = inet:port_number() -
    -
    -

    -Port of the local endpoint. -

    -
    -
    -

    Return the IP and port of the local endpoint.

    -
    -
    -
    -
    +

    accept(LSocket, Timeout) -> {ok, CSocket} | {error, closed | timeout | atom()}

    +
    LSocket = CSocket = any()
    +

    Listening socket.

    +
    +
    Timeout = timeout()
    +

    Accept timeout.

    +
    +
    +

    Accept a connection on the given listening socket.

    +

    The accept_ack callback will be used to initialize the socket after accepting the connection. This is most useful when the transport is not raw TCP, like with SSL for example.

    +

    accept_ack(CSocket, Timeout) -> ok

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    Timeout = timeout()
    +

    Ack timeout.

    +
    +
    +

    Perform post-accept initialization of the connection.

    +

    This function will be called by connection processes before performing any socket operation. It allows transports that require extra initialization to perform their task and make the socket ready to use.

    +

    close(Socket) -> ok

    +
    Socket = any()
    +

    Socket opened with listen/1 or accept/2.

    +
    +
    +

    Close the given socket.

    +

    controlling_process(Socket, Pid) -> ok | {error, closed | not_owner | atom()}

    +
    Socket = any()
    +

    Socket opened with listen/1 or accept/2.

    +
    +
    Pid = pid()
    +

    Pid of the new owner of the socket.

    +
    +
    +

    Change the controlling process for the given socket.

    +

    The controlling process is the process that is allowed to perform operations on the socket, and that will receive messages from the socket when active mode is used. When the controlling process dies, the socket is closed.

    +

    listen(TransOpts) -> {ok, LSocket} | {error, atom()}

    +
    TransOpts = any()
    +

    Transport options.

    +
    +
    LSocket = any()
    +

    Listening socket.

    +
    +
    +

    Listen for connections on the given port.

    +

    The port is given as part of the transport options under the key port. Any other option is transport dependent.

    +

    The socket returned by this call can then be used to accept connections. It is not possible to send or receive data from the listening socket.

    +

    messages() -> {OK, Closed, Error}

    +
    OK = Closed = Error = atom()
    +

    Tuple names.

    +
    +
    +

    Return the atoms used to identify messages sent in active mode.

    +

    name() -> Name

    +
    Name = atom()
    +

    Transport module name.

    +
    +
    +

    Return the name of the transport.

    +

    peername(CSocket) -> {ok, {IP, Port}} | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    IP = inet:ip_address()
    +

    IP of the remote endpoint.

    +
    +
    Port = inet:port_number()
    +

    Port of the remote endpoint.

    +
    +
    +

    Return the IP and port of the remote endpoint.

    +

    recv(CSocket, Length, Timeout) -> {ok, Packet} | {error, closed | timeout | atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    Length = non_neg_integer()
    +

    Requested length.

    +
    +
    Timeout = timeout()
    +

    Receive timeout.

    +
    +
    Packet = iodata() | any()
    +

    Data received.

    +
    +
    +

    Receive data from the given socket when in passive mode.

    +

    Trying to receive data from a socket that is in active mode will return an error.

    +

    A length of 0 will return any data available on the socket.

    +

    While it is possible to use the timeout value infinity, this is highly discouraged as this could cause your process to get stuck waiting for data that will never come. This may happen when a socket becomes half-open due to a crash of the remote endpoint. Wi-Fi going down is another common culprit of this issue.

    +

    send(CSocket, Packet) -> ok | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    Packet = iodata()
    +

    Data to be sent.

    +
    +
    +

    Send data to the given socket.

    +

    sendfile(CSocket, File) -> sendfile(CSocket, File, 0, 0, [])

    +

    Alias of ranch_transport:sendfile/5.

    +

    sendfile(CSocket, File, Offset, Bytes) -> sendfile(CSocket, File, Offset, Bytes, [])

    +

    Alias of ranch_transport:sendfile/5.

    +

    sendfile(CSocket, File, Offset, Bytes, SfOpts) -> {ok, SentBytes} | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    File = file:filename_all() | file:fd()
    +

    Filename or file descriptor for the file to be sent.

    +
    +
    Offset = non_neg_integer()
    +

    Begin sending at this position in the file.

    +
    +
    Bytes = non_neg_integer()
    +

    Send this many bytes.

    +
    +
    SentBytes = non_neg_integer()
    +

    This many bytes were sent.

    +
    +
    SfOpts = sendfile_opts()
    +

    Sendfile options.

    +
    +
    +

    Send data from a file to the given socket.

    +

    The file may be sent full or in parts, and may be specified by its filename or by an already open file descriptor.

    +

    Transports that manipulate TCP directly may use the file:sendfile/{2,4,5} function, which calls the sendfile syscall where applicable (on Linux, for example). Other transports can use the sendfile/6 function exported from this module.

    +

    setopts(CSocket, SockOpts) -> ok | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    SockOpts = any()
    +

    Socket options.

    +
    +
    +

    Change options for the given socket.

    +

    This is mainly useful for switching to active or passive mode or to set protocol-specific options.

    +

    shutdown(CSocket, How) -> ok | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    How = read | write | read_write
    +

    Which side(s) of the socket to close.

    +
    +
    +

    Immediately close the socket in one or two directions.

    +

    sockname(Socket) -> {ok, {IP, Port}} | {error, atom()}

    +
    Socket = any()
    +

    Socket opened with listen/1 or accept/2.

    +
    +
    IP = inet:ip_address()
    +

    IP of the local endpoint.

    +
    +
    Port = inet:port_number()
    +

    Port of the local endpoint.

    +
    +
    +

    Return the IP and port of the local endpoint.

    Exports

    -
    -
    -

    sendfile(Transport, CSocket, File, Offset, Bytes, SfOpts) → {ok, SentBytes} | {error, atom()}

    -
    -
    -Transport = module() -
    -
    -

    -Transport module for this socket. -

    -
    -
    -CSocket = any() -
    -
    -

    -Socket for this connection. -

    -
    -
    -File = file:filename_all() | file:fd() -
    -
    -

    -Filename or file descriptor for the file to be sent. -

    -
    -
    -Offset = non_neg_integer() -
    -
    -

    -Begin sending at this position in the file. -

    -
    -
    -Bytes = non_neg_integer() -
    -
    -

    -Send this many bytes. -

    -
    -
    -SentBytes = non_neg_integer() -
    -
    -

    -This many bytes were sent. -

    -
    -
    -SfOpts = sendfile_opts() -
    -
    -

    -Sendfile options. -

    -
    -
    -

    Send data from a file to the given socket.

    -

    This function emulates the function file:sendfile/{2,4,5} -and may be used when transports are not manipulating TCP -directly.

    -
    -
    -
    +

    sendfile(Transport, CSocket, File, Offset, Bytes, SfOpts) -> {ok, SentBytes} | {error, atom()}

    +
    Transport = module()
    +

    Transport module for this socket.

    +
    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    File = file:filename_all() | file:fd()
    +

    Filename or file descriptor for the file to be sent.

    +
    +
    Offset = non_neg_integer()
    +

    Begin sending at this position in the file.

    +
    +
    Bytes = non_neg_integer()
    +

    Send this many bytes.

    +
    +
    SentBytes = non_neg_integer()
    +

    This many bytes were sent.

    +
    +
    SfOpts = sendfile_opts()
    +

    Sendfile options.

    +
    +
    +

    Send data from a file to the given socket.

    +

    This function emulates the function file:sendfile/{2,4,5} and may be used when transports are not manipulating TCP directly.

    + @@ -584,6 +288,8 @@ directly.

    +
  • 1.5
  • +
  • 1.4
  • 1.3
  • diff --git a/docs/en/ranch/1.5/guide/embedded.asciidoc b/docs/en/ranch/1.5/guide/embedded.asciidoc new file mode 100644 index 00000000..55c018b1 --- /dev/null +++ b/docs/en/ranch/1.5/guide/embedded.asciidoc @@ -0,0 +1,48 @@ +== Embedded mode + +Embedded mode allows you to insert Ranch listeners directly +in your supervision tree. This allows for greater fault tolerance +control by permitting the shutdown of a listener due to the +failure of another part of the application and vice versa. + +=== Embedding + +To embed Ranch in your application you can simply add the child specs +to your supervision tree. This can all be done in the `init/1` function +of one of your application supervisors. + +Ranch requires at the minimum two kinds of child specs for embedding. +First, you need to add `ranch_sup` to your supervision tree, only once, +regardless of the number of listeners you will use. Then you need to +add the child specs for each listener. + +Ranch has a convenience function for getting the listeners child specs +called `ranch:child_spec/5`, that works like `ranch:start_listener/5`, +except that it doesn't start anything, it only returns child specs. + +As for `ranch_sup`, the child spec is simple enough to not require a +convenience function. + +The following example adds both `ranch_sup` and one listener to another +application's supervision tree. + +.Embed Ranch directly in your supervision tree + +[source,erlang] +---- +init([]) -> + RanchSupSpec = {ranch_sup, {ranch_sup, start_link, []}, + permanent, 5000, supervisor, [ranch_sup]}, + ListenerSpec = ranch:child_spec(echo, 100, + ranch_tcp, [{port, 5555}], + echo_protocol, [] + ), + {ok, {{one_for_one, 10, 10}, [RanchSupSpec, ListenerSpec]}}. +---- + +Remember, you can add as many listener child specs as needed, but only +one `ranch_sup` spec! + +It is recommended that your architecture makes sure that all listeners +are restarted if `ranch_sup` fails. See the Ranch internals chapter for +more details on how Ranch does it. diff --git a/docs/en/ranch/1.5/guide/embedded/index.html b/docs/en/ranch/1.5/guide/embedded/index.html new file mode 100644 index 00000000..e3dab665 --- /dev/null +++ b/docs/en/ranch/1.5/guide/embedded/index.html @@ -0,0 +1,184 @@ + + + + + + + + + + Nine Nines: Embedded mode + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +

    Embedded mode

    + +

    Embedded mode allows you to insert Ranch listeners directly in your supervision tree. This allows for greater fault tolerance control by permitting the shutdown of a listener due to the failure of another part of the application and vice versa.

    +

    Embedding

    +

    To embed Ranch in your application you can simply add the child specs to your supervision tree. This can all be done in the init/1 function of one of your application supervisors.

    +

    Ranch requires at the minimum two kinds of child specs for embedding. First, you need to add ranch_sup to your supervision tree, only once, regardless of the number of listeners you will use. Then you need to add the child specs for each listener.

    +

    Ranch has a convenience function for getting the listeners child specs called ranch:child_spec/5, that works like ranch:start_listener/5, except that it doesn't start anything, it only returns child specs.

    +

    As for ranch_sup, the child spec is simple enough to not require a convenience function.

    +

    The following example adds both ranch_sup and one listener to another application's supervision tree.

    +
    Embed Ranch directly in your supervision tree
    +
    +
    init([]) ->
    +	RanchSupSpec = {ranch_sup, {ranch_sup, start_link, []},
    +		permanent, 5000, supervisor, [ranch_sup]},
    +	ListenerSpec = ranch:child_spec(echo, 100,
    +		ranch_tcp, [{port, 5555}],
    +		echo_protocol, []
    +	),
    +	{ok, {{one_for_one, 10, 10}, [RanchSupSpec, ListenerSpec]}}.
    +
    +

    Remember, you can add as many listener child specs as needed, but only one ranch_sup spec!

    +

    It is recommended that your architecture makes sure that all listeners are restarted if ranch_sup fails. See the Ranch internals chapter for more details on how Ranch does it.

    + + + + + + + + + + + + + + + + +
    + +
    + + +

    + Ranch + 1.5 + + User Guide +

    + + + +

    Navigation

    + +

    Version select

    + + +
    +
    +
    +
    + + + + + + + + + diff --git a/docs/en/ranch/1.5/guide/index.html b/docs/en/ranch/1.5/guide/index.html new file mode 100644 index 00000000..860a61cd --- /dev/null +++ b/docs/en/ranch/1.5/guide/index.html @@ -0,0 +1,156 @@ + + + + + + + + + + Nine Nines: Ranch User Guide + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +

    Ranch User Guide

    + + + + + + + + +
    + +
    + + +

    + Ranch + 1.5 + + User Guide +

    + + + +

    Navigation

    + +

    Version select

    + + +
    +
    +
    +
    + + + + + + + + + diff --git a/docs/en/ranch/1.5/guide/internals.asciidoc b/docs/en/ranch/1.5/guide/internals.asciidoc new file mode 100644 index 00000000..c5bde58f --- /dev/null +++ b/docs/en/ranch/1.5/guide/internals.asciidoc @@ -0,0 +1,94 @@ +== Internals + +This chapter may not apply to embedded Ranch as embedding allows you +to use an architecture specific to your application, which may or may +not be compatible with the description of the Ranch application. + +Note that for everything related to efficiency and performance, +you should perform the benchmarks yourself to get the numbers that +matter to you. Generic benchmarks found on the web may or may not +be of use to you, you can never know until you benchmark your own +system. + +=== Architecture + +Ranch is an OTP application. + +Like all OTP applications, Ranch has a top supervisor. It is responsible +for supervising the `ranch_server` process and all the listeners that +will be started. + +The `ranch_server` gen_server is a central process keeping track of the +listeners and their acceptors. It does so through the use of a public ets +table called `ranch_server`. The table is owned by the top supervisor +to improve fault tolerance. This way if the `ranch_server` gen_server +fails, it doesn't lose any information and the restarted process can +continue as if nothing happened. + +Ranch uses a custom supervisor for managing connections. This supervisor +keeps track of the number of connections and handles connection limits +directly. While it is heavily optimized to perform the task of creating +connection processes for accepted connections, it is still following the +OTP principles and the usual `sys` and `supervisor` calls will work on +it as expected. + +Listeners are grouped into the `ranch_listener_sup` supervisor and +consist of three kinds of processes: the listener gen_server, the +acceptor processes and the connection processes, both grouped under +their own supervisor. All of these processes are registered to the +`ranch_server` gen_server with varying amount of information. + +All socket operations, including listening for connections, go through +transport handlers. Accepted connections are given to the protocol handler. +Transport handlers are simple callback modules for performing operations on +sockets. Protocol handlers start a new process, which receives socket +ownership, with no requirements on how the code should be written inside +that new process. + +=== Number of acceptors + +The second argument to `ranch:start_listener/5` is the number of +processes that will be accepting connections. Care should be taken +when choosing this number. + +First of all, it should not be confused with the maximum number +of connections. Acceptor processes are only used for accepting and +have nothing else in common with connection processes. Therefore +there is nothing to be gained from setting this number too high, +in fact it can slow everything else down. + +Second, this number should be high enough to allow Ranch to accept +connections concurrently. But the number of cores available doesn't +seem to be the only factor for choosing this number, as we can +observe faster accepts if we have more acceptors than cores. It +might be entirely dependent on the protocol, however. + +Our observations suggest that using 100 acceptors on modern hardware +is a good solution, as it's big enough to always have acceptors ready +and it's low enough that it doesn't have a negative impact on the +system's performances. + +=== Platform-specific TCP features + +Some socket options are platform-specific and not supported by `inet`. +They can be of interest because they generally are related to +optimizations provided by the underlying OS. They can still be enabled +thanks to the `raw` option, for which we will see an example. + +One of these features is `TCP_DEFER_ACCEPT` on Linux. It is a simplified +accept mechanism which will wait for application data to come in before +handing out the connection to the Erlang process. + +This is especially useful if you expect many connections to be mostly +idle, perhaps part of a connection pool. They can be handled by the +kernel directly until they send any real data, instead of allocating +resources to idle connections. + +To enable this mechanism, the following option can be used. + +.Using raw transport options + +[source,erlang] +{raw, 6, 9, << 30:32/native >>} + +It means go on layer 6, turn on option 9 with the given integer parameter. diff --git a/docs/en/ranch/1.5/guide/internals/index.html b/docs/en/ranch/1.5/guide/internals/index.html new file mode 100644 index 00000000..10bb644b --- /dev/null +++ b/docs/en/ranch/1.5/guide/internals/index.html @@ -0,0 +1,184 @@ + + + + + + + + + + Nine Nines: Internals + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +

    Internals

    + +

    This chapter may not apply to embedded Ranch as embedding allows you to use an architecture specific to your application, which may or may not be compatible with the description of the Ranch application.

    +

    Note that for everything related to efficiency and performance, you should perform the benchmarks yourself to get the numbers that matter to you. Generic benchmarks found on the web may or may not be of use to you, you can never know until you benchmark your own system.

    +

    Architecture

    +

    Ranch is an OTP application.

    +

    Like all OTP applications, Ranch has a top supervisor. It is responsible for supervising the ranch_server process and all the listeners that will be started.

    +

    The ranch_server gen_server is a central process keeping track of the listeners and their acceptors. It does so through the use of a public ets table called ranch_server. The table is owned by the top supervisor to improve fault tolerance. This way if the ranch_server gen_server fails, it doesn't lose any information and the restarted process can continue as if nothing happened.

    +

    Ranch uses a custom supervisor for managing connections. This supervisor keeps track of the number of connections and handles connection limits directly. While it is heavily optimized to perform the task of creating connection processes for accepted connections, it is still following the OTP principles and the usual sys and supervisor calls will work on it as expected.

    +

    Listeners are grouped into the ranch_listener_sup supervisor and consist of three kinds of processes: the listener gen_server, the acceptor processes and the connection processes, both grouped under their own supervisor. All of these processes are registered to the ranch_server gen_server with varying amount of information.

    +

    All socket operations, including listening for connections, go through transport handlers. Accepted connections are given to the protocol handler. Transport handlers are simple callback modules for performing operations on sockets. Protocol handlers start a new process, which receives socket ownership, with no requirements on how the code should be written inside that new process.

    +

    Number of acceptors

    +

    The second argument to ranch:start_listener/5 is the number of processes that will be accepting connections. Care should be taken when choosing this number.

    +

    First of all, it should not be confused with the maximum number of connections. Acceptor processes are only used for accepting and have nothing else in common with connection processes. Therefore there is nothing to be gained from setting this number too high, in fact it can slow everything else down.

    +

    Second, this number should be high enough to allow Ranch to accept connections concurrently. But the number of cores available doesn't seem to be the only factor for choosing this number, as we can observe faster accepts if we have more acceptors than cores. It might be entirely dependent on the protocol, however.

    +

    Our observations suggest that using 100 acceptors on modern hardware is a good solution, as it's big enough to always have acceptors ready and it's low enough that it doesn't have a negative impact on the system's performances.

    +

    Platform-specific TCP features

    +

    Some socket options are platform-specific and not supported by inet. They can be of interest because they generally are related to optimizations provided by the underlying OS. They can still be enabled thanks to the raw option, for which we will see an example.

    +

    One of these features is TCP_DEFER_ACCEPT on Linux. It is a simplified accept mechanism which will wait for application data to come in before handing out the connection to the Erlang process.

    +

    This is especially useful if you expect many connections to be mostly idle, perhaps part of a connection pool. They can be handled by the kernel directly until they send any real data, instead of allocating resources to idle connections.

    +

    To enable this mechanism, the following option can be used.

    +
    Using raw transport options
    +
    +
    {raw, 6, 9, << 30:32/native >>}
    +
    +

    It means go on layer 6, turn on option 9 with the given integer parameter.

    + + + + + + + + + + + + + + + + +
    + +
    + + +

    + Ranch + 1.5 + + User Guide +

    + + + +

    Navigation

    + +

    Version select

    + + +
    +
    +
    +
    + + + + + + + + + diff --git a/docs/en/ranch/1.5/guide/introduction.asciidoc b/docs/en/ranch/1.5/guide/introduction.asciidoc new file mode 100644 index 00000000..ac27862e --- /dev/null +++ b/docs/en/ranch/1.5/guide/introduction.asciidoc @@ -0,0 +1,28 @@ +== Introduction + +Ranch is a socket acceptor pool for TCP protocols. + +Ranch aims to provide everything you need to accept TCP connections +with a small code base and low latency while being easy to use directly +as an application or to embed into your own. + +=== Prerequisites + +It is assumed the developer already knows Erlang and has some experience +with socket programming and TCP protocols. + +=== Supported platforms + +Ranch is tested and supported on Linux, FreeBSD, OSX and Windows. + +Ranch is developed for Erlang/OTP R16B+. + +There are known issues with the SSL application found in Erlang/OTP +18.3.2 and 18.3.3. These versions are therefore not supported. + +Ranch may be compiled on earlier Erlang versions with small source code +modifications but there is no guarantee that it will work as expected. + +=== Versioning + +Ranch uses http://semver.org/[Semantic Versioning 2.0.0] diff --git a/docs/en/ranch/1.5/guide/introduction/index.html b/docs/en/ranch/1.5/guide/introduction/index.html new file mode 100644 index 00000000..f9c50f8f --- /dev/null +++ b/docs/en/ranch/1.5/guide/introduction/index.html @@ -0,0 +1,168 @@ + + + + + + + + + + Nine Nines: Introduction + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +

    Introduction

    + +

    Ranch is a socket acceptor pool for TCP protocols.

    +

    Ranch aims to provide everything you need to accept TCP connections with a small code base and low latency while being easy to use directly as an application or to embed into your own.

    +

    Prerequisites

    +

    It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols.

    +

    Supported platforms

    +

    Ranch is tested and supported on Linux, FreeBSD, OSX and Windows.

    +

    Ranch is developed for Erlang/OTP R16B+.

    +

    There are known issues with the SSL application found in Erlang/OTP 18.3.2 and 18.3.3. These versions are therefore not supported.

    +

    Ranch may be compiled on earlier Erlang versions with small source code modifications but there is no guarantee that it will work as expected.

    +

    Versioning

    +

    Ranch uses Semantic Versioning 2.0.0

    + + + + + + + + + + + + + + + + +
    + +
    + + +

    + Ranch + 1.5 + + User Guide +

    + + + +

    Navigation

    + +

    Version select

    + + +
    +
    +
    +
    + + + + + + + + + diff --git a/docs/en/ranch/1.5/guide/listeners.asciidoc b/docs/en/ranch/1.5/guide/listeners.asciidoc new file mode 100644 index 00000000..97afa223 --- /dev/null +++ b/docs/en/ranch/1.5/guide/listeners.asciidoc @@ -0,0 +1,320 @@ +== Listeners + +A listener is a set of processes whose role is to listen on a port +for new connections. It manages a pool of acceptor processes, each +of them indefinitely accepting connections. When it does, it starts +a new process executing the protocol handler code. All the socket +programming is abstracted through the use of transport handlers. + +The listener takes care of supervising all the acceptor and connection +processes, allowing developers to focus on building their application. + +=== Starting a listener + +Ranch does nothing by default. It is up to the application developer +to request that Ranch listens for connections. + +A listener can be started and stopped at will. + +When starting a listener, a number of different settings are required: + +* A name to identify it locally and be able to interact with it. +* The number of acceptors in the pool. +* A transport handler and its associated options. +* A protocol handler and its associated options. + +Ranch includes both TCP and SSL transport handlers, respectively +`ranch_tcp` and `ranch_ssl`. + +A listener can be started by calling the `ranch:start_listener/5` +function. Before doing so however, you must ensure that the `ranch` +application is started. + +.Starting the Ranch application + +[source,erlang] +ok = application:start(ranch). + +You are then ready to start a listener. Let's call it `tcp_echo`. It will +have a pool of 100 acceptors, use a TCP transport and forward connections +to the `echo_protocol` handler. + +.Starting a listener for TCP connections on port 5555 + +[source,erlang] +{ok, _} = ranch:start_listener(tcp_echo, + ranch_tcp, [{port, 5555}], + echo_protocol, [] +). + +You can try this out by compiling and running the `tcp_echo` example in the +examples directory. To do so, open a shell in the 'examples/tcp_echo/' +directory and run the following command: + +.Building and starting a Ranch example + +[source,bash] +$ make run + +You can then connect to it using telnet and see the echo server reply +everything you send to it. Then when you're done testing, you can use +the `Ctrl+]` key to escape to the telnet command line and type +`quit` to exit. + +.Connecting to the example listener with telnet + +[source,bash] +---- +$ telnet localhost 5555 +Trying 127.0.0.1... +Connected to localhost. +Escape character is '^]'. +Hello! +Hello! +It works! +It works! +^] + +telnet> quit +Connection closed. +---- + +=== Stopping a listener + +All you need to stop a Ranch listener is to call the +`ranch:stop_listener/1` function with the listener's name +as argument. In the previous section we started the listener +named `tcp_echo`. We can now stop it. + +.Stopping a listener + +[source,erlang] +ranch:stop_listener(tcp_echo). + +=== Default transport options + +By default the socket will be set to return `binary` data, with the +options `{active, false}`, `{packet, raw}`, `{reuseaddr, true}` set. +These values can't be overriden when starting the listener, but +they can be overriden using `Transport:setopts/2` in the protocol. + +It will also set `{backlog, 1024}` and `{nodelay, true}`, which +can be overriden at listener startup. + +=== Listening on a random port + +You do not have to specify a specific port to listen on. If you give +the port number 0, or if you omit the port number entirely, Ranch will +start listening on a random port. + +You can retrieve this port number by calling `ranch:get_port/1`. The +argument is the name of the listener you gave in `ranch:start_listener/5`. + +.Starting a listener for TCP connections on a random port + +[source,erlang] +{ok, _} = ranch:start_listener(tcp_echo, + ranch_tcp, [{port, 0}], + echo_protocol, [] +). +Port = ranch:get_port(tcp_echo). + +=== Listening on privileged ports + +Some systems limit access to ports below 1024 for security reasons. +This can easily be identified by an `{error, eacces}` error when trying +to open a listening socket on such a port. + +The methods for listening on privileged ports vary between systems, +please refer to your system's documentation for more information. + +We recommend the use of port rewriting for systems with a single server, +and load balancing for systems with multiple servers. Documenting these +solutions is however out of the scope of this guide. + +=== Accepting connections on an existing socket + +If you want to accept connections on an existing socket, you can use the +`socket` transport option, which should just be the relevant data returned +from the connect function for the transport or the underlying socket library +(`gen_tcp:connect`, `ssl:connect`). The accept function will then be +called on the passed in socket. You should connect the socket in +`{active, false}` mode, as well. + +Note, however, that because of a bug in SSL, you cannot change ownership of an +SSL listen socket prior to R16. Ranch will catch the error thrown, but the +owner of the SSL socket will remain as whatever process created the socket. +However, this will not affect accept behaviour unless the owner process dies, +in which case the socket is closed. Therefore, to use this feature with SSL +with an erlang release prior to R16, ensure that the SSL socket is opened in a +persistant process. + +=== Limiting the number of concurrent connections + +The `max_connections` transport option allows you to limit the number +of concurrent connections. It defaults to 1024. Its purpose is to +prevent your system from being overloaded and ensuring all the +connections are handled optimally. + +.Customizing the maximum number of concurrent connections + +[source,erlang] +{ok, _} = ranch:start_listener(tcp_echo, + ranch_tcp, [{port, 5555}, {max_connections, 100}], + echo_protocol, [] +). + +You can disable this limit by setting its value to the atom `infinity`. + +.Disabling the limit for the number of connections + +[source,erlang] +{ok, _} = ranch:start_listener(tcp_echo, + ranch_tcp, [{port, 5555}, {max_connections, infinity}], + echo_protocol, [] +). + +The maximum number of connections is a soft limit. In practice, it +can reach `max_connections` + the number of acceptors. + +When the maximum number of connections is reached, Ranch will stop +accepting connections. This will not result in further connections +being rejected, as the kernel option allows queueing incoming +connections. The size of this queue is determined by the `backlog` +option and defaults to 1024. Ranch does not know about the number +of connections that are in the backlog. + +You may not always want connections to be counted when checking for +`max_connections`. For example you might have a protocol where both +short-lived and long-lived connections are possible. If the long-lived +connections are mostly waiting for messages, then they don't consume +much resources and can safely be removed from the count. + +To remove the connection from the count, you must call the +`ranch:remove_connection/1` from within the connection process, +with the name of the listener as the only argument. + +.Removing a connection from the count of connections + +[source,erlang] +ranch:remove_connection(Ref). + +As seen in the chapter covering protocols, this pid is received as the +first argument of the protocol's `start_link/4` callback. + +You can modify the `max_connections` value on a running listener by +using the `ranch:set_max_connections/2` function, with the name of the +listener as first argument and the new value as the second. + +.Upgrading the maximum number of connections + +[source,erlang] +ranch:set_max_connections(tcp_echo, MaxConns). + +The change will occur immediately. + +=== Customizing the number of acceptor processes + +By default Ranch will use 10 acceptor processes. Their role is +to accept connections and spawn a connection process for every +new connection. + +This number can be tweaked to improve performance. A good +number is typically between 10 or 100 acceptors. You must +measure to find the best value for your application. + +.Specifying a custom number of acceptor processes + +[source,erlang] +{ok, _} = ranch:start_listener(tcp_echo, + ranch_tcp, [{port, 5555}, {num_acceptors, 42}], + echo_protocol, [] +). + +=== When running out of file descriptors + +Operating systems have limits on the number of sockets +which can be opened by applications. When this maximum is +reached the listener can no longer accept new connections. The +accept rate of the listener will be automatically reduced, and a +warning message will be logged. + +---- +=ERROR REPORT==== 13-Jan-2016::12:24:38 === +Ranch acceptor reducing accept rate: out of file descriptors +---- + +If you notice messages like this you should increase the number +of file-descriptors which can be opened by your application. How +this should be done is operating-system dependent. Please consult +the documentation of your operating system. + +=== Using a supervisor for connection processes + +Ranch allows you to define the type of process that will be used +for the connection processes. By default it expects a `worker`. +When the `connection_type` configuration value is set to `supervisor`, +Ranch will consider that the connection process it manages is a +supervisor and will reflect that in its supervision tree. + +Connection processes of type `supervisor` can either handle the +socket directly or through one of their children. In the latter +case the start function for the connection process must return +two pids: the pid of the supervisor you created (that will be +supervised) and the pid of the protocol handling process (that +will receive the socket). + +Instead of returning `{ok, ConnPid}`, simply return +`{ok, SupPid, ConnPid}`. + +It is very important that the connection process be created +under the supervisor process so that everything works as intended. +If not, you will most likely experience issues when the supervised +process is stopped. + +=== Upgrading + +Ranch allows you to upgrade the protocol options. This takes effect +immediately and for all subsequent connections. + +To upgrade the protocol options, call `ranch:set_protocol_options/2` +with the name of the listener as first argument and the new options +as the second. + +.Upgrading the protocol options + +[source,erlang] +ranch:set_protocol_options(tcp_echo, NewOpts). + +All future connections will use the new options. + +You can also retrieve the current options similarly by +calling `ranch:get_protocol_options/1`. + +.Retrieving the current protocol options + +[source,erlang] +Opts = ranch:get_protocol_options(tcp_echo). + +=== Obtaining information about listeners + +Ranch provides two functions for retrieving information about the +listeners, for reporting and diagnostic purposes. + +The `ranch:info/0` function will return detailed information +about all listeners. + +.Retrieving detailed information +[source,erlang] +ranch:info(). + +The `ranch:procs/2` function will return all acceptor or listener +processes for a given listener. + +.Get all acceptor processes +[source,erlang] +ranch:procs(tcp_echo, acceptors). + +.Get all connection processes +[source,erlang] +ranch:procs(tcp_echo, connections). diff --git a/docs/en/ranch/1.5/guide/listeners/index.html b/docs/en/ranch/1.5/guide/listeners/index.html new file mode 100644 index 00000000..3f33574b --- /dev/null +++ b/docs/en/ranch/1.5/guide/listeners/index.html @@ -0,0 +1,367 @@ + + + + + + + + + + Nine Nines: Listeners + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +

    Listeners

    + +

    A listener is a set of processes whose role is to listen on a port for new connections. It manages a pool of acceptor processes, each of them indefinitely accepting connections. When it does, it starts a new process executing the protocol handler code. All the socket programming is abstracted through the use of transport handlers.

    +

    The listener takes care of supervising all the acceptor and connection processes, allowing developers to focus on building their application.

    +

    Starting a listener

    +

    Ranch does nothing by default. It is up to the application developer to request that Ranch listens for connections.

    +

    A listener can be started and stopped at will.

    +

    When starting a listener, a number of different settings are required:

    +
    • A name to identify it locally and be able to interact with it. +
    • +
    • The number of acceptors in the pool. +
    • +
    • A transport handler and its associated options. +
    • +
    • A protocol handler and its associated options. +
    • +
    +

    Ranch includes both TCP and SSL transport handlers, respectively ranch_tcp and ranch_ssl.

    +

    A listener can be started by calling the ranch:start_listener/5 function. Before doing so however, you must ensure that the ranch application is started.

    +
    Starting the Ranch application
    +
    +
    ok = application:start(ranch).
    +
    +

    You are then ready to start a listener. Let's call it tcp_echo. It will have a pool of 100 acceptors, use a TCP transport and forward connections to the echo_protocol handler.

    +
    Starting a listener for TCP connections on port 5555
    +
    +
    {ok, _} = ranch:start_listener(tcp_echo,
    +	ranch_tcp, [{port, 5555}],
    +	echo_protocol, []
    +).
    +
    +

    You can try this out by compiling and running the tcp_echo example in the examples directory. To do so, open a shell in the examples/tcp_echo/ directory and run the following command:

    +
    Building and starting a Ranch example
    +
    +
    $ make run
    +
    +

    You can then connect to it using telnet and see the echo server reply everything you send to it. Then when you're done testing, you can use the Ctrl+] key to escape to the telnet command line and type quit to exit.

    +
    Connecting to the example listener with telnet
    +
    +
    $ telnet localhost 5555
    +Trying 127.0.0.1...
    +Connected to localhost.
    +Escape character is '^]'.
    +Hello!
    +Hello!
    +It works!
    +It works!
    +^]
    +
    +telnet> quit
    +Connection closed.
    +
    +

    Stopping a listener

    +

    All you need to stop a Ranch listener is to call the ranch:stop_listener/1 function with the listener's name as argument. In the previous section we started the listener named tcp_echo. We can now stop it.

    +
    Stopping a listener
    +
    +
    ranch:stop_listener(tcp_echo).
    +
    +

    Default transport options

    +

    By default the socket will be set to return binary data, with the options {active, false}, {packet, raw}, {reuseaddr, true} set. These values can't be overriden when starting the listener, but they can be overriden using Transport:setopts/2 in the protocol.

    +

    It will also set {backlog, 1024} and {nodelay, true}, which can be overriden at listener startup.

    +

    Listening on a random port

    +

    You do not have to specify a specific port to listen on. If you give the port number 0, or if you omit the port number entirely, Ranch will start listening on a random port.

    +

    You can retrieve this port number by calling ranch:get_port/1. The argument is the name of the listener you gave in ranch:start_listener/5.

    +
    Starting a listener for TCP connections on a random port
    +
    +
    {ok, _} = ranch:start_listener(tcp_echo,
    +	ranch_tcp, [{port, 0}],
    +	echo_protocol, []
    +).
    +Port = ranch:get_port(tcp_echo).
    +
    +

    Listening on privileged ports

    +

    Some systems limit access to ports below 1024 for security reasons. This can easily be identified by an {error, eacces} error when trying to open a listening socket on such a port.

    +

    The methods for listening on privileged ports vary between systems, please refer to your system's documentation for more information.

    +

    We recommend the use of port rewriting for systems with a single server, and load balancing for systems with multiple servers. Documenting these solutions is however out of the scope of this guide.

    +

    Accepting connections on an existing socket

    +

    If you want to accept connections on an existing socket, you can use the socket transport option, which should just be the relevant data returned from the connect function for the transport or the underlying socket library (gen_tcp:connect, ssl:connect). The accept function will then be called on the passed in socket. You should connect the socket in {active, false} mode, as well.

    +

    Note, however, that because of a bug in SSL, you cannot change ownership of an SSL listen socket prior to R16. Ranch will catch the error thrown, but the owner of the SSL socket will remain as whatever process created the socket. However, this will not affect accept behaviour unless the owner process dies, in which case the socket is closed. Therefore, to use this feature with SSL with an erlang release prior to R16, ensure that the SSL socket is opened in a persistant process.

    +

    Limiting the number of concurrent connections

    +

    The max_connections transport option allows you to limit the number of concurrent connections. It defaults to 1024. Its purpose is to prevent your system from being overloaded and ensuring all the connections are handled optimally.

    +
    Customizing the maximum number of concurrent connections
    +
    +
    {ok, _} = ranch:start_listener(tcp_echo,
    +	ranch_tcp, [{port, 5555}, {max_connections, 100}],
    +	echo_protocol, []
    +).
    +
    +

    You can disable this limit by setting its value to the atom infinity.

    +
    Disabling the limit for the number of connections
    +
    +
    {ok, _} = ranch:start_listener(tcp_echo,
    +	ranch_tcp, [{port, 5555}, {max_connections, infinity}],
    +	echo_protocol, []
    +).
    +
    +

    The maximum number of connections is a soft limit. In practice, it can reach max_connections
    the number of acceptors.

    +

    When the maximum number of connections is reached, Ranch will stop accepting connections. This will not result in further connections being rejected, as the kernel option allows queueing incoming connections. The size of this queue is determined by the backlog option and defaults to 1024. Ranch does not know about the number of connections that are in the backlog.

    +

    You may not always want connections to be counted when checking for max_connections. For example you might have a protocol where both short-lived and long-lived connections are possible. If the long-lived connections are mostly waiting for messages, then they don't consume much resources and can safely be removed from the count.

    +

    To remove the connection from the count, you must call the ranch:remove_connection/1 from within the connection process, with the name of the listener as the only argument.

    +
    Removing a connection from the count of connections
    +
    +
    ranch:remove_connection(Ref).
    +
    +

    As seen in the chapter covering protocols, this pid is received as the first argument of the protocol's start_link/4 callback.

    +

    You can modify the max_connections value on a running listener by using the ranch:set_max_connections/2 function, with the name of the listener as first argument and the new value as the second.

    +
    Upgrading the maximum number of connections
    +
    +
    ranch:set_max_connections(tcp_echo, MaxConns).
    +
    +

    The change will occur immediately.

    +

    Customizing the number of acceptor processes

    +

    By default Ranch will use 10 acceptor processes. Their role is to accept connections and spawn a connection process for every new connection.

    +

    This number can be tweaked to improve performance. A good number is typically between 10 or 100 acceptors. You must measure to find the best value for your application.

    +
    Specifying a custom number of acceptor processes
    +
    +
    {ok, _} = ranch:start_listener(tcp_echo,
    +	ranch_tcp, [{port, 5555}, {num_acceptors, 42}],
    +	echo_protocol, []
    +).
    +
    +

    When running out of file descriptors

    +

    Operating systems have limits on the number of sockets which can be opened by applications. When this maximum is reached the listener can no longer accept new connections. The accept rate of the listener will be automatically reduced, and a warning message will be logged.

    +
    =ERROR REPORT==== 13-Jan-2016::12:24:38 ===
    +Ranch acceptor reducing accept rate: out of file descriptors
    +

    If you notice messages like this you should increase the number of file-descriptors which can be opened by your application. How this should be done is operating-system dependent. Please consult the documentation of your operating system.

    +

    Using a supervisor for connection processes

    +

    Ranch allows you to define the type of process that will be used for the connection processes. By default it expects a worker. When the connection_type configuration value is set to supervisor, Ranch will consider that the connection process it manages is a supervisor and will reflect that in its supervision tree.

    +

    Connection processes of type supervisor can either handle the socket directly or through one of their children. In the latter case the start function for the connection process must return two pids: the pid of the supervisor you created (that will be supervised) and the pid of the protocol handling process (that will receive the socket).

    +

    Instead of returning {ok, ConnPid}, simply return {ok, SupPid, ConnPid}.

    +

    It is very important that the connection process be created under the supervisor process so that everything works as intended. If not, you will most likely experience issues when the supervised process is stopped.

    +

    Upgrading

    +

    Ranch allows you to upgrade the protocol options. This takes effect immediately and for all subsequent connections.

    +

    To upgrade the protocol options, call ranch:set_protocol_options/2 with the name of the listener as first argument and the new options as the second.

    +
    Upgrading the protocol options
    +
    +
    ranch:set_protocol_options(tcp_echo, NewOpts).
    +
    +

    All future connections will use the new options.

    +

    You can also retrieve the current options similarly by calling ranch:get_protocol_options/1.

    +
    Retrieving the current protocol options
    +
    +
    Opts = ranch:get_protocol_options(tcp_echo).
    +
    +

    Obtaining information about listeners

    +

    Ranch provides two functions for retrieving information about the listeners, for reporting and diagnostic purposes.

    +

    The ranch:info/0 function will return detailed information about all listeners.

    +
    Retrieving detailed information
    +
    +
    ranch:info().
    +
    +

    The ranch:procs/2 function will return all acceptor or listener processes for a given listener.

    +
    Get all acceptor processes
    +
    +
    ranch:procs(tcp_echo, acceptors).
    +
    +
    Get all connection processes
    +
    +
    ranch:procs(tcp_echo, connections).
    +
    + + + + + + + + + + + + + + + + +
    + +
    + + +

    + Ranch + 1.5 + + User Guide +

    + + + +

    Navigation

    + +

    Version select

    + + +
    +
    +
    +
    + + + + + + + + + diff --git a/docs/en/ranch/1.5/guide/parsers.asciidoc b/docs/en/ranch/1.5/guide/parsers.asciidoc new file mode 100644 index 00000000..9eacbfa9 --- /dev/null +++ b/docs/en/ranch/1.5/guide/parsers.asciidoc @@ -0,0 +1,92 @@ +== Writing parsers + +There are three kinds of protocols: + +* Text protocols +* Schema-less binary protocols +* Schema-based binary protocols + +This chapter introduces the first two kinds. It will not cover +more advanced topics such as continuations or parser generators. + +This chapter isn't specifically about Ranch, we assume here that +you know how to read data from the socket. The data you read and +the data that hasn't been parsed is saved in a buffer. Every +time you read from the socket, the data read is appended to the +buffer. What happens next depends on the kind of protocol. We +will only cover the first two. + +=== Parsing text + +Text protocols are generally line based. This means that we can't +do anything with them until we receive the full line. + +A simple way to get a full line is to use `binary:split/{2,3}`. + +.Using binary:split/2 to get a line of input + +[source,erlang] +case binary:split(Buffer, <<"\n">>) of + [_] -> + get_more_data(Buffer); + [Line, Rest] -> + handle_line(Line, Rest) +end. + +In the above example, we can have two results. Either there was +a line break in the buffer and we get it split into two parts, +the line and the rest of the buffer; or there was no line break +in the buffer and we need to get more data from the socket. + +Next, we need to parse the line. The simplest way is to again +split, here on space. The difference is that we want to split +on all spaces character, as we want to tokenize the whole string. + +.Using binary:split/3 to split text + +[source,erlang] +case binary:split(Line, <<" ">>, [global]) of + [<<"HELLO">>] -> + be_polite(); + [<<"AUTH">>, User, Password] -> + authenticate_user(User, Password); + [<<"QUIT">>, Reason] -> + quit(Reason) + %% ... +end. + +Pretty simple, right? Match on the command name, get the rest +of the tokens in variables and call the respective functions. + +After doing this, you will want to check if there is another +line in the buffer, and handle it immediately if any. +Otherwise wait for more data. + +=== Parsing binary + +Binary protocols can be more varied, although most of them are +pretty similar. The first four bytes of a frame tend to be +the size of the frame, which is followed by a certain number +of bytes for the type of frame and then various parameters. + +Sometimes the size of the frame includes the first four bytes, +sometimes not. Other times this size is encoded over two bytes. +And even other times little-endian is used instead of big-endian. + +The general idea stays the same though. + +.Using binary pattern matching to split frames + +[source,erlang] +<< Size:32, _/bits >> = Buffer, +case Buffer of + << Frame:Size/binary, Rest/bits >> -> + handle_frame(Frame, Rest); + _ -> + get_more_data(Buffer) +end. + +You will then need to parse this frame using binary pattern +matching, and handle it. Then you will want to check if there +is another frame fully received in the buffer, and handle it +immediately if any. Otherwise wait for more data. diff --git a/docs/en/ranch/1.5/guide/parsers/index.html b/docs/en/ranch/1.5/guide/parsers/index.html new file mode 100644 index 00000000..b52a430f --- /dev/null +++ b/docs/en/ranch/1.5/guide/parsers/index.html @@ -0,0 +1,223 @@ + + + + + + + + + + Nine Nines: Writing parsers + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +

    Writing parsers

    + +

    There are three kinds of protocols:

    +
    • Text protocols +
    • +
    • Schema-less binary protocols +
    • +
    • Schema-based binary protocols +
    • +
    +

    This chapter introduces the first two kinds. It will not cover more advanced topics such as continuations or parser generators.

    +

    This chapter isn't specifically about Ranch, we assume here that you know how to read data from the socket. The data you read and the data that hasn't been parsed is saved in a buffer. Every time you read from the socket, the data read is appended to the buffer. What happens next depends on the kind of protocol. We will only cover the first two.

    +

    Parsing text

    +

    Text protocols are generally line based. This means that we can't do anything with them until we receive the full line.

    +

    A simple way to get a full line is to use binary:split/{2,3}.

    +
    Using binary:split/2 to get a line of input
    +
    +
    case binary:split(Buffer, <<"\n">>) of
    +	[_] ->
    +		get_more_data(Buffer);
    +	[Line, Rest] ->
    +		handle_line(Line, Rest)
    +end.
    +
    +

    In the above example, we can have two results. Either there was a line break in the buffer and we get it split into two parts, the line and the rest of the buffer; or there was no line break in the buffer and we need to get more data from the socket.

    +

    Next, we need to parse the line. The simplest way is to again split, here on space. The difference is that we want to split on all spaces character, as we want to tokenize the whole string.

    +
    Using binary:split/3 to split text
    +
    +
    case binary:split(Line, <<" ">>, [global]) of
    +	[<<"HELLO">>] ->
    +		be_polite();
    +	[<<"AUTH">>, User, Password] ->
    +		authenticate_user(User, Password);
    +	[<<"QUIT">>, Reason] ->
    +		quit(Reason)
    +	%% ...
    +end.
    +
    +

    Pretty simple, right? Match on the command name, get the rest of the tokens in variables and call the respective functions.

    +

    After doing this, you will want to check if there is another line in the buffer, and handle it immediately if any. Otherwise wait for more data.

    +

    Parsing binary

    +

    Binary protocols can be more varied, although most of them are pretty similar. The first four bytes of a frame tend to be the size of the frame, which is followed by a certain number of bytes for the type of frame and then various parameters.

    +

    Sometimes the size of the frame includes the first four bytes, sometimes not. Other times this size is encoded over two bytes. And even other times little-endian is used instead of big-endian.

    +

    The general idea stays the same though.

    +
    Using binary pattern matching to split frames
    +
    +
    << Size:32, _/bits >> = Buffer,
    +case Buffer of
    +	<< Frame:Size/binary, Rest/bits >> ->
    +		handle_frame(Frame, Rest);
    +	_ ->
    +		get_more_data(Buffer)
    +end.
    +
    +

    You will then need to parse this frame using binary pattern matching, and handle it. Then you will want to check if there is another frame fully received in the buffer, and handle it immediately if any. Otherwise wait for more data.

    + + + + + + + + + + + + + + + + +
    + +
    + + +

    + Ranch + 1.5 + + User Guide +

    + + + +

    Navigation

    + +

    Version select

    + + +
    +
    +
    +
    + + + + + + + + + diff --git a/docs/en/ranch/1.5/guide/protocols.asciidoc b/docs/en/ranch/1.5/guide/protocols.asciidoc new file mode 100644 index 00000000..b9a31f27 --- /dev/null +++ b/docs/en/ranch/1.5/guide/protocols.asciidoc @@ -0,0 +1,99 @@ +== Protocols + +A protocol handler starts a connection process and defines the +protocol logic executed in this process. + +=== Writing a protocol handler + +All protocol handlers must implement the `ranch_protocol` behavior +which defines a single callback, `start_link/4`. This callback is +responsible for spawning a new process for handling the connection. +It receives four arguments: the name of the listener, the socket, the +transport handler being used and the protocol options defined in +the call to `ranch:start_listener/5`. This callback must +return `{ok, Pid}`, with `Pid` the pid of the new process. + +The newly started process can then freely initialize itself. However, +it must call `ranch:accept_ack/1` before doing any socket operation. +This will ensure the connection process is the owner of the socket. +It expects the listener's name as argument. + +.Acknowledge accepting the socket + +[source,erlang] +ok = ranch:accept_ack(Ref). + +If your protocol code requires specific socket options, you should +set them while initializing your connection process, after +calling `ranch:accept_ack/1`. You can use `Transport:setopts/2` +for that purpose. + +Following is the complete protocol code for the example found +in `examples/tcp_echo/`. + +.Protocol module that echoes everything it receives + +[source,erlang] +---- +-module(echo_protocol). +-behaviour(ranch_protocol). + +-export([start_link/4]). +-export([init/4]). + +start_link(Ref, Socket, Transport, Opts) -> + Pid = spawn_link(?MODULE, init, [Ref, Socket, Transport, Opts]), + {ok, Pid}. + +init(Ref, Socket, Transport, _Opts = []) -> + ok = ranch:accept_ack(Ref), + loop(Socket, Transport). + +loop(Socket, Transport) -> + case Transport:recv(Socket, 0, 5000) of + {ok, Data} -> + Transport:send(Socket, Data), + loop(Socket, Transport); + _ -> + ok = Transport:close(Socket) + end. +---- + +=== Using gen_server + +Special processes like the ones that use the `gen_server` or `gen_fsm` +behaviours have the particularity of having their `start_link` call not +return until the `init` function returns. This is problematic, because +you won't be able to call `ranch:accept_ack/1` from the `init` callback +as this would cause a deadlock to happen. + +Use the `gen_server:enter_loop/3` function. It allows you to start your process +normally (although it must be started with `proc_lib` like all special +processes), then perform any needed operations before falling back into +the normal `gen_server` execution loop. + +.Use a gen_server for protocol handling + +[source,erlang] +---- +-module(my_protocol). +-behaviour(gen_server). +-behaviour(ranch_protocol). + +-export([start_link/4]). +-export([init/1]). +%% Exports of other gen_server callbacks here. + +start_link(Ref, Socket, Transport, Opts) -> + {ok, proc_lib:spawn_link(?MODULE, init, [{Ref, Socket, Transport, Opts}])}. + +init({Ref, Socket, Transport, _Opts = []}) -> + %% Perform any required state initialization here. + ok = ranch:accept_ack(Ref), + ok = Transport:setopts(Socket, [{active, once}]), + gen_server:enter_loop(?MODULE, [], {state, Socket, Transport}). + +%% Other gen_server callbacks here. +---- + +Check the `tcp_reverse` example for a complete example. diff --git a/docs/en/ranch/1.5/guide/protocols/index.html b/docs/en/ranch/1.5/guide/protocols/index.html new file mode 100644 index 00000000..4f8c6a29 --- /dev/null +++ b/docs/en/ranch/1.5/guide/protocols/index.html @@ -0,0 +1,230 @@ + + + + + + + + + + Nine Nines: Protocols + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +

    Protocols

    + +

    A protocol handler starts a connection process and defines the protocol logic executed in this process.

    +

    Writing a protocol handler

    +

    All protocol handlers must implement the ranch_protocol behavior which defines a single callback, start_link/4. This callback is responsible for spawning a new process for handling the connection. It receives four arguments: the name of the listener, the socket, the transport handler being used and the protocol options defined in the call to ranch:start_listener/5. This callback must return {ok, Pid}, with Pid the pid of the new process.

    +

    The newly started process can then freely initialize itself. However, it must call ranch:accept_ack/1 before doing any socket operation. This will ensure the connection process is the owner of the socket. It expects the listener's name as argument.

    +
    Acknowledge accepting the socket
    +
    +
    ok = ranch:accept_ack(Ref).
    +
    +

    If your protocol code requires specific socket options, you should set them while initializing your connection process, after calling ranch:accept_ack/1. You can use Transport:setopts/2 for that purpose.

    +

    Following is the complete protocol code for the example found in examples/tcp_echo/.

    +
    Protocol module that echoes everything it receives
    +
    +
    -module(echo_protocol).
    +-behaviour(ranch_protocol).
    +
    +-export([start_link/4]).
    +-export([init/4]).
    +
    +start_link(Ref, Socket, Transport, Opts) ->
    +	Pid = spawn_link(?MODULE, init, [Ref, Socket, Transport, Opts]),
    +	{ok, Pid}.
    +
    +init(Ref, Socket, Transport, _Opts = []) ->
    +	ok = ranch:accept_ack(Ref),
    +	loop(Socket, Transport).
    +
    +loop(Socket, Transport) ->
    +	case Transport:recv(Socket, 0, 5000) of
    +		{ok, Data} ->
    +			Transport:send(Socket, Data),
    +			loop(Socket, Transport);
    +		_ ->
    +			ok = Transport:close(Socket)
    +	end.
    +
    +

    Using gen_server

    +

    Special processes like the ones that use the gen_server or gen_fsm behaviours have the particularity of having their start_link call not return until the init function returns. This is problematic, because you won't be able to call ranch:accept_ack/1 from the init callback as this would cause a deadlock to happen.

    +

    Use the gen_server:enter_loop/3 function. It allows you to start your process normally (although it must be started with proc_lib like all special processes), then perform any needed operations before falling back into the normal gen_server execution loop.

    +
    Use a gen_server for protocol handling
    +
    +
    -module(my_protocol).
    +-behaviour(gen_server).
    +-behaviour(ranch_protocol).
    +
    +-export([start_link/4]).
    +-export([init/1]).
    +%% Exports of other gen_server callbacks here.
    +
    +start_link(Ref, Socket, Transport, Opts) ->
    +	{ok, proc_lib:spawn_link(?MODULE, init, [{Ref, Socket, Transport, Opts}])}.
    +
    +init({Ref, Socket, Transport, _Opts = []}) ->
    +	%% Perform any required state initialization here.
    +	ok = ranch:accept_ack(Ref),
    +	ok = Transport:setopts(Socket, [{active, once}]),
    +	gen_server:enter_loop(?MODULE, [], {state, Socket, Transport}).
    +
    +%% Other gen_server callbacks here.
    +
    +

    Check the tcp_reverse example for a complete example.

    + + + + + + + + + + + + + + + + +
    + +
    + + +

    + Ranch + 1.5 + + User Guide +

    + + + +

    Navigation

    + +

    Version select

    + + +
    +
    +
    +
    + + + + + + + + + diff --git a/docs/en/ranch/1.5/guide/ssl_auth.asciidoc b/docs/en/ranch/1.5/guide/ssl_auth.asciidoc new file mode 100644 index 00000000..de16107a --- /dev/null +++ b/docs/en/ranch/1.5/guide/ssl_auth.asciidoc @@ -0,0 +1,120 @@ +== SSL client authentication + +=== Purpose + +SSL client authentication is a mechanism allowing applications to +identify certificates. This allows your application to make sure that +the client is an authorized certificate, but makes no claim about +whether the user can be trusted. This can be combined with a password +based authentication to attain greater security. + +The server only needs to retain the certificate serial number and +the certificate issuer to authenticate the certificate. Together, +they can be used to uniquely identify a certicate. + +As Ranch allows the same protocol code to be used for both SSL and +non-SSL transports, you need to make sure you are in an SSL context +before attempting to perform an SSL client authentication. This +can be done by checking the return value of `Transport:name/0`. + +=== Obtaining client certificates + +You can obtain client certificates from various sources. You can +generate them yourself, or you can use a service like CAcert.org +which allows you to generate client and server certificates for +free. + +Following are the steps you need to take to create a CAcert.org +account, generate a certificate and install it in your favorite +browser. + +* Open http://cacert.org in your favorite browser +* Root Certificate link: install both certificates +* Join (Register an account) +* Verify your account (check your email inbox!) +* Log in +* Client Certificates: New +* Follow instructions to create the certificate +* Install the certificate in your browser + +You can optionally save the certificate for later use, for example +to extract the `IssuerID` information as will be detailed later on. + +=== Transport configuration + +The SSL transport does not request a client certificate by default. +You need to specify the `{verify, verify_peer}` option when starting +the listener to enable this behavior. + +.Configure a listener for SSL authentication + +[source,erlang] +{ok, _} = ranch:start_listener(my_ssl, + ranch_ssl, [ + {port, SSLPort}, + {certfile, PathToCertfile}, + {cacertfile, PathToCACertfile}, + {verify, verify_peer} + ], + my_protocol, [] +). + +In this example we set the required `port` and `certfile`, but also +the `cacertfile` containing the CACert.org root certificate, and +the option to request the client certificate. + +If you enable the `{verify, verify_peer}` option and the client does +not have a client certificate configured for your domain, then no +certificate will be sent. This allows you to use SSL for more than +just authenticated clients. + +=== Authentication + +To authenticate users, you must first save the certificate information +required. If you have your users' certificate files, you can simply +load the certificate and retrieve the information directly. + +.Retrieve the issuer ID from a certificate + +[source,erlang] +---- +certfile_to_issuer_id(Filename) -> + {ok, Data} = file:read_file(Filename), + [{'Certificate', Cert, not_encrypted}] = public_key:pem_decode(Data), + {ok, IssuerID} = public_key:pkix_issuer_id(Cert, self), + IssuerID. +---- + +The `IssuerID` variable contains both the certificate serial number +and the certificate issuer stored in a tuple, so this value alone can +be used to uniquely identify the user certificate. You can save this +value in a database, a configuration file or any other place where an +Erlang term can be stored and retrieved. + +To retrieve the `IssuerID` from a running connection, you need to first +retrieve the client certificate and then extract this information from +it. Ranch does not provide a function to retrieve the client certificate. +Instead you can use the `ssl:peercert/1` function. Once you have the +certificate, you can again use the `public_key:pkix_issuer_id/2` to +extract the `IssuerID` value. + +The following function returns the `IssuerID` or `false` if no client +certificate was found. This snippet is intended to be used from your +protocol code. + +.Retrieve the issuer ID from the certificate for the current connection + +[source,erlang] +---- +socket_to_issuer_id(Socket) -> + case ssl:peercert(Socket) of + {error, no_peercert} -> + false; + {ok, Cert} -> + {ok, IssuerID} = public_key:pkix_issuer_id(Cert, self), + IssuerID + end. +---- + +You then only need to match the `IssuerID` value to authenticate the +user. diff --git a/docs/en/ranch/1.5/guide/ssl_auth/index.html b/docs/en/ranch/1.5/guide/ssl_auth/index.html new file mode 100644 index 00000000..d1103fd8 --- /dev/null +++ b/docs/en/ranch/1.5/guide/ssl_auth/index.html @@ -0,0 +1,236 @@ + + + + + + + + + + Nine Nines: SSL client authentication + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +

    SSL client authentication

    + +

    Purpose

    +

    SSL client authentication is a mechanism allowing applications to identify certificates. This allows your application to make sure that the client is an authorized certificate, but makes no claim about whether the user can be trusted. This can be combined with a password based authentication to attain greater security.

    +

    The server only needs to retain the certificate serial number and the certificate issuer to authenticate the certificate. Together, they can be used to uniquely identify a certicate.

    +

    As Ranch allows the same protocol code to be used for both SSL and non-SSL transports, you need to make sure you are in an SSL context before attempting to perform an SSL client authentication. This can be done by checking the return value of Transport:name/0.

    +

    Obtaining client certificates

    +

    You can obtain client certificates from various sources. You can generate them yourself, or you can use a service like CAcert.org which allows you to generate client and server certificates for free.

    +

    Following are the steps you need to take to create a CAcert.org account, generate a certificate and install it in your favorite browser.

    +
    • Open http://cacert.org in your favorite browser +
    • +
    • Root Certificate link: install both certificates +
    • +
    • Join (Register an account) +
    • +
    • Verify your account (check your email inbox!) +
    • +
    • Log in +
    • +
    • Client Certificates: New +
    • +
    • Follow instructions to create the certificate +
    • +
    • Install the certificate in your browser +
    • +
    +

    You can optionally save the certificate for later use, for example to extract the IssuerID information as will be detailed later on.

    +

    Transport configuration

    +

    The SSL transport does not request a client certificate by default. You need to specify the {verify, verify_peer} option when starting the listener to enable this behavior.

    +
    Configure a listener for SSL authentication
    +
    +
    {ok, _} = ranch:start_listener(my_ssl,
    +	ranch_ssl, [
    +		{port, SSLPort},
    +		{certfile, PathToCertfile},
    +		{cacertfile, PathToCACertfile},
    +		{verify, verify_peer}
    +	],
    +	my_protocol, []
    +).
    +
    +

    In this example we set the required port and certfile, but also the cacertfile containing the CACert.org root certificate, and the option to request the client certificate.

    +

    If you enable the {verify, verify_peer} option and the client does not have a client certificate configured for your domain, then no certificate will be sent. This allows you to use SSL for more than just authenticated clients.

    +

    Authentication

    +

    To authenticate users, you must first save the certificate information required. If you have your users' certificate files, you can simply load the certificate and retrieve the information directly.

    +
    Retrieve the issuer ID from a certificate
    +
    +
    certfile_to_issuer_id(Filename) ->
    +	{ok, Data} = file:read_file(Filename),
    +	[{'Certificate', Cert, not_encrypted}] = public_key:pem_decode(Data),
    +	{ok, IssuerID} = public_key:pkix_issuer_id(Cert, self),
    +	IssuerID.
    +
    +

    The IssuerID variable contains both the certificate serial number and the certificate issuer stored in a tuple, so this value alone can be used to uniquely identify the user certificate. You can save this value in a database, a configuration file or any other place where an Erlang term can be stored and retrieved.

    +

    To retrieve the IssuerID from a running connection, you need to first retrieve the client certificate and then extract this information from it. Ranch does not provide a function to retrieve the client certificate. Instead you can use the ssl:peercert/1 function. Once you have the certificate, you can again use the public_key:pkix_issuer_id/2 to extract the IssuerID value.

    +

    The following function returns the IssuerID or false if no client certificate was found. This snippet is intended to be used from your protocol code.

    +
    Retrieve the issuer ID from the certificate for the current connection
    +
    +
    socket_to_issuer_id(Socket) ->
    +	case ssl:peercert(Socket) of
    +		{error, no_peercert} ->
    +			false;
    +		{ok, Cert} ->
    +			{ok, IssuerID} = public_key:pkix_issuer_id(Cert, self),
    +			IssuerID
    +	end.
    +
    +

    You then only need to match the IssuerID value to authenticate the user.

    + + + + + + + + + + + + + + + + +
    + +
    + + +

    + Ranch + 1.5 + + User Guide +

    + + + +

    Navigation

    + +

    Version select

    + + +
    +
    +
    +
    + + + + + + + + + diff --git a/docs/en/ranch/1.5/guide/transports.asciidoc b/docs/en/ranch/1.5/guide/transports.asciidoc new file mode 100644 index 00000000..f5bb17eb --- /dev/null +++ b/docs/en/ranch/1.5/guide/transports.asciidoc @@ -0,0 +1,161 @@ +== Transports + +A transport defines the interface to interact with a socket. + +Transports can be used for connecting, listening and accepting +connections, but also for receiving and sending data. Both +passive and active mode are supported, although all sockets +are initialized as passive. + +=== TCP transport + +The TCP transport is a thin wrapper around `gen_tcp`. + +=== SSL transport + +The SSL transport is a thin wrapper around `ssl`. + +Ranch depends on `ssl` by default so any necessary +dependencies will start when Ranch is started. It is +possible to remove the dependency when the SSL transport +will not be used. Refer to your release build tool's +documentation for more information. + +When embedding Ranch listeners that have an SSL transport, +your application must depend on the `ssl` application for +proper behavior. + +=== Sending and receiving data + +This section assumes that `Transport` is a valid transport handler +(like `ranch_tcp` or `ranch_ssl`) and `Socket` is a connected +socket obtained through the listener. + +You can send data to a socket by calling the `Transport:send/2` +function. The data can be given as `iodata()`, which is defined as +`binary() | iolist()`. All the following calls will work: + +.Sending data to the socket + +[source,erlang] +---- +Transport:send(Socket, <<"Ranch is cool!">>). +Transport:send(Socket, "Ranch is cool!"). +Transport:send(Socket, ["Ranch", ["is", "cool!"]]). +Transport:send(Socket, ["Ranch", [<<"is">>, "cool!"]]). +---- + +You can receive data either in passive or in active mode. Passive mode +means that you will perform a blocking `Transport:recv/3` call, while +active mode means that you will receive the data as a message. + +By default, all data will be received as binary. It is possible to +receive data as strings, although this is not recommended as binaries +are a more efficient construct, especially for binary protocols. + +Receiving data using passive mode requires a single function call. The +first argument is the socket, and the third argument is a timeout duration +before the call returns with `{error, timeout}`. + +The second argument is the amount of data in bytes that we want to receive. +The function will wait for data until it has received exactly this amount. +If you are not expecting a precise size, you can specify 0 which will make +this call return as soon as data was read, regardless of its size. + +.Receiving data from the socket in passive mode + +[source,erlang] +{ok, Data} = Transport:recv(Socket, 0, 5000). + +Active mode requires you to inform the socket that you want to receive +data as a message and to write the code to actually receive it. + +There are two kinds of active modes: `{active, once}` and +`{active, true}`. The first will send a single message before going +back to passive mode; the second will send messages indefinitely. +We recommend not using the `{active, true}` mode as it could quickly +flood your process mailbox. It's better to keep the data in the socket +and read it only when required. + +Three different messages can be received: + +* `{OK, Socket, Data}` +* `{Closed, Socket}` +* `{Error, Socket, Reason}` + +The value of `OK`, `Closed` and `Error` can be different +depending on the transport being used. To be able to properly match +on them you must first call the `Transport:messages/0` function. + +.Retrieving the transport's active message identifiers + +[source,erlang] +{OK, Closed, Error} = Transport:messages(). + +To start receiving messages you will need to call the `Transport:setopts/2` +function, and do so every time you want to receive data. + +.Receiving messages from the socket in active mode + +[source,erlang] +---- +{OK, Closed, Error} = Transport:messages(), +Transport:setopts(Socket, [{active, once}]), +receive + {OK, Socket, Data} -> + io:format("data received: ~p~n", [Data]); + {Closed, Socket} -> + io:format("socket got closed!~n"); + {Error, Socket, Reason} -> + io:format("error happened: ~p~n", [Reason]) +end. +---- + +You can easily integrate active sockets with existing Erlang code as all +you really need is just a few more clauses when receiving messages. + +=== Sending files + +As in the previous section it is assumed `Transport` is a valid transport +handler and `Socket` is a connected socket obtained through the listener. + +To send a whole file, with name `Filename`, over a socket: + +.Sending a file by filename + +[source,erlang] +{ok, SentBytes} = Transport:sendfile(Socket, Filename). + +Or part of a file, with `Offset` greater than or equal to 0, `Bytes` number of +bytes and chunks of size `ChunkSize`: + +.Sending part of a file by filename in chunks + +[source,erlang] +Opts = [{chunk_size, ChunkSize}], +{ok, SentBytes} = Transport:sendfile(Socket, Filename, Offset, Bytes, Opts). + +To improve efficiency when sending multiple parts of the same file it is also +possible to use a file descriptor opened in raw mode: + +.Sending a file opened in raw mode + +[source,erlang] +{ok, RawFile} = file:open(Filename, [raw, read, binary]), +{ok, SentBytes} = Transport:sendfile(Socket, RawFile, Offset, Bytes, Opts). + +=== Writing a transport handler + +A transport handler is a module implementing the `ranch_transport` behavior. +It defines a certain number of callbacks that must be written in order to +allow transparent usage of the transport handler. + +The behavior doesn't define the socket options available when opening a +socket. These do not need to be common to all transports as it's easy enough +to write different initialization functions for the different transports that +will be used. With one exception though. The `setopts/2` function *must* +implement the `{active, once}` and the `{active, true}` options. + +If the transport handler doesn't have a native implementation of `sendfile/5` a +fallback is available, `ranch_transport:sendfile/6`. The extra first argument +is the transport's module. See `ranch_ssl` for an example. diff --git a/docs/en/ranch/1.5/guide/transports/index.html b/docs/en/ranch/1.5/guide/transports/index.html new file mode 100644 index 00000000..6b732dd7 --- /dev/null +++ b/docs/en/ranch/1.5/guide/transports/index.html @@ -0,0 +1,261 @@ + + + + + + + + + + Nine Nines: Transports + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +

    Transports

    + +

    A transport defines the interface to interact with a socket.

    +

    Transports can be used for connecting, listening and accepting connections, but also for receiving and sending data. Both passive and active mode are supported, although all sockets are initialized as passive.

    +

    TCP transport

    +

    The TCP transport is a thin wrapper around gen_tcp.

    +

    SSL transport

    +

    The SSL transport is a thin wrapper around ssl.

    +

    Ranch depends on ssl by default so any necessary dependencies will start when Ranch is started. It is possible to remove the dependency when the SSL transport will not be used. Refer to your release build tool's documentation for more information.

    +

    When embedding Ranch listeners that have an SSL transport, your application must depend on the ssl application for proper behavior.

    +

    Sending and receiving data

    +

    This section assumes that Transport is a valid transport handler (like ranch_tcp or ranch_ssl) and Socket is a connected socket obtained through the listener.

    +

    You can send data to a socket by calling the Transport:send/2 function. The data can be given as iodata(), which is defined as binary() | iolist(). All the following calls will work:

    +
    Sending data to the socket
    +
    +
    Transport:send(Socket, <<"Ranch is cool!">>).
    +Transport:send(Socket, "Ranch is cool!").
    +Transport:send(Socket, ["Ranch", ["is", "cool!"]]).
    +Transport:send(Socket, ["Ranch", [<<"is">>, "cool!"]]).
    +
    +

    You can receive data either in passive or in active mode. Passive mode means that you will perform a blocking Transport:recv/3 call, while active mode means that you will receive the data as a message.

    +

    By default, all data will be received as binary. It is possible to receive data as strings, although this is not recommended as binaries are a more efficient construct, especially for binary protocols.

    +

    Receiving data using passive mode requires a single function call. The first argument is the socket, and the third argument is a timeout duration before the call returns with {error, timeout}.

    +

    The second argument is the amount of data in bytes that we want to receive. The function will wait for data until it has received exactly this amount. If you are not expecting a precise size, you can specify 0 which will make this call return as soon as data was read, regardless of its size.

    +
    Receiving data from the socket in passive mode
    +
    +
    {ok, Data} = Transport:recv(Socket, 0, 5000).
    +
    +

    Active mode requires you to inform the socket that you want to receive data as a message and to write the code to actually receive it.

    +

    There are two kinds of active modes: {active, once} and {active, true}. The first will send a single message before going back to passive mode; the second will send messages indefinitely. We recommend not using the {active, true} mode as it could quickly flood your process mailbox. It's better to keep the data in the socket and read it only when required.

    +

    Three different messages can be received:

    +
    • {OK, Socket, Data} +
    • +
    • {Closed, Socket} +
    • +
    • {Error, Socket, Reason} +
    • +
    +

    The value of OK, Closed and Error can be different depending on the transport being used. To be able to properly match on them you must first call the Transport:messages/0 function.

    +
    Retrieving the transport's active message identifiers
    +
    +
    {OK, Closed, Error} = Transport:messages().
    +
    +

    To start receiving messages you will need to call the Transport:setopts/2 function, and do so every time you want to receive data.

    +
    Receiving messages from the socket in active mode
    +
    +
    {OK, Closed, Error} = Transport:messages(),
    +Transport:setopts(Socket, [{active, once}]),
    +receive
    +	{OK, Socket, Data} ->
    +		io:format("data received: ~p~n", [Data]);
    +	{Closed, Socket} ->
    +		io:format("socket got closed!~n");
    +	{Error, Socket, Reason} ->
    +		io:format("error happened: ~p~n", [Reason])
    +end.
    +
    +

    You can easily integrate active sockets with existing Erlang code as all you really need is just a few more clauses when receiving messages.

    +

    Sending files

    +

    As in the previous section it is assumed Transport is a valid transport handler and Socket is a connected socket obtained through the listener.

    +

    To send a whole file, with name Filename, over a socket:

    +
    Sending a file by filename
    +
    +
    {ok, SentBytes} = Transport:sendfile(Socket, Filename).
    +
    +

    Or part of a file, with Offset greater than or equal to 0, Bytes number of bytes and chunks of size ChunkSize:

    +
    Sending part of a file by filename in chunks
    +
    +
    Opts = [{chunk_size, ChunkSize}],
    +{ok, SentBytes} = Transport:sendfile(Socket, Filename, Offset, Bytes, Opts).
    +
    +

    To improve efficiency when sending multiple parts of the same file it is also possible to use a file descriptor opened in raw mode:

    +
    Sending a file opened in raw mode
    +
    +
    {ok, RawFile} = file:open(Filename, [raw, read, binary]),
    +{ok, SentBytes} = Transport:sendfile(Socket, RawFile, Offset, Bytes, Opts).
    +
    +

    Writing a transport handler

    +

    A transport handler is a module implementing the ranch_transport behavior. It defines a certain number of callbacks that must be written in order to allow transparent usage of the transport handler.

    +

    The behavior doesn't define the socket options available when opening a socket. These do not need to be common to all transports as it's easy enough to write different initialization functions for the different transports that will be used. With one exception though. The setopts/2 function must implement the {active, once} and the {active, true} options.

    +

    If the transport handler doesn't have a native implementation of sendfile/5 a fallback is available, ranch_transport:sendfile/6. The extra first argument is the transport's module. See ranch_ssl for an example.

    + + + + + + + + + + + + + + + + +
    + +
    + + +

    + Ranch + 1.5 + + User Guide +

    + + + +

    Navigation

    + +

    Version select

    + + +
    +
    +
    +
    + + + + + + + + + diff --git a/docs/en/ranch/1.5/manual/index.html b/docs/en/ranch/1.5/manual/index.html new file mode 100644 index 00000000..7a40ebd6 --- /dev/null +++ b/docs/en/ranch/1.5/manual/index.html @@ -0,0 +1,152 @@ + + + + + + + + + + Nine Nines: Ranch Function Reference + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +

    Ranch Function Reference

    + + + + + + + + +
    + +
    + + +

    + Ranch + 1.5 + Function Reference + +

    + + + +

    Navigation

    + +

    Version select

    + + +
    +
    +
    +
    + + + + + + + + + diff --git a/docs/en/ranch/1.5/manual/ranch/index.html b/docs/en/ranch/1.5/manual/ranch/index.html new file mode 100644 index 00000000..f3c2d021 --- /dev/null +++ b/docs/en/ranch/1.5/manual/ranch/index.html @@ -0,0 +1,364 @@ + + + + + + + + + + Nine Nines: ranch(3) + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +

    ranch(3)

    + +

    Name

    +

    ranch - socket acceptor pool

    +

    Description

    +

    The ranch module provides functions for starting and manipulating Ranch listeners.

    +

    Types

    +

    max_conns() = non_neg_integer() | infinity

    +

    Maximum number of connections allowed on this listener.

    +

    This is a soft limit. The actual number of connections might be slightly above the limit due to concurrency when accepting new connections. Some connections may also be removed from this count explicitly by the user code.

    +

    opt()

    +
    +
    opt() = {ack_timeout, timeout()}
    +	| {connection_type, worker | supervisor}
    +	| {max_connections, max_conns()}
    +	| {num_acceptors, pos_integer()}
    +	| {shutdown, timeout() | brutal_kill}
    +	| {socket, any()}
    +
    +

    Ranch-specific transport options.

    +

    These options are not passed on to the transports. They are used by Ranch while setting up the listeners.

    +

    ref() = any()

    +

    Unique name used to refer to a listener.

    +

    Option descriptions

    +

    None of the options are required.

    +
    ack_timeout (5000)
    +

    Maximum allowed time for the ranch:accept_ack/1 call to finish.

    +
    +
    connection_type (worker)
    +

    Type of process that will handle the connection.

    +
    +
    max_connections (1024)
    +

    Maximum number of active connections. Soft limit. Using infinity will disable the limit entirely.

    +
    +
    num_acceptors (10)
    +

    Number of processes that accept connections.

    +
    +
    shutdown (5000)
    +

    Maximum allowed time for children to stop on listener shutdown.

    +
    +
    socket
    +

    Listening socket opened externally to be used instead of calling Transport:listen/1.

    +
    +
    +

    Exports

    +

    accept_ack(Ref) -> ok

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    +

    Acknowledge that the connection is accepted.

    +

    This function MUST be used by a connection process to inform Ranch that it initialized properly and let it perform any additional operations before the socket can be safely used.

    +

    child_spec(Ref, NumAcceptors, Transport, TransOpts, Protocol, ProtoOpts) -> supervisor:child_spec()

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    NumAcceptors = non_neg_integer()
    +

    Number of acceptor processes.

    +
    +
    Transport = module()
    +

    Transport module.

    +
    +
    TransOpts = any()
    +

    Transport options.

    +
    +
    Protocol = module()
    +

    Protocol module.

    +
    +
    ProtoOpts = any()
    +

    Protocol options.

    +
    +
    +

    Return child specifications for a new listener.

    +

    This function can be used to embed a listener directly in an application instead of letting Ranch handle it.

    +

    get_addr(Ref) -> {IP, Port}

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    IP = inet:ip_address()
    +

    IP of the interface used by this listener.

    +
    +
    Port = inet:port_number()
    +

    Port number used by this listener.

    +
    +
    +

    Return the IP address and port for the given listener.

    +

    get_max_connections(Ref) -> MaxConns

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    MaxConns = max_conns()
    +

    Current maximum number of connections.

    +
    +
    +

    Return the max number of connections allowed for the given listener.

    +

    get_port(Ref) -> Port

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    Port = inet:port_number()
    +

    Port number used by this listener.

    +
    +
    +

    Return the port for the given listener.

    +

    get_protocol_options(Ref) -> ProtoOpts

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    ProtoOpts = any()
    +

    Current protocol options.

    +
    +
    +

    Return the protocol options set for the given listener.

    +

    info() -> [{Ref, [{Key, Value}]}]

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    Key = atom()
    +

    Information key.

    +
    +
    Value = any()
    +

    Information value.

    +
    +
    +

    Return detailed information about all Ranch listeners.

    +

    The following keys are defined:

    +
    pid
    +

    Pid of the listener's top-level supervisor.

    +
    +
    ip
    +

    Interface Ranch listens on.

    +
    +
    port
    +

    Port number Ranch listens on.

    +
    +
    num_acceptors
    +

    Number of acceptor processes.

    +
    +
    max_connections
    +

    Maximum number of connections.

    +
    +
    active_connections
    +

    Number of active connections.

    +
    +
    all_connections
    +

    Number of connections, including those removed from the count.

    +
    +
    transport
    +

    Transport module.

    +
    +
    transport_options
    +

    Transport options.

    +
    +
    protocol
    +

    Protocol module.

    +
    +
    protocol_options
    +

    Protocol options.

    +
    +
    +

    procs(Ref, acceptors | connections) -> [pid()]

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    +

    Return all acceptor or connection processes for one listener.

    +

    remove_connection(Ref) -> ok

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    +

    Do not count this connection when limiting the number of connections.

    +

    You can use this function for long-running connection processes which spend most of their time idling rather than consuming resources. This allows Ranch to accept a lot more connections without sacrificing the latency of the system.

    +

    This function may only be called from a connection process.

    +

    set_max_connections(Ref, MaxConns) -> ok

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    MaxConns = max_conns()
    +

    New maximum number of connections.

    +
    +
    +

    Set the max number of connections for the given listener.

    +

    The change will be applied immediately. If the new value is smaller than the previous one, Ranch will not kill the extra connections, but will wait for them to terminate properly.

    +

    set_protocol_options(Ref, ProtoOpts) -> ok

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    ProtoOpts = any()
    +

    New protocol options.

    +
    +
    +

    Set the protocol options for the given listener.

    +

    The change will be applied immediately for all new connections. Old connections will not receive the new options.

    +

    start_listener(Ref, NumAcceptors, Transport, TransOpts, Protocol, ProtoOpts) -> {ok, pid()} | {error, badarg}

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    NumAcceptors = non_neg_integer()
    +

    Number of acceptor processes.

    +
    +
    Transport = module()
    +

    Transport module.

    +
    +
    TransOpts = any()
    +

    Transport options.

    +
    +
    Protocol = module()
    +

    Protocol module.

    +
    +
    ProtoOpts = any()
    +

    Protocol options.

    +
    +
    +

    Start listening for connections using the given transport and protocol. Returns the pid for this listener's supervisor.

    +

    There are additional transport options that apply regardless of transport. They allow configuring how the connections are supervised, rate limited and more. Please consult the previous section for more details.

    +

    stop_listener(Ref) -> ok | {error, not_found}

    +
    Ref = ref()
    +

    Listener name.

    +
    +
    +

    Stop the given listener.

    +

    The listener is stopped gracefully, first by closing the listening port, then by stopping the connection processes. These processes are stopped according to the shutdown transport option, which may be set to brutally kill all connection processes or give them some time to stop properly.

    +

    This function does not return until the listener is completely stopped.

    + + + + + + +
    + +
    + + +

    + Ranch + 1.5 + Function Reference + +

    + + + +

    Navigation

    + +

    Version select

    + + +
    +
    +
    +
    + + + + + + + + + diff --git a/docs/en/ranch/1.5/manual/ranch_app/index.html b/docs/en/ranch/1.5/manual/ranch_app/index.html new file mode 100644 index 00000000..0cf53650 --- /dev/null +++ b/docs/en/ranch/1.5/manual/ranch_app/index.html @@ -0,0 +1,150 @@ + + + + + + + + + + Nine Nines: ranch(7) + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +

    ranch(7)

    + +

    Name

    +

    ranch - Socket acceptor pool for TCP protocols.

    +

    Dependencies

    +

    The ranch application depends on the ssl application to start. It is used for handling secure connections, when the transport is ranch_ssl. It can be disabled if SSL is not used.

    +

    Environment

    +

    The ranch application defines one application environment configuration parameter.

    +
    profile (false)
    +

    When enabled, Ranch will start eprof profiling automatically.

    +
    +
    +

    You can use the ranch_app:profile_output/0 function to stop profiling and output the results to the files procs.profile and total.profile. Do not use in production.

    + + + + + + +
    + +
    + + +

    + Ranch + 1.5 + Function Reference + +

    + + + +

    Navigation

    + +

    Version select

    + + +
    +
    +
    +
    + + + + + + + + + diff --git a/docs/en/ranch/1.5/manual/ranch_protocol/index.html b/docs/en/ranch/1.5/manual/ranch_protocol/index.html new file mode 100644 index 00000000..507edc7d --- /dev/null +++ b/docs/en/ranch/1.5/manual/ranch_protocol/index.html @@ -0,0 +1,165 @@ + + + + + + + + + + Nine Nines: ranch_protocol(3) + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +

    ranch_protocol(3)

    + +

    Name

    +

    ranch_protocol - behaviour for protocol modules

    +

    Description

    +

    The ranch_protocol behaviour defines the interface used by Ranch protocols.

    +

    Types

    +

    None.

    +

    Callbacks

    + +
    Ref = ranch:ref()
    +

    Listener name.

    +
    +
    Socket = any()
    +

    Socket for this connection.

    +
    +
    Transport = module()
    +

    Transport module for this socket.

    +
    +
    ProtoOpts = any()
    +

    Protocol options.

    +
    +
    +

    Start a new connection process for the given socket.

    +

    The only purpose of this callback is to start a process that will handle the socket. It must spawn the process, link and then return the new pid. This function will always be called from inside a supervisor.

    +

    This callback can also return two pids. The first pid is the pid of the process that will be supervised. The second pid is the pid of the process that will receive ownership of the socket. This second process must be a child of the first. This form is only available when connection_type is set to supervisor.

    +

    If any other value is returned, the supervisor will close the socket and assume no process has been started.

    +

    Do not perform any operations in this callback, as this would block the supervisor responsible for starting connection processes and degrade performance severely.

    + + + + + + +
    + +
    + + +

    + Ranch + 1.5 + Function Reference + +

    + + + +

    Navigation

    + +

    Version select

    + + +
    +
    +
    +
    + + + + + + + + + diff --git a/docs/en/ranch/1.5/manual/ranch_ssl/index.html b/docs/en/ranch/1.5/manual/ranch_ssl/index.html new file mode 100644 index 00000000..139f475c --- /dev/null +++ b/docs/en/ranch/1.5/manual/ranch_ssl/index.html @@ -0,0 +1,306 @@ + + + + + + + + + + Nine Nines: ranch_ssl(3) + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +

    ranch_ssl(3)

    + +

    Name

    +

    ranch_ssl - SSL transport module

    +

    Description

    +

    The ranch_ssl module implements an SSL Ranch transport.

    +

    Types

    +

    ssl_opt()

    +
    +
    ssl_opt() = {alpn_preferred_protocols, [binary()]}
    +	| {beast_mitigation, one_n_minus_one | zero_n | disabled}
    +	| {cacertfile, string()}
    +	| {cacerts, [public_key:der_encoded()]}
    +	| {cert, public_key:der_encoded()}
    +	| {certfile, string()}
    +	| {ciphers, [ssl:erl_cipher_suite()] | string()}
    +	| {client_renegotiation, boolean()}
    +	| {crl_cache, {module(), {internal | any(), list()}}}
    +	| {crl_check, boolean() | peer | best_effort}
    +	| {depth, 0..255}
    +	| {dh, public_key:der_encoded()}
    +	| {dhfile, string()}
    +	| {fail_if_no_peer_cert, boolean()}
    +	| {hibernate_after, integer() | undefined}
    +	| {honor_cipher_order, boolean()}
    +	| {key, {'RSAPrivateKey' | 'DSAPrivateKey' | 'PrivateKeyInfo', public_key:der_encoded()}}
    +	| {keyfile, string()}
    +	| {log_alert, boolean()}
    +	| {next_protocols_advertised, [binary()]}
    +	| {padding_check, boolean()}
    +	| {partial_chain, fun(([public_key:der_encoded()]) -> {trusted_ca, public_key:der_encoded()} | unknown_ca)}
    +	| {password, string()}
    +	| {psk_identity, string()}
    +	| {reuse_session, fun()}
    +	| {reuse_sessions, boolean()}
    +	| {secure_renegotiate, boolean()}
    +	| {signature_algs, [{atom(), atom()}]}
    +	| {sni_fun, fun()}
    +	| {sni_hosts, [{string(), ssl_opt()}]}
    +	| {user_lookup_fun, {fun(), any()}}
    +	| {v2_hello_compatible, boolean()}
    +	| {verify, ssl:verify_type()}
    +	| {verify_fun, {fun(), any()}}
    +	| {versions, [atom()]}.
    +
    +

    SSL-specific listen options.

    +

    opt() = ranch_tcp:opt() | ssl_opt()

    +

    Listen options.

    +

    opts() = [opt()]

    +

    List of listen options.

    +

    Option descriptions

    +

    Specifying a certificate is mandatory, either through the cert or the certfile option. None of the other options are required.

    +

    The default value is given next to the option name.

    +
    alpn_preferred_protocols
    +

    Perform Application-Layer Protocol Negotiation with the given list of preferred protocols.

    +
    +
    beast_mitigation
    +

    Change the BEAST mitigation strategy for SSL-3.0 and TLS-1.0 to interoperate with legacy software.

    +
    +
    cacertfile
    +

    Path to PEM encoded trusted certificates file used to verify peer certificates.

    +
    +
    cacerts
    +

    List of DER encoded trusted certificates.

    +
    +
    cert
    +

    DER encoded user certificate.

    +
    +
    certfile
    +

    Path to the PEM encoded user certificate file. May also contain the private key.

    +
    +
    ciphers
    +

    List of ciphers that clients are allowed to use.

    +
    +
    client_renegotiation (true)
    +

    Whether to allow client-initiated renegotiation.

    +
    +
    crl_cache ({ssl_crl_cache, {internal, []}})
    +

    Customize the module used to cache Certificate Revocation Lists.

    +
    +
    crl_check (false)
    +

    Whether to perform CRL check on all certificates in the chain during validation.

    +
    +
    depth (1)
    +

    Maximum of intermediate certificates allowed in the certification path.

    +
    +
    dh
    +

    DER encoded Diffie-Hellman parameters.

    +
    +
    dhfile
    +

    Path to the PEM encoded Diffie-Hellman parameters file.

    +
    +
    fail_if_no_peer_cert (false)
    +

    Whether to refuse the connection if the client sends an empty certificate.

    +
    +
    hibernate_after (undefined)
    +

    Time in ms after which SSL socket processes go into hibernation to reduce memory usage.

    +
    +
    honor_cipher_order (false)
    +

    If true, use the server's preference for cipher selection. If false, use the client's preference.

    +
    +
    key
    +

    DER encoded user private key.

    +
    +
    keyfile
    +

    Path to the PEM encoded private key file, if different than the certfile.

    +
    +
    log_alert (true)
    +

    If false, error reports will not be displayed.

    +
    +
    next_protocols_advertised
    +

    List of protocols to send to the client if it supports the Next Protocol extension.

    +
    +
    nodelay (true)
    +

    Whether to enable TCP_NODELAY.

    +
    +
    padding_check
    +

    Allow disabling the block cipher padding check for TLS-1.0 to be able to interoperate with legacy software.

    +
    +
    partial_chain
    +

    Claim an intermediate CA in the chain as trusted.

    +
    +
    password
    +

    Password to the private key file, if password protected.

    +
    +
    psk_identity
    +

    Provide the given PSK identity hint to the client during the handshake.

    +
    +
    reuse_session
    +

    Custom policy to decide whether a session should be reused.

    +
    +
    reuse_sessions (false)
    +

    Whether to allow session reuse.

    +
    +
    secure_renegotiate (false)
    +

    Whether to reject renegotiation attempts that do not conform to RFC5746.

    +
    +
    signature_algs
    +

    The TLS signature algorithm extension may be used, from TLS 1.2, to negotiate which signature algorithm to use during the TLS handshake.

    +
    +
    sni_fun
    +

    Function called when the client requests a host using Server Name Indication. Returns options to apply.

    +
    +
    sni_hosts
    +

    Options to apply for the host that matches what the client requested with Server Name Indication.

    +
    +
    user_lookup_fun
    +

    Function called to determine the shared secret when using PSK, or provide parameters when using SRP.

    +
    +
    v2_hello_compatible
    +

    Accept clients that send hello messages in SSL-2.0 format while offering supported SSL/TLS versions.

    +
    +
    verify (verify_none)
    +

    Use verify_peer to request a certificate from the client.

    +
    +
    verify_fun
    +

    Custom policy to decide whether a client certificate is valid.

    +
    +
    versions
    +

    TLS protocol versions that will be supported.

    +
    +
    +

    Note that the client will not send a certificate unless the value for the verify option is set to verify_peer. This means that the fail_if_no_peer_cert only apply when combined with the verify option. The verify_fun option allows greater control over the client certificate validation.

    +

    The options sni_fun and sni_hosts are mutually exclusive.

    +

    Exports

    +

    None.

    + + + + + + +
    + +
    + + +

    + Ranch + 1.5 + Function Reference + +

    + + + +

    Navigation

    + +

    Version select

    + + +
    +
    +
    +
    + + + + + + + + + diff --git a/docs/en/ranch/1.5/manual/ranch_tcp/index.html b/docs/en/ranch/1.5/manual/ranch_tcp/index.html new file mode 100644 index 00000000..ce4f4adc --- /dev/null +++ b/docs/en/ranch/1.5/manual/ranch_tcp/index.html @@ -0,0 +1,259 @@ + + + + + + + + + + Nine Nines: ranch_tcp(3) + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +

    ranch_tcp(3)

    + +

    Name

    +

    ranch_tcp - TCP transport module

    +

    Description

    +

    The ranch_tcp module implements a TCP Ranch transport.

    +

    Note that due to bugs in OTP up to at least R16B02, it is recommended to disable async threads when using the sendfile function of this transport, as it can make the threads stuck indefinitely.

    +

    Types

    +

    opt()

    +
    +
    opt() = {backlog, non_neg_integer()}
    +	| {buffer, non_neg_integer()}
    +	| {delay_send, boolean()}
    +	| {dontroute, boolean()}
    +	| {exit_on_close, boolean()}
    +	| {fd, non_neg_integer()}
    +	| {high_msgq_watermark, non_neg_integer()}
    +	| {high_watermark, non_neg_integer()}
    +	| inet
    +	| inet6
    +	| {ip, inet:ip_address()}
    +	| {ipv6_v6only, boolean()}
    +	| {keepalive, boolean()}
    +	| {linger, {boolean(), non_neg_integer()}}
    +	| {low_msgq_watermark, non_neg_integer()}
    +	| {low_watermark, non_neg_integer()}
    +	| {nodelay, boolean()}
    +	| {port, inet:port_number()}
    +	| {priority, integer()}
    +	| {raw, non_neg_integer(), non_neg_integer(), binary()}
    +	| {recbuf, non_neg_integer()}
    +	| {send_timeout, timeout()}
    +	| {send_timeout_close, boolean()}
    +	| {sndbuf, non_neg_integer()}
    +	| {tos, integer()}
    +
    +

    Listen options.

    +

    This does not represent the entirety of the options that can be set on the socket, but only the options that may be set independently of protocol implementation.

    +

    opts() = [opt()]

    +

    List of listen options.

    +

    Option descriptions

    +

    None of the options are required.

    +

    Please consult the gen_tcp and inet manuals for a more thorough description of these options. This manual only aims to provide a short description along with what the defaults are. Defaults may be different in Ranch compared to gen_tcp. Defaults are given next to the option name.

    +
    backlog (1024)
    +

    Max length of the queue of pending connections.

    +
    +
    buffer
    +

    Size of the buffer used by the Erlang driver. Default is system-dependent.

    +
    +
    delay_send (false)
    +

    Always queue packets before sending, to send fewer, larger packets over the network.

    +
    +
    dontroute (false)
    +

    Don't send via a gateway, only send to directly connected hosts.

    +
    +
    exit_on_close (true)
    +

    Disable to allow sending data after a close has been detected.

    +
    +
    fd
    +

    File descriptor of the socket, if it was opened externally.

    +
    +
    high_msgq_watermark (8192)
    +

    Limit in the amount of data in the socket message queue before the socket queue becomes busy.

    +
    +
    high_watermark (8192)
    +

    Limit in the amount of data in the ERTS socket implementation's queue before the socket becomes busy.

    +
    +
    inet
    +

    Set up the socket for IPv4.

    +
    +
    inet6
    +

    Set up the socket for IPv6.

    +
    +
    ip
    +

    Interface to listen on. Listen on all interfaces by default.

    +
    +
    ipv6_v6only (false)
    +

    Listen on IPv4 and IPv6 (false) or only on IPv6 (true). Use with inet6.

    +
    +
    keepalive (false)
    +

    Enable sending of keep-alive messages.

    +
    +
    linger ({false, 0})
    +

    Whether to wait and how long to flush data sent before closing the socket.

    +
    +
    low_msgq_watermark (4096)
    +

    Amount of data in the socket message queue before the socket queue leaves busy state.

    +
    +
    low_watermark (4096)
    +

    Amount of data in the ERTS socket implementation's queue before the socket leaves busy state.

    +
    +
    nodelay (true)
    +

    Whether to enable TCP_NODELAY.

    +
    +
    port (0)
    +

    TCP port number to listen on. 0 means a random port will be used.

    +
    +
    priority (0)
    +

    Priority value for all packets to be sent by this socket.

    +
    +
    recbuf
    +

    Minimum size of the socket's receive buffer. Default is system-dependent.

    +
    +
    send_timeout (30000)
    +

    How long the send call may wait for confirmation before returning.

    +
    +
    send_timeout_close (true)
    +

    Whether to close the socket when the confirmation wasn't received.

    +
    +
    sndbuf
    +

    Minimum size of the socket's send buffer. Default is system-dependent.

    +
    +
    tos
    +

    Value for the IP_TOS IP level option. Use with caution.

    +
    +
    +

    In addition, the raw option can be used to set system-specific options by specifying the protocol level, the option number and the actual option value specified as a binary. This option is not portable. Use with caution.

    +

    Exports

    +

    None.

    + + + + + + +
    + +
    + + +

    + Ranch + 1.5 + Function Reference + +

    + + + +

    Navigation

    + +

    Version select

    + + +
    +
    +
    +
    + + + + + + + + + diff --git a/docs/en/ranch/1.5/manual/ranch_transport/index.html b/docs/en/ranch/1.5/manual/ranch_transport/index.html new file mode 100644 index 00000000..87994787 --- /dev/null +++ b/docs/en/ranch/1.5/manual/ranch_transport/index.html @@ -0,0 +1,363 @@ + + + + + + + + + + Nine Nines: ranch_transport(3) + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +

    ranch_transport(3)

    + +

    Name

    +

    ranch_transport - behaviour for transport modules

    +

    Description

    +

    The ranch_transport behaviour defines the interface used by Ranch transports.

    +

    Types

    +

    sendfile_opts() = [{chunk_size, non_neg_integer()}]

    +

    Options used by the sendfile function and callbacks.

    +

    Allows configuring the chunk size, in bytes. Defaults to 8191 bytes.

    +

    Callbacks

    +

    accept(LSocket, Timeout) -> {ok, CSocket} | {error, closed | timeout | atom()}

    +
    LSocket = CSocket = any()
    +

    Listening socket.

    +
    +
    Timeout = timeout()
    +

    Accept timeout.

    +
    +
    +

    Accept a connection on the given listening socket.

    +

    The accept_ack callback will be used to initialize the socket after accepting the connection. This is most useful when the transport is not raw TCP, like with SSL for example.

    +

    accept_ack(CSocket, Timeout) -> ok

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    Timeout = timeout()
    +

    Ack timeout.

    +
    +
    +

    Perform post-accept initialization of the connection.

    +

    This function will be called by connection processes before performing any socket operation. It allows transports that require extra initialization to perform their task and make the socket ready to use.

    +

    close(Socket) -> ok

    +
    Socket = any()
    +

    Socket opened with listen/1 or accept/2.

    +
    +
    +

    Close the given socket.

    +

    controlling_process(Socket, Pid) -> ok | {error, closed | not_owner | atom()}

    +
    Socket = any()
    +

    Socket opened with listen/1 or accept/2.

    +
    +
    Pid = pid()
    +

    Pid of the new owner of the socket.

    +
    +
    +

    Change the controlling process for the given socket.

    +

    The controlling process is the process that is allowed to perform operations on the socket, and that will receive messages from the socket when active mode is used. When the controlling process dies, the socket is closed.

    +

    listen(TransOpts) -> {ok, LSocket} | {error, atom()}

    +
    TransOpts = any()
    +

    Transport options.

    +
    +
    LSocket = any()
    +

    Listening socket.

    +
    +
    +

    Listen for connections on the given port.

    +

    The port is given as part of the transport options under the key port. Any other option is transport dependent.

    +

    The socket returned by this call can then be used to accept connections. It is not possible to send or receive data from the listening socket.

    +

    messages() -> {OK, Closed, Error}

    +
    OK = Closed = Error = atom()
    +

    Tuple names.

    +
    +
    +

    Return the atoms used to identify messages sent in active mode.

    +

    name() -> Name

    +
    Name = atom()
    +

    Transport module name.

    +
    +
    +

    Return the name of the transport.

    +

    peername(CSocket) -> {ok, {IP, Port}} | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    IP = inet:ip_address()
    +

    IP of the remote endpoint.

    +
    +
    Port = inet:port_number()
    +

    Port of the remote endpoint.

    +
    +
    +

    Return the IP and port of the remote endpoint.

    +

    recv(CSocket, Length, Timeout) -> {ok, Packet} | {error, closed | timeout | atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    Length = non_neg_integer()
    +

    Requested length.

    +
    +
    Timeout = timeout()
    +

    Receive timeout.

    +
    +
    Packet = iodata() | any()
    +

    Data received.

    +
    +
    +

    Receive data from the given socket when in passive mode.

    +

    Trying to receive data from a socket that is in active mode will return an error.

    +

    A length of 0 will return any data available on the socket.

    +

    While it is possible to use the timeout value infinity, this is highly discouraged as this could cause your process to get stuck waiting for data that will never come. This may happen when a socket becomes half-open due to a crash of the remote endpoint. Wi-Fi going down is another common culprit of this issue.

    +

    send(CSocket, Packet) -> ok | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    Packet = iodata()
    +

    Data to be sent.

    +
    +
    +

    Send data to the given socket.

    +

    sendfile(CSocket, File) -> sendfile(CSocket, File, 0, 0, [])

    +

    Alias of ranch_transport:sendfile/5.

    +

    sendfile(CSocket, File, Offset, Bytes) -> sendfile(CSocket, File, Offset, Bytes, [])

    +

    Alias of ranch_transport:sendfile/5.

    +

    sendfile(CSocket, File, Offset, Bytes, SfOpts) -> {ok, SentBytes} | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    File = file:filename_all() | file:fd()
    +

    Filename or file descriptor for the file to be sent.

    +
    +
    Offset = non_neg_integer()
    +

    Begin sending at this position in the file.

    +
    +
    Bytes = non_neg_integer()
    +

    Send this many bytes.

    +
    +
    SentBytes = non_neg_integer()
    +

    This many bytes were sent.

    +
    +
    SfOpts = sendfile_opts()
    +

    Sendfile options.

    +
    +
    +

    Send data from a file to the given socket.

    +

    The file may be sent full or in parts, and may be specified by its filename or by an already open file descriptor.

    +

    Transports that manipulate TCP directly may use the file:sendfile/{2,4,5} function, which calls the sendfile syscall where applicable (on Linux, for example). Other transports can use the sendfile/6 function exported from this module.

    +

    setopts(CSocket, SockOpts) -> ok | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    SockOpts = any()
    +

    Socket options.

    +
    +
    +

    Change options for the given socket.

    +

    This is mainly useful for switching to active or passive mode or to set protocol-specific options.

    +

    getopts(CSocket, SockOpts) -> {ok, SockOptValues} | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    SockOpts = [atom]
    +

    Socket option names.

    +
    +
    SockOptValues = list()
    +

    Socket options.

    +
    +
    +

    Get options for the given socket.

    +

    getstat(CSocket) -> {ok, SockStatValues} | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    SockStatValues = list()
    +

    Socket statistics.

    +
    +
    +

    Get statistics for the given socket.

    +

    getstat(CSocket, SockStats) -> {ok, SockStatValues} | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    SockStats = [atom()]
    +

    Socket statistic names.

    +
    +
    SockStatValues = list()
    +

    Socket statistics.

    +
    +
    +

    Get statistics for the given socket.

    +

    shutdown(CSocket, How) -> ok | {error, atom()}

    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    How = read | write | read_write
    +

    Which side(s) of the socket to close.

    +
    +
    +

    Immediately close the socket in one or two directions.

    +

    sockname(Socket) -> {ok, {IP, Port}} | {error, atom()}

    +
    Socket = any()
    +

    Socket opened with listen/1 or accept/2.

    +
    +
    IP = inet:ip_address()
    +

    IP of the local endpoint.

    +
    +
    Port = inet:port_number()
    +

    Port of the local endpoint.

    +
    +
    +

    Return the IP and port of the local endpoint.

    +

    Exports

    +

    sendfile(Transport, CSocket, File, Offset, Bytes, SfOpts) -> {ok, SentBytes} | {error, atom()}

    +
    Transport = module()
    +

    Transport module for this socket.

    +
    +
    CSocket = any()
    +

    Socket for this connection.

    +
    +
    File = file:filename_all() | file:fd()
    +

    Filename or file descriptor for the file to be sent.

    +
    +
    Offset = non_neg_integer()
    +

    Begin sending at this position in the file.

    +
    +
    Bytes = non_neg_integer()
    +

    Send this many bytes.

    +
    +
    SentBytes = non_neg_integer()
    +

    This many bytes were sent.

    +
    +
    SfOpts = sendfile_opts()
    +

    Sendfile options.

    +
    +
    +

    Send data from a file to the given socket.

    +

    This function emulates the function file:sendfile/{2,4,5} and may be used when transports are not manipulating TCP directly.

    + + + + + + +
    + +
    + + +

    + Ranch + 1.5 + Function Reference + +

    + + + +

    Navigation

    + +

    Version select

    + + +
    +
    +
    +
    + + + + + + + + + diff --git a/docs/index.html b/docs/index.html index f7a623bf..0070fe3a 100644 --- a/docs/index.html +++ b/docs/index.html @@ -146,6 +146,13 @@ -

    Contribute

    -

    Do you have examples, tutorials, videos about one or more -of my projects? I would happily include them on this page.

    - -
    +

    Do you have examples, tutorials, videos about one or more of my projects? I would happily include them on this page.

    +

    Send me an email with the details.

    + diff --git a/docs/index.xml b/docs/index.xml index 1089c86f..33a58867 100644 --- a/docs/index.xml +++ b/docs/index.xml @@ -17,8 +17,9 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/installation/ On Unix Erlang.mk requires GNU Make to be installed. While it will currently work with GNU Make 3.81, support for this version is deprecated and will be removed in 2017. We recommend GNU Make 4.1 or later. - Git and Erlang/OTP must also be installed. - Some functionality requires that Autoconf 2.59 or later be installed, in order to compile Erlang/OTP. Erlang/OTP may have further requirements depending on your needs. +Git and Erlang/OTP must also be installed. +Some functionality requires that Autoconf 2.59 or later be installed, in order to compile Erlang/OTP. Erlang/OTP may have further requirements depending on your needs. +Some packages may require additional libraries. @@ -28,11 +29,12 @@ https://ninenines.eu/docs/en/gun/1.0/guide/introduction/ Gun is an HTTP client for Erlang/OTP. - Gun supports the HTTP/2, HTTP/1.1 and Websocket protocols. - Prerequisites Knowledge of Erlang, but also of the HTTP/1.1, HTTP/2 and Websocket protocols is required in order to read this guide. - Supported platforms Gun is tested and supported on Linux, FreeBSD, Windows and OSX. - Gun is developed for Erlang/OTP 19.0 and newer. - License Gun uses the ISC License. +Gun supports the HTTP/2, HTTP/1.1 and Websocket protocols. +Prerequisites Knowledge of Erlang, but also of the HTTP/1.1, HTTP/2 and Websocket protocols is required in order to read this guide. +Supported platforms Gun is tested and supported on Linux, FreeBSD, Windows and OSX. +Gun is developed for Erlang/OTP 19.0 and newer. +License Gun uses the ISC License. +Copyright (c) 2013-2018, Loïc Hoguin &lt;essen@ninenines.eu&gt; Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. @@ -42,9 +44,9 @@ https://ninenines.eu/docs/en/ranch/1.2/guide/introduction/ Ranch is a socket acceptor pool for TCP protocols. - Ranch aims to provide everything you need to accept TCP connections with a small code base and low latency while being easy to use directly as an application or to embed into your own. - Prerequisites It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols. - Supported platforms Ranch is tested and supported on Linux. +Ranch aims to provide everything you need to accept TCP connections with a small code base and low latency while being easy to use directly as an application or to embed into your own. +Prerequisites It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols. +Supported platforms Ranch is tested and supported on Linux. @@ -54,9 +56,9 @@ https://ninenines.eu/docs/en/ranch/1.3/guide/introduction/ Ranch is a socket acceptor pool for TCP protocols. - Ranch aims to provide everything you need to accept TCP connections with a small code base and low latency while being easy to use directly as an application or to embed into your own. - Prerequisites It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols. - Supported platforms Ranch is tested and supported on Linux, FreeBSD, OSX and Windows. +Ranch aims to provide everything you need to accept TCP connections with a small code base and low latency while being easy to use directly as an application or to embed into your own. +Prerequisites It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols. +Supported platforms Ranch is tested and supported on Linux, FreeBSD, OSX and Windows. @@ -66,9 +68,21 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/introduction/ Ranch is a socket acceptor pool for TCP protocols. - Ranch aims to provide everything you need to accept TCP connections with a small code base and low latency while being easy to use directly as an application or to embed into your own. - Prerequisites It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols. - Supported platforms Ranch is tested and supported on Linux, FreeBSD, OSX and Windows. +Ranch aims to provide everything you need to accept TCP connections with a small code base and low latency while being easy to use directly as an application or to embed into your own. +Prerequisites It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols. +Supported platforms Ranch is tested and supported on Linux, FreeBSD, OSX and Windows. + + + + Introduction + https://ninenines.eu/docs/en/ranch/1.5/guide/introduction/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/guide/introduction/ + Ranch is a socket acceptor pool for TCP protocols. +Ranch aims to provide everything you need to accept TCP connections with a small code base and low latency while being easy to use directly as an application or to embed into your own. +Prerequisites It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols. +Supported platforms Ranch is tested and supported on Linux, FreeBSD, OSX and Windows. @@ -78,8 +92,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/modern_web/ Cowboy is a server for the modern Web. This chapter explains what it means and details all the standards involved. - Cowboy supports all the standards listed in this document. - HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. +Cowboy supports all the standards listed in this document. +HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. The protocol is binary, greatly reducing the resources needed to parse it. @@ -89,8 +103,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/modern_web/ Cowboy is a server for the modern Web. This chapter explains what it means and details all the standards involved. - Cowboy supports all the standards listed in this document. - HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. +Cowboy supports all the standards listed in this document. +HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. The protocol is binary, greatly reducing the resources needed to parse it. @@ -100,8 +114,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/modern_web/ Cowboy is a server for the modern Web. This chapter explains what it means and details all the standards involved. - Cowboy supports all the standards listed in this document. - HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. +Cowboy supports all the standards listed in this document. +HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. The protocol is binary, greatly reducing the resources needed to parse it. @@ -111,8 +125,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/modern_web/ Cowboy is a server for the modern Web. This chapter explains what it means and details all the standards involved. - Cowboy supports all the standards listed in this document. - HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. +Cowboy supports all the standards listed in this document. +HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. The protocol is binary, greatly reducing the resources needed to parse it. @@ -122,8 +136,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/modern_web/ Cowboy is a server for the modern Web. This chapter explains what it means and details all the standards involved. - Cowboy supports all the standards listed in this document. - HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. +Cowboy supports all the standards listed in this document. +HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. The protocol is binary, greatly reducing the resources needed to parse it. @@ -133,7 +147,7 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/erlang_web/ Erlang is the ideal platform for writing Web applications. Its features are a perfect match for the requirements of modern Web applications. - The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. +The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. @@ -143,7 +157,7 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/erlang_web/ Erlang is the ideal platform for writing Web applications. Its features are a perfect match for the requirements of modern Web applications. - The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. +The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. @@ -153,7 +167,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/erlang_web/ Erlang is the ideal platform for writing Web applications. Its features are a perfect match for the requirements of modern Web applications. - The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. +The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. @@ -163,7 +177,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/erlang_web/ Erlang is the ideal platform for writing Web applications. Its features are a perfect match for the requirements of modern Web applications. - The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. +The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. @@ -173,7 +187,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/erlang_web/ Erlang is the ideal platform for writing Web applications. Its features are a perfect match for the requirements of modern Web applications. - The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. +The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. @@ -183,8 +197,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/getting_started/ This chapter explains how to get started using Erlang.mk. - Creating a folder for your project The first step is always to create a new folder that will contain your project. - $ mkdir hello_joe $ cd hello_joe Most people tend to put all their projects side by side in a common folder. We recommend keeping an organization similar to your remote repositories. For example, for GitHub users, put all your projects in a common folder with the same name as your username. +Creating a folder for your project The first step is always to create a new folder that will contain your project. +$ mkdir hello_joe $ cd hello_joe Most people tend to put all their projects side by side in a common folder. We recommend keeping an organization similar to your remote repositories. For example, for GitHub users, put all your projects in a common folder with the same name as your username. @@ -194,7 +208,7 @@ https://ninenines.eu/docs/en/ranch/1.2/guide/listeners/ A listener is a set of processes whose role is to listen on a port for new connections. It manages a pool of acceptor processes, each of them indefinitely accepting connections. When it does, it starts a new process executing the protocol handler code. All the socket programming is abstracted through the user of transport handlers. - The listener takes care of supervising all the acceptor and connection processes, allowing developers to focus on building their application. +The listener takes care of supervising all the acceptor and connection processes, allowing developers to focus on building their application. @@ -204,7 +218,7 @@ https://ninenines.eu/docs/en/ranch/1.3/guide/listeners/ A listener is a set of processes whose role is to listen on a port for new connections. It manages a pool of acceptor processes, each of them indefinitely accepting connections. When it does, it starts a new process executing the protocol handler code. All the socket programming is abstracted through the use of transport handlers. - The listener takes care of supervising all the acceptor and connection processes, allowing developers to focus on building their application. +The listener takes care of supervising all the acceptor and connection processes, allowing developers to focus on building their application. @@ -214,7 +228,17 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/listeners/ A listener is a set of processes whose role is to listen on a port for new connections. It manages a pool of acceptor processes, each of them indefinitely accepting connections. When it does, it starts a new process executing the protocol handler code. All the socket programming is abstracted through the use of transport handlers. - The listener takes care of supervising all the acceptor and connection processes, allowing developers to focus on building their application. +The listener takes care of supervising all the acceptor and connection processes, allowing developers to focus on building their application. + + + + Listeners + https://ninenines.eu/docs/en/ranch/1.5/guide/listeners/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/guide/listeners/ + A listener is a set of processes whose role is to listen on a port for new connections. It manages a pool of acceptor processes, each of them indefinitely accepting connections. When it does, it starts a new process executing the protocol handler code. All the socket programming is abstracted through the use of transport handlers. +The listener takes care of supervising all the acceptor and connection processes, allowing developers to focus on building their application. @@ -224,9 +248,10 @@ https://ninenines.eu/docs/en/gun/1.0/guide/start/ This chapter describes how to start and stop the Gun application. - Setting up Specify Gun as a dependency to your application in your favorite build tool. - With Erlang.mk this is done by adding gun to the DEPS variable in your Makefile. - Adding Gun as an Erlang.mk dependency DEPS = gun Starting Gun is an OTP application. It needs to be started before you can use it. +Setting up Specify Gun as a dependency to your application in your favorite build tool. +With Erlang.mk this is done by adding gun to the DEPS variable in your Makefile. +Adding Gun as an Erlang.mk dependency DEPS = gun Starting Gun is an OTP application. It needs to be started before you can use it. +Starting Gun in an Erlang shell 1&gt; application:ensure_all_started(gun). @@ -236,9 +261,9 @@ https://ninenines.eu/docs/en/gun/1.0/guide/protocols/ This chapter describes the protocols supported and the operations available to them. - HTTP/1.1 HTTP/1.1 is a text request-response protocol. The client sends a request, the server sends back a response. - Gun provides convenience functions for performing GET, HEAD, OPTIONS, POST, PATCH, PUT, and DELETE requests. All these functions are aliases of gun:request/4,5,6 for the respective methods. Gun also provides a gun:data/4 function for streaming the request body. - Gun will send a gun_inform message for every intermediate informational responses received. +HTTP/1.1 HTTP/1.1 is a text request-response protocol. The client sends a request, the server sends back a response. +Gun provides convenience functions for performing GET, HEAD, OPTIONS, POST, PATCH, PUT, and DELETE requests. All these functions are aliases of gun:request/4,5,6 for the respective methods. Gun also provides a gun:data/4 function for streaming the request body. +Gun will send a gun_inform message for every intermediate informational responses received. @@ -248,9 +273,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/introduction/ Cowboy is a small, fast and modern HTTP server for Erlang/OTP. - Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. - Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. - Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. +Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. +Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. +Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. @@ -260,9 +285,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/introduction/ Cowboy is a small, fast and modern HTTP server for Erlang/OTP. - Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. - Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. - Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. +Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. +Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. +Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. @@ -272,9 +297,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/introduction/ Cowboy is a small, fast and modern HTTP server for Erlang/OTP. - Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. - Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. - Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. +Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. +Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. +Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. @@ -284,9 +309,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/introduction/ Cowboy is a small, fast and modern HTTP server for Erlang/OTP. - Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. - Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. - Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. +Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. +Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. +Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. @@ -296,9 +321,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/introduction/ Cowboy is a small, fast and modern HTTP server for Erlang/OTP. - Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. - Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. - Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. +Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. +Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. +Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. @@ -308,9 +333,9 @@ https://ninenines.eu/docs/en/ranch/1.2/guide/transports/ A transport defines the interface to interact with a socket. - Transports can be used for connecting, listening and accepting connections, but also for receiving and sending data. Both passive and active mode are supported, although all sockets are initialized as passive. - TCP transport The TCP transport is a thin wrapper around gen_tcp. - SSL transport The SSL transport is a thin wrapper around ssl. It requires the crypto, asn1, public_key and ssl applications to be started. +Transports can be used for connecting, listening and accepting connections, but also for receiving and sending data. Both passive and active mode are supported, although all sockets are initialized as passive. +TCP transport The TCP transport is a thin wrapper around gen_tcp. +SSL transport The SSL transport is a thin wrapper around ssl. It requires the crypto, asn1, public_key and ssl applications to be started. @@ -320,10 +345,10 @@ https://ninenines.eu/docs/en/ranch/1.3/guide/transports/ A transport defines the interface to interact with a socket. - Transports can be used for connecting, listening and accepting connections, but also for receiving and sending data. Both passive and active mode are supported, although all sockets are initialized as passive. - TCP transport The TCP transport is a thin wrapper around gen_tcp. - SSL transport The SSL transport is a thin wrapper around ssl. - Ranch depends on ssl by default so any necessary dependencies will start when Ranch is started. +Transports can be used for connecting, listening and accepting connections, but also for receiving and sending data. Both passive and active mode are supported, although all sockets are initialized as passive. +TCP transport The TCP transport is a thin wrapper around gen_tcp. +SSL transport The SSL transport is a thin wrapper around ssl. +Ranch depends on ssl by default so any necessary dependencies will start when Ranch is started. @@ -333,10 +358,23 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/transports/ A transport defines the interface to interact with a socket. - Transports can be used for connecting, listening and accepting connections, but also for receiving and sending data. Both passive and active mode are supported, although all sockets are initialized as passive. - TCP transport The TCP transport is a thin wrapper around gen_tcp. - SSL transport The SSL transport is a thin wrapper around ssl. - Ranch depends on ssl by default so any necessary dependencies will start when Ranch is started. +Transports can be used for connecting, listening and accepting connections, but also for receiving and sending data. Both passive and active mode are supported, although all sockets are initialized as passive. +TCP transport The TCP transport is a thin wrapper around gen_tcp. +SSL transport The SSL transport is a thin wrapper around ssl. +Ranch depends on ssl by default so any necessary dependencies will start when Ranch is started. + + + + Transports + https://ninenines.eu/docs/en/ranch/1.5/guide/transports/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/guide/transports/ + A transport defines the interface to interact with a socket. +Transports can be used for connecting, listening and accepting connections, but also for receiving and sending data. Both passive and active mode are supported, although all sockets are initialized as passive. +TCP transport The TCP transport is a thin wrapper around gen_tcp. +SSL transport The SSL transport is a thin wrapper around ssl. +Ranch depends on ssl by default so any necessary dependencies will start when Ranch is started. @@ -345,9 +383,9 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/erlang.mk/1/guide/overview/ - Now that you know how to get started, let&#8217;s take a look at what Erlang.mk can do for you. - Building your project Erlang.mk is first and foremost a build tool. It is especially tailored for Erlang developers and follows widely accepted practices in the Erlang community. - Erlang.mk will happily build all Erlang-specific files you throw at it. Other kinds of files too, like C or C++ code when you are working on a NIF or a port driver. + Now that you know how to get started, let&apos;s take a look at what Erlang.mk can do for you. +Building your project Erlang.mk is first and foremost a build tool. It is especially tailored for Erlang developers and follows widely accepted practices in the Erlang community. +Erlang.mk will happily build all Erlang-specific files you throw at it. Other kinds of files too, like C or C++ code when you are working on a NIF or a port driver. @@ -357,8 +395,8 @@ https://ninenines.eu/docs/en/gun/1.0/guide/connect/ This chapter describes how to open, monitor and close a connection using the Gun client. - Gun connections Gun is designed with the HTTP/2 and Websocket protocols in mind. They are built for long-running connections that allow concurrent exchange of data, either in the form of request/responses for HTTP/2 or in the form of messages for Websocket. - A Gun connection is an Erlang process that manages a socket to a remote endpoint. +Gun connections Gun is designed with the HTTP/2 and Websocket protocols in mind. They are built for long-running connections that allow concurrent exchange of data, either in the form of request/responses for HTTP/2 or in the form of messages for Websocket. +A Gun connection is an Erlang process that manages a socket to a remote endpoint. @@ -368,7 +406,7 @@ https://ninenines.eu/docs/en/ranch/1.2/guide/protocols/ A protocol handler starts a connection process and defines the protocol logic executed in this process. - Writing a protocol handler All protocol handlers must implement the ranch_protocol behavior which defines a single callback, start_link/4. This callback is responsible for spawning a new process for handling the connection. It receives four arguments: the name of the listener, the socket, the transport handler being used and the protocol options defined in the call to ranch:start_listener/6. +Writing a protocol handler All protocol handlers must implement the ranch_protocol behavior which defines a single callback, start_link/4. This callback is responsible for spawning a new process for handling the connection. It receives four arguments: the name of the listener, the socket, the transport handler being used and the protocol options defined in the call to ranch:start_listener/6. @@ -378,7 +416,7 @@ https://ninenines.eu/docs/en/ranch/1.3/guide/protocols/ A protocol handler starts a connection process and defines the protocol logic executed in this process. - Writing a protocol handler All protocol handlers must implement the ranch_protocol behavior which defines a single callback, start_link/4. This callback is responsible for spawning a new process for handling the connection. It receives four arguments: the name of the listener, the socket, the transport handler being used and the protocol options defined in the call to ranch:start_listener/6. +Writing a protocol handler All protocol handlers must implement the ranch_protocol behavior which defines a single callback, start_link/4. This callback is responsible for spawning a new process for handling the connection. It receives four arguments: the name of the listener, the socket, the transport handler being used and the protocol options defined in the call to ranch:start_listener/6. @@ -388,7 +426,17 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/protocols/ A protocol handler starts a connection process and defines the protocol logic executed in this process. - Writing a protocol handler All protocol handlers must implement the ranch_protocol behavior which defines a single callback, start_link/4. This callback is responsible for spawning a new process for handling the connection. It receives four arguments: the name of the listener, the socket, the transport handler being used and the protocol options defined in the call to ranch:start_listener/5. +Writing a protocol handler All protocol handlers must implement the ranch_protocol behavior which defines a single callback, start_link/4. This callback is responsible for spawning a new process for handling the connection. It receives four arguments: the name of the listener, the socket, the transport handler being used and the protocol options defined in the call to ranch:start_listener/5. + + + + Protocols + https://ninenines.eu/docs/en/ranch/1.5/guide/protocols/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/guide/protocols/ + A protocol handler starts a connection process and defines the protocol logic executed in this process. +Writing a protocol handler All protocol handlers must implement the ranch_protocol behavior which defines a single callback, start_link/4. This callback is responsible for spawning a new process for handling the connection. It receives four arguments: the name of the listener, the socket, the transport handler being used and the protocol options defined in the call to ranch:start_listener/5. @@ -398,7 +446,7 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/getting_started/ Erlang is more than a language, it is also an operating system for your applications. Erlang developers rarely write standalone modules, they write libraries or applications, and then bundle those into what is called a release. A release contains the Erlang VM plus all applications required to run the node, so it can be pushed to production directly. - This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. +This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. @@ -408,7 +456,7 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/getting_started/ Erlang is more than a language, it is also an operating system for your applications. Erlang developers rarely write standalone modules, they write libraries or applications, and then bundle those into what is called a release. A release contains the Erlang VM plus all applications required to run the node, so it can be pushed to production directly. - This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. +This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. @@ -418,7 +466,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/getting_started/ Erlang is more than a language, it is also an operating system for your applications. Erlang developers rarely write standalone modules, they write libraries or applications, and then bundle those into what is called a release. A release contains the Erlang VM plus all applications required to run the node, so it can be pushed to production directly. - This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. +This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. @@ -428,7 +476,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/getting_started/ Erlang is more than a language, it is also an operating system for your applications. Erlang developers rarely write standalone modules, they write libraries or applications, and then bundle those into what is called a release. A release contains the Erlang VM plus all applications required to run the node, so it can be pushed to production directly. - This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. +This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. @@ -438,7 +486,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/getting_started/ Erlang is more than a language, it is also an operating system for your applications. Erlang developers rarely write standalone modules, they write libraries or applications, and then bundle those into what is called a release. A release contains the Erlang VM plus all applications required to run the node, so it can be pushed to production directly. - This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. +This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. @@ -448,8 +496,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/updating/ This chapter describes how to update the erlang.mk file in your repository. - Initial bootstrap The first time you use Erlang.mk, it will bootstrap itself. It always uses the most recent version for this, so you don&#8217;t have to update after creating your project. - Updating Later on though, updating becomes a necessity. Erlang.mk developers and contributors relentlessly improve the project and add new features; it would be a waste not to benefit from this. +Initial bootstrap The first time you use Erlang.mk, it will bootstrap itself. It always uses the most recent version for this, so you don&apos;t have to update after creating your project. +Updating Later on though, updating becomes a necessity. Erlang.mk developers and contributors relentlessly improve the project and add new features; it would be a waste not to benefit from this. @@ -459,9 +507,9 @@ https://ninenines.eu/docs/en/gun/1.0/guide/http/ This chapter describes how to use the Gun client for communicating with an HTTP/1.1 or HTTP/2 server. - Streams Every time a request is initiated, Gun creates a stream. A stream reference uniquely identifies a set of request and response and must be used to perform additional operations with a stream or to identify its messages. - Stream references use the Erlang reference data type and are therefore unique. - Streams can be canceled at any time. +Streams Every time a request is initiated, Gun creates a stream. A stream reference uniquely identifies a set of request and response and must be used to perform additional operations with a stream or to identify its messages. +Stream references use the Erlang reference data type and are therefore unique. +Streams can be canceled at any time. @@ -471,7 +519,7 @@ https://ninenines.eu/docs/en/ranch/1.2/guide/embedded/ Embedded mode allows you to insert Ranch listeners directly in your supervision tree. This allows for greater fault tolerance control by permitting the shutdown of a listener due to the failure of another part of the application and vice versa. - Embedding To embed Ranch in your application you can simply add the child specs to your supervision tree. This can all be done in the init/1 function of one of your application supervisors. +Embedding To embed Ranch in your application you can simply add the child specs to your supervision tree. This can all be done in the init/1 function of one of your application supervisors. @@ -481,7 +529,7 @@ https://ninenines.eu/docs/en/ranch/1.3/guide/embedded/ Embedded mode allows you to insert Ranch listeners directly in your supervision tree. This allows for greater fault tolerance control by permitting the shutdown of a listener due to the failure of another part of the application and vice versa. - Embedding To embed Ranch in your application you can simply add the child specs to your supervision tree. This can all be done in the init/1 function of one of your application supervisors. +Embedding To embed Ranch in your application you can simply add the child specs to your supervision tree. This can all be done in the init/1 function of one of your application supervisors. @@ -491,7 +539,17 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/embedded/ Embedded mode allows you to insert Ranch listeners directly in your supervision tree. This allows for greater fault tolerance control by permitting the shutdown of a listener due to the failure of another part of the application and vice versa. - Embedding To embed Ranch in your application you can simply add the child specs to your supervision tree. This can all be done in the init/1 function of one of your application supervisors. +Embedding To embed Ranch in your application you can simply add the child specs to your supervision tree. This can all be done in the init/1 function of one of your application supervisors. + + + + Embedded mode + https://ninenines.eu/docs/en/ranch/1.5/guide/embedded/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/guide/embedded/ + Embedded mode allows you to insert Ranch listeners directly in your supervision tree. This allows for greater fault tolerance control by permitting the shutdown of a listener due to the failure of another part of the application and vice versa. +Embedding To embed Ranch in your application you can simply add the child specs to your supervision tree. This can all be done in the init/1 function of one of your application supervisors. @@ -501,9 +559,10 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/limitations/ No software is perfect. - It&#8217;s very important, when evaluating and when using a tool, to understand its limitations, so as to avoid making mistakes and wasting valuable time. - This chapter lists all known limitations of Erlang.mk. - Erlang must be available Currently Erlang.mk requires you to install Erlang beforehand. Installing Erlang is not always easy, particularly if you need a specific version of Erlang for a specific project. +It&apos;s very important, when evaluating and when using a tool, to understand its limitations, so as to avoid making mistakes and wasting valuable time. +This chapter lists all known limitations of Erlang.mk. +Erlang must be available Currently Erlang.mk requires you to install Erlang beforehand. Installing Erlang is not always easy, particularly if you need a specific version of Erlang for a specific project. +In addition, the Erlang being used must be in your $PATH before you use Erlang. @@ -513,8 +572,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/flow_diagram/ Cowboy is a lightweight HTTP server with support for HTTP/1.1, HTTP/2 and Websocket. - It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. - Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. +Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +After Ranch accepts a new connection, whether it is an HTTP/1. @@ -524,8 +584,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/flow_diagram/ Cowboy is a lightweight HTTP server with support for HTTP/1.1, HTTP/2 and Websocket. - It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. - Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. +Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +After Ranch accepts a new connection, whether it is an HTTP/1. @@ -535,8 +596,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/flow_diagram/ Cowboy is a lightweight HTTP server with support for HTTP/1.1, HTTP/2 and Websocket. - It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. - Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. +Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +After Ranch accepts a new connection, whether it is an HTTP/1. @@ -546,8 +608,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/flow_diagram/ Cowboy is a lightweight HTTP server with support for HTTP/1.1, HTTP/2 and Websocket. - It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. - Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. +Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +After Ranch accepts a new connection, whether it is an HTTP/1. @@ -557,8 +620,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/flow_diagram/ Cowboy is a lightweight HTTP server with support for HTTP/1.1, HTTP/2 and Websocket. - It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. - Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. +Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +After Ranch accepts a new connection, whether it is an HTTP/1. @@ -568,8 +632,8 @@ https://ninenines.eu/docs/en/gun/1.0/guide/websocket/ This chapter describes how to use the Gun client for communicating with a Websocket server. - HTTP upgrade Websocket is a protocol built on top of HTTP. To use Websocket, you must first request for the connection to be upgraded. Only HTTP/1.1 connections can be upgraded to Websocket, so you might need to restrict the protocol to HTTP/1.1 if you are planning to use Websocket over TLS. - You must use the gun:ws_upgrade/2,3,4 function to upgrade to Websocket. +HTTP upgrade Websocket is a protocol built on top of HTTP. To use Websocket, you must first request for the connection to be upgraded. Only HTTP/1.1 connections can be upgraded to Websocket, so you might need to restrict the protocol to HTTP/1.1 if you are planning to use Websocket over TLS. +You must use the gun:ws_upgrade/2,3,4 function to upgrade to Websocket. @@ -579,8 +643,8 @@ https://ninenines.eu/docs/en/ranch/1.2/guide/parsers/ There are three kinds of protocols: - Text protocols Schema-less binary protocols Schema-based binary protocols This chapter introduces the first two kinds. It will not cover more advanced topics such as continuations or parser generators. - This chapter isn&#8217;t specifically about Ranch, we assume here that you know how to read data from the socket. The data you read and the data that hasn&#8217;t been parsed is saved in a buffer. +Text protocols Schema-less binary protocols Schema-based binary protocols This chapter introduces the first two kinds. It will not cover more advanced topics such as continuations or parser generators. +This chapter isn&apos;t specifically about Ranch, we assume here that you know how to read data from the socket. The data you read and the data that hasn&apos;t been parsed is saved in a buffer. @@ -590,8 +654,8 @@ https://ninenines.eu/docs/en/ranch/1.3/guide/parsers/ There are three kinds of protocols: - Text protocols Schema-less binary protocols Schema-based binary protocols This chapter introduces the first two kinds. It will not cover more advanced topics such as continuations or parser generators. - This chapter isn&#8217;t specifically about Ranch, we assume here that you know how to read data from the socket. The data you read and the data that hasn&#8217;t been parsed is saved in a buffer. +Text protocols Schema-less binary protocols Schema-based binary protocols This chapter introduces the first two kinds. It will not cover more advanced topics such as continuations or parser generators. +This chapter isn&apos;t specifically about Ranch, we assume here that you know how to read data from the socket. The data you read and the data that hasn&apos;t been parsed is saved in a buffer. @@ -601,8 +665,19 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/parsers/ There are three kinds of protocols: - Text protocols Schema-less binary protocols Schema-based binary protocols This chapter introduces the first two kinds. It will not cover more advanced topics such as continuations or parser generators. - This chapter isn&#8217;t specifically about Ranch, we assume here that you know how to read data from the socket. The data you read and the data that hasn&#8217;t been parsed is saved in a buffer. +Text protocols Schema-less binary protocols Schema-based binary protocols This chapter introduces the first two kinds. It will not cover more advanced topics such as continuations or parser generators. +This chapter isn&apos;t specifically about Ranch, we assume here that you know how to read data from the socket. The data you read and the data that hasn&apos;t been parsed is saved in a buffer. + + + + Writing parsers + https://ninenines.eu/docs/en/ranch/1.5/guide/parsers/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/guide/parsers/ + There are three kinds of protocols: +Text protocols Schema-less binary protocols Schema-based binary protocols This chapter introduces the first two kinds. It will not cover more advanced topics such as continuations or parser generators. +This chapter isn&apos;t specifically about Ranch, we assume here that you know how to read data from the socket. The data you read and the data that hasn&apos;t been parsed is saved in a buffer. @@ -612,9 +687,9 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/app/ Erlang.mk can do a lot of things, but it is, first and foremost, a build tool. In this chapter we will cover the basics of building a project with Erlang.mk. - For most of this chapter, we will assume that you are using a project generated by Erlang.mk. - How to build To build a project, all you have to do is type make: - $ make It will work regardless of your project: OTP applications, library applications, NIFs, port drivers or even releases. +For most of this chapter, we will assume that you are using a project generated by Erlang.mk. +How to build To build a project, all you have to do is type make: +$ make It will work regardless of your project: OTP applications, library applications, NIFs, port drivers or even releases. @@ -624,8 +699,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/listeners/ A listener is a set of processes that listens on a port for new connections. Incoming connections get handled by Cowboy. Depending on the connection handshake, one or another protocol may be used. - This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. - Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. +This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. +Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. Both of them support the HTTP/1. @@ -635,8 +710,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/listeners/ A listener is a set of processes that listens on a port for new connections. Incoming connections get handled by Cowboy. Depending on the connection handshake, one or another protocol may be used. - This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. - Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. +This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. +Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. Both of them support the HTTP/1. @@ -646,8 +721,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/listeners/ A listener is a set of processes that listens on a port for new connections. Incoming connections get handled by Cowboy. Depending on the connection handshake, one or another protocol may be used. - This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. - Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. +This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. +Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. Both of them support the HTTP/1. @@ -657,8 +732,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/listeners/ A listener is a set of processes that listens on a port for new connections. Incoming connections get handled by Cowboy. Depending on the connection handshake, one or another protocol may be used. - This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. - Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. +This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. +Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. Both of them support the HTTP/1. @@ -668,8 +743,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/listeners/ A listener is a set of processes that listens on a port for new connections. Incoming connections get handled by Cowboy. Depending on the connection handshake, one or another protocol may be used. - This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. - Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. +This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. +Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. Both of them support the HTTP/1. @@ -679,7 +754,7 @@ https://ninenines.eu/docs/en/ranch/1.2/guide/ssl_auth/ Purpose SSL client authentication is a mechanism allowing applications to identify certificates. This allows your application to make sure that the client is an authorized certificate, but makes no claim about whether the user can be trusted. This can be combined with a password based authentication to attain greater security. - The server only needs to retain the certificate serial number and the certificate issuer to authenticate the certificate. Together, they can be used to uniquely identify a certicate. +The server only needs to retain the certificate serial number and the certificate issuer to authenticate the certificate. Together, they can be used to uniquely identify a certicate. @@ -689,7 +764,7 @@ https://ninenines.eu/docs/en/ranch/1.3/guide/ssl_auth/ Purpose SSL client authentication is a mechanism allowing applications to identify certificates. This allows your application to make sure that the client is an authorized certificate, but makes no claim about whether the user can be trusted. This can be combined with a password based authentication to attain greater security. - The server only needs to retain the certificate serial number and the certificate issuer to authenticate the certificate. Together, they can be used to uniquely identify a certicate. +The server only needs to retain the certificate serial number and the certificate issuer to authenticate the certificate. Together, they can be used to uniquely identify a certicate. @@ -699,7 +774,17 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/ssl_auth/ Purpose SSL client authentication is a mechanism allowing applications to identify certificates. This allows your application to make sure that the client is an authorized certificate, but makes no claim about whether the user can be trusted. This can be combined with a password based authentication to attain greater security. - The server only needs to retain the certificate serial number and the certificate issuer to authenticate the certificate. Together, they can be used to uniquely identify a certicate. +The server only needs to retain the certificate serial number and the certificate issuer to authenticate the certificate. Together, they can be used to uniquely identify a certicate. + + + + SSL client authentication + https://ninenines.eu/docs/en/ranch/1.5/guide/ssl_auth/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/guide/ssl_auth/ + Purpose SSL client authentication is a mechanism allowing applications to identify certificates. This allows your application to make sure that the client is an authorized certificate, but makes no claim about whether the user can be trusted. This can be combined with a password based authentication to attain greater security. +The server only needs to retain the certificate serial number and the certificate issuer to authenticate the certificate. Together, they can be used to uniquely identify a certicate. @@ -709,8 +794,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/deps/ Erlang.mk can fetch and compile the dependencies that your project requires. Erlang.mk improves upon the concepts introduced by Rebar, so they should be familiar to many seasoned Erlang developers. - Erlang.mk is not a package manager, nor is it trying to be, but it does include an index of Erlang packages to make discovering useful projects easier. - This chapter will explain how to use packages, add dependencies to your project or bundle them directly in a single repository. +Erlang.mk is not a package manager, nor is it trying to be, but it does include an index of Erlang packages to make discovering useful projects easier. +This chapter will explain how to use packages, add dependencies to your project or bundle them directly in a single repository. @@ -720,9 +805,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/routing/ Cowboy does nothing by default. - To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. - When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&#8217;s a match, the route&#8217;s associated handler is executed. - Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. +To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. +When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&apos;s a match, the route&apos;s associated handler is executed. +Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. @@ -732,9 +817,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/routing/ Cowboy does nothing by default. - To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. - When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&#8217;s a match, the route&#8217;s associated handler is executed. - Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. +To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. +When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&apos;s a match, the route&apos;s associated handler is executed. +Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. @@ -744,9 +829,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/routing/ Cowboy does nothing by default. - To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. - When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&#8217;s a match, the route&#8217;s associated handler is executed. - Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. +To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. +When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&apos;s a match, the route&apos;s associated handler is executed. +Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. @@ -756,9 +841,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/routing/ Cowboy does nothing by default. - To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. - When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&#8217;s a match, the route&#8217;s associated handler is executed. - Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. +To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. +When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&apos;s a match, the route&apos;s associated handler is executed. +Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. @@ -768,9 +853,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/routing/ Cowboy does nothing by default. - To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. - When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&#8217;s a match, the route&#8217;s associated handler is executed. - Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. +To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. +When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&apos;s a match, the route&apos;s associated handler is executed. +Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. @@ -780,8 +865,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/ports/ Erlang.mk can not only build Erlang projects, but also the C code that some projects come with, like NIFs and port drivers. - There are two ways to build the C code: using a custom Makefile, or making Erlang.mk do it directly. The C code will be built as needed when you run make. - C source code location and Erlang environment The C source code should be located in the $(C_SRC_DIR) directory. +There are two ways to build the C code: using a custom Makefile, or making Erlang.mk do it directly. The C code will be built as needed when you run make. +C source code location and Erlang environment The C source code should be located in the $(C_SRC_DIR) directory. @@ -791,7 +876,7 @@ https://ninenines.eu/docs/en/ranch/1.2/guide/internals/ This chapter may not apply to embedded Ranch as embedding allows you to use an architecture specific to your application, which may or may not be compatible with the description of the Ranch application. - Note that for everything related to efficiency and performance, you should perform the benchmarks yourself to get the numbers that matter to you. Generic benchmarks found on the web may or may not be of use to you, you can never know until you benchmark your own system. +Note that for everything related to efficiency and performance, you should perform the benchmarks yourself to get the numbers that matter to you. Generic benchmarks found on the web may or may not be of use to you, you can never know until you benchmark your own system. @@ -801,7 +886,7 @@ https://ninenines.eu/docs/en/ranch/1.3/guide/internals/ This chapter may not apply to embedded Ranch as embedding allows you to use an architecture specific to your application, which may or may not be compatible with the description of the Ranch application. - Note that for everything related to efficiency and performance, you should perform the benchmarks yourself to get the numbers that matter to you. Generic benchmarks found on the web may or may not be of use to you, you can never know until you benchmark your own system. +Note that for everything related to efficiency and performance, you should perform the benchmarks yourself to get the numbers that matter to you. Generic benchmarks found on the web may or may not be of use to you, you can never know until you benchmark your own system. @@ -811,7 +896,17 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/internals/ This chapter may not apply to embedded Ranch as embedding allows you to use an architecture specific to your application, which may or may not be compatible with the description of the Ranch application. - Note that for everything related to efficiency and performance, you should perform the benchmarks yourself to get the numbers that matter to you. Generic benchmarks found on the web may or may not be of use to you, you can never know until you benchmark your own system. +Note that for everything related to efficiency and performance, you should perform the benchmarks yourself to get the numbers that matter to you. Generic benchmarks found on the web may or may not be of use to you, you can never know until you benchmark your own system. + + + + Internals + https://ninenines.eu/docs/en/ranch/1.5/guide/internals/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/guide/internals/ + This chapter may not apply to embedded Ranch as embedding allows you to use an architecture specific to your application, which may or may not be compatible with the description of the Ranch application. +Note that for everything related to efficiency and performance, you should perform the benchmarks yourself to get the numbers that matter to you. Generic benchmarks found on the web may or may not be of use to you, you can never know until you benchmark your own system. @@ -821,9 +916,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/constraints/ Constraints are validation and conversion functions applied to user input. - They are used in various places in Cowboy, including the router and the cowboy_req match functions. - Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. - A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. +They are used in various places in Cowboy, including the router and the cowboy_req match functions. +Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. +A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. @@ -833,9 +928,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/constraints/ Constraints are validation and conversion functions applied to user input. - They are used in various places in Cowboy, including the router and the cowboy_req match functions. - Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. - A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. +They are used in various places in Cowboy, including the router and the cowboy_req match functions. +Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. +A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. @@ -845,9 +940,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/constraints/ Constraints are validation and conversion functions applied to user input. - They are used in various places in Cowboy, including the router and the cowboy_req match functions. - Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. - A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. +They are used in various places in Cowboy, including the router and the cowboy_req match functions. +Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. +A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. @@ -857,9 +952,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/constraints/ Constraints are validation and conversion functions applied to user input. - They are used in various places in Cowboy, including the router and the cowboy_req match functions. - Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. - A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. +They are used in various places in Cowboy, including the router and the cowboy_req match functions. +Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. +A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. @@ -869,9 +964,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/constraints/ Constraints are validation and conversion functions applied to user input. - They are used in various places in Cowboy, including the router and the cowboy_req match functions. - Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. - A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. +They are used in various places in Cowboy, including the router and the cowboy_req match functions. +Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. +A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. @@ -881,8 +976,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/releases/ Erlang.mk relies on Relx for generating releases. This chapter covers the Erlang.mk-specific bits. Consult the Relx website for more information. - Setup Erlang.mk will create a release if it detects a Relx configuration file in the $(RELX_CONFIG) location. This defaults to $(CURDIR)/relx.config. You can override it by defining the variable before including Erlang.mk: - RELX_CONFIG = $(CURDIR)/webchat.config Relx does not need to be installed. Erlang.mk will download and build it automatically. +Setup Erlang.mk will create a release if it detects a Relx configuration file in the $(RELX_CONFIG) location. This defaults to $(CURDIR)/relx.config. You can override it by defining the variable before including Erlang.mk: +RELX_CONFIG = $(CURDIR)/webchat.config Relx does not need to be installed. Erlang.mk will download and build it automatically. @@ -892,9 +987,9 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/sfx/ Erlang.mk allows you to package Relx releases as self-extracting archives. These archives contain all the files in the release and come in the form of a script that will extract and run the release automatically. - This allows you to package the release as a single file that can then be executed. - This feature is currently experimental. Feedback is much appreciated. - Generating the self-extracting archive To generate a self-extracting release, all you need to do is pass the SFX=1 variable to Make when you build the release: +This allows you to package the release as a single file that can then be executed. +This feature is currently experimental. Feedback is much appreciated. +Generating the self-extracting archive To generate a self-extracting release, all you need to do is pass the SFX=1 variable to Make when you build the release: @@ -904,10 +999,10 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/handlers/ Handlers are Erlang modules that handle HTTP requests. - Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. - This callback receives the Req object and the initial state defined in the router configuration. - A handler that does nothing would look like this: - init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. +Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. +This callback receives the Req object and the initial state defined in the router configuration. +A handler that does nothing would look like this: +init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. @@ -917,10 +1012,10 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/handlers/ Handlers are Erlang modules that handle HTTP requests. - Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. - This callback receives the Req object and the initial state defined in the router configuration. - A handler that does nothing would look like this: - init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. +Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. +This callback receives the Req object and the initial state defined in the router configuration. +A handler that does nothing would look like this: +init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. @@ -930,10 +1025,10 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/handlers/ Handlers are Erlang modules that handle HTTP requests. - Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. - This callback receives the Req object and the initial state defined in the router configuration. - A handler that does nothing would look like this: - init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. +Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. +This callback receives the Req object and the initial state defined in the router configuration. +A handler that does nothing would look like this: +init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. @@ -943,10 +1038,10 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/handlers/ Handlers are Erlang modules that handle HTTP requests. - Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. - This callback receives the Req object and the initial state defined in the router configuration. - A handler that does nothing would look like this: - init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. +Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. +This callback receives the Req object and the initial state defined in the router configuration. +A handler that does nothing would look like this: +init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. @@ -956,10 +1051,10 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/handlers/ Handlers are Erlang modules that handle HTTP requests. - Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. - This callback receives the Req object and the initial state defined in the router configuration. - A handler that does nothing would look like this: - init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. +Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. +This callback receives the Req object and the initial state defined in the router configuration. +A handler that does nothing would look like this: +init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. @@ -969,9 +1064,9 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/escripts/ Escripts are an alternative to release. They are meant to be used for small command line executables written in Erlang. - They are not self-contained, unlike releases. Erlang must be installed for them to run. This however means that they are fairly small compared to releases. - For self-contained executables, check self-extracting releases. - Requirements Erlang.mk uses p7zip by default to generate the escript archive. Make sure it is installed. On most systems the package is named p7zip; on Ubuntu you need p7zip-full. +They are not self-contained, unlike releases. Erlang must be installed for them to run. This however means that they are fairly small compared to releases. +For self-contained executables, check self-extracting releases. +Requirements Erlang.mk uses p7zip by default to generate the escript archive. Make sure it is installed. On most systems the package is named p7zip; on Ubuntu you need p7zip-full. @@ -981,7 +1076,7 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/loop_handlers/ Loop handlers are a special kind of HTTP handlers used when the response can not be sent right away. The handler enters instead a receive loop waiting for the right message before it can send a response. - Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. +Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. @@ -991,7 +1086,7 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/loop_handlers/ Loop handlers are a special kind of HTTP handlers used when the response can not be sent right away. The handler enters instead a receive loop waiting for the right message before it can send a response. - Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. +Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. @@ -1001,7 +1096,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/loop_handlers/ Loop handlers are a special kind of HTTP handlers used when the response can not be sent right away. The handler enters instead a receive loop waiting for the right message before it can send a response. - Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. +Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. @@ -1011,7 +1106,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/loop_handlers/ Loop handlers are a special kind of HTTP handlers used when the response can not be sent right away. The handler enters instead a receive loop waiting for the right message before it can send a response. - Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. +Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. @@ -1021,7 +1116,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/loop_handlers/ Loop handlers are a special kind of HTTP handlers used when the response can not be sent right away. The handler enters instead a receive loop waiting for the right message before it can send a response. - Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. +Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. @@ -1031,7 +1126,7 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/kerl/ Erlang.mk comes with integrated support for Kerl, a shell script that automates the downloading, building and installing of Erlang/OTP. It can be used to easily build a specific Erlang/OTP version (with or without custom build options) or maintain different versions side by side. - Erlang versions Erlang.mk uses the Git tags from Erlang/OTP to identify OTP versions. The most recent tag at the time of writing is OTP-20.0.4, which is a patch release of OTP-20. +Erlang versions Erlang.mk uses the Git tags from Erlang/OTP to identify OTP versions. The most recent tag at the time of writing is OTP-20.0.4, which is a patch release of OTP-20. @@ -1041,8 +1136,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/static_files/ Cowboy comes with a ready to use handler for serving static files. It is provided as a convenience for serving files during development. - For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. - The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. +For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. +The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. @@ -1052,8 +1147,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/static_files/ Cowboy comes with a ready to use handler for serving static files. It is provided as a convenience for serving files during development. - For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. - The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. +For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. +The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. @@ -1063,8 +1158,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/static_files/ Cowboy comes with a ready to use handler for serving static files. It is provided as a convenience for serving files during development. - For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. - The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. +For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. +The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. @@ -1074,8 +1169,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/static_files/ Cowboy comes with a ready to use handler for serving static files. It is provided as a convenience for serving files during development. - For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. - The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. +For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. +The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. @@ -1085,8 +1180,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/static_files/ Cowboy comes with a ready to use handler for serving static files. It is provided as a convenience for serving files during development. - For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. - The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. +For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. +The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. @@ -1096,7 +1191,7 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/compat/ Erlang.mk tries its best to be compatible with the other Erlang build tools. It can use dependencies written with other build tools in mind, and can also make your projects usable by those build tools as well. Erlang.mk is like the cool kid that gets along with everybody. - In this chapter I will use the term Rebar project to refer to a project built using Rebar 2, Rebar 3 or Mad. +In this chapter I will use the term Rebar project to refer to a project built using Rebar 2, Rebar 3 or Mad. @@ -1106,8 +1201,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/asciidoc/ Erlang.mk provides rules for generating documentation from AsciiDoc files. It can automatically build a user guide PDF, chunked HTML documentation and Unix manual pages. - Requirements It is necessary to have AsciiDoc, xsltproc and dblatex installed on your system for Erlang.mk to generate documentation from AsciiDoc sources. - Writing AsciiDoc documentation AsciiDoc is a text document format for writing notes, documentation, articles, books, ebooks, slideshows, web pages, man pages and blogs. +Requirements It is necessary to have AsciiDoc, xsltproc and dblatex installed on your system for Erlang.mk to generate documentation from AsciiDoc sources. +Writing AsciiDoc documentation AsciiDoc is a text document format for writing notes, documentation, articles, books, ebooks, slideshows, web pages, man pages and blogs. AsciiDoc files can be translated to many formats including HTML, PDF, EPUB, man page. @@ -1117,8 +1212,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/req/ The Req object is a variable used for obtaining information about a request, read its body or send a response. - It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. - The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. +It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. +The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. @@ -1128,8 +1223,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/req/ The Req object is a variable used for obtaining information about a request, read its body or send a response. - It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. - The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. +It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. +The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. @@ -1139,8 +1234,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/req/ The Req object is a variable used for obtaining information about a request, read its body or send a response. - It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. - The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. +It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. +The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. @@ -1150,8 +1245,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/req/ The Req object is a variable used for obtaining information about a request, read its body or send a response. - It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. - The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. +It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. +The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. @@ -1161,8 +1256,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/req/ The Req object is a variable used for obtaining information about a request, read its body or send a response. - It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. - The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. +It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. +The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. @@ -1172,9 +1267,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/req_body/ The request body can be read using the Req object. - Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. - Cowboy will not cache the body, it is therefore only possible to read it once. - You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. +Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. +Cowboy will not cache the body, it is therefore only possible to read it once. +You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. @@ -1184,9 +1279,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/req_body/ The request body can be read using the Req object. - Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. - Cowboy will not cache the body, it is therefore only possible to read it once. - You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. +Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. +Cowboy will not cache the body, it is therefore only possible to read it once. +You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. @@ -1196,9 +1291,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/req_body/ The request body can be read using the Req object. - Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. - Cowboy will not cache the body, it is therefore only possible to read it once. - You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. +Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. +Cowboy will not cache the body, it is therefore only possible to read it once. +You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. @@ -1208,9 +1303,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/req_body/ The request body can be read using the Req object. - Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. - Cowboy will not cache the body, it is therefore only possible to read it once. - You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. +Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. +Cowboy will not cache the body, it is therefore only possible to read it once. +You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. @@ -1220,9 +1315,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/req_body/ The request body can be read using the Req object. - Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. - Cowboy will not cache the body, it is therefore only possible to read it once. - You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. +Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. +Cowboy will not cache the body, it is therefore only possible to read it once. +You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. @@ -1232,9 +1327,9 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/edoc/ Erlang.mk provides a thin wrapper on top of EDoc, an application that generates documentation based on comments found in modules. - Writing EDoc comments The EDoc user guide explains everything you need to know about EDoc comments. - Configuration The EDOC_OPTS variable allows you to specify additional EDoc options. Options are documented in the EDoc manual. - A common use for this variable is to enable Markdown in doc comments, using the edown application: +Writing EDoc comments The EDoc user guide explains everything you need to know about EDoc comments. +Configuration The EDOC_OPTS variable allows you to specify additional EDoc options. Options are documented in the EDoc manual. +A common use for this variable is to enable Markdown in doc comments, using the edown application: @@ -1244,8 +1339,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/sphinx/ Erlang.mk includes targets for running the Sphinx documentation generator, which can produce documentation in various formats, like HTML, man pages, Texinfo, LaTeX, and others. - Writing Sphinx documentation Sphinx generates documentation from a set of reST documents. There is a quick start guide on Sphinx' website. For Erlang.mk, we&#8217;ll set up a minimal environment instead. - Basic setup By default, Erlang.mk expects Sphinx documentation to be placed in the doc directory, with doc/conf. +Writing Sphinx documentation Sphinx generates documentation from a set of reST documents. There is a quick start guide on Sphinx&apos; website. For Erlang.mk, we&apos;ll set up a minimal environment instead. +Basic setup By default, Erlang.mk expects Sphinx documentation to be placed in the doc directory, with doc/conf. @@ -1255,8 +1350,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/resp/ The response must be sent using the Req object. - Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. - Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. +Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +While only one response is allowed for every request, HTTP/2 introduced a mechanism that allows the server to push additional resources related to the response. @@ -1266,8 +1362,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/resp/ The response must be sent using the Req object. - Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. - Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. +Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +While only one response is allowed for every request, HTTP/2 introduced a mechanism that allows the server to push additional resources related to the response. @@ -1277,8 +1374,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/resp/ The response must be sent using the Req object. - Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. - Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. +Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +While only one response is allowed for every request, HTTP/2 introduced a mechanism that allows the server to push additional resources related to the response. @@ -1288,8 +1386,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/resp/ The response must be sent using the Req object. - Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. - Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. +Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +While only one response is allowed for every request, HTTP/2 introduced a mechanism that allows the server to push additional resources related to the response. @@ -1299,8 +1398,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/resp/ The response must be sent using the Req object. - Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. - Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. +Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +While only one response is allowed for every request, HTTP/2 introduced a mechanism that allows the server to push additional resources related to the response. @@ -1310,8 +1410,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/shell/ Erlang.mk provides a convenient target for starting a shell with all the paths set properly to experiment with your code. - Configuration The SHELL_DEPS variable can be used to define dependencies that are only to be used when the make shell command is called. For example, if you want to use kjell as your shell: - SHELL_DEPS = kjell Dependencies are downloaded and compiled the first time you run the make shell command. +Configuration The SHELL_DEPS variable can be used to define dependencies that are only to be used when the make shell command is called. For example, if you want to use kjell as your shell: +SHELL_DEPS = kjell Dependencies are downloaded and compiled the first time you run the make shell command. @@ -1321,7 +1421,7 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/cookies/ Cookies are a mechanism allowing applications to maintain state on top of the stateless HTTP protocol. - Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). +Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). @@ -1331,7 +1431,7 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/cookies/ Cookies are a mechanism allowing applications to maintain state on top of the stateless HTTP protocol. - Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). +Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). @@ -1341,7 +1441,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/cookies/ Cookies are a mechanism allowing applications to maintain state on top of the stateless HTTP protocol. - Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). +Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). @@ -1351,7 +1451,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/cookies/ Cookies are a mechanism allowing applications to maintain state on top of the stateless HTTP protocol. - Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). +Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). @@ -1361,7 +1461,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/cookies/ Cookies are a mechanism allowing applications to maintain state on top of the stateless HTTP protocol. - Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). +Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). @@ -1371,8 +1471,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/eunit/ EUnit is the tool of choice for unit testing. Erlang.mk automates a few things on top of EUnit, including the discovery and running of unit tests. - Writing tests The EUnit user guide is the best place to learn how to write tests. Of note is that all functions ending with _test or _test_ will be picked up as EUnit test cases. - Erlang.mk will automatically pick up tests found in any of the Erlang modules of your application. +Writing tests The EUnit user guide is the best place to learn how to write tests. Of note is that all functions ending with _test or _test_ will be picked up as EUnit test cases. +Erlang.mk will automatically pick up tests found in any of the Erlang modules of your application. @@ -1382,8 +1482,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/multipart/ Multipart originates from MIME, an Internet standard that extends the format of emails. - A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. - In the context of HTTP, multipart is most often used with the multipart/form-data media type. +A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. +In the context of HTTP, multipart is most often used with the multipart/form-data media type. @@ -1393,8 +1493,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/multipart/ Multipart originates from MIME, an Internet standard that extends the format of emails. - A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. - In the context of HTTP, multipart is most often used with the multipart/form-data media type. +A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. +In the context of HTTP, multipart is most often used with the multipart/form-data media type. @@ -1404,8 +1504,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/multipart/ Multipart originates from MIME, an Internet standard that extends the format of emails. - A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. - In the context of HTTP, multipart is most often used with the multipart/form-data media type. +A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. +In the context of HTTP, multipart is most often used with the multipart/form-data media type. @@ -1415,8 +1515,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/multipart/ Multipart originates from MIME, an Internet standard that extends the format of emails. - A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. - In the context of HTTP, multipart is most often used with the multipart/form-data media type. +A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. +In the context of HTTP, multipart is most often used with the multipart/form-data media type. @@ -1426,8 +1526,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/multipart/ Multipart originates from MIME, an Internet standard that extends the format of emails. - A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. - In the context of HTTP, multipart is most often used with the multipart/form-data media type. +A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. +In the context of HTTP, multipart is most often used with the multipart/form-data media type. @@ -1436,9 +1536,9 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/erlang.mk/1/guide/common_test/ - Common Test is Erlang&#8217;s functional testing framework. Erlang.mk automates the discovery and running of Common Test suites. - Writing tests The Common Test user guide is the best place to learn how to write tests. Erlang.mk requires that file names for test suites end with _SUITE.erl and that the files be located in the $(TEST_DIR) directory. This defaults to test/. - Configuration The CT_OPTS variable allows you to set extra Common Test options. + Common Test is Erlang&apos;s functional testing framework. Erlang.mk automates the discovery and running of Common Test suites. +Writing tests The Common Test user guide is the best place to learn how to write tests. Erlang.mk requires that file names for test suites end with _SUITE.erl and that the files be located in the $(TEST_DIR) directory. This defaults to test/. +Configuration The CT_OPTS variable allows you to set extra Common Test options. @@ -1448,8 +1548,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/rest_principles/ This chapter will attempt to define the concepts behind REST and explain what makes a service RESTful. - REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&#8217;s highly misguided at best. - We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. +REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&apos;s highly misguided at best. +We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. @@ -1459,8 +1559,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/rest_principles/ This chapter will attempt to define the concepts behind REST and explain what makes a service RESTful. - REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&#8217;s highly misguided at best. - We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. +REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&apos;s highly misguided at best. +We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. @@ -1470,8 +1570,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/rest_principles/ This chapter will attempt to define the concepts behind REST and explain what makes a service RESTful. - REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&#8217;s highly misguided at best. - We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. +REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&apos;s highly misguided at best. +We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. @@ -1481,8 +1581,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/rest_principles/ This chapter will attempt to define the concepts behind REST and explain what makes a service RESTful. - REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&#8217;s highly misguided at best. - We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. +REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&apos;s highly misguided at best. +We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. @@ -1492,8 +1592,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/rest_principles/ This chapter will attempt to define the concepts behind REST and explain what makes a service RESTful. - REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&#8217;s highly misguided at best. - We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. +REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&apos;s highly misguided at best. +We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. @@ -1503,12 +1603,12 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/triq/ Triq is a QuickCheck-like library for property-based testing. Erlang.mk automates discovery and checking of Triq properties. - To run all tests (including Triq): - $ make tests To run all tests and static checks (including Triq): - $ make check You can also run Triq separately: - $ make triq To check properties from a single module: - $ make triq t=foo_tests To check a single property: - $ make triq t=foo_tests:bar +To run all tests (including Triq): +$ make tests To run all tests and static checks (including Triq): +$ make check You can also run Triq separately: +$ make triq To check properties from a single module: +$ make triq t=foo_tests To check a single property: +$ make triq t=foo_tests:bar @@ -1517,9 +1617,10 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.0/guide/rest_handlers/ - REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&#8217;s behavior. - The REST handler is the recommended way to handle HTTP requests. - Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. + REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&apos;s behavior. +The REST handler is the recommended way to handle HTTP requests. +Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. +init(Req, State) -&gt; {cowboy_rest, Req, State}. @@ -1528,9 +1629,10 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.1/guide/rest_handlers/ - REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&#8217;s behavior. - The REST handler is the recommended way to handle HTTP requests. - Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. + REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&apos;s behavior. +The REST handler is the recommended way to handle HTTP requests. +Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. +init(Req, State) -&gt; {cowboy_rest, Req, State}. @@ -1539,9 +1641,10 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.2/guide/rest_handlers/ - REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&#8217;s behavior. - The REST handler is the recommended way to handle HTTP requests. - Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. + REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&apos;s behavior. +The REST handler is the recommended way to handle HTTP requests. +Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. +init(Req, State) -&gt; {cowboy_rest, Req, State}. @@ -1550,9 +1653,10 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.3/guide/rest_handlers/ - REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&#8217;s behavior. - The REST handler is the recommended way to handle HTTP requests. - Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. + REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&apos;s behavior. +The REST handler is the recommended way to handle HTTP requests. +Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. +init(Req, State) -&gt; {cowboy_rest, Req, State}. @@ -1561,9 +1665,10 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.4/guide/rest_handlers/ - REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&#8217;s behavior. - The REST handler is the recommended way to handle HTTP requests. - Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. + REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&apos;s behavior. +The REST handler is the recommended way to handle HTTP requests. +Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. +init(Req, State) -&gt; {cowboy_rest, Req, State}. @@ -1572,8 +1677,7 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/erlang.mk/1/guide/coverage/ - Placeholder chapter. - + Placeholder chapter. @@ -1583,7 +1687,7 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/ci/ Erlang.mk comes with some support for continuous integration, aimed at open source projects that need to support more than one specific Erlang/OTP release. (If you target one specific release, check the OTP version pinning section of the OTP version management chapter.) - Configuring Erlang/OTP versions to test To use the CI plugin you must first configure which versions of Erlang/OTP will be used. Erlang.mk provides three separate configuration variables depending on whether you need a normal OTP release, a HiPE-enabled release or an ErLLVM-enabled release. +Configuring Erlang/OTP versions to test To use the CI plugin you must first configure which versions of Erlang/OTP will be used. Erlang.mk provides three separate configuration variables depending on whether you need a normal OTP release, a HiPE-enabled release or an ErLLVM-enabled release. @@ -1593,8 +1697,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/rest_flowcharts/ This chapter will explain the REST handler state machine through a number of different diagrams. - There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. - All paths start with the "Start" diagram, and all paths excluding the OPTIONS path go through the "Content negotiation" +There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. +All paths start with the &quot;Start&quot; diagram, and all paths excluding the OPTIONS path go through the &quot;Content negotiation&quot; diagram and optionally the &quot;Conditional requests&quot; diagram if the resource exists. @@ -1604,8 +1708,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/rest_flowcharts/ This chapter will explain the REST handler state machine through a number of different diagrams. - There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. - All paths start with the "Start" diagram, and all paths excluding the OPTIONS path go through the "Content negotiation" +There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. +All paths start with the &quot;Start&quot; diagram, and all paths excluding the OPTIONS path go through the &quot;Content negotiation&quot; diagram and optionally the &quot;Conditional requests&quot; diagram if the resource exists. @@ -1615,8 +1719,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/rest_flowcharts/ This chapter will explain the REST handler state machine through a number of different diagrams. - There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. - All paths start with the "Start" diagram, and all paths excluding the OPTIONS path go through the "Content negotiation" +There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. +All paths start with the &quot;Start&quot; diagram, and all paths excluding the OPTIONS path go through the &quot;Content negotiation&quot; diagram and optionally the &quot;Conditional requests&quot; diagram if the resource exists. @@ -1626,8 +1730,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/rest_flowcharts/ This chapter will explain the REST handler state machine through a number of different diagrams. - There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. - All paths start with the "Start" diagram, and all paths excluding the OPTIONS path go through the "Content negotiation" +There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. +All paths start with the &quot;Start&quot; diagram, and all paths excluding the OPTIONS path go through the &quot;Content negotiation&quot; diagram and optionally the &quot;Conditional requests&quot; diagram if the resource exists. @@ -1637,8 +1741,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/rest_flowcharts/ This chapter will explain the REST handler state machine through a number of different diagrams. - There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. - All paths start with the "Start" diagram, and all paths excluding the OPTIONS path go through the "Content negotiation" +There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. +All paths start with the &quot;Start&quot; diagram, and all paths excluding the OPTIONS path go through the &quot;Content negotiation&quot; diagram and optionally the &quot;Conditional requests&quot; diagram if the resource exists. @@ -1648,8 +1752,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/dialyzer/ Dialyzer is a tool that will detect discrepancies in your program. It does so using a technique known as success typing analysis which has the advantage of providing no false positives. Dialyzer is able to detect type errors, dead code and more. - Erlang.mk provides a wrapper around Dialyzer. - How it works Dialyzer requires a PLT file to work. The PLT file contains the analysis information from all applications which are not expected to change, or rarely do. +Erlang.mk provides a wrapper around Dialyzer. +How it works Dialyzer requires a PLT file to work. The PLT file contains the analysis information from all applications which are not expected to change, or rarely do. @@ -1659,7 +1763,7 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/resource_design/ This chapter aims to provide you with a list of questions you must answer in order to write a good resource handler. It is meant to be usable as a step by step guide. - The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. +The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. @@ -1669,7 +1773,7 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/resource_design/ This chapter aims to provide you with a list of questions you must answer in order to write a good resource handler. It is meant to be usable as a step by step guide. - The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. +The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. @@ -1679,7 +1783,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/resource_design/ This chapter aims to provide you with a list of questions you must answer in order to write a good resource handler. It is meant to be usable as a step by step guide. - The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. +The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. @@ -1689,7 +1793,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/resource_design/ This chapter aims to provide you with a list of questions you must answer in order to write a good resource handler. It is meant to be usable as a step by step guide. - The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. +The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. @@ -1699,7 +1803,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/resource_design/ This chapter aims to provide you with a list of questions you must answer in order to write a good resource handler. It is meant to be usable as a step by step guide. - The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. +The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. @@ -1708,8 +1812,7 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/erlang.mk/1/guide/xref/ - Placeholder chapter. - + Placeholder chapter. @@ -1719,8 +1822,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/external_plugins/ It is often convenient to be able to keep the build files used by all your projects in one place. Those files could be Makefiles, configuration files, templates and more. - Erlang.mk allows you to automatically load plugins from dependencies. Plugins can do anything, including defining new variables, defining file templates, hooking themselves inside the normal Erlang.mk processing or even adding new rules. - You can load plugins using one of two methods. +Erlang.mk allows you to automatically load plugins from dependencies. Plugins can do anything, including defining new variables, defining file templates, hooking themselves inside the normal Erlang.mk processing or even adding new rules. +You can load plugins using one of two methods. @@ -1730,8 +1833,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/ws_protocol/ This chapter explains what Websocket is and why it is a vital component of soft realtime Web applications. - Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. - Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). +Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. +Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). @@ -1741,8 +1844,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/ws_protocol/ This chapter explains what Websocket is and why it is a vital component of soft realtime Web applications. - Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. - Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). +Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. +Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). @@ -1752,8 +1855,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/ws_protocol/ This chapter explains what Websocket is and why it is a vital component of soft realtime Web applications. - Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. - Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). +Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. +Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). @@ -1763,8 +1866,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/ws_protocol/ This chapter explains what Websocket is and why it is a vital component of soft realtime Web applications. - Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. - Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). +Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. +Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). @@ -1774,8 +1877,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/ws_protocol/ This chapter explains what Websocket is and why it is a vital component of soft realtime Web applications. - Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. - Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). +Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. +Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). @@ -1785,10 +1888,11 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/external_plugins_list/ This is a non-exhaustive list of Erlang.mk plugins, sorted alphabetically. - efene.mk An Efene plugin for Erlang.mk. Efene is an alternative language for the BEAM. - elixir.mk An Elixir plugin for Erlang.mk. Elixir is an alternative language for the BEAM. - elvis.mk An Elvis plugin for Erlang.mk. Elvis is an Erlang style reviewer. - geas Geas gives aggregated information on a project and its dependencies, and is available as an Erlang. +efene.mk An Efene plugin for Erlang.mk. Efene is an alternative language for the BEAM. +elixir.mk An Elixir plugin for Erlang.mk. Elixir is an alternative language for the BEAM. +elvis.mk An Elvis plugin for Erlang.mk. Elvis is an Erlang style reviewer. +geas Geas gives aggregated information on a project and its dependencies, and is available as an Erlang.mk plugin. +hexer.mk An Hex plugin for Erlang. @@ -1798,7 +1902,7 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/ws_handlers/ Websocket handlers provide an interface for upgrading HTTP/1.1 connections to Websocket and sending or receiving frames on the Websocket connection. - As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. +As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. @@ -1808,7 +1912,7 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/ws_handlers/ Websocket handlers provide an interface for upgrading HTTP/1.1 connections to Websocket and sending or receiving frames on the Websocket connection. - As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. +As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. @@ -1818,7 +1922,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/ws_handlers/ Websocket handlers provide an interface for upgrading HTTP/1.1 connections to Websocket and sending or receiving frames on the Websocket connection. - As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. +As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. @@ -1828,7 +1932,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/ws_handlers/ Websocket handlers provide an interface for upgrading HTTP/1.1 connections to Websocket and sending or receiving frames on the Websocket connection. - As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. +As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. @@ -1838,7 +1942,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/ws_handlers/ Websocket handlers provide an interface for upgrading HTTP/1.1 connections to Websocket and sending or receiving frames on the Websocket connection. - As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. +As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. @@ -1848,8 +1952,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/streams/ A stream is the set of messages that form an HTTP request/response pair. - The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. - All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. +The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. +All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. @@ -1859,8 +1963,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/streams/ A stream is the set of messages that form an HTTP request/response pair. - The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. - All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. +The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. +All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. @@ -1870,8 +1974,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/streams/ A stream is the set of messages that form an HTTP request/response pair. - The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. - All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. +The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. +All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. @@ -1881,8 +1985,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/streams/ A stream is the set of messages that form an HTTP request/response pair. - The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. - All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. +The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. +All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. @@ -1892,8 +1996,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/streams/ A stream is the set of messages that form an HTTP request/response pair. - The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. - All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. +The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. +All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. @@ -1903,9 +2007,9 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/why/ Why would you choose Erlang.mk, if not for its many features? This chapter will attempt to answer that. - Erlang.mk is fast Erlang.mk is as fast as it gets. - Erlang.mk will group the compilation of files so as to avoid running the BEAM more than necessary. This saves many seconds compared to traditional Makefiles, even on small projects. - Erlang.mk will not try to be too smart. It provides a simple solution that works for most people, and gives additional options for projects that run into edge cases, often in the form of extra variables or rules to be defined. +Erlang.mk is fast Erlang.mk is as fast as it gets. +Erlang.mk will group the compilation of files so as to avoid running the BEAM more than necessary. This saves many seconds compared to traditional Makefiles, even on small projects. +Erlang.mk will not try to be too smart. It provides a simple solution that works for most people, and gives additional options for projects that run into edge cases, often in the form of extra variables or rules to be defined. @@ -1915,8 +2019,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/middlewares/ Cowboy delegates the request processing to middleware components. By default, two middlewares are defined, for the routing and handling of the request, as is detailed in most of this guide. - Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. - Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. +Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. +Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. @@ -1926,8 +2030,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/middlewares/ Cowboy delegates the request processing to middleware components. By default, two middlewares are defined, for the routing and handling of the request, as is detailed in most of this guide. - Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. - Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. +Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. +Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. @@ -1937,8 +2041,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/middlewares/ Cowboy delegates the request processing to middleware components. By default, two middlewares are defined, for the routing and handling of the request, as is detailed in most of this guide. - Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. - Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. +Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. +Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. @@ -1948,8 +2052,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/middlewares/ Cowboy delegates the request processing to middleware components. By default, two middlewares are defined, for the routing and handling of the request, as is detailed in most of this guide. - Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. - Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. +Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. +Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. @@ -1959,8 +2063,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/middlewares/ Cowboy delegates the request processing to middleware components. By default, two middlewares are defined, for the routing and handling of the request, as is detailed in most of this guide. - Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. - Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. +Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. +Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. @@ -1970,8 +2074,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/history/ This chapter aims to be a brief record of the life of the Erlang.mk project. - Before Erlang.mk Erlang.mk originates from the Cowboy project. Cowboy started as a Rebar project and I, Loïc Hoguin, was very happy with it for a couple years. Over time however I started getting annoyed and frustrated by a number of things, including bad defaults, changing defaults and overall slowness. - In particular, at the time I gave up on Rebar, the Cowboy test suite was taking about five minutes to run. +Before Erlang.mk Erlang.mk originates from the Cowboy project. Cowboy started as a Rebar project and I, Loïc Hoguin, was very happy with it for a couple years. Over time however I started getting annoyed and frustrated by a number of things, including bad defaults, changing defaults and overall slowness. +In particular, at the time I gave up on Rebar, the Cowboy test suite was taking about five minutes to run. @@ -1981,9 +2085,10 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/contributing/ You are welcome and encouraged to contribute. - This is how. - Priorities From the most important to the least important: - Bugs Package issues/additions Refactoring Features Bugs If you have found a bug, you should open a ticket. Include everything relevant including the command you used, output, a link to the code that triggers the issue, why you think this is a bug, etc. +This is how. +Priorities From the most important to the least important: +Bugs Package issues/additions Refactoring Features Bugs If you have found a bug, you should open a ticket. Include everything relevant including the command you used, output, a link to the code that triggers the issue, why you think this is a bug, etc. +If you think you have found a bug but you are not sure, you should open a ticket as previously explained. @@ -1993,7 +2098,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/migrating_from_2.2/ The following patch versions were released since Cowboy 2.2: - Cowboy 2.2.2 While fixing the miscount in the previous patch release an issue was introduced where HTTP/2 bodies could be sent out of orders when using iolists. This has been corrected. Cowboy 2.2.1 Colons are now allowed within path segments in routes provided to cowboy_router:compile/1 as long as they are not the first character of the path segment. +Cowboy 2.2.2 While fixing the miscount in the previous patch release an issue was introduced where HTTP/2 bodies could be sent out of orders when using iolists. This has been corrected. Cowboy 2.2.1 Colons are now allowed within path segments in routes provided to cowboy_router:compile/1 as long as they are not the first character of the path segment. The cowboy_req:delete_resp_header/2 function will no longer crash when no response header was set before calling it. @@ -2003,8 +2108,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/migrating_from_1.0/ A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req interface in particular has seen a massive revamp. Hooks are gone, their functionality can now be achieved via stream handlers. - The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. - Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. +The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. +Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. Erlang/OTP 19. @@ -2014,7 +2119,7 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/migrating_from_2.0/ Cowboy 2.1 focused on adding features that were temporarily removed in Cowboy 2.0. A number of bugs found in the 2.0 release were also fixed. - Features added It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object. Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response. +Features added It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object. Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response. The expect: 100-continue header is now handled automatically. @@ -2024,7 +2129,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/migrating_from_2.2/ Cowboy 2.3 focused on making the Cowboy processes behave properly according to OTP principles. This version is a very good milestone toward that goal and most of everything should now work. Release upgrades and a few details will be improved in future versions. - Features added Add support for all functions from the module sys. Note that Cowboy currently does not implement the sys debugging mechanisms as tracing is recommended instead. +Features added Add support for all functions from the module sys. Note that Cowboy currently does not implement the sys debugging mechanisms as tracing is recommended instead. Add a max_frame_size option for Websocket handlers to close the connection when the client attempts to send a frame that&apos;s too large. @@ -2034,7 +2139,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/migrating_from_2.3/ Cowboy 2.4 focused on improving the HTTP/2 implementation. All existing tests from RFC7540 and the h2spec test suite now all pass. Numerous options have been added to control SETTINGS and related behavior. In addition experimental support for Websocket over HTTP/2 was added. - Features added Add experimental support for Websocket over HTTP/2. You can use the enable_connect_protocol option to enable. It implements the following draft: https://tools.ietf.org/html/draft-ietf-httpbis-h2-websockets-01 Add options max_decode_table_size and max_encode_table_size to restrict the size of the HPACK compression dictionary. +Features added Add experimental support for Websocket over HTTP/2. You can use the enable_connect_protocol option to enable. It implements the following draft: https://tools.ietf.org/html/draft-ietf-httpbis-h2-websockets-01 Add options max_decode_table_size and max_encode_table_size to restrict the size of the HPACK compression dictionary. @@ -2044,7 +2149,7 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/specs/ This chapter intends to list all the specification documents for or related to HTTP. - HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload REST: Fielding&#8217;s Dissertation RFC 1945: HTTP/1. +HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload REST: Fielding&apos;s Dissertation RFC 1945: HTTP/1. @@ -2054,8 +2159,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/migrating_from_1.0/ A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req interface in particular has seen a massive revamp. Hooks are gone, their functionality can now be achieved via stream handlers. - The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. - Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. +The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. +Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. Erlang/OTP 19. @@ -2065,7 +2170,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/migrating_from_2.1/ Cowboy 2.2 focused on adding features required for writing gRPC servers and on completing test suites for the core HTTP RFCs, fixing many bugs along the way. - Features added Add support for sending trailers at the end of response bodies. Trailers are additional header fields that may be sent after the body to add more information to the response. Their usage is required in gRPC servers. They are optional and may be discarded in other scenarios (for example if the request goes through an HTTP/1. +Features added Add support for sending trailers at the end of response bodies. Trailers are additional header fields that may be sent after the body to add more information to the response. Their usage is required in gRPC servers. They are optional and may be discarded in other scenarios (for example if the request goes through an HTTP/1. @@ -2075,7 +2180,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/migrating_from_2.1/ Cowboy 2.2 focused on adding features required for writing gRPC servers and on completing test suites for the core HTTP RFCs, fixing many bugs along the way. - Features added Add support for sending trailers at the end of response bodies. Trailers are additional header fields that may be sent after the body to add more information to the response. Their usage is required in gRPC servers. They are optional and may be discarded in other scenarios (for example if the request goes through an HTTP/1. +Features added Add support for sending trailers at the end of response bodies. Trailers are additional header fields that may be sent after the body to add more information to the response. Their usage is required in gRPC servers. They are optional and may be discarded in other scenarios (for example if the request goes through an HTTP/1. @@ -2085,7 +2190,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/migrating_from_2.2/ Cowboy 2.3 focused on making the Cowboy processes behave properly according to OTP principles. This version is a very good milestone toward that goal and most of everything should now work. Release upgrades and a few details will be improved in future versions. - Features added Add support for all functions from the module sys. Note that Cowboy currently does not implement the sys debugging mechanisms as tracing is recommended instead. +Features added Add support for all functions from the module sys. Note that Cowboy currently does not implement the sys debugging mechanisms as tracing is recommended instead. Add a max_frame_size option for Websocket handlers to close the connection when the client attempts to send a frame that&apos;s too large. @@ -2095,7 +2200,7 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/specs/ This chapter intends to list all the specification documents for or related to HTTP. - HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload REST: Fielding&#8217;s Dissertation RFC 1945: HTTP/1. +HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload REST: Fielding&apos;s Dissertation RFC 1945: HTTP/1. @@ -2105,7 +2210,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/migrating_from_2.0/ Cowboy 2.1 focused on adding features that were temporarily removed in Cowboy 2.0. A number of bugs found in the 2.0 release were also fixed. - Features added It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object. Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response. +Features added It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object. Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response. The expect: 100-continue header is now handled automatically. @@ -2115,7 +2220,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/migrating_from_2.0/ Cowboy 2.1 focused on adding features that were temporarily removed in Cowboy 2.0. A number of bugs found in the 2.0 release were also fixed. - Features added It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object. Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response. +Features added It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object. Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response. The expect: 100-continue header is now handled automatically. @@ -2125,7 +2230,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/migrating_from_2.1/ Cowboy 2.2 focused on adding features required for writing gRPC servers and on completing test suites for the core HTTP RFCs, fixing many bugs along the way. - Features added Add support for sending trailers at the end of response bodies. Trailers are additional header fields that may be sent after the body to add more information to the response. Their usage is required in gRPC servers. They are optional and may be discarded in other scenarios (for example if the request goes through an HTTP/1. +Features added Add support for sending trailers at the end of response bodies. Trailers are additional header fields that may be sent after the body to add more information to the response. Their usage is required in gRPC servers. They are optional and may be discarded in other scenarios (for example if the request goes through an HTTP/1. @@ -2135,8 +2240,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/migrating_from_1.0/ A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req interface in particular has seen a massive revamp. Hooks are gone, their functionality can now be achieved via stream handlers. - The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. - Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. +The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. +Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. Erlang/OTP 19. @@ -2146,8 +2251,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/migrating_from_1.0/ A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req interface in particular has seen a massive revamp. Hooks are gone, their functionality can now be achieved via stream handlers. - The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. - Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. +The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. +Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. Erlang/OTP 19. @@ -2157,7 +2262,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/migrating_from_2.0/ Cowboy 2.1 focused on adding features that were temporarily removed in Cowboy 2.0. A number of bugs found in the 2.0 release were also fixed. - Features added It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object. Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response. +Features added It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object. Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response. The expect: 100-continue header is now handled automatically. @@ -2167,7 +2272,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/specs/ This chapter intends to list all the specification documents for or related to HTTP. - HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload REST: Fielding&#8217;s Dissertation RFC 1945: HTTP/1. +HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload REST: Fielding&apos;s Dissertation RFC 1945: HTTP/1. @@ -2177,7 +2282,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/specs/ This chapter intends to list all the specification documents for or related to HTTP. - HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload PROXY: The PROXY protocol REST: Fielding&#8217;s Dissertation RFC 1945: HTTP/1. +HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload PROXY: The PROXY protocol REST: Fielding&apos;s Dissertation RFC 1945: HTTP/1. @@ -2187,8 +2292,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/migrating_from_1.0/ A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req interface in particular has seen a massive revamp. Hooks are gone, their functionality can now be achieved via stream handlers. - The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. - Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. +The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. +Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. Erlang/OTP 19. @@ -2198,7 +2303,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/specs/ This chapter intends to list all the specification documents for or related to HTTP. - HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload PROXY: The PROXY protocol REST: Fielding&#8217;s Dissertation RFC 1945: HTTP/1. +HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload PROXY: The PROXY protocol REST: Fielding&apos;s Dissertation RFC 1945: HTTP/1. @@ -2208,10 +2313,10 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2221,10 +2326,10 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2234,10 +2339,10 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2247,10 +2352,10 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2260,10 +2365,10 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2272,7 +2377,7 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.0/guide/ - Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Migrating from Cowboy 1. + Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Migrating from Cowboy 1. @@ -2281,7 +2386,7 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.1/guide/ - Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Migrating from Cowboy 2. + Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Migrating from Cowboy 2. @@ -2290,7 +2395,7 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.2/guide/ - Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Changes since Cowboy 2. + Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Changes since Cowboy 2. @@ -2299,7 +2404,7 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.3/guide/ - Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Migrating from Cowboy 2. + Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Migrating from Cowboy 2. @@ -2308,7 +2413,7 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.4/guide/ - Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Migrating from Cowboy 2. + Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Migrating from Cowboy 2. @@ -2317,7 +2422,7 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/erlang.mk/1/guide/ - Installation Getting started Overview Updating Erlang.mk Limitations Code Building Packages and dependencies NIFs and port drivers Releases Self-extracting releases Escripts OTP version management Compatibility with other build tools Documentation Asciidoc documentation EDoc comments Sphinx documentation Tests Erlang shell EUnit Common Test Triq Code coverage Continuous integration Dialyzer Xref Third-party plugins External plugins List of plugins About Erlang. + Installation Getting started Overview Updating Erlang.mk Limitations Code Building Packages and dependencies NIFs and port drivers Releases Self-extracting releases Escripts OTP version management Compatibility with other build tools Documentation Asciidoc documentation EDoc comments Sphinx documentation Tests Erlang shell EUnit Common Test Triq Code coverage Continuous integration Dialyzer Xref Third-party plugins External plugins List of plugins About Erlang. @@ -2327,9 +2432,9 @@ https://ninenines.eu/docs/en/gun/1.0/manual/ Name gun - HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP - Description Gun is an HTTP client for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Gun aims to provide an easy to use, asynchronous and always-connected client. It maintains a permanent connection to the server and reconnects automatically when necessary. - Modules gun(3) - Asynchronous HTTP client Dependencies cowlib(7) - Support library for manipulating Web protocols ssl - Secure communication over sockets All these applications must be started before the gun application. +Description Gun is an HTTP client for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Gun aims to provide an easy to use, asynchronous and always-connected client. It maintains a permanent connection to the server and reconnects automatically when necessary. +Modules gun(3) - Asynchronous HTTP client Dependencies cowlib(7) - Support library for manipulating Web protocols ssl - Secure communication over sockets All these applications must be started before the gun application. @@ -2338,7 +2443,7 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/gun/1.0/guide/ - Introduction Starting and stopping Supported protocols Connection Using HTTP Using Websocket + Introduction Starting and stopping Supported protocols Connection Using HTTP Using Websocket @@ -2348,8 +2453,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/http_status_codes/ Name HTTP status codes - status codes used by Cowboy - Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. - 100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. +Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. +100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. This behavior can be disabled using the appropriate body option. @@ -2359,8 +2464,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/http_status_codes/ Name HTTP status codes - status codes used by Cowboy - Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. - 100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. +Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. +100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. This behavior can be disabled using the appropriate body option. @@ -2370,8 +2475,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/http_status_codes/ Name HTTP status codes - status codes used by Cowboy - Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. - 100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. +Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. +100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. This behavior can be disabled using the appropriate body option. @@ -2381,8 +2486,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/http_status_codes/ Name HTTP status codes - status codes used by Cowboy - Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. - 100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. +Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. +100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. This behavior can be disabled using the appropriate body option. @@ -2392,8 +2497,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/http_status_codes/ Name HTTP status codes - status codes used by Cowboy - Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. - 100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. +Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. +100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. This behavior can be disabled using the appropriate body option. @@ -2402,7 +2507,7 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/ranch/1.2/manual/ - ranch(7) ranch(3) ranch_protocol(3) ranch_ssl(3) ranch_tcp(3) ranch_transport(3) + ranch(7) ranch(3) ranch_protocol(3) ranch_ssl(3) ranch_tcp(3) ranch_transport(3) @@ -2411,7 +2516,7 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/ranch/1.3/manual/ - ranch(7) ranch(3) ranch_protocol(3) ranch_ssl(3) ranch_tcp(3) ranch_transport(3) + ranch(7) ranch(3) ranch_protocol(3) ranch_ssl(3) ranch_tcp(3) ranch_transport(3) @@ -2420,7 +2525,16 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/ranch/1.4/manual/ - ranch(7) ranch(3) ranch_protocol(3) ranch_ssl(3) ranch_tcp(3) ranch_transport(3) + ranch(7) ranch(3) ranch_protocol(3) ranch_ssl(3) ranch_tcp(3) ranch_transport(3) + + + + Ranch Function Reference + https://ninenines.eu/docs/en/ranch/1.5/manual/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/manual/ + ranch(7) ranch(3) ranch_protocol(3) ranch_ssl(3) ranch_tcp(3) ranch_transport(3) @@ -2429,7 +2543,7 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/ranch/1.2/guide/ - Introduction Listeners Transports Protocols Embedded mode Writing parsers SSL client authentication Internals + Introduction Listeners Transports Protocols Embedded mode Writing parsers SSL client authentication Internals @@ -2438,7 +2552,7 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/ranch/1.3/guide/ - Introduction Listeners Transports Protocols Embedded mode Writing parsers SSL client authentication Internals + Introduction Listeners Transports Protocols Embedded mode Writing parsers SSL client authentication Internals @@ -2447,7 +2561,16 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/ranch/1.4/guide/ - Introduction Listeners Transports Protocols Embedded mode Writing parsers SSL client authentication Internals + Introduction Listeners Transports Protocols Embedded mode Writing parsers SSL client authentication Internals + + + + Ranch User Guide + https://ninenines.eu/docs/en/ranch/1.5/guide/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/guide/ + Introduction Listeners Transports Protocols Embedded mode Writing parsers SSL client authentication Internals @@ -2457,8 +2580,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy/ Name cowboy - HTTP server - Description The module cowboy provides convenience functions for manipulating Ranch listeners. - Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&#8217;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. +Description The module cowboy provides convenience functions for manipulating Ranch listeners. +Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&apos;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. @@ -2468,8 +2591,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy/ Name cowboy - HTTP server - Description The module cowboy provides convenience functions for manipulating Ranch listeners. - Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&#8217;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. +Description The module cowboy provides convenience functions for manipulating Ranch listeners. +Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&apos;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. @@ -2479,8 +2602,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy/ Name cowboy - HTTP server - Description The module cowboy provides convenience functions for manipulating Ranch listeners. - Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&#8217;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. +Description The module cowboy provides convenience functions for manipulating Ranch listeners. +Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&apos;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. @@ -2490,8 +2613,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy/ Name cowboy - HTTP server - Description The module cowboy provides convenience functions for manipulating Ranch listeners. - Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&#8217;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. +Description The module cowboy provides convenience functions for manipulating Ranch listeners. +Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&apos;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. @@ -2501,8 +2624,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy/ Name cowboy - HTTP server - Description The module cowboy provides convenience functions for manipulating Ranch listeners. - Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&#8217;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. +Description The module cowboy provides convenience functions for manipulating Ranch listeners. +Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&apos;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. @@ -2512,10 +2635,10 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_app/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2525,10 +2648,10 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_app/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2538,10 +2661,10 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_app/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2551,10 +2674,10 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_app/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2564,10 +2687,10 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_app/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2576,11 +2699,11 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy.set_env/ - Name cowboy:set_env - Update a listener&#8217;s environment value - Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. - This is most useful for updating the routes dynamically, without having to restart the listener. - The new value will only be available to new connections. Pre-existing connections will still use the old value. - Arguments Name The name of the listener to update. + Name cowboy:set_env - Update a listener&apos;s environment value +Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. +This is most useful for updating the routes dynamically, without having to restart the listener. +The new value will only be available to new connections. Pre-existing connections will still use the old value. +Arguments Name The name of the listener to update. @@ -2589,11 +2712,11 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy.set_env/ - Name cowboy:set_env - Update a listener&#8217;s environment value - Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. - This is most useful for updating the routes dynamically, without having to restart the listener. - The new value will only be available to new connections. Pre-existing connections will still use the old value. - Arguments Name The name of the listener to update. + Name cowboy:set_env - Update a listener&apos;s environment value +Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. +This is most useful for updating the routes dynamically, without having to restart the listener. +The new value will only be available to new connections. Pre-existing connections will still use the old value. +Arguments Name The name of the listener to update. @@ -2602,11 +2725,11 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy.set_env/ - Name cowboy:set_env - Update a listener&#8217;s environment value - Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. - This is most useful for updating the routes dynamically, without having to restart the listener. - The new value will only be available to new connections. Pre-existing connections will still use the old value. - Arguments Name The name of the listener to update. + Name cowboy:set_env - Update a listener&apos;s environment value +Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. +This is most useful for updating the routes dynamically, without having to restart the listener. +The new value will only be available to new connections. Pre-existing connections will still use the old value. +Arguments Name The name of the listener to update. @@ -2615,11 +2738,11 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy.set_env/ - Name cowboy:set_env - Update a listener&#8217;s environment value - Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. - This is most useful for updating the routes dynamically, without having to restart the listener. - The new value will only be available to new connections. Pre-existing connections will still use the old value. - Arguments Name The name of the listener to update. + Name cowboy:set_env - Update a listener&apos;s environment value +Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. +This is most useful for updating the routes dynamically, without having to restart the listener. +The new value will only be available to new connections. Pre-existing connections will still use the old value. +Arguments Name The name of the listener to update. @@ -2628,11 +2751,11 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy.set_env/ - Name cowboy:set_env - Update a listener&#8217;s environment value - Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. - This is most useful for updating the routes dynamically, without having to restart the listener. - The new value will only be available to new connections. Pre-existing connections will still use the old value. - Arguments Name The name of the listener to update. + Name cowboy:set_env - Update a listener&apos;s environment value +Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. +This is most useful for updating the routes dynamically, without having to restart the listener. +The new value will only be available to new connections. Pre-existing connections will still use the old value. +Arguments Name The name of the listener to update. @@ -2642,8 +2765,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy.start_clear/ Name cowboy:start_clear - Listen for connections using plain TCP - Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -2653,8 +2777,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy.start_clear/ Name cowboy:start_clear - Listen for connections using plain TCP - Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -2664,8 +2789,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy.start_clear/ Name cowboy:start_clear - Listen for connections using plain TCP - Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -2675,8 +2801,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy.start_clear/ Name cowboy:start_clear - Listen for connections using plain TCP - Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -2686,8 +2813,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy.start_clear/ Name cowboy:start_clear - Listen for connections using plain TCP - Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -2697,9 +2825,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy.start_tls/ Name cowboy:start_tls - Listen for connections using TLS - Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. - Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. +Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -2709,9 +2837,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy.start_tls/ Name cowboy:start_tls - Listen for connections using TLS - Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. - Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. +Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -2721,9 +2849,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy.start_tls/ Name cowboy:start_tls - Listen for connections using TLS - Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. - Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. +Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -2733,9 +2861,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy.start_tls/ Name cowboy:start_tls - Listen for connections using TLS - Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. - Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. +Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -2745,9 +2873,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy.start_tls/ Name cowboy:start_tls - Listen for connections using TLS - Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. - Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. +Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -2757,10 +2885,12 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy.stop_listener/ Name cowboy:stop_listener - Stop the given listener - Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. - Alias of ranch:stop_listener(3). - Arguments Name The name of the listener to be stopped. The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. - Return value The atom ok is returned on success. +Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. +Alias of ranch:stop_listener(3). +Arguments Name The name of the listener to be stopped. +The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. + Return value The atom ok is returned on success. +The {error, not_found} tuple is returned when the listener does not exist. @@ -2770,10 +2900,12 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy.stop_listener/ Name cowboy:stop_listener - Stop the given listener - Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. - Alias of ranch:stop_listener(3). - Arguments Name The name of the listener to be stopped. The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. - Return value The atom ok is returned on success. +Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. +Alias of ranch:stop_listener(3). +Arguments Name The name of the listener to be stopped. +The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. + Return value The atom ok is returned on success. +The {error, not_found} tuple is returned when the listener does not exist. @@ -2783,10 +2915,12 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy.stop_listener/ Name cowboy:stop_listener - Stop the given listener - Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. - Alias of ranch:stop_listener(3). - Arguments Name The name of the listener to be stopped. The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. - Return value The atom ok is returned on success. +Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. +Alias of ranch:stop_listener(3). +Arguments Name The name of the listener to be stopped. +The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. + Return value The atom ok is returned on success. +The {error, not_found} tuple is returned when the listener does not exist. @@ -2796,10 +2930,12 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy.stop_listener/ Name cowboy:stop_listener - Stop the given listener - Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. - Alias of ranch:stop_listener(3). - Arguments Name The name of the listener to be stopped. The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. - Return value The atom ok is returned on success. +Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. +Alias of ranch:stop_listener(3). +Arguments Name The name of the listener to be stopped. +The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. + Return value The atom ok is returned on success. +The {error, not_found} tuple is returned when the listener does not exist. @@ -2809,10 +2945,12 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy.stop_listener/ Name cowboy:stop_listener - Stop the given listener - Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. - Alias of ranch:stop_listener(3). - Arguments Name The name of the listener to be stopped. The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. - Return value The atom ok is returned on success. +Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. +Alias of ranch:stop_listener(3). +Arguments Name The name of the listener to be stopped. +The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. + Return value The atom ok is returned on success. +The {error, not_found} tuple is returned when the listener does not exist. @@ -2822,10 +2960,10 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_constraints/ Name cowboy_constraints - Constraints - Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. - Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. - Exports Built-in constraints: - cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. +Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. +Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. +Exports Built-in constraints: +cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. @@ -2835,10 +2973,10 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_constraints/ Name cowboy_constraints - Constraints - Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. - Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. - Exports Built-in constraints: - cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. +Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. +Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. +Exports Built-in constraints: +cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. @@ -2848,10 +2986,10 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_constraints/ Name cowboy_constraints - Constraints - Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. - Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. - Exports Built-in constraints: - cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. +Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. +Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. +Exports Built-in constraints: +cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. @@ -2861,10 +2999,10 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_constraints/ Name cowboy_constraints - Constraints - Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. - Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. - Exports Built-in constraints: - cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. +Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. +Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. +Exports Built-in constraints: +cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. @@ -2874,10 +3012,10 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_constraints/ Name cowboy_constraints - Constraints - Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. - Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. - Exports Built-in constraints: - cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. +Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. +Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. +Exports Built-in constraints: +cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. @@ -2887,10 +3025,10 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_constraints.int/ Name cowboy_constraints:int - Integer constraint - Description Constraint functions implement a number of different operations. - int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. - int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. - int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. +Description Constraint functions implement a number of different operations. +int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. +int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. +int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. @@ -2900,10 +3038,10 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_constraints.int/ Name cowboy_constraints:int - Integer constraint - Description Constraint functions implement a number of different operations. - int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. - int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. - int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. +Description Constraint functions implement a number of different operations. +int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. +int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. +int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. @@ -2913,10 +3051,10 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_constraints.int/ Name cowboy_constraints:int - Integer constraint - Description Constraint functions implement a number of different operations. - int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. - int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. - int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. +Description Constraint functions implement a number of different operations. +int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. +int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. +int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. @@ -2926,10 +3064,10 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_constraints.int/ Name cowboy_constraints:int - Integer constraint - Description Constraint functions implement a number of different operations. - int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. - int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. - int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. +Description Constraint functions implement a number of different operations. +int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. +int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. +int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. @@ -2939,10 +3077,10 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_constraints.int/ Name cowboy_constraints:int - Integer constraint - Description Constraint functions implement a number of different operations. - int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. - int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. - int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. +Description Constraint functions implement a number of different operations. +int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. +int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. +int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. @@ -2952,11 +3090,11 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_constraints.nonempty/ Name cowboy_constraints:nonempty - Non-empty constraint - Description Constraint functions implement a number of different operations. - nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. - nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. - nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. - Arguments Arguments vary depending on the operation. +Description Constraint functions implement a number of different operations. +nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. +nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. +nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. +Arguments Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument. @@ -2966,11 +3104,11 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_constraints.nonempty/ Name cowboy_constraints:nonempty - Non-empty constraint - Description Constraint functions implement a number of different operations. - nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. - nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. - nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. - Arguments Arguments vary depending on the operation. +Description Constraint functions implement a number of different operations. +nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. +nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. +nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. +Arguments Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument. @@ -2980,11 +3118,11 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_constraints.nonempty/ Name cowboy_constraints:nonempty - Non-empty constraint - Description Constraint functions implement a number of different operations. - nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. - nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. - nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. - Arguments Arguments vary depending on the operation. +Description Constraint functions implement a number of different operations. +nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. +nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. +nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. +Arguments Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument. @@ -2994,11 +3132,11 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_constraints.nonempty/ Name cowboy_constraints:nonempty - Non-empty constraint - Description Constraint functions implement a number of different operations. - nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. - nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. - nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. - Arguments Arguments vary depending on the operation. +Description Constraint functions implement a number of different operations. +nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. +nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. +nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. +Arguments Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument. @@ -3008,11 +3146,11 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_constraints.nonempty/ Name cowboy_constraints:nonempty - Non-empty constraint - Description Constraint functions implement a number of different operations. - nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. - nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. - nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. - Arguments Arguments vary depending on the operation. +Description Constraint functions implement a number of different operations. +nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. +nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. +nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. +Arguments Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument. @@ -3022,9 +3160,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_handler/ Name cowboy_handler - Plain HTTP handlers - Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. - This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. - This module also defines a callback interface for handling HTTP requests. +Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. +This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. +This module also defines a callback interface for handling HTTP requests. @@ -3034,9 +3172,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_handler/ Name cowboy_handler - Plain HTTP handlers - Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. - This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. - This module also defines a callback interface for handling HTTP requests. +Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. +This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. +This module also defines a callback interface for handling HTTP requests. @@ -3046,9 +3184,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_handler/ Name cowboy_handler - Plain HTTP handlers - Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. - This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. - This module also defines a callback interface for handling HTTP requests. +Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. +This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. +This module also defines a callback interface for handling HTTP requests. @@ -3058,9 +3196,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_handler/ Name cowboy_handler - Plain HTTP handlers - Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. - This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. - This module also defines a callback interface for handling HTTP requests. +Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. +This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. +This module also defines a callback interface for handling HTTP requests. @@ -3070,9 +3208,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_handler/ Name cowboy_handler - Plain HTTP handlers - Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. - This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. - This module also defines a callback interface for handling HTTP requests. +Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. +This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. +This module also defines a callback interface for handling HTTP requests. @@ -3082,9 +3220,11 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_handler.terminate/ Name cowboy_handler:terminate - Terminate the handler - Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. - Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. - Arguments Reason Reason for termination. PartialReq The Req object. +Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. +Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. +Arguments Reason Reason for termination. + PartialReq The Req object. +It is possible to remove fields from the Req object to save memory when the handler has no concept of requests/responses. @@ -3094,9 +3234,11 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_handler.terminate/ Name cowboy_handler:terminate - Terminate the handler - Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. - Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. - Arguments Reason Reason for termination. PartialReq The Req object. +Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. +Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. +Arguments Reason Reason for termination. + PartialReq The Req object. +It is possible to remove fields from the Req object to save memory when the handler has no concept of requests/responses. @@ -3106,9 +3248,11 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_handler.terminate/ Name cowboy_handler:terminate - Terminate the handler - Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. - Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. - Arguments Reason Reason for termination. PartialReq The Req object. +Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. +Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. +Arguments Reason Reason for termination. + PartialReq The Req object. +It is possible to remove fields from the Req object to save memory when the handler has no concept of requests/responses. @@ -3118,9 +3262,11 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_handler.terminate/ Name cowboy_handler:terminate - Terminate the handler - Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. - Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. - Arguments Reason Reason for termination. PartialReq The Req object. +Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. +Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. +Arguments Reason Reason for termination. + PartialReq The Req object. +It is possible to remove fields from the Req object to save memory when the handler has no concept of requests/responses. @@ -3130,9 +3276,11 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_handler.terminate/ Name cowboy_handler:terminate - Terminate the handler - Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. - Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. - Arguments Reason Reason for termination. PartialReq The Req object. +Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. +Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. +Arguments Reason Reason for termination. + PartialReq The Req object. +It is possible to remove fields from the Req object to save memory when the handler has no concept of requests/responses. @@ -3142,8 +3290,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_http/ Name cowboy_http - HTTP/1.1 - Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. +Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. @@ -3153,8 +3301,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_http/ Name cowboy_http - HTTP/1.1 - Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. +Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. @@ -3164,8 +3312,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_http/ Name cowboy_http - HTTP/1.1 - Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), max_skip_body_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. +Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), max_skip_body_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. @@ -3175,8 +3323,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_http/ Name cowboy_http - HTTP/1.1 - Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), max_skip_body_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. +Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), max_skip_body_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. @@ -3186,8 +3334,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_http/ Name cowboy_http - HTTP/1.1 - Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), max_skip_body_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. +Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), max_skip_body_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. @@ -3197,10 +3345,10 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_http2/ Name cowboy_http2 - HTTP/2 - Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), middlewares =&gt; [module()], preface_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. - This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions. - It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2. +Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), middlewares =&gt; [module()], preface_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. +This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions. +It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2. @@ -3210,10 +3358,10 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_http2/ Name cowboy_http2 - HTTP/2 - Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), middlewares =&gt; [module()], preface_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. - This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions. - It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2. +Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), middlewares =&gt; [module()], preface_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. +This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions. +It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2. @@ -3223,10 +3371,10 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_http2/ Name cowboy_http2 - HTTP/2 - Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), middlewares =&gt; [module()], preface_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. - This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions. - It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2. +Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), middlewares =&gt; [module()], preface_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. +This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions. +It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2. @@ -3236,10 +3384,10 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_http2/ Name cowboy_http2 - HTTP/2 - Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), middlewares =&gt; [module()], preface_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. - This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions. - It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2. +Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), middlewares =&gt; [module()], preface_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. +This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions. +It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2. @@ -3249,8 +3397,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_http2/ Name cowboy_http2 - HTTP/2 - Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, enable_connect_protocol =&gt; boolean(), env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), initial_connection_window_size =&gt; 65535..16#7fffffff, initial_stream_window_size =&gt; 0..16#7fffffff, max_concurrent_streams =&gt; non_neg_integer() | infinity, max_decode_table_size =&gt; non_neg_integer(), max_encode_table_size =&gt; non_neg_integer(), max_frame_size_received =&gt; 16384..16777215, max_frame_size_sent =&gt; 16384..16777215 | infinity, middlewares =&gt; [module()], preface_timeout =&gt; timeout(), settings_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. +Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, enable_connect_protocol =&gt; boolean(), env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), initial_connection_window_size =&gt; 65535..16#7fffffff, initial_stream_window_size =&gt; 0..16#7fffffff, max_concurrent_streams =&gt; non_neg_integer() | infinity, max_decode_table_size =&gt; non_neg_integer(), max_encode_table_size =&gt; non_neg_integer(), max_frame_size_received =&gt; 16384..16777215, max_frame_size_sent =&gt; 16384..16777215 | infinity, middlewares =&gt; [module()], preface_timeout =&gt; timeout(), settings_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. @@ -3260,10 +3408,10 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_loop/ Name cowboy_loop - Loop handlers - Description The module cowboy_loop defines a callback interface for long running HTTP connections. - You should switch to this behavior for long polling, server-sent events and similar long-running requests. - There are generally two usage patterns: - Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). +Description The module cowboy_loop defines a callback interface for long running HTTP connections. +You should switch to this behavior for long polling, server-sent events and similar long-running requests. +There are generally two usage patterns: +Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). @@ -3273,10 +3421,10 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_loop/ Name cowboy_loop - Loop handlers - Description The module cowboy_loop defines a callback interface for long running HTTP connections. - You should switch to this behavior for long polling, server-sent events and similar long-running requests. - There are generally two usage patterns: - Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). +Description The module cowboy_loop defines a callback interface for long running HTTP connections. +You should switch to this behavior for long polling, server-sent events and similar long-running requests. +There are generally two usage patterns: +Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). @@ -3286,10 +3434,10 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_loop/ Name cowboy_loop - Loop handlers - Description The module cowboy_loop defines a callback interface for long running HTTP connections. - You should switch to this behavior for long polling, server-sent events and similar long-running requests. - There are generally two usage patterns: - Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). +Description The module cowboy_loop defines a callback interface for long running HTTP connections. +You should switch to this behavior for long polling, server-sent events and similar long-running requests. +There are generally two usage patterns: +Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). @@ -3299,10 +3447,10 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_loop/ Name cowboy_loop - Loop handlers - Description The module cowboy_loop defines a callback interface for long running HTTP connections. - You should switch to this behavior for long polling, server-sent events and similar long-running requests. - There are generally two usage patterns: - Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). +Description The module cowboy_loop defines a callback interface for long running HTTP connections. +You should switch to this behavior for long polling, server-sent events and similar long-running requests. +There are generally two usage patterns: +Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). @@ -3312,10 +3460,10 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_loop/ Name cowboy_loop - Loop handlers - Description The module cowboy_loop defines a callback interface for long running HTTP connections. - You should switch to this behavior for long polling, server-sent events and similar long-running requests. - There are generally two usage patterns: - Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). +Description The module cowboy_loop defines a callback interface for long running HTTP connections. +You should switch to this behavior for long polling, server-sent events and similar long-running requests. +There are generally two usage patterns: +Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). @@ -3325,10 +3473,10 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_middleware/ Name cowboy_middleware - Middlewares - Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. - Middlewares process the request sequentially in the order they are configured. - Callbacks Middlewares implement the following interface: - execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. +Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. +Middlewares process the request sequentially in the order they are configured. +Callbacks Middlewares implement the following interface: +execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. It must execute the middleware and return with instructions for Cowboy. @@ -3338,10 +3486,10 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_middleware/ Name cowboy_middleware - Middlewares - Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. - Middlewares process the request sequentially in the order they are configured. - Callbacks Middlewares implement the following interface: - execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. +Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. +Middlewares process the request sequentially in the order they are configured. +Callbacks Middlewares implement the following interface: +execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. It must execute the middleware and return with instructions for Cowboy. @@ -3351,10 +3499,10 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_middleware/ Name cowboy_middleware - Middlewares - Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. - Middlewares process the request sequentially in the order they are configured. - Callbacks Middlewares implement the following interface: - execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. +Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. +Middlewares process the request sequentially in the order they are configured. +Callbacks Middlewares implement the following interface: +execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. It must execute the middleware and return with instructions for Cowboy. @@ -3364,10 +3512,10 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_middleware/ Name cowboy_middleware - Middlewares - Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. - Middlewares process the request sequentially in the order they are configured. - Callbacks Middlewares implement the following interface: - execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. +Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. +Middlewares process the request sequentially in the order they are configured. +Callbacks Middlewares implement the following interface: +execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. It must execute the middleware and return with instructions for Cowboy. @@ -3377,10 +3525,10 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_middleware/ Name cowboy_middleware - Middlewares - Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. - Middlewares process the request sequentially in the order they are configured. - Callbacks Middlewares implement the following interface: - execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. +Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. +Middlewares process the request sequentially in the order they are configured. +Callbacks Middlewares implement the following interface: +execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. It must execute the middleware and return with instructions for Cowboy. @@ -3390,12 +3538,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req/ Name cowboy_req - HTTP request and response - Description The module cowboy_req provides functions to access, manipulate and respond to requests. - There are four types of functions in this module. They can be differentiated by their name and their return type: - Type Name pattern Return type access - no verb, parse_*, match_* - Value - question +Description The module cowboy_req provides functions to access, manipulate and respond to requests. +There are four types of functions in this module. They can be differentiated by their name and their return type: +Type Name pattern Return type access no verb, parse_*, match_* Value question has_* boolean() modification set_* Req action any other verb ok | {Result, Value, Req} Any Req returned must be used in place of the one passed as argument. @@ -3405,12 +3550,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req/ Name cowboy_req - HTTP request and response - Description The module cowboy_req provides functions to access, manipulate and respond to requests. - There are four types of functions in this module. They can be differentiated by their name and their return type: - Type Name pattern Return type access - no verb, parse_*, match_* - Value - question +Description The module cowboy_req provides functions to access, manipulate and respond to requests. +There are four types of functions in this module. They can be differentiated by their name and their return type: +Type Name pattern Return type access no verb, parse_*, match_* Value question has_* boolean() modification set_* Req action any other verb ok | {Result, Value, Req} Any Req returned must be used in place of the one passed as argument. @@ -3420,12 +3562,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req/ Name cowboy_req - HTTP request and response - Description The module cowboy_req provides functions to access, manipulate and respond to requests. - There are four types of functions in this module. They can be differentiated by their name and their return type: - Type Name pattern Return type access - no verb, parse_*, match_* - Value - question +Description The module cowboy_req provides functions to access, manipulate and respond to requests. +There are four types of functions in this module. They can be differentiated by their name and their return type: +Type Name pattern Return type access no verb, parse_*, match_* Value question has_* boolean() modification set_* Req action any other verb ok | {Result, Value, Req} Any Req returned must be used in place of the one passed as argument. @@ -3435,12 +3574,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req/ Name cowboy_req - HTTP request and response - Description The module cowboy_req provides functions to access, manipulate and respond to requests. - There are four types of functions in this module. They can be differentiated by their name and their return type: - Type Name pattern Return type access - no verb, parse_*, match_* - Value - question +Description The module cowboy_req provides functions to access, manipulate and respond to requests. +There are four types of functions in this module. They can be differentiated by their name and their return type: +Type Name pattern Return type access no verb, parse_*, match_* Value question has_* boolean() modification set_* Req action any other verb ok | {Result, Value, Req} Any Req returned must be used in place of the one passed as argument. @@ -3450,12 +3586,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req/ Name cowboy_req - HTTP request and response - Description The module cowboy_req provides functions to access, manipulate and respond to requests. - There are four types of functions in this module. They can be differentiated by their name and their return type: - Type Name pattern Return type access - no verb, parse_*, match_* - Value - question +Description The module cowboy_req provides functions to access, manipulate and respond to requests. +There are four types of functions in this module. They can be differentiated by their name and their return type: +Type Name pattern Return type access no verb, parse_*, match_* Value question has_* boolean() modification set_* Req action any other verb ok | {Result, Value, Req} Any Req returned must be used in place of the one passed as argument. @@ -3465,8 +3598,11 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.binding/ Name cowboy_req:binding - Access a value bound from the route - Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. - Arguments Name Desired binding name as an atom. Req The Req object. Default Default value returned when the binding is missing. +Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. +Arguments Name Desired binding name as an atom. + Req The Req object. + Default Default value returned when the binding is missing. + Return value By default the value is a case sensitive binary string, however constraints may change the type of this value (for example automatically converting numbers to integer). @@ -3476,8 +3612,11 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.binding/ Name cowboy_req:binding - Access a value bound from the route - Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. - Arguments Name Desired binding name as an atom. Req The Req object. Default Default value returned when the binding is missing. +Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. +Arguments Name Desired binding name as an atom. + Req The Req object. + Default Default value returned when the binding is missing. + Return value By default the value is a case sensitive binary string, however constraints may change the type of this value (for example automatically converting numbers to integer). @@ -3487,8 +3626,11 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.binding/ Name cowboy_req:binding - Access a value bound from the route - Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. - Arguments Name Desired binding name as an atom. Req The Req object. Default Default value returned when the binding is missing. +Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. +Arguments Name Desired binding name as an atom. + Req The Req object. + Default Default value returned when the binding is missing. + Return value By default the value is a case sensitive binary string, however constraints may change the type of this value (for example automatically converting numbers to integer). @@ -3498,8 +3640,11 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.binding/ Name cowboy_req:binding - Access a value bound from the route - Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. - Arguments Name Desired binding name as an atom. Req The Req object. Default Default value returned when the binding is missing. +Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. +Arguments Name Desired binding name as an atom. + Req The Req object. + Default Default value returned when the binding is missing. + Return value By default the value is a case sensitive binary string, however constraints may change the type of this value (for example automatically converting numbers to integer). @@ -3509,8 +3654,11 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.binding/ Name cowboy_req:binding - Access a value bound from the route - Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. - Arguments Name Desired binding name as an atom. Req The Req object. Default Default value returned when the binding is missing. +Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. +Arguments Name Desired binding name as an atom. + Req The Req object. + Default Default value returned when the binding is missing. + Return value By default the value is a case sensitive binary string, however constraints may change the type of this value (for example automatically converting numbers to integer). @@ -3520,9 +3668,10 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.bindings/ Name cowboy_req:bindings - Access all values bound from the route - Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. - Arguments Req The Req object. Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). - Changelog 2. +Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. +Arguments Req The Req object. + Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). +Changelog 2.0: Only the values are returned, they are no longer wrapped in a tuple. @@ -3532,9 +3681,10 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.bindings/ Name cowboy_req:bindings - Access all values bound from the route - Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. - Arguments Req The Req object. Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). - Changelog 2. +Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. +Arguments Req The Req object. + Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). +Changelog 2.0: Only the values are returned, they are no longer wrapped in a tuple. @@ -3544,9 +3694,10 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.bindings/ Name cowboy_req:bindings - Access all values bound from the route - Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. - Arguments Req The Req object. Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). - Changelog 2. +Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. +Arguments Req The Req object. + Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). +Changelog 2.0: Only the values are returned, they are no longer wrapped in a tuple. @@ -3556,9 +3707,10 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.bindings/ Name cowboy_req:bindings - Access all values bound from the route - Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. - Arguments Req The Req object. Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). - Changelog 2. +Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. +Arguments Req The Req object. + Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). +Changelog 2.0: Only the values are returned, they are no longer wrapped in a tuple. @@ -3568,9 +3720,10 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.bindings/ Name cowboy_req:bindings - Access all values bound from the route - Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. - Arguments Req The Req object. Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). - Changelog 2. +Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. +Arguments Req The Req object. + Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). +Changelog 2.0: Only the values are returned, they are no longer wrapped in a tuple. @@ -3580,9 +3733,10 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.body_length/ Name cowboy_req:body_length - Body length - Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. - The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. - Arguments Req The Req object. Return value The length of the request body, or undefined if it is not known. +Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. +The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. +Arguments Req The Req object. + Return value The length of the request body, or undefined if it is not known. @@ -3592,9 +3746,10 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.body_length/ Name cowboy_req:body_length - Body length - Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. - The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. - Arguments Req The Req object. Return value The length of the request body, or undefined if it is not known. +Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. +The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. +Arguments Req The Req object. + Return value The length of the request body, or undefined if it is not known. @@ -3604,9 +3759,10 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.body_length/ Name cowboy_req:body_length - Body length - Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. - The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. - Arguments Req The Req object. Return value The length of the request body, or undefined if it is not known. +Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. +The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. +Arguments Req The Req object. + Return value The length of the request body, or undefined if it is not known. @@ -3616,9 +3772,10 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.body_length/ Name cowboy_req:body_length - Body length - Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. - The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. - Arguments Req The Req object. Return value The length of the request body, or undefined if it is not known. +Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. +The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. +Arguments Req The Req object. + Return value The length of the request body, or undefined if it is not known. @@ -3628,9 +3785,10 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.body_length/ Name cowboy_req:body_length - Body length - Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. - The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. - Arguments Req The Req object. Return value The length of the request body, or undefined if it is not known. +Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. +The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. +Arguments Req The Req object. + Return value The length of the request body, or undefined if it is not known. @@ -3640,9 +3798,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.cert/ Name cowboy_req:cert - Client TLS certificate - Description cert(Req :: cowboy_req:req()) -&gt; binary() | undefined Return the peer&#8217;s TLS certificate. - Using the default configuration this function will always return undefined. You need to explicitly configure Cowboy to request the client certificate. To do this you need to set the verify transport option to verify_peer: - {ok, _} = cowboy:start_tls(example, [ {port, 8443}, {cert, "path/to/cert.pem"}, {verify, verify_peer} ], #{ env =&gt; #{dispatch =&gt; Dispatch} }). +Description cert(Req :: cowboy_req:req()) -&gt; binary() | undefined Return the peer&apos;s TLS certificate. +Using the default configuration this function will always return undefined. You need to explicitly configure Cowboy to request the client certificate. To do this you need to set the verify transport option to verify_peer: +{ok, _} = cowboy:start_tls(example, [ {port, 8443}, {cert, "path/to/cert.pem"}, {verify, verify_peer} ], #{ env =&gt; #{dispatch =&gt; Dispatch} }). @@ -3652,9 +3810,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.cert/ Name cowboy_req:cert - Client TLS certificate - Description cert(Req :: cowboy_req:req()) -&gt; binary() | undefined Return the peer&#8217;s TLS certificate. - Using the default configuration this function will always return undefined. You need to explicitly configure Cowboy to request the client certificate. To do this you need to set the verify transport option to verify_peer: - {ok, _} = cowboy:start_tls(example, [ {port, 8443}, {cert, "path/to/cert.pem"}, {verify, verify_peer} ], #{ env =&gt; #{dispatch =&gt; Dispatch} }). +Description cert(Req :: cowboy_req:req()) -&gt; binary() | undefined Return the peer&apos;s TLS certificate. +Using the default configuration this function will always return undefined. You need to explicitly configure Cowboy to request the client certificate. To do this you need to set the verify transport option to verify_peer: +{ok, _} = cowboy:start_tls(example, [ {port, 8443}, {cert, "path/to/cert.pem"}, {verify, verify_peer} ], #{ env =&gt; #{dispatch =&gt; Dispatch} }). @@ -3664,9 +3822,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.cert/ Name cowboy_req:cert - Client TLS certificate - Description cert(Req :: cowboy_req:req()) -&gt; binary() | undefined Return the peer&#8217;s TLS certificate. - Using the default configuration this function will always return undefined. You need to explicitly configure Cowboy to request the client certificate. To do this you need to set the verify transport option to verify_peer: - {ok, _} = cowboy:start_tls(example, [ {port, 8443}, {cert, "path/to/cert.pem"}, {verify, verify_peer} ], #{ env =&gt; #{dispatch =&gt; Dispatch} }). +Description cert(Req :: cowboy_req:req()) -&gt; binary() | undefined Return the peer&apos;s TLS certificate. +Using the default configuration this function will always return undefined. You need to explicitly configure Cowboy to request the client certificate. To do this you need to set the verify transport option to verify_peer: +{ok, _} = cowboy:start_tls(example, [ {port, 8443}, {cert, "path/to/cert.pem"}, {verify, verify_peer} ], #{ env =&gt; #{dispatch =&gt; Dispatch} }). @@ -3676,9 +3834,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.cert/ Name cowboy_req:cert - Client TLS certificate - Description cert(Req :: cowboy_req:req()) -&gt; binary() | undefined Return the peer&#8217;s TLS certificate. - Using the default configuration this function will always return undefined. You need to explicitly configure Cowboy to request the client certificate. To do this you need to set the verify transport option to verify_peer: - {ok, _} = cowboy:start_tls(example, [ {port, 8443}, {cert, "path/to/cert.pem"}, {verify, verify_peer} ], #{ env =&gt; #{dispatch =&gt; Dispatch} }). +Description cert(Req :: cowboy_req:req()) -&gt; binary() | undefined Return the peer&apos;s TLS certificate. +Using the default configuration this function will always return undefined. You need to explicitly configure Cowboy to request the client certificate. To do this you need to set the verify transport option to verify_peer: +{ok, _} = cowboy:start_tls(example, [ {port, 8443}, {cert, "path/to/cert.pem"}, {verify, verify_peer} ], #{ env =&gt; #{dispatch =&gt; Dispatch} }). @@ -3688,9 +3846,11 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.delete_resp_header/ Name cowboy_req:delete_resp_header - Delete a response header - Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. + Req The Req object. + Return value A new Req object is returned. @@ -3700,9 +3860,11 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.delete_resp_header/ Name cowboy_req:delete_resp_header - Delete a response header - Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. + Req The Req object. + Return value A new Req object is returned. @@ -3712,9 +3874,11 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.delete_resp_header/ Name cowboy_req:delete_resp_header - Delete a response header - Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. + Req The Req object. + Return value A new Req object is returned. @@ -3724,9 +3888,11 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.delete_resp_header/ Name cowboy_req:delete_resp_header - Delete a response header - Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. + Req The Req object. + Return value A new Req object is returned. @@ -3736,9 +3902,11 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.delete_resp_header/ Name cowboy_req:delete_resp_header - Delete a response header - Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. + Req The Req object. + Return value A new Req object is returned. @@ -3748,9 +3916,10 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.has_body/ Name cowboy_req:has_body - Is there a request body? - Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. - Arguments Req The Req object. Return value A boolean indicating whether the request has a body. - Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). +Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. +Arguments Req The Req object. + Return value A boolean indicating whether the request has a body. +Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). See also cowboy_req(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3) @@ -3760,9 +3929,10 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.has_body/ Name cowboy_req:has_body - Is there a request body? - Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. - Arguments Req The Req object. Return value A boolean indicating whether the request has a body. - Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). +Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. +Arguments Req The Req object. + Return value A boolean indicating whether the request has a body. +Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). See also cowboy_req(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3) @@ -3772,9 +3942,10 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.has_body/ Name cowboy_req:has_body - Is there a request body? - Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. - Arguments Req The Req object. Return value A boolean indicating whether the request has a body. - Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). +Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. +Arguments Req The Req object. + Return value A boolean indicating whether the request has a body. +Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). See also cowboy_req(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3) @@ -3784,9 +3955,10 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.has_body/ Name cowboy_req:has_body - Is there a request body? - Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. - Arguments Req The Req object. Return value A boolean indicating whether the request has a body. - Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). +Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. +Arguments Req The Req object. + Return value A boolean indicating whether the request has a body. +Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). See also cowboy_req(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3) @@ -3796,9 +3968,10 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.has_body/ Name cowboy_req:has_body - Is there a request body? - Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. - Arguments Req The Req object. Return value A boolean indicating whether the request has a body. - Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). +Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. +Arguments Req The Req object. + Return value A boolean indicating whether the request has a body. +Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). See also cowboy_req(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3) @@ -3808,10 +3981,11 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.has_resp_body/ Name cowboy_req:has_resp_body - Is there a response body? - Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. - Arguments Req The Req object. Return value A boolean indicating whether a response body has been set. - This function will return false when an empty response body has been set. - Changelog 1. +Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. +Arguments Req The Req object. + Return value A boolean indicating whether a response body has been set. +This function will return false when an empty response body has been set. +Changelog 1.0: Function introduced. Examples Check whether a body has been set false = cowboy_req:has_resp_body(Req0), Req1 = cowboy_req:set_resp_body(&lt;&lt;" @@ -3821,10 +3995,11 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.has_resp_body/ Name cowboy_req:has_resp_body - Is there a response body? - Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. - Arguments Req The Req object. Return value A boolean indicating whether a response body has been set. - This function will return false when an empty response body has been set. - Changelog 1. +Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. +Arguments Req The Req object. + Return value A boolean indicating whether a response body has been set. +This function will return false when an empty response body has been set. +Changelog 1.0: Function introduced. Examples Check whether a body has been set false = cowboy_req:has_resp_body(Req0), Req1 = cowboy_req:set_resp_body(&lt;&lt;" @@ -3834,10 +4009,11 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.has_resp_body/ Name cowboy_req:has_resp_body - Is there a response body? - Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. - Arguments Req The Req object. Return value A boolean indicating whether a response body has been set. - This function will return false when an empty response body has been set. - Changelog 1. +Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. +Arguments Req The Req object. + Return value A boolean indicating whether a response body has been set. +This function will return false when an empty response body has been set. +Changelog 1.0: Function introduced. Examples Check whether a body has been set false = cowboy_req:has_resp_body(Req0), Req1 = cowboy_req:set_resp_body(&lt;&lt;" @@ -3847,10 +4023,11 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.has_resp_body/ Name cowboy_req:has_resp_body - Is there a response body? - Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. - Arguments Req The Req object. Return value A boolean indicating whether a response body has been set. - This function will return false when an empty response body has been set. - Changelog 1. +Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. +Arguments Req The Req object. + Return value A boolean indicating whether a response body has been set. +This function will return false when an empty response body has been set. +Changelog 1.0: Function introduced. Examples Check whether a body has been set false = cowboy_req:has_resp_body(Req0), Req1 = cowboy_req:set_resp_body(&lt;&lt;" @@ -3860,10 +4037,11 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.has_resp_body/ Name cowboy_req:has_resp_body - Is there a response body? - Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. - Arguments Req The Req object. Return value A boolean indicating whether a response body has been set. - This function will return false when an empty response body has been set. - Changelog 1. +Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. +Arguments Req The Req object. + Return value A boolean indicating whether a response body has been set. +This function will return false when an empty response body has been set. +Changelog 1.0: Function introduced. Examples Check whether a body has been set false = cowboy_req:has_resp_body(Req0), Req1 = cowboy_req:set_resp_body(&lt;&lt;" @@ -3873,9 +4051,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.has_resp_header/ Name cowboy_req:has_resp_header - Is the given response header set? - Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. @@ -3885,9 +4063,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.has_resp_header/ Name cowboy_req:has_resp_header - Is the given response header set? - Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. @@ -3897,9 +4075,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.has_resp_header/ Name cowboy_req:has_resp_header - Is the given response header set? - Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. @@ -3909,9 +4087,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.has_resp_header/ Name cowboy_req:has_resp_header - Is the given response header set? - Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. @@ -3921,9 +4099,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.has_resp_header/ Name cowboy_req:has_resp_header - Is the given response header set? - Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. @@ -3933,8 +4111,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.header/ Name cowboy_req:header - HTTP header - Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Headers can also be obtained using pattern matching: @@ -3944,8 +4123,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.header/ Name cowboy_req:header - HTTP header - Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Headers can also be obtained using pattern matching: @@ -3955,8 +4135,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.header/ Name cowboy_req:header - HTTP header - Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Headers can also be obtained using pattern matching: @@ -3966,8 +4147,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.header/ Name cowboy_req:header - HTTP header - Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Headers can also be obtained using pattern matching: @@ -3977,8 +4159,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.header/ Name cowboy_req:header - HTTP header - Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Headers can also be obtained using pattern matching: @@ -3988,10 +4171,11 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.headers/ Name cowboy_req:headers - HTTP headers - Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. - Request headers can also be obtained using pattern matching: - #{headers := Headers} = Req. Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2. +Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. +Request headers can also be obtained using pattern matching: +#{headers := Headers} = Req. Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Only the headers are returned, they are no longer wrapped in a tuple. @@ -4001,10 +4185,11 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.headers/ Name cowboy_req:headers - HTTP headers - Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. - Request headers can also be obtained using pattern matching: - #{headers := Headers} = Req. Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2. +Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. +Request headers can also be obtained using pattern matching: +#{headers := Headers} = Req. Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Only the headers are returned, they are no longer wrapped in a tuple. @@ -4014,10 +4199,11 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.headers/ Name cowboy_req:headers - HTTP headers - Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. - Request headers can also be obtained using pattern matching: - #{headers := Headers} = Req. Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2. +Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. +Request headers can also be obtained using pattern matching: +#{headers := Headers} = Req. Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Only the headers are returned, they are no longer wrapped in a tuple. @@ -4027,10 +4213,11 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.headers/ Name cowboy_req:headers - HTTP headers - Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. - Request headers can also be obtained using pattern matching: - #{headers := Headers} = Req. Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2. +Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. +Request headers can also be obtained using pattern matching: +#{headers := Headers} = Req. Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Only the headers are returned, they are no longer wrapped in a tuple. @@ -4040,10 +4227,11 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.headers/ Name cowboy_req:headers - HTTP headers - Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. - Request headers can also be obtained using pattern matching: - #{headers := Headers} = Req. Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2. +Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. +Request headers can also be obtained using pattern matching: +#{headers := Headers} = Req. Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Only the headers are returned, they are no longer wrapped in a tuple. @@ -4053,9 +4241,11 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.host/ Name cowboy_req:host - URI host name - Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. - The host name can also be obtained using pattern matching: - #{host := Host} = Req. Arguments Req The Req object. Return value The host name is returned as a lowercase binary string. It is case insensitive. +Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. +The host name can also be obtained using pattern matching: +#{host := Host} = Req. Arguments Req The Req object. + Return value The host name is returned as a lowercase binary string. It is case insensitive. +Changelog 2.0: Only the host name is returned, it is no longer wrapped in a tuple. @@ -4065,9 +4255,11 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.host/ Name cowboy_req:host - URI host name - Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. - The host name can also be obtained using pattern matching: - #{host := Host} = Req. Arguments Req The Req object. Return value The host name is returned as a lowercase binary string. It is case insensitive. +Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. +The host name can also be obtained using pattern matching: +#{host := Host} = Req. Arguments Req The Req object. + Return value The host name is returned as a lowercase binary string. It is case insensitive. +Changelog 2.0: Only the host name is returned, it is no longer wrapped in a tuple. @@ -4077,9 +4269,11 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.host/ Name cowboy_req:host - URI host name - Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. - The host name can also be obtained using pattern matching: - #{host := Host} = Req. Arguments Req The Req object. Return value The host name is returned as a lowercase binary string. It is case insensitive. +Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. +The host name can also be obtained using pattern matching: +#{host := Host} = Req. Arguments Req The Req object. + Return value The host name is returned as a lowercase binary string. It is case insensitive. +Changelog 2.0: Only the host name is returned, it is no longer wrapped in a tuple. @@ -4089,9 +4283,11 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.host/ Name cowboy_req:host - URI host name - Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. - The host name can also be obtained using pattern matching: - #{host := Host} = Req. Arguments Req The Req object. Return value The host name is returned as a lowercase binary string. It is case insensitive. +Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. +The host name can also be obtained using pattern matching: +#{host := Host} = Req. Arguments Req The Req object. + Return value The host name is returned as a lowercase binary string. It is case insensitive. +Changelog 2.0: Only the host name is returned, it is no longer wrapped in a tuple. @@ -4101,9 +4297,11 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.host/ Name cowboy_req:host - URI host name - Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. - The host name can also be obtained using pattern matching: - #{host := Host} = Req. Arguments Req The Req object. Return value The host name is returned as a lowercase binary string. It is case insensitive. +Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. +The host name can also be obtained using pattern matching: +#{host := Host} = Req. Arguments Req The Req object. + Return value The host name is returned as a lowercase binary string. It is case insensitive. +Changelog 2.0: Only the host name is returned, it is no longer wrapped in a tuple. @@ -4112,10 +4310,12 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.host_info/ - Name cowboy_req:host_info - Access the route&#8217;s heading host segments - Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case insensitive binary strings. + Name cowboy_req:host_info - Access the route&apos;s heading host segments +Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case insensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -4124,10 +4324,12 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.host_info/ - Name cowboy_req:host_info - Access the route&#8217;s heading host segments - Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case insensitive binary strings. + Name cowboy_req:host_info - Access the route&apos;s heading host segments +Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case insensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -4136,10 +4338,12 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.host_info/ - Name cowboy_req:host_info - Access the route&#8217;s heading host segments - Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case insensitive binary strings. + Name cowboy_req:host_info - Access the route&apos;s heading host segments +Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case insensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -4148,10 +4352,12 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.host_info/ - Name cowboy_req:host_info - Access the route&#8217;s heading host segments - Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case insensitive binary strings. + Name cowboy_req:host_info - Access the route&apos;s heading host segments +Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case insensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -4160,10 +4366,12 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.host_info/ - Name cowboy_req:host_info - Access the route&#8217;s heading host segments - Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case insensitive binary strings. + Name cowboy_req:host_info - Access the route&apos;s heading host segments +Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case insensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -4173,8 +4381,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.inform/ Name cowboy_req:inform - Send an informational response - Description inform(Status, Req :: cowboy_req:req()) -&gt; inform(StatusCode, #{}, Req) inform(Status, Headers, Req :: cowboy_req:req()) -&gt; ok Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send an informational response. - Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly. +Description inform(Status, Req :: cowboy_req:req()) -&gt; inform(StatusCode, #{}, Req) inform(Status, Headers, Req :: cowboy_req:req()) -&gt; ok Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send an informational response. +Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly. +Any number of informational responses can be sent as long as they are sent before the proper response. @@ -4184,8 +4393,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.inform/ Name cowboy_req:inform - Send an informational response - Description inform(Status, Req :: cowboy_req:req()) -&gt; inform(StatusCode, #{}, Req) inform(Status, Headers, Req :: cowboy_req:req()) -&gt; ok Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send an informational response. - Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly. +Description inform(Status, Req :: cowboy_req:req()) -&gt; inform(StatusCode, #{}, Req) inform(Status, Headers, Req :: cowboy_req:req()) -&gt; ok Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send an informational response. +Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly. +Any number of informational responses can be sent as long as they are sent before the proper response. @@ -4195,8 +4405,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.inform/ Name cowboy_req:inform - Send an informational response - Description inform(Status, Req :: cowboy_req:req()) -&gt; inform(StatusCode, #{}, Req) inform(Status, Headers, Req :: cowboy_req:req()) -&gt; ok Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send an informational response. - Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly. +Description inform(Status, Req :: cowboy_req:req()) -&gt; inform(StatusCode, #{}, Req) inform(Status, Headers, Req :: cowboy_req:req()) -&gt; ok Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send an informational response. +Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly. +Any number of informational responses can be sent as long as they are sent before the proper response. @@ -4206,8 +4417,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.inform/ Name cowboy_req:inform - Send an informational response - Description inform(Status, Req :: cowboy_req:req()) -&gt; inform(StatusCode, #{}, Req) inform(Status, Headers, Req :: cowboy_req:req()) -&gt; ok Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send an informational response. - Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly. +Description inform(Status, Req :: cowboy_req:req()) -&gt; inform(StatusCode, #{}, Req) inform(Status, Headers, Req :: cowboy_req:req()) -&gt; ok Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send an informational response. +Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly. +Any number of informational responses can be sent as long as they are sent before the proper response. @@ -4217,8 +4429,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.match_cookies/ Name cowboy_req:match_cookies - Match cookies against constraints - Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. - Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. +Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. +Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. @@ -4228,8 +4440,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.match_cookies/ Name cowboy_req:match_cookies - Match cookies against constraints - Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. - Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. +Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. +Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. @@ -4239,8 +4451,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.match_cookies/ Name cowboy_req:match_cookies - Match cookies against constraints - Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. - Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. +Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. +Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. @@ -4250,8 +4462,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.match_cookies/ Name cowboy_req:match_cookies - Match cookies against constraints - Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. - Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. +Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. +Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. @@ -4261,8 +4473,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.match_cookies/ Name cowboy_req:match_cookies - Match cookies against constraints - Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. - Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. +Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. +Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. @@ -4272,8 +4484,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.match_qs/ Name cowboy_req:match_qs - Match the query string against constraints - Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. - Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. +Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. +Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. @@ -4283,8 +4495,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.match_qs/ Name cowboy_req:match_qs - Match the query string against constraints - Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. - Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. +Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. +Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. @@ -4294,8 +4506,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.match_qs/ Name cowboy_req:match_qs - Match the query string against constraints - Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. - Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. +Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. +Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. @@ -4305,8 +4517,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.match_qs/ Name cowboy_req:match_qs - Match the query string against constraints - Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. - Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. +Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. +Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. @@ -4316,8 +4528,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.match_qs/ Name cowboy_req:match_qs - Match the query string against constraints - Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. - Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. +Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. +Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. @@ -4327,9 +4539,11 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.method/ Name cowboy_req:method - HTTP method - Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&#8217;s HTTP method. - The method can also be obtained using pattern matching: - #{method := Method} = Req. Arguments Req The Req object. Return value The request&#8217;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&apos;s HTTP method. +The method can also be obtained using pattern matching: +#{method := Method} = Req. Arguments Req The Req object. + Return value The request&apos;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Changelog 2.0: Only the method is returned, it is no longer wrapped in a tuple. @@ -4339,9 +4553,11 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.method/ Name cowboy_req:method - HTTP method - Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&#8217;s HTTP method. - The method can also be obtained using pattern matching: - #{method := Method} = Req. Arguments Req The Req object. Return value The request&#8217;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&apos;s HTTP method. +The method can also be obtained using pattern matching: +#{method := Method} = Req. Arguments Req The Req object. + Return value The request&apos;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Changelog 2.0: Only the method is returned, it is no longer wrapped in a tuple. @@ -4351,9 +4567,11 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.method/ Name cowboy_req:method - HTTP method - Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&#8217;s HTTP method. - The method can also be obtained using pattern matching: - #{method := Method} = Req. Arguments Req The Req object. Return value The request&#8217;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&apos;s HTTP method. +The method can also be obtained using pattern matching: +#{method := Method} = Req. Arguments Req The Req object. + Return value The request&apos;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Changelog 2.0: Only the method is returned, it is no longer wrapped in a tuple. @@ -4363,9 +4581,11 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.method/ Name cowboy_req:method - HTTP method - Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&#8217;s HTTP method. - The method can also be obtained using pattern matching: - #{method := Method} = Req. Arguments Req The Req object. Return value The request&#8217;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&apos;s HTTP method. +The method can also be obtained using pattern matching: +#{method := Method} = Req. Arguments Req The Req object. + Return value The request&apos;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Changelog 2.0: Only the method is returned, it is no longer wrapped in a tuple. @@ -4375,9 +4595,11 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.method/ Name cowboy_req:method - HTTP method - Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&#8217;s HTTP method. - The method can also be obtained using pattern matching: - #{method := Method} = Req. Arguments Req The Req object. Return value The request&#8217;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&apos;s HTTP method. +The method can also be obtained using pattern matching: +#{method := Method} = Req. Arguments Req The Req object. + Return value The request&apos;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Changelog 2.0: Only the method is returned, it is no longer wrapped in a tuple. @@ -4387,11 +4609,12 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.parse_cookies/ Name cowboy_req:parse_cookies - Parse cookie headers - Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. - Alias for cowboy_req:parse_header([cookie], Req). - When the cookie header is missing, [] is returned. - While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. - Arguments Req The Req object. +Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. +Alias for cowboy_req:parse_header(&lt;&lt;&quot;cookie&quot;&gt;&gt;, Req). +When the cookie header is missing, [] is returned. +While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. +Arguments Req The Req object. + Return value The cookies are returned as a list of key/values. @@ -4401,11 +4624,12 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.parse_cookies/ Name cowboy_req:parse_cookies - Parse cookie headers - Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. - Alias for cowboy_req:parse_header([cookie], Req). - When the cookie header is missing, [] is returned. - While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. - Arguments Req The Req object. +Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. +Alias for cowboy_req:parse_header(&lt;&lt;&quot;cookie&quot;&gt;&gt;, Req). +When the cookie header is missing, [] is returned. +While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. +Arguments Req The Req object. + Return value The cookies are returned as a list of key/values. @@ -4415,11 +4639,12 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.parse_cookies/ Name cowboy_req:parse_cookies - Parse cookie headers - Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. - Alias for cowboy_req:parse_header([cookie], Req). - When the cookie header is missing, [] is returned. - While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. - Arguments Req The Req object. +Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. +Alias for cowboy_req:parse_header(&lt;&lt;&quot;cookie&quot;&gt;&gt;, Req). +When the cookie header is missing, [] is returned. +While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. +Arguments Req The Req object. + Return value The cookies are returned as a list of key/values. @@ -4429,11 +4654,12 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.parse_cookies/ Name cowboy_req:parse_cookies - Parse cookie headers - Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. - Alias for cowboy_req:parse_header([cookie], Req). - When the cookie header is missing, [] is returned. - While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. - Arguments Req The Req object. +Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. +Alias for cowboy_req:parse_header(&lt;&lt;&quot;cookie&quot;&gt;&gt;, Req). +When the cookie header is missing, [] is returned. +While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. +Arguments Req The Req object. + Return value The cookies are returned as a list of key/values. @@ -4443,11 +4669,12 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.parse_cookies/ Name cowboy_req:parse_cookies - Parse cookie headers - Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. - Alias for cowboy_req:parse_header([cookie], Req). - When the cookie header is missing, [] is returned. - While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. - Arguments Req The Req object. +Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. +Alias for cowboy_req:parse_header(&lt;&lt;&quot;cookie&quot;&gt;&gt;, Req). +When the cookie header is missing, [] is returned. +While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. +Arguments Req The Req object. + Return value The cookies are returned as a list of key/values. @@ -4457,8 +4684,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.parse_header/ Name cowboy_req:parse_header - Parse the given HTTP header - Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +The type of the parsed value varies depending on the header. @@ -4468,8 +4696,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.parse_header/ Name cowboy_req:parse_header - Parse the given HTTP header - Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +The type of the parsed value varies depending on the header. @@ -4479,8 +4708,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.parse_header/ Name cowboy_req:parse_header - Parse the given HTTP header - Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +The type of the parsed value varies depending on the header. @@ -4490,8 +4720,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.parse_header/ Name cowboy_req:parse_header - Parse the given HTTP header - Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +The type of the parsed value varies depending on the header. @@ -4501,8 +4732,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.parse_header/ Name cowboy_req:parse_header - Parse the given HTTP header - Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +The type of the parsed value varies depending on the header. @@ -4512,8 +4744,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.parse_qs/ Name cowboy_req:parse_qs - Parse the query string - Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. - Arguments Req The Req object. Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. +Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. +Arguments Req The Req object. + Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. Both key and value are case sensitive. @@ -4523,8 +4756,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.parse_qs/ Name cowboy_req:parse_qs - Parse the query string - Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. - Arguments Req The Req object. Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. +Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. +Arguments Req The Req object. + Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. Both key and value are case sensitive. @@ -4534,8 +4768,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.parse_qs/ Name cowboy_req:parse_qs - Parse the query string - Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. - Arguments Req The Req object. Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. +Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. +Arguments Req The Req object. + Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. Both key and value are case sensitive. @@ -4545,8 +4780,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.parse_qs/ Name cowboy_req:parse_qs - Parse the query string - Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. - Arguments Req The Req object. Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. +Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. +Arguments Req The Req object. + Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. Both key and value are case sensitive. @@ -4556,8 +4792,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.parse_qs/ Name cowboy_req:parse_qs - Parse the query string - Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. - Arguments Req The Req object. Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. +Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. +Arguments Req The Req object. + Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. Both key and value are case sensitive. @@ -4567,10 +4804,11 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.path/ Name cowboy_req:path - URI path - Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. - The path can also be obtained using pattern matching: - #{path := Path} = Req. Arguments Req The Req object. Return value The path is returned as a binary string. It is case sensitive. - Changelog 2. +Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. +The path can also be obtained using pattern matching: +#{path := Path} = Req. Arguments Req The Req object. + Return value The path is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the path is returned, it is no longer wrapped in a tuple. @@ -4580,10 +4818,11 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.path/ Name cowboy_req:path - URI path - Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. - The path can also be obtained using pattern matching: - #{path := Path} = Req. Arguments Req The Req object. Return value The path is returned as a binary string. It is case sensitive. - Changelog 2. +Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. +The path can also be obtained using pattern matching: +#{path := Path} = Req. Arguments Req The Req object. + Return value The path is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the path is returned, it is no longer wrapped in a tuple. @@ -4593,10 +4832,11 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.path/ Name cowboy_req:path - URI path - Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. - The path can also be obtained using pattern matching: - #{path := Path} = Req. Arguments Req The Req object. Return value The path is returned as a binary string. It is case sensitive. - Changelog 2. +Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. +The path can also be obtained using pattern matching: +#{path := Path} = Req. Arguments Req The Req object. + Return value The path is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the path is returned, it is no longer wrapped in a tuple. @@ -4606,10 +4846,11 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.path/ Name cowboy_req:path - URI path - Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. - The path can also be obtained using pattern matching: - #{path := Path} = Req. Arguments Req The Req object. Return value The path is returned as a binary string. It is case sensitive. - Changelog 2. +Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. +The path can also be obtained using pattern matching: +#{path := Path} = Req. Arguments Req The Req object. + Return value The path is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the path is returned, it is no longer wrapped in a tuple. @@ -4619,10 +4860,11 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.path/ Name cowboy_req:path - URI path - Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. - The path can also be obtained using pattern matching: - #{path := Path} = Req. Arguments Req The Req object. Return value The path is returned as a binary string. It is case sensitive. - Changelog 2. +Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. +The path can also be obtained using pattern matching: +#{path := Path} = Req. Arguments Req The Req object. + Return value The path is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the path is returned, it is no longer wrapped in a tuple. @@ -4631,10 +4873,12 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.path_info/ - Name cowboy_req:path_info - Access the route&#8217;s trailing path segments - Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case sensitive binary strings. + Name cowboy_req:path_info - Access the route&apos;s trailing path segments +Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case sensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -4643,10 +4887,12 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.path_info/ - Name cowboy_req:path_info - Access the route&#8217;s trailing path segments - Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case sensitive binary strings. + Name cowboy_req:path_info - Access the route&apos;s trailing path segments +Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case sensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -4655,10 +4901,12 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.path_info/ - Name cowboy_req:path_info - Access the route&#8217;s trailing path segments - Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case sensitive binary strings. + Name cowboy_req:path_info - Access the route&apos;s trailing path segments +Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case sensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -4667,10 +4915,12 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.path_info/ - Name cowboy_req:path_info - Access the route&#8217;s trailing path segments - Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case sensitive binary strings. + Name cowboy_req:path_info - Access the route&apos;s trailing path segments +Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case sensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -4679,10 +4929,12 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.path_info/ - Name cowboy_req:path_info - Access the route&#8217;s trailing path segments - Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case sensitive binary strings. + Name cowboy_req:path_info - Access the route&apos;s trailing path segments +Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case sensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -4692,10 +4944,11 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.peer/ Name cowboy_req:peer - Peer address and port - Description peer(Req :: cowboy_req:req()) -&gt; Peer Peer :: {inet:ip_address(), inet:port_number()} Return the peer&#8217;s IP address and port number. - The peer can also be obtained using pattern matching: - #{peer := {IP, Port}} = Req. Arguments Req The Req object. Return value The peer&#8217;s IP address and port number. - The peer is not necessarily the client&#8217;s IP address and port. +Description peer(Req :: cowboy_req:req()) -&gt; Peer Peer :: {inet:ip_address(), inet:port_number()} Return the peer&apos;s IP address and port number. +The peer can also be obtained using pattern matching: +#{peer := {IP, Port}} = Req. Arguments Req The Req object. + Return value The peer&apos;s IP address and port number. +The peer is not necessarily the client&apos;s IP address and port. It is the IP address of the endpoint connecting directly to the server, which may be a gateway or a proxy. @@ -4705,9 +4958,11 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.peer/ Name cowboy_req:peer - Peer address and port - Description peer(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the peer&#8217;s IP address and port number. - The peer information can also be obtained using pattern matching: - #{peer := {IP, Port}} = Req. Arguments Req The Req object. Return value The peer&#8217;s IP address and port number. +Description peer(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the peer&apos;s IP address and port number. +The peer information can also be obtained using pattern matching: +#{peer := {IP, Port}} = Req. Arguments Req The Req object. + Return value The peer&apos;s IP address and port number. +The peer is not necessarily the client&apos;s IP address and port. It is the IP address of the endpoint connecting directly to the server, which may be a gateway or a proxy. @@ -4717,9 +4972,11 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.peer/ Name cowboy_req:peer - Peer address and port - Description peer(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the peer&#8217;s IP address and port number. - The peer information can also be obtained using pattern matching: - #{peer := {IP, Port}} = Req. Arguments Req The Req object. Return value The peer&#8217;s IP address and port number. +Description peer(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the peer&apos;s IP address and port number. +The peer information can also be obtained using pattern matching: +#{peer := {IP, Port}} = Req. Arguments Req The Req object. + Return value The peer&apos;s IP address and port number. +The peer is not necessarily the client&apos;s IP address and port. It is the IP address of the endpoint connecting directly to the server, which may be a gateway or a proxy. @@ -4729,9 +4986,11 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.peer/ Name cowboy_req:peer - Peer address and port - Description peer(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the peer&#8217;s IP address and port number. - The peer information can also be obtained using pattern matching: - #{peer := {IP, Port}} = Req. Arguments Req The Req object. Return value The peer&#8217;s IP address and port number. +Description peer(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the peer&apos;s IP address and port number. +The peer information can also be obtained using pattern matching: +#{peer := {IP, Port}} = Req. Arguments Req The Req object. + Return value The peer&apos;s IP address and port number. +The peer is not necessarily the client&apos;s IP address and port. It is the IP address of the endpoint connecting directly to the server, which may be a gateway or a proxy. @@ -4741,9 +5000,11 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.peer/ Name cowboy_req:peer - Peer address and port - Description peer(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the peer&#8217;s IP address and port number. - The peer information can also be obtained using pattern matching: - #{peer := {IP, Port}} = Req. Arguments Req The Req object. Return value The peer&#8217;s IP address and port number. +Description peer(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the peer&apos;s IP address and port number. +The peer information can also be obtained using pattern matching: +#{peer := {IP, Port}} = Req. Arguments Req The Req object. + Return value The peer&apos;s IP address and port number. +The peer is not necessarily the client&apos;s IP address and port. It is the IP address of the endpoint connecting directly to the server, which may be a gateway or a proxy. @@ -4753,10 +5014,10 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.port/ Name cowboy_req:port - URI port number - Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. - Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. - The port number can also be obtained using pattern matching: - #{port := Port} = Req. +Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. +Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. +The port number can also be obtained using pattern matching: +#{port := Port} = Req. Arguments Req The Req object. @@ -4766,10 +5027,10 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.port/ Name cowboy_req:port - URI port number - Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. - Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. - The port number can also be obtained using pattern matching: - #{port := Port} = Req. +Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. +Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. +The port number can also be obtained using pattern matching: +#{port := Port} = Req. Arguments Req The Req object. @@ -4779,10 +5040,10 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.port/ Name cowboy_req:port - URI port number - Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. - Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. - The port number can also be obtained using pattern matching: - #{port := Port} = Req. +Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. +Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. +The port number can also be obtained using pattern matching: +#{port := Port} = Req. Arguments Req The Req object. @@ -4792,10 +5053,10 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.port/ Name cowboy_req:port - URI port number - Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. - Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. - The port number can also be obtained using pattern matching: - #{port := Port} = Req. +Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. +Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. +The port number can also be obtained using pattern matching: +#{port := Port} = Req. Arguments Req The Req object. @@ -4805,10 +5066,10 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.port/ Name cowboy_req:port - URI port number - Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. - Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. - The port number can also be obtained using pattern matching: - #{port := Port} = Req. +Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. +Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. +The port number can also be obtained using pattern matching: +#{port := Port} = Req. Arguments Req The Req object. @@ -4818,8 +5079,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.push/ Name cowboy_req:push - Push a resource to the client - Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. - Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. +Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. +Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. @@ -4829,8 +5090,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.push/ Name cowboy_req:push - Push a resource to the client - Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. - Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. +Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. +Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. @@ -4840,8 +5101,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.push/ Name cowboy_req:push - Push a resource to the client - Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. - Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. +Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. +Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. @@ -4851,8 +5112,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.push/ Name cowboy_req:push - Push a resource to the client - Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. - Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. +Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. +Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. @@ -4862,8 +5123,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.push/ Name cowboy_req:push - Push a resource to the client - Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. - Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. +Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. +Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. @@ -4873,9 +5134,11 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.qs/ Name cowboy_req:qs - URI query string - Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. - The query string can also be obtained using pattern matching: - #{qs := Qs} = Req. Arguments Req The Req object. Return value The query string is returned as a binary string. It is case sensitive. +Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. +The query string can also be obtained using pattern matching: +#{qs := Qs} = Req. Arguments Req The Req object. + Return value The query string is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the query string is returned, it is no longer wrapped in a tuple. @@ -4885,9 +5148,11 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.qs/ Name cowboy_req:qs - URI query string - Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. - The query string can also be obtained using pattern matching: - #{qs := Qs} = Req. Arguments Req The Req object. Return value The query string is returned as a binary string. It is case sensitive. +Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. +The query string can also be obtained using pattern matching: +#{qs := Qs} = Req. Arguments Req The Req object. + Return value The query string is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the query string is returned, it is no longer wrapped in a tuple. @@ -4897,9 +5162,11 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.qs/ Name cowboy_req:qs - URI query string - Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. - The query string can also be obtained using pattern matching: - #{qs := Qs} = Req. Arguments Req The Req object. Return value The query string is returned as a binary string. It is case sensitive. +Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. +The query string can also be obtained using pattern matching: +#{qs := Qs} = Req. Arguments Req The Req object. + Return value The query string is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the query string is returned, it is no longer wrapped in a tuple. @@ -4909,9 +5176,11 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.qs/ Name cowboy_req:qs - URI query string - Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. - The query string can also be obtained using pattern matching: - #{qs := Qs} = Req. Arguments Req The Req object. Return value The query string is returned as a binary string. It is case sensitive. +Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. +The query string can also be obtained using pattern matching: +#{qs := Qs} = Req. Arguments Req The Req object. + Return value The query string is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the query string is returned, it is no longer wrapped in a tuple. @@ -4921,9 +5190,11 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.qs/ Name cowboy_req:qs - URI query string - Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. - The query string can also be obtained using pattern matching: - #{qs := Qs} = Req. Arguments Req The Req object. Return value The query string is returned as a binary string. It is case sensitive. +Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. +The query string can also be obtained using pattern matching: +#{qs := Qs} = Req. Arguments Req The Req object. + Return value The query string is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the query string is returned, it is no longer wrapped in a tuple. @@ -4933,8 +5204,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.read_body/ Name cowboy_req:read_body - Read the request body - Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. - This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. +Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. +This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. @@ -4944,8 +5215,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.read_body/ Name cowboy_req:read_body - Read the request body - Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. - This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. +Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. +This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. @@ -4955,8 +5226,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.read_body/ Name cowboy_req:read_body - Read the request body - Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. - This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. +Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. +This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. @@ -4966,8 +5237,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.read_body/ Name cowboy_req:read_body - Read the request body - Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. - This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. +Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. +This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. @@ -4977,8 +5248,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.read_body/ Name cowboy_req:read_body - Read the request body - Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. - This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. +Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. +This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. @@ -4988,8 +5259,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.read_part/ Name cowboy_req:read_part - Read the next multipart headers - Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. +Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. @@ -4999,8 +5270,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.read_part/ Name cowboy_req:read_part - Read the next multipart headers - Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. +Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. @@ -5010,8 +5281,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.read_part/ Name cowboy_req:read_part - Read the next multipart headers - Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. +Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. @@ -5021,8 +5292,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.read_part/ Name cowboy_req:read_part - Read the next multipart headers - Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. +Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. @@ -5032,8 +5303,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.read_part/ Name cowboy_req:read_part - Read the next multipart headers - Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. +Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. @@ -5042,9 +5313,9 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.read_part_body/ - Name cowboy_req:read_part_body - Read the current part&#8217;s body - Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. + Name cowboy_req:read_part_body - Read the current part&apos;s body +Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function returns the body of the current part. @@ -5053,9 +5324,9 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.read_part_body/ - Name cowboy_req:read_part_body - Read the current part&#8217;s body - Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. + Name cowboy_req:read_part_body - Read the current part&apos;s body +Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function returns the body of the current part. @@ -5064,9 +5335,9 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.read_part_body/ - Name cowboy_req:read_part_body - Read the current part&#8217;s body - Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. + Name cowboy_req:read_part_body - Read the current part&apos;s body +Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function returns the body of the current part. @@ -5075,9 +5346,9 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.read_part_body/ - Name cowboy_req:read_part_body - Read the current part&#8217;s body - Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. + Name cowboy_req:read_part_body - Read the current part&apos;s body +Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function returns the body of the current part. @@ -5086,9 +5357,9 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.read_part_body/ - Name cowboy_req:read_part_body - Read the current part&#8217;s body - Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. + Name cowboy_req:read_part_body - Read the current part&apos;s body +Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function returns the body of the current part. @@ -5098,9 +5369,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.read_urlencoded_body/ Name cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body - Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. - This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. - The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. +Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. +This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. +The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. @@ -5110,9 +5381,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.read_urlencoded_body/ Name cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body - Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. - This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. - The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. +Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. +This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. +The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. @@ -5122,9 +5393,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.read_urlencoded_body/ Name cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body - Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. - This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. - The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. +Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. +This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. +The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. @@ -5134,9 +5405,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.read_urlencoded_body/ Name cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body - Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. - This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. - The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. +Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. +This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. +The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. @@ -5146,9 +5417,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.read_urlencoded_body/ Name cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body - Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. - This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. - The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. +Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. +This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. +The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. @@ -5158,8 +5429,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.reply/ Name cowboy_req:reply - Send the response - Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5169,8 +5440,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.reply/ Name cowboy_req:reply - Send the response - Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5180,8 +5451,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.reply/ Name cowboy_req:reply - Send the response - Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5191,8 +5462,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.reply/ Name cowboy_req:reply - Send the response - Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5202,8 +5473,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.reply/ Name cowboy_req:reply - Send the response - Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5213,9 +5484,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.resp_header/ Name cowboy_req:resp_header - Response header - Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. - The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. +The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5225,9 +5496,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.resp_header/ Name cowboy_req:resp_header - Response header - Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. - The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. +The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5237,9 +5508,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.resp_header/ Name cowboy_req:resp_header - Response header - Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. - The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. +The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5249,9 +5520,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.resp_header/ Name cowboy_req:resp_header - Response header - Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. - The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. +The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5261,9 +5532,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.resp_header/ Name cowboy_req:resp_header - Response header - Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. - The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. +The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5273,9 +5544,10 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.resp_headers/ Name cowboy_req:resp_headers - Response headers - Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. - Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). +Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. +Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). See also cowboy_req(3), cowboy_req:resp_header(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3) @@ -5285,9 +5557,10 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.resp_headers/ Name cowboy_req:resp_headers - Response headers - Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. - Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). +Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. +Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). See also cowboy_req(3), cowboy_req:resp_header(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3) @@ -5297,9 +5570,10 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.resp_headers/ Name cowboy_req:resp_headers - Response headers - Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. - Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). +Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. +Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). See also cowboy_req(3), cowboy_req:resp_header(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3) @@ -5309,9 +5583,10 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.resp_headers/ Name cowboy_req:resp_headers - Response headers - Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. - Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). +Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. +Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). See also cowboy_req(3), cowboy_req:resp_header(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3) @@ -5321,9 +5596,10 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.resp_headers/ Name cowboy_req:resp_headers - Response headers - Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. - Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). +Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. +Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). See also cowboy_req(3), cowboy_req:resp_header(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3) @@ -5333,10 +5609,12 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.scheme/ Name cowboy_req:scheme - URI scheme - Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. - The scheme can also be obtained using pattern matching: - #{scheme := Scheme} = Req. Arguments Req The Req object. Return value The scheme is returned as a binary. It is case insensitive. - Cowboy will only set the scheme to &lt;&lt;" +Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. +The scheme can also be obtained using pattern matching: +#{scheme := Scheme} = Req. Arguments Req The Req object. + Return value The scheme is returned as a binary. It is case insensitive. +Cowboy will only set the scheme to &lt;&lt;&quot;http&quot;&gt;&gt; or &lt;&lt;&quot;https&quot;&gt;&gt;. +Changelog 2.0: Function introduced. @@ -5346,10 +5624,12 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.scheme/ Name cowboy_req:scheme - URI scheme - Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. - The scheme can also be obtained using pattern matching: - #{scheme := Scheme} = Req. Arguments Req The Req object. Return value The scheme is returned as a binary. It is case insensitive. - Cowboy will only set the scheme to &lt;&lt;" +Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. +The scheme can also be obtained using pattern matching: +#{scheme := Scheme} = Req. Arguments Req The Req object. + Return value The scheme is returned as a binary. It is case insensitive. +Cowboy will only set the scheme to &lt;&lt;&quot;http&quot;&gt;&gt; or &lt;&lt;&quot;https&quot;&gt;&gt;. +Changelog 2.0: Function introduced. @@ -5359,10 +5639,12 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.scheme/ Name cowboy_req:scheme - URI scheme - Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. - The scheme can also be obtained using pattern matching: - #{scheme := Scheme} = Req. Arguments Req The Req object. Return value The scheme is returned as a binary. It is case insensitive. - Cowboy will only set the scheme to &lt;&lt;" +Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. +The scheme can also be obtained using pattern matching: +#{scheme := Scheme} = Req. Arguments Req The Req object. + Return value The scheme is returned as a binary. It is case insensitive. +Cowboy will only set the scheme to &lt;&lt;&quot;http&quot;&gt;&gt; or &lt;&lt;&quot;https&quot;&gt;&gt;. +Changelog 2.0: Function introduced. @@ -5372,10 +5654,12 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.scheme/ Name cowboy_req:scheme - URI scheme - Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. - The scheme can also be obtained using pattern matching: - #{scheme := Scheme} = Req. Arguments Req The Req object. Return value The scheme is returned as a binary. It is case insensitive. - Cowboy will only set the scheme to &lt;&lt;" +Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. +The scheme can also be obtained using pattern matching: +#{scheme := Scheme} = Req. Arguments Req The Req object. + Return value The scheme is returned as a binary. It is case insensitive. +Cowboy will only set the scheme to &lt;&lt;&quot;http&quot;&gt;&gt; or &lt;&lt;&quot;https&quot;&gt;&gt;. +Changelog 2.0: Function introduced. @@ -5385,10 +5669,12 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.scheme/ Name cowboy_req:scheme - URI scheme - Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. - The scheme can also be obtained using pattern matching: - #{scheme := Scheme} = Req. Arguments Req The Req object. Return value The scheme is returned as a binary. It is case insensitive. - Cowboy will only set the scheme to &lt;&lt;" +Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. +The scheme can also be obtained using pattern matching: +#{scheme := Scheme} = Req. Arguments Req The Req object. + Return value The scheme is returned as a binary. It is case insensitive. +Cowboy will only set the scheme to &lt;&lt;&quot;http&quot;&gt;&gt; or &lt;&lt;&quot;https&quot;&gt;&gt;. +Changelog 2.0: Function introduced. @@ -5398,9 +5684,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_body/ Name cowboy_req:set_resp_body - Set the response body - Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. - The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. - This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. +Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. +The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. +This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. @@ -5410,9 +5696,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_body/ Name cowboy_req:set_resp_body - Set the response body - Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. - The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. - This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. +Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. +The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. +This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. @@ -5422,9 +5708,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_body/ Name cowboy_req:set_resp_body - Set the response body - Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. - The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. - This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. +Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. +The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. +This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. @@ -5434,9 +5720,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_body/ Name cowboy_req:set_resp_body - Set the response body - Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. - The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. - This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. +Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. +The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. +This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. @@ -5446,9 +5732,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_body/ Name cowboy_req:set_resp_body - Set the response body - Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. - The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. - This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. +Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. +The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. +This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. @@ -5458,9 +5744,11 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_cookie/ Name cowboy_req:set_resp_cookie - Set a cookie - Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. - Note that cookie names are case sensitive. - Arguments Name Cookie name. +Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. +Note that cookie names are case sensitive. +Arguments Name Cookie name. + Value Cookie value. + Req The Req object. @@ -5470,9 +5758,11 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_cookie/ Name cowboy_req:set_resp_cookie - Set a cookie - Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. - Note that cookie names are case sensitive. - Arguments Name Cookie name. +Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. +Note that cookie names are case sensitive. +Arguments Name Cookie name. + Value Cookie value. + Req The Req object. @@ -5482,9 +5772,11 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_cookie/ Name cowboy_req:set_resp_cookie - Set a cookie - Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. - Note that cookie names are case sensitive. - Arguments Name Cookie name. +Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. +Note that cookie names are case sensitive. +Arguments Name Cookie name. + Value Cookie value. + Req The Req object. @@ -5494,9 +5786,11 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_cookie/ Name cowboy_req:set_resp_cookie - Set a cookie - Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. - Note that cookie names are case sensitive. - Arguments Name Cookie name. +Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. +Note that cookie names are case sensitive. +Arguments Name Cookie name. + Value Cookie value. + Req The Req object. @@ -5506,9 +5800,11 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_cookie/ Name cowboy_req:set_resp_cookie - Set a cookie - Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. - Note that cookie names are case sensitive. - Arguments Name Cookie name. +Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. +Note that cookie names are case sensitive. +Arguments Name Cookie name. + Value Cookie value. + Req The Req object. @@ -5518,8 +5814,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_header/ Name cowboy_req:set_resp_header - Set a response header - Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. @@ -5529,8 +5826,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_header/ Name cowboy_req:set_resp_header - Set a response header - Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. @@ -5540,8 +5838,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_header/ Name cowboy_req:set_resp_header - Set a response header - Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. @@ -5551,8 +5850,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_header/ Name cowboy_req:set_resp_header - Set a response header - Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. @@ -5562,8 +5862,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_header/ Name cowboy_req:set_resp_header - Set a response header - Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. @@ -5573,9 +5874,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_headers/ Name cowboy_req:set_resp_headers - Set several response headers - Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. +Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. @@ -5585,9 +5886,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_headers/ Name cowboy_req:set_resp_headers - Set several response headers - Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. +Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. @@ -5597,9 +5898,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_headers/ Name cowboy_req:set_resp_headers - Set several response headers - Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. +Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. @@ -5609,9 +5910,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_headers/ Name cowboy_req:set_resp_headers - Set several response headers - Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. +Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. @@ -5621,9 +5922,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_headers/ Name cowboy_req:set_resp_headers - Set several response headers - Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. +Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. @@ -5633,9 +5934,11 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.sock/ Name cowboy_req:sock - Socket address and port - Description sock(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the socket&#8217;s IP address and port number. - The socket information can also be obtained using pattern matching: - #{sock := {IP, Port}} = Req. Arguments Req The Req object. Return value The socket&#8217;s local IP address and port number. +Description sock(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the socket&apos;s IP address and port number. +The socket information can also be obtained using pattern matching: +#{sock := {IP, Port}} = Req. Arguments Req The Req object. + Return value The socket&apos;s local IP address and port number. +Changelog 2.1: Function introduced. Examples Get the socket&apos;s IP address and port number. @@ -5645,9 +5948,11 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.sock/ Name cowboy_req:sock - Socket address and port - Description sock(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the socket&#8217;s IP address and port number. - The socket information can also be obtained using pattern matching: - #{sock := {IP, Port}} = Req. Arguments Req The Req object. Return value The socket&#8217;s local IP address and port number. +Description sock(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the socket&apos;s IP address and port number. +The socket information can also be obtained using pattern matching: +#{sock := {IP, Port}} = Req. Arguments Req The Req object. + Return value The socket&apos;s local IP address and port number. +Changelog 2.1: Function introduced. Examples Get the socket&apos;s IP address and port number. @@ -5657,9 +5962,11 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.sock/ Name cowboy_req:sock - Socket address and port - Description sock(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the socket&#8217;s IP address and port number. - The socket information can also be obtained using pattern matching: - #{sock := {IP, Port}} = Req. Arguments Req The Req object. Return value The socket&#8217;s local IP address and port number. +Description sock(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the socket&apos;s IP address and port number. +The socket information can also be obtained using pattern matching: +#{sock := {IP, Port}} = Req. Arguments Req The Req object. + Return value The socket&apos;s local IP address and port number. +Changelog 2.1: Function introduced. Examples Get the socket&apos;s IP address and port number. @@ -5669,9 +5976,11 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.sock/ Name cowboy_req:sock - Socket address and port - Description sock(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the socket&#8217;s IP address and port number. - The socket information can also be obtained using pattern matching: - #{sock := {IP, Port}} = Req. Arguments Req The Req object. Return value The socket&#8217;s local IP address and port number. +Description sock(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the socket&apos;s IP address and port number. +The socket information can also be obtained using pattern matching: +#{sock := {IP, Port}} = Req. Arguments Req The Req object. + Return value The socket&apos;s local IP address and port number. +Changelog 2.1: Function introduced. Examples Get the socket&apos;s IP address and port number. @@ -5681,9 +5990,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.stream_body/ Name cowboy_req:stream_body - Stream the response body - Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. - This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. - The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. +Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. +This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. +The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. The final call should use fin (possibly with an empty data value). @@ -5693,9 +6002,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.stream_body/ Name cowboy_req:stream_body - Stream the response body - Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. - This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. - The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. +Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. +This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. +The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. The final call should use fin (possibly with an empty data value). @@ -5705,9 +6014,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.stream_body/ Name cowboy_req:stream_body - Stream the response body - Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. - This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. - The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. +Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. +This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. +The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. The final call should use fin (possibly with an empty data value) or be a call to the cowboy_req:stream_trailers(3) function. @@ -5717,9 +6026,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.stream_body/ Name cowboy_req:stream_body - Stream the response body - Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. - This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. - The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. +Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. +This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. +The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. The final call should use fin (possibly with an empty data value) or be a call to the cowboy_req:stream_trailers(3) function. @@ -5729,9 +6038,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.stream_body/ Name cowboy_req:stream_body - Stream the response body - Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. - This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. - The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. +Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. +This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. +The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. The final call should use fin (possibly with an empty data value) or be a call to the cowboy_req:stream_trailers(3) function. @@ -5741,9 +6050,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.stream_reply/ Name cowboy_req:stream_reply - Send the response headers - Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. +Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3. @@ -5753,9 +6062,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.stream_reply/ Name cowboy_req:stream_reply - Send the response headers - Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. +Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3. @@ -5765,9 +6074,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.stream_reply/ Name cowboy_req:stream_reply - Send the response headers - Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. +Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3. @@ -5777,9 +6086,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.stream_reply/ Name cowboy_req:stream_reply - Send the response headers - Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. +Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3. @@ -5789,9 +6098,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.stream_reply/ Name cowboy_req:stream_reply - Send the response headers - Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. +Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3. @@ -5801,9 +6110,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.stream_trailers/ Name cowboy_req:stream_trailers - Send the response trailers - Description stream_trailers(Trailers, Req :: cowboy_req:req()) -&gt; ok Trailers :: cowboy:http_headers() Send the response trailers and terminate the stream. - This function can only be called once, after initiating a response using cowboy_req:stream_reply(3) and sending zero or more body chunks using cowboy_req:stream_body(3) with the nofin argument set. The function stream_trailers/2 implies fin and automatically terminate the response. - You must list all field names sent in trailers in the trailer header, otherwise they might be dropped by intermediaries or clients. +Description stream_trailers(Trailers, Req :: cowboy_req:req()) -&gt; ok Trailers :: cowboy:http_headers() Send the response trailers and terminate the stream. +This function can only be called once, after initiating a response using cowboy_req:stream_reply(3) and sending zero or more body chunks using cowboy_req:stream_body(3) with the nofin argument set. The function stream_trailers/2 implies fin and automatically terminate the response. +You must list all field names sent in trailers in the trailer header, otherwise they might be dropped by intermediaries or clients. @@ -5813,9 +6122,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.stream_trailers/ Name cowboy_req:stream_trailers - Send the response trailers - Description stream_trailers(Trailers, Req :: cowboy_req:req()) -&gt; ok Trailers :: cowboy:http_headers() Send the response trailers and terminate the stream. - This function can only be called once, after initiating a response using cowboy_req:stream_reply(3) and sending zero or more body chunks using cowboy_req:stream_body(3) with the nofin argument set. The function stream_trailers/2 implies fin and automatically terminate the response. - You must list all field names sent in trailers in the trailer header, otherwise they might be dropped by intermediaries or clients. +Description stream_trailers(Trailers, Req :: cowboy_req:req()) -&gt; ok Trailers :: cowboy:http_headers() Send the response trailers and terminate the stream. +This function can only be called once, after initiating a response using cowboy_req:stream_reply(3) and sending zero or more body chunks using cowboy_req:stream_body(3) with the nofin argument set. The function stream_trailers/2 implies fin and automatically terminate the response. +You must list all field names sent in trailers in the trailer header, otherwise they might be dropped by intermediaries or clients. @@ -5825,9 +6134,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.stream_trailers/ Name cowboy_req:stream_trailers - Send the response trailers - Description stream_trailers(Trailers, Req :: cowboy_req:req()) -&gt; ok Trailers :: cowboy:http_headers() Send the response trailers and terminate the stream. - This function can only be called once, after initiating a response using cowboy_req:stream_reply(3) and sending zero or more body chunks using cowboy_req:stream_body(3) with the nofin argument set. The function stream_trailers/2 implies fin and automatically terminate the response. - You must list all field names sent in trailers in the trailer header, otherwise they might be dropped by intermediaries or clients. +Description stream_trailers(Trailers, Req :: cowboy_req:req()) -&gt; ok Trailers :: cowboy:http_headers() Send the response trailers and terminate the stream. +This function can only be called once, after initiating a response using cowboy_req:stream_reply(3) and sending zero or more body chunks using cowboy_req:stream_body(3) with the nofin argument set. The function stream_trailers/2 implies fin and automatically terminate the response. +You must list all field names sent in trailers in the trailer header, otherwise they might be dropped by intermediaries or clients. @@ -5837,8 +6146,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.uri/ Name cowboy_req:uri - Reconstructed URI - Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. - By default Cowboy will build a URI using the components found in the request. +Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. +By default Cowboy will build a URI using the components found in the request. @@ -5848,8 +6157,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.uri/ Name cowboy_req:uri - Reconstructed URI - Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. - By default Cowboy will build a URI using the components found in the request. +Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. +By default Cowboy will build a URI using the components found in the request. @@ -5859,8 +6168,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.uri/ Name cowboy_req:uri - Reconstructed URI - Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. - By default Cowboy will build a URI using the components found in the request. +Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. +By default Cowboy will build a URI using the components found in the request. @@ -5870,8 +6179,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.uri/ Name cowboy_req:uri - Reconstructed URI - Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. - By default Cowboy will build a URI using the components found in the request. +Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. +By default Cowboy will build a URI using the components found in the request. @@ -5881,8 +6190,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.uri/ Name cowboy_req:uri - Reconstructed URI - Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. - By default Cowboy will build a URI using the components found in the request. +Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. +By default Cowboy will build a URI using the components found in the request. @@ -5892,9 +6201,11 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.version/ Name cowboy_req:version - HTTP version - Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. - The version can also be obtained using pattern matching: - #{version := Version} = Req. Arguments Req The Req object. Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. +The version can also be obtained using pattern matching: +#{version := Version} = Req. Arguments Req The Req object. + Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Changelog 2.0: Only the version is returned, it is no longer wrapped in a tuple. @@ -5904,9 +6215,11 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.version/ Name cowboy_req:version - HTTP version - Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. - The version can also be obtained using pattern matching: - #{version := Version} = Req. Arguments Req The Req object. Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. +The version can also be obtained using pattern matching: +#{version := Version} = Req. Arguments Req The Req object. + Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Changelog 2.0: Only the version is returned, it is no longer wrapped in a tuple. @@ -5916,9 +6229,11 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.version/ Name cowboy_req:version - HTTP version - Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. - The version can also be obtained using pattern matching: - #{version := Version} = Req. Arguments Req The Req object. Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. +The version can also be obtained using pattern matching: +#{version := Version} = Req. Arguments Req The Req object. + Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Changelog 2.0: Only the version is returned, it is no longer wrapped in a tuple. @@ -5928,9 +6243,11 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.version/ Name cowboy_req:version - HTTP version - Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. - The version can also be obtained using pattern matching: - #{version := Version} = Req. Arguments Req The Req object. Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. +The version can also be obtained using pattern matching: +#{version := Version} = Req. Arguments Req The Req object. + Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Changelog 2.0: Only the version is returned, it is no longer wrapped in a tuple. @@ -5940,9 +6257,11 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.version/ Name cowboy_req:version - HTTP version - Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. - The version can also be obtained using pattern matching: - #{version := Version} = Req. Arguments Req The Req object. Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. +The version can also be obtained using pattern matching: +#{version := Version} = Req. Arguments Req The Req object. + Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Changelog 2.0: Only the version is returned, it is no longer wrapped in a tuple. @@ -5952,10 +6271,10 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_rest/ Name cowboy_rest - REST handlers - Description The module cowboy_rest implements the HTTP state machine. - Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). - Callbacks REST handlers implement the following interface: - init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. +Description The module cowboy_rest implements the HTTP state machine. +Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). +Callbacks REST handlers implement the following interface: +init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. @@ -5965,10 +6284,10 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_rest/ Name cowboy_rest - REST handlers - Description The module cowboy_rest implements the HTTP state machine. - Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). - Callbacks REST handlers implement the following interface: - init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} | {{switch_handler, Module}, Req, State} | {{switch_handler, Module, Opts}, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Module :: module() Opts :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. +Description The module cowboy_rest implements the HTTP state machine. +Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). +Callbacks REST handlers implement the following interface: +init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} | {{switch_handler, Module}, Req, State} | {{switch_handler, Module, Opts}, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Module :: module() Opts :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. @@ -5978,10 +6297,10 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_rest/ Name cowboy_rest - REST handlers - Description The module cowboy_rest implements the HTTP state machine. - Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). - Callbacks REST handlers implement the following interface: - init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} | {{switch_handler, Module}, Req, State} | {{switch_handler, Module, Opts}, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Module :: module() Opts :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. +Description The module cowboy_rest implements the HTTP state machine. +Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). +Callbacks REST handlers implement the following interface: +init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} | {{switch_handler, Module}, Req, State} | {{switch_handler, Module, Opts}, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Module :: module() Opts :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. @@ -5991,10 +6310,10 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_rest/ Name cowboy_rest - REST handlers - Description The module cowboy_rest implements the HTTP state machine. - Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). - Callbacks REST handlers implement the following interface: - init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} | {{switch_handler, Module}, Req, State} | {{switch_handler, Module, Opts}, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Module :: module() Opts :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. +Description The module cowboy_rest implements the HTTP state machine. +Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). +Callbacks REST handlers implement the following interface: +init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} | {{switch_handler, Module}, Req, State} | {{switch_handler, Module, Opts}, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Module :: module() Opts :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. @@ -6004,10 +6323,10 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_rest/ Name cowboy_rest - REST handlers - Description The module cowboy_rest implements the HTTP state machine. - Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). - Callbacks REST handlers implement the following interface: - init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} | {{switch_handler, Module}, Req, State} | {{switch_handler, Module, Opts}, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Module :: module() Opts :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. +Description The module cowboy_rest implements the HTTP state machine. +Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). +Callbacks REST handlers implement the following interface: +init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} | {{switch_handler, Module}, Req, State} | {{switch_handler, Module, Opts}, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Module :: module() Opts :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. @@ -6017,9 +6336,10 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_router/ Name cowboy_router - Router middleware - Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. - The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. - When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. +The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. +When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +The router will stop execution when no route matches. @@ -6029,9 +6349,10 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_router/ Name cowboy_router - Router middleware - Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. - The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. - When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. +The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. +When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +The router will stop execution when no route matches. @@ -6041,9 +6362,10 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_router/ Name cowboy_router - Router middleware - Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. - The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. - When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. +The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. +When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +The router will stop execution when no route matches. @@ -6053,9 +6375,10 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_router/ Name cowboy_router - Router middleware - Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. - The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. - When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. +The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. +When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +The router will stop execution when no route matches. @@ -6065,9 +6388,10 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_router/ Name cowboy_router - Router middleware - Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. - The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. - When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. +The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. +When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +The router will stop execution when no route matches. @@ -6077,9 +6401,11 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_router.compile/ Name cowboy_router:compile - Compile routes to the resources - Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. - Takes a human readable list of routes and transforms it into a form more efficient to process. - Arguments Routes Human readable list of routes. Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. +Takes a human readable list of routes and transforms it into a form more efficient to process. +Arguments Routes Human readable list of routes. + Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Changelog 1.0: Function introduced. Examples Compile routes and start a listener Dispatch = cowboy_router:compile([ {'_', [ {" @@ -6089,9 +6415,11 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_router.compile/ Name cowboy_router:compile - Compile routes to the resources - Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. - Takes a human readable list of routes and transforms it into a form more efficient to process. - Arguments Routes Human readable list of routes. Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. +Takes a human readable list of routes and transforms it into a form more efficient to process. +Arguments Routes Human readable list of routes. + Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Changelog 1.0: Function introduced. Examples Compile routes and start a listener Dispatch = cowboy_router:compile([ {'_', [ {" @@ -6101,9 +6429,11 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_router.compile/ Name cowboy_router:compile - Compile routes to the resources - Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. - Takes a human readable list of routes and transforms it into a form more efficient to process. - Arguments Routes Human readable list of routes. Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. +Takes a human readable list of routes and transforms it into a form more efficient to process. +Arguments Routes Human readable list of routes. + Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Changelog 1.0: Function introduced. Examples Compile routes and start a listener Dispatch = cowboy_router:compile([ {'_', [ {" @@ -6113,9 +6443,11 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_router.compile/ Name cowboy_router:compile - Compile routes to the resources - Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. - Takes a human readable list of routes and transforms it into a form more efficient to process. - Arguments Routes Human readable list of routes. Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. +Takes a human readable list of routes and transforms it into a form more efficient to process. +Arguments Routes Human readable list of routes. + Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Changelog 1.0: Function introduced. Examples Compile routes and start a listener Dispatch = cowboy_router:compile([ {'_', [ {" @@ -6125,9 +6457,11 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_router.compile/ Name cowboy_router:compile - Compile routes to the resources - Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. - Takes a human readable list of routes and transforms it into a form more efficient to process. - Arguments Routes Human readable list of routes. Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. +Takes a human readable list of routes and transforms it into a form more efficient to process. +Arguments Routes Human readable list of routes. + Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Changelog 1.0: Function introduced. Examples Compile routes and start a listener Dispatch = cowboy_router:compile([ {'_', [ {" @@ -6137,9 +6471,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_static/ Name cowboy_static - Static file handler - Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. - The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. - Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. +Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. +The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. +Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. @@ -6149,9 +6483,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_static/ Name cowboy_static - Static file handler - Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. - The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. - Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. +Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. +The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. +Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. @@ -6161,9 +6495,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_static/ Name cowboy_static - Static file handler - Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. - The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. - Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. +Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. +The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. +Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. @@ -6173,9 +6507,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_static/ Name cowboy_static - Static file handler - Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. - The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. - Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. +Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. +The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. +Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. @@ -6185,9 +6519,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_static/ Name cowboy_static - Static file handler - Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. - The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. - Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. +Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. +The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. +Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. @@ -6197,9 +6531,10 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_stream/ Name cowboy_handler - Stream handlers - Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. - An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. - Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. +An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. +Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Extra care must be taken when implementing stream handlers to ensure compatibility. @@ -6209,9 +6544,10 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_stream/ Name cowboy_handler - Stream handlers - Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. - An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. - Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. +An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. +Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Extra care must be taken when implementing stream handlers to ensure compatibility. @@ -6221,9 +6557,10 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_stream/ Name cowboy_handler - Stream handlers - Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. - An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. - Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. +An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. +Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Extra care must be taken when implementing stream handlers to ensure compatibility. @@ -6233,9 +6570,10 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_stream/ Name cowboy_handler - Stream handlers - Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. - An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. - Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. +An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. +Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Extra care must be taken when implementing stream handlers to ensure compatibility. @@ -6245,9 +6583,10 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_stream/ Name cowboy_handler - Stream handlers - Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. - An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. - Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. +An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. +Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Extra care must be taken when implementing stream handlers to ensure compatibility. @@ -6257,9 +6596,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_websocket/ Name cowboy_websocket - Websocket - Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. - Callbacks Websocket handlers must implement the following callback interface: - init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. +Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. +Callbacks Websocket handlers must implement the following callback interface: +init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. @@ -6269,9 +6608,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_websocket/ Name cowboy_websocket - Websocket - Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. - Callbacks Websocket handlers must implement the following callback interface: - init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. +Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. +Callbacks Websocket handlers must implement the following callback interface: +init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. @@ -6281,9 +6620,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_websocket/ Name cowboy_websocket - Websocket - Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. - Callbacks Websocket handlers must implement the following callback interface: - init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. +Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. +Callbacks Websocket handlers must implement the following callback interface: +init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. @@ -6293,9 +6632,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_websocket/ Name cowboy_websocket - Websocket - Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. - Callbacks Websocket handlers must implement the following callback interface: - init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. +Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. +Callbacks Websocket handlers must implement the following callback interface: +init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. @@ -6305,9 +6644,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_websocket/ Name cowboy_websocket - Websocket - Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. - Callbacks Websocket handlers must implement the following callback interface: - init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. +Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. +Callbacks Websocket handlers must implement the following callback interface: +init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. @@ -6317,9 +6656,9 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun/ Name gun - Asynchronous HTTP client - Description The gun module provides an asynchronous interface for connecting and communicating with Web servers over HTTP, HTTP/2 or Websocket. - Exports Connection: - gun:open(3) - Open a connection to the given host and port gun:open_unix(3) - Open a connection to the given Unix domain socket gun:close(3) - Brutally close the connection gun:info(3) - Obtain information about the connection Requests: +Description The gun module provides an asynchronous interface for connecting and communicating with Web servers over HTTP, HTTP/2 or Websocket. +Exports Connection: +gun:open(3) - Open a connection to the given host and port gun:open_unix(3) - Open a connection to the given Unix domain socket gun:close(3) - Brutally close the connection gun:info(3) - Obtain information about the connection Requests: @@ -6329,9 +6668,9 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun_app/ Name gun - HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP - Description Gun is an HTTP client for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Gun aims to provide an easy to use, asynchronous and always-connected client. It maintains a permanent connection to the server and reconnects automatically when necessary. - Modules gun(3) - Asynchronous HTTP client Dependencies cowlib(7) - Support library for manipulating Web protocols ssl - Secure communication over sockets All these applications must be started before the gun application. +Description Gun is an HTTP client for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Gun aims to provide an easy to use, asynchronous and always-connected client. It maintains a permanent connection to the server and reconnects automatically when necessary. +Modules gun(3) - Asynchronous HTTP client Dependencies cowlib(7) - Support library for manipulating Web protocols ssl - Secure communication over sockets All these applications must be started before the gun application. @@ -6341,8 +6680,8 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.await/ Name gun:await - Wait for a response - Description await(ConnPid, StreamRef) -&gt; await(ConnPid, StreamRef, 5000, MonitorRef) await(ConnPid, StreamRef, MonitorRef) -&gt; await(ConnPid, StreamRef, 5000, MonitorRef) await(ConnPid, StreamRef, Timeout) -&gt; await(ConnPid, StreamRef, Timeout, MonitorRef) await(ConnPid, StreamRef, Timeout, MonitorRef) -&gt; Result ConnPid :: pid() StreamRef :: reference() MonitorRef :: reference() Timeout :: timeout() Result :: tuple() - see below Wait for a response. - This function waits for a message from the given stream and returns it as a tuple. +Description await(ConnPid, StreamRef) -&gt; await(ConnPid, StreamRef, 5000, MonitorRef) await(ConnPid, StreamRef, MonitorRef) -&gt; await(ConnPid, StreamRef, 5000, MonitorRef) await(ConnPid, StreamRef, Timeout) -&gt; await(ConnPid, StreamRef, Timeout, MonitorRef) await(ConnPid, StreamRef, Timeout, MonitorRef) -&gt; Result ConnPid :: pid() StreamRef :: reference() MonitorRef :: reference() Timeout :: timeout() Result :: tuple() - see below Wait for a response. +This function waits for a message from the given stream and returns it as a tuple. @@ -6352,7 +6691,7 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.await_body/ Name gun:await_body - Wait for the complete response body - Description await_body(ConnPid, StreamRef) -&gt; await_body(ConnPid, StreamRef, 5000, MonitorRef) await_body(ConnPid, StreamRef, MonitorRef) -&gt; await_body(ConnPid, StreamRef, 5000, MonitorRef) await_body(ConnPid, StreamRef, Timeout) -&gt; await_body(ConnPid, StreamRef, Timeout, MonitorRef) await_body(ConnPid, StreamRef, Timeout, MonitorRef) -&gt; {ok, Body} | {ok, Body, Trailers} | {error, Reason} ConnPid :: pid() StreamRef :: reference() MonitorRef :: reference() Timeout :: timeout() Body :: binary() Trailers :: [{binary(), binary()}] Reason :: timeout | any() Wait for the complete response body. +Description await_body(ConnPid, StreamRef) -&gt; await_body(ConnPid, StreamRef, 5000, MonitorRef) await_body(ConnPid, StreamRef, MonitorRef) -&gt; await_body(ConnPid, StreamRef, 5000, MonitorRef) await_body(ConnPid, StreamRef, Timeout) -&gt; await_body(ConnPid, StreamRef, Timeout, MonitorRef) await_body(ConnPid, StreamRef, Timeout, MonitorRef) -&gt; {ok, Body} | {ok, Body, Trailers} | {error, Reason} ConnPid :: pid() StreamRef :: reference() MonitorRef :: reference() Timeout :: timeout() Body :: binary() Trailers :: [{binary(), binary()}] Reason :: timeout | any() Wait for the complete response body. @@ -6362,8 +6701,8 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.await_up/ Name gun:await_up - Wait for the connection to be up - Description await_up(ConnPid) -&gt; await_up(ConnPid, 5000, MonitorRef) await_up(ConnPid, MonitorRef) -&gt; await_up(ConnPid, 5000, MonitorRef) await_up(ConnPid, Timeout) -&gt; await_up(ConnPid, Timeout, MonitorRef) await_up(ConnPid, Timeout, MonitorRef) -&gt; {ok, Protocol} | {error, Reason} ConnPid :: pid() MonitorRef :: reference() Timeout :: timeout() Protocol :: http | http2 Reason :: timeout | any() Wait for the connection to be up. - Arguments ConnPid The pid of the Gun connection process. +Description await_up(ConnPid) -&gt; await_up(ConnPid, 5000, MonitorRef) await_up(ConnPid, MonitorRef) -&gt; await_up(ConnPid, 5000, MonitorRef) await_up(ConnPid, Timeout) -&gt; await_up(ConnPid, Timeout, MonitorRef) await_up(ConnPid, Timeout, MonitorRef) -&gt; {ok, Protocol} | {error, Reason} ConnPid :: pid() MonitorRef :: reference() Timeout :: timeout() Protocol :: http | http2 Reason :: timeout | any() Wait for the connection to be up. +Arguments ConnPid The pid of the Gun connection process. @@ -6373,9 +6712,9 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.cancel/ Name gun:cancel - Cancel the given stream - Description cancel(ConnPid, StreamRef) -&gt; ok ConnPid :: pid() StreamRef :: reference() Cancel the given stream. - The behavior of this function depends on the protocol selected. - HTTP/1.1 does not support this feature. Gun will simply silence the stream and stop relaying messages. Gun may also decide to close the connection if the response body is too large, to avoid wasting time and bandwidth. +Description cancel(ConnPid, StreamRef) -&gt; ok ConnPid :: pid() StreamRef :: reference() Cancel the given stream. +The behavior of this function depends on the protocol selected. +HTTP/1.1 does not support this feature. Gun will simply silence the stream and stop relaying messages. Gun may also decide to close the connection if the response body is too large, to avoid wasting time and bandwidth. @@ -6385,9 +6724,10 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.close/ Name gun:close - Brutally close the connection - Description close(ConnPid) -&gt; ok ConnPid :: pid() Brutally close the connection. - Arguments ConnPid The pid of the Gun connection process. Return value The atom ok is returned. - Changelog 1.0: Function introduced. Examples Close the connection ok = gun:close(ConnPid). See also gun(3), gun:open(3), gun:open_unix(3) +Description close(ConnPid) -&gt; ok ConnPid :: pid() Brutally close the connection. +Arguments ConnPid The pid of the Gun connection process. + Return value The atom ok is returned. +Changelog 1.0: Function introduced. Examples Close the connection ok = gun:close(ConnPid). See also gun(3), gun:open(3), gun:open_unix(3) @@ -6397,9 +6737,9 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.data/ Name gun:data - Stream the body of a request - Description data(ConnPid, StreamRef, IsFin, Data) -&gt; ok ConnPid :: pid() StreamRef :: reference() IsFin :: fin | nofin Data :: iodata() Stream the body of a request. - This function can only be used if the original request had headers indicating that a body would be streamed. - All calls to this function must use the nofin flag except for the last which must use fin to indicate the end of the request body. +Description data(ConnPid, StreamRef, IsFin, Data) -&gt; ok ConnPid :: pid() StreamRef :: reference() IsFin :: fin | nofin Data :: iodata() Stream the body of a request. +This function can only be used if the original request had headers indicating that a body would be streamed. +All calls to this function must use the nofin flag except for the last which must use fin to indicate the end of the request body. @@ -6409,8 +6749,11 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.delete/ Name gun:delete - Delete a resource - Description delete(ConnPid, Path) -&gt; delete(ConnPid, Path, [], #{}). delete(ConnPid, Path, Headers) -&gt; delete(ConnPid, Path, Headers, #{}) delete(ConnPid, Path, Headers, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] ReqOpts :: gun:req_opts() StreamRef :: reference() Delete a resource. - Arguments ConnPid The pid of the Gun connection process. Path Path to the resource. +Description delete(ConnPid, Path) -&gt; delete(ConnPid, Path, [], #{}). delete(ConnPid, Path, Headers) -&gt; delete(ConnPid, Path, Headers, #{}) delete(ConnPid, Path, Headers, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] ReqOpts :: gun:req_opts() StreamRef :: reference() Delete a resource. +Arguments ConnPid The pid of the Gun connection process. + Path Path to the resource. + Headers Additional request headers. + ReqOpts Request options. @@ -6420,9 +6763,11 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.flush/ Name gun:flush - Flush all messages related to a connection or a stream - Description flush(ConnPid) -&gt; ok flush(StreamRef) -&gt; ok ConnPid :: pid() StreamRef :: reference() Flush all messages related to a connection or a stream. - Arguments Either of these arguments may be provided: - ConnPid The pid of the Gun connection process. StreamRef Identifier of the stream for the original request. +Description flush(ConnPid) -&gt; ok flush(StreamRef) -&gt; ok ConnPid :: pid() StreamRef :: reference() Flush all messages related to a connection or a stream. +Arguments Either of these arguments may be provided: +ConnPid The pid of the Gun connection process. + StreamRef Identifier of the stream for the original request. + Return value The atom ok is returned. @@ -6432,8 +6777,10 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.get/ Name gun:get - Get a resource representation - Description get(ConnPid, Path) -&gt; get(ConnPid, Path, [], #{}). get(ConnPid, Path, Headers) -&gt; get(ConnPid, Path, Headers, #{}) get(ConnPid, Path, Headers, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] ReqOpts :: gun:req_opts() StreamRef :: reference() Get a resource representation. - Arguments ConnPid The pid of the Gun connection process. Path Path to the resource. +Description get(ConnPid, Path) -&gt; get(ConnPid, Path, [], #{}). get(ConnPid, Path, Headers) -&gt; get(ConnPid, Path, Headers, #{}) get(ConnPid, Path, Headers, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] ReqOpts :: gun:req_opts() StreamRef :: reference() Get a resource representation. +Arguments ConnPid The pid of the Gun connection process. + Path Path to the resource. + Headers Additional request headers. @@ -6443,8 +6790,8 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.head/ Name gun:head - Get headers of a resource representation - Description head(ConnPid, Path) -&gt; head(ConnPid, Path, [], #{}). head(ConnPid, Path, Headers) -&gt; head(ConnPid, Path, Headers, #{}) head(ConnPid, Path, Headers, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] ReqOpts :: gun:req_opts() StreamRef :: reference() Get headers of a resource representation. - This function performs the same operation as gun:get(3), except the server will not send the resource representation, only the response&#8217;s status code and headers. +Description head(ConnPid, Path) -&gt; head(ConnPid, Path, [], #{}). head(ConnPid, Path, Headers) -&gt; head(ConnPid, Path, Headers, #{}) head(ConnPid, Path, Headers, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] ReqOpts :: gun:req_opts() StreamRef :: reference() Get headers of a resource representation. +This function performs the same operation as gun:get(3), except the server will not send the resource representation, only the response&apos;s status code and headers. @@ -6454,9 +6801,10 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.info/ Name gun:info - Obtain information about the connection - Description info(ConnPid) -&gt; Info ConnPid :: pid() Info :: #{ sock_ip =&gt; inet:ip_address(), sock_port =&gt; inet:port_number() } Obtain information about the connection. - Arguments ConnPid The pid of the Gun connection process. Return value A map is returned containing various informations about the connection. - Changelog 1. +Description info(ConnPid) -&gt; Info ConnPid :: pid() Info :: #{ sock_ip =&gt; inet:ip_address(), sock_port =&gt; inet:port_number() } Obtain information about the connection. +Arguments ConnPid The pid of the Gun connection process. + Return value A map is returned containing various informations about the connection. +Changelog 1.0: Function introduced. Examples Obtain information about the connection Info = gun:info(ConnPid). See also gun(3), gun:open(3), gun:open_unix(3) @@ -6466,8 +6814,10 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.open/ Name gun:open - Open a connection to the given host and port - Description open(Host, Port) -&gt; open(Host, Port, #{}) open(Host, Port, Opts) -&gt; {ok, pid()} | {error, any()} Host :: inet:hostname() | inet:ip_address() Port :: inet:port_number() Opts :: gun:opts() Open a connection to the given host and port. - Arguments Host Host or IP address to connect to. Port Port to connect to. +Description open(Host, Port) -&gt; open(Host, Port, #{}) open(Host, Port, Opts) -&gt; {ok, pid()} | {error, any()} Host :: inet:hostname() | inet:ip_address() Port :: inet:port_number() Opts :: gun:opts() Open a connection to the given host and port. +Arguments Host Host or IP address to connect to. + Port Port to connect to. + Opts Options for this connection. @@ -6477,8 +6827,10 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.open_unix/ Name gun:open_unix - Open a connection to the given Unix domain socket - Description open_unix(SocketPath, Opts) -&gt; {ok, pid()} | {error, any()} SocketPath :: string() Opts :: gun:opts() Open a connection to the given Unix domain socket. - Arguments SocketPath Path to the Unix domain socket to connect to. Opts Options for this connection. Return value The pid of the newly created Gun process is returned. +Description open_unix(SocketPath, Opts) -&gt; {ok, pid()} | {error, any()} SocketPath :: string() Opts :: gun:opts() Open a connection to the given Unix domain socket. +Arguments SocketPath Path to the Unix domain socket to connect to. + Opts Options for this connection. + Return value The pid of the newly created Gun process is returned. Note that this does not indicate that the connection has been successfully opened; the gun_up(3) message will be sent for that. @@ -6488,8 +6840,8 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.options/ Name gun:options - Query the capabilities of the server or a resource - Description options(ConnPid, Path) -&gt; options(ConnPid, Path, [], #{}). options(ConnPid, Path, Headers) -&gt; options(ConnPid, Path, Headers, #{}) options(ConnPid, Path, Headers, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] ReqOpts :: gun:req_opts() StreamRef :: reference() Query the capabilities of the server or a resource. - The special path "*" can be used to obtain information about the server as a whole. +Description options(ConnPid, Path) -&gt; options(ConnPid, Path, [], #{}). options(ConnPid, Path, Headers) -&gt; options(ConnPid, Path, Headers, #{}) options(ConnPid, Path, Headers, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] ReqOpts :: gun:req_opts() StreamRef :: reference() Query the capabilities of the server or a resource. +The special path &quot;*&quot; can be used to obtain information about the server as a whole. @@ -6499,8 +6851,8 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.patch/ Name gun:patch - Apply a set of changes to a resource - Description patch(ConnPid, Path, Headers) -&gt; StreamRef patch(ConnPid, Path, Headers, Body) -&gt; patch(ConnPid, Path, Headers, Body, #{}) patch(ConnPid, Path, Headers, Body, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] Body :: iodata() ReqOpts :: gun:req_opts() StreamRef :: reference() Apply a set of changes to a resource. - The behavior of this function varies depending on whether a body is provided. +Description patch(ConnPid, Path, Headers) -&gt; StreamRef patch(ConnPid, Path, Headers, Body) -&gt; patch(ConnPid, Path, Headers, Body, #{}) patch(ConnPid, Path, Headers, Body, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] Body :: iodata() ReqOpts :: gun:req_opts() StreamRef :: reference() Apply a set of changes to a resource. +The behavior of this function varies depending on whether a body is provided. @@ -6509,9 +6861,9 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/gun/1.0/manual/gun.post/ - Name gun:post - Process the enclosed representation according to a resource&#8217;s own semantics - Description post(ConnPid, Path, Headers) -&gt; StreamRef post(ConnPid, Path, Headers, Body) -&gt; post(ConnPid, Path, Headers, Body, #{}) post(ConnPid, Path, Headers, Body, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] Body :: iodata() ReqOpts :: gun:req_opts() StreamRef :: reference() Process the enclosed representation according to a resource&#8217;s own semantics. - The behavior of this function varies depending on whether a body is provided. + Name gun:post - Process the enclosed representation according to a resource&apos;s own semantics +Description post(ConnPid, Path, Headers) -&gt; StreamRef post(ConnPid, Path, Headers, Body) -&gt; post(ConnPid, Path, Headers, Body, #{}) post(ConnPid, Path, Headers, Body, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] Body :: iodata() ReqOpts :: gun:req_opts() StreamRef :: reference() Process the enclosed representation according to a resource&apos;s own semantics. +The behavior of this function varies depending on whether a body is provided. @@ -6521,8 +6873,9 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.put/ Name gun:put - Create or replace a resource - Description put(ConnPid, Path, Headers) -&gt; StreamRef put(ConnPid, Path, Headers, Body) -&gt; put(ConnPid, Path, Headers, Body, #{}) put(ConnPid, Path, Headers, Body, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] Body :: iodata() ReqOpts :: gun:req_opts() StreamRef :: reference() Create or replace a resource. - The behavior of this function varies depending on whether a body is provided. +Description put(ConnPid, Path, Headers) -&gt; StreamRef put(ConnPid, Path, Headers, Body) -&gt; put(ConnPid, Path, Headers, Body, #{}) put(ConnPid, Path, Headers, Body, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] Body :: iodata() ReqOpts :: gun:req_opts() StreamRef :: reference() Create or replace a resource. +The behavior of this function varies depending on whether a body is provided. +The function put/3 expects either a content-length or content-type header to indicate that a body will be sent afterwards. @@ -6532,8 +6885,8 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.request/ Name gun:request - Perform the given request - Description request(ConnPid, Method, Path, Headers) -&gt; StreamRef request(ConnPid, Method, Path, Headers, Body) -&gt; request(ConnPid, Method, Path, Headers, Body, #{}) request(ConnPid, Method, Path, Headers, Body, ReqOpts) -&gt; StreamRef ConnPid :: pid() Method :: binary() Path :: iodata() Headers :: [{binary(), iodata()}] Body :: iodata() ReqOpts :: gun:req_opts() StreamRef :: reference() Perform the given request. - This is a general purpose function that should only be used when other method-specific functions do not apply. +Description request(ConnPid, Method, Path, Headers) -&gt; StreamRef request(ConnPid, Method, Path, Headers, Body) -&gt; request(ConnPid, Method, Path, Headers, Body, #{}) request(ConnPid, Method, Path, Headers, Body, ReqOpts) -&gt; StreamRef ConnPid :: pid() Method :: binary() Path :: iodata() Headers :: [{binary(), iodata()}] Body :: iodata() ReqOpts :: gun:req_opts() StreamRef :: reference() Perform the given request. +This is a general purpose function that should only be used when other method-specific functions do not apply. @@ -6543,9 +6896,10 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.ws_send/ Name gun:ws_send - Send Websocket frames - Description ws_send(ConnPid, Frames) -&gt; ok ConnPid :: pid() Frames :: Frame | [Frame] Frame :: close | ping | pong | {text | binary | close | ping | pong, iodata()} | {close, non_neg_integer(), iodata()} Send Websocket frames. - The connection must first be upgraded to Websocket using the function gun:ws_upgrade(3). - Arguments ConnPid The pid of the Gun connection process. +Description ws_send(ConnPid, Frames) -&gt; ok ConnPid :: pid() Frames :: Frame | [Frame] Frame :: close | ping | pong | {text | binary | close | ping | pong, iodata()} | {close, non_neg_integer(), iodata()} Send Websocket frames. +The connection must first be upgraded to Websocket using the function gun:ws_upgrade(3). +Arguments ConnPid The pid of the Gun connection process. + Frames A Websocket frame. @@ -6555,9 +6909,9 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun.ws_upgrade/ Name gun:ws_upgrade - Upgrade to Websocket - Description ws_upgrade(ConnPid, Path) -&gt; ws_upgrade(ConnPid, Path, []) ws_upgrade(ConnPid, Path, Headers) -&gt; StreamRef ws_upgrade(ConnPid, Path, Headers, WsOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] WsOpts :: gun:ws_opts StreamRef :: reference() Upgrade to Websocket. - The behavior of this function depends on the protocol selected. - HTTP/1.1 cannot handle Websocket and HTTP requests concurrently. The upgrade, if successful, will result in the complete takeover of the connection. +Description ws_upgrade(ConnPid, Path) -&gt; ws_upgrade(ConnPid, Path, []) ws_upgrade(ConnPid, Path, Headers) -&gt; StreamRef ws_upgrade(ConnPid, Path, Headers, WsOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] WsOpts :: gun:ws_opts StreamRef :: reference() Upgrade to Websocket. +The behavior of this function depends on the protocol selected. +HTTP/1.1 cannot handle Websocket and HTTP requests concurrently. The upgrade, if successful, will result in the complete takeover of the connection. @@ -6567,10 +6921,10 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun_data/ Name gun_data - Response body - Description {gun_data, ConnPid, StreamRef, IsFin, Data} ConnPid :: pid() StreamRef :: reference() IsFin :: fin | nofin Data :: binary() Response body. - This message informs the relevant process that the server sent a all or part of the body for the response to the original request. - A data message is always preceded by a response message. - The response body may be terminated either by a data message with the flag fin set or by a gun_trailers(3) message. +Description {gun_data, ConnPid, StreamRef, IsFin, Data} ConnPid :: pid() StreamRef :: reference() IsFin :: fin | nofin Data :: binary() Response body. +This message informs the relevant process that the server sent a all or part of the body for the response to the original request. +A data message is always preceded by a response message. +The response body may be terminated either by a data message with the flag fin set or by a gun_trailers(3) message. @@ -6580,9 +6934,9 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun_down/ Name gun_down - The connection is down - Description {gun_down, ConnPid, Protocol, Reason, KilledStreams, UnprocessedStreams} ConnPid :: pid() Protocol :: http | http2 | ws Reason :: any() KilledStreams :: [reference()] UnprocessedStreams :: [reference()] The connection is down. - This message informs the owner process that the connection was lost. Depending on the retry and retry_timeout options Gun may automatically attempt to reconnect. - When the connection goes back up, Gun will not attempt to retry requests. +Description {gun_down, ConnPid, Protocol, Reason, KilledStreams, UnprocessedStreams} ConnPid :: pid() Protocol :: http | http2 | ws Reason :: any() KilledStreams :: [reference()] UnprocessedStreams :: [reference()] The connection is down. +This message informs the owner process that the connection was lost. Depending on the retry and retry_timeout options Gun may automatically attempt to reconnect. +When the connection goes back up, Gun will not attempt to retry requests. @@ -6592,8 +6946,8 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun_error/ Name gun_error - Stream or connection-wide error - Description {gun_error, ConnPid, StreamRef, Reason} {gun_error, ConnPid, Reason} ConnPid :: pid() StreamRef :: reference() Reason :: any() Stream or connection-wide error. - These messages inform the relevant process that an error occurred. A reference is given when the error pertains to a specific stream. Connection-wide errors do not imply that the connection is no longer usable, they are used for all errors that are not specific to a stream. +Description {gun_error, ConnPid, StreamRef, Reason} {gun_error, ConnPid, Reason} ConnPid :: pid() StreamRef :: reference() Reason :: any() Stream or connection-wide error. +These messages inform the relevant process that an error occurred. A reference is given when the error pertains to a specific stream. Connection-wide errors do not imply that the connection is no longer usable, they are used for all errors that are not specific to a stream. @@ -6603,9 +6957,9 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun_inform/ Name gun_inform - Informational response - Description {gun_inform, ConnPid, StreamRef, Status, Headers} ConnPid :: pid() StreamRef :: reference() Status :: 100..199 Headers :: [{binary(), binary()}] Informational response. - This message informs the relevant process that the server sent an informational response to the original request. - Informational responses are only intermediate responses and provide no guarantees as to what the final response will be. An informational response always precedes the response to the original request. +Description {gun_inform, ConnPid, StreamRef, Status, Headers} ConnPid :: pid() StreamRef :: reference() Status :: 100..199 Headers :: [{binary(), binary()}] Informational response. +This message informs the relevant process that the server sent an informational response to the original request. +Informational responses are only intermediate responses and provide no guarantees as to what the final response will be. An informational response always precedes the response to the original request. @@ -6615,9 +6969,9 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun_push/ Name gun_push - Server-initiated push - Description {gun_push, ConnPid, StreamRef, NewStreamRef, Method, URI, Headers} ConnPid :: pid() StreamRef :: reference() NewStreamRef :: reference() Method :: binary() URI :: binary() Headers :: [{binary(), binary()}] Server-initiated push. - This message informs the relevant process that the server is pushing a resource related to the effective target URI of the original request. - A server-initiated push message always precedes the response to the original request. +Description {gun_push, ConnPid, StreamRef, NewStreamRef, Method, URI, Headers} ConnPid :: pid() StreamRef :: reference() NewStreamRef :: reference() Method :: binary() URI :: binary() Headers :: [{binary(), binary()}] Server-initiated push. +This message informs the relevant process that the server is pushing a resource related to the effective target URI of the original request. +A server-initiated push message always precedes the response to the original request. @@ -6627,9 +6981,11 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun_response/ Name gun_response - Response - Description {gun_response, ConnPid, StreamRef, IsFin, Status, Headers} ConnPid :: pid() StreamRef :: reference() IsFin :: fin | nofin Status :: non_neg_integer() Headers :: [{binary(), binary()}] Response. - This message informs the relevant process that the server sent a response to the original request. - Elements ConnPid The pid of the Gun connection process. StreamRef Identifier of the stream for the original request. +Description {gun_response, ConnPid, StreamRef, IsFin, Status, Headers} ConnPid :: pid() StreamRef :: reference() IsFin :: fin | nofin Status :: non_neg_integer() Headers :: [{binary(), binary()}] Response. +This message informs the relevant process that the server sent a response to the original request. +Elements ConnPid The pid of the Gun connection process. + StreamRef Identifier of the stream for the original request. + IsFin Whether this message terminates the response. @@ -6639,10 +6995,12 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun_trailers/ Name gun_trailers - Response trailers - Description {gun_trailers, ConnPid, StreamRef, Headers} ConnPid :: pid() StreamRef :: reference() Headers :: [{binary(), binary()}] Response trailers. - This message informs the relevant process that the server sent response trailers for the response to the original request. - A trailers message terminates the response. - Elements ConnPid The pid of the Gun connection process. StreamRef Identifier of the stream for the original request. +Description {gun_trailers, ConnPid, StreamRef, Headers} ConnPid :: pid() StreamRef :: reference() Headers :: [{binary(), binary()}] Response trailers. +This message informs the relevant process that the server sent response trailers for the response to the original request. +A trailers message terminates the response. +Elements ConnPid The pid of the Gun connection process. + StreamRef Identifier of the stream for the original request. + Headers Trailing headers sent after the response body. @@ -6652,9 +7010,9 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun_up/ Name gun_up - The connection is up - Description {gun_up, ConnPid, Protocol} ConnPid :: pid() Protocol :: http | http2 The connection is up. - This message informs the owner process that the connection or reconnection completed. - Gun will now start processing the messages it received while waiting for the connection to be up. If this is a reconnection, then this may not be desirable for all requests. +Description {gun_up, ConnPid, Protocol} ConnPid :: pid() Protocol :: http | http2 The connection is up. +This message informs the owner process that the connection or reconnection completed. +Gun will now start processing the messages it received while waiting for the connection to be up. If this is a reconnection, then this may not be desirable for all requests. Those requests should be cancelled when the connection goes down, and any subsequent messages ignored. @@ -6664,9 +7022,9 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun_upgrade/ Name gun_upgrade - Successful protocol upgrade - Description {gun_upgrade, ConnPid, StreamRef, Protocols, Headers} ConnPid :: pid() StreamRef :: reference() Protocols :: [&lt;&lt;"websocket"&gt;&gt;] Headers :: [{binary(), binary()}] Successful protocol upgrade. - This message informs the relevant process that the server accepted to upgrade to one or more protocols given in the original request. - The exact semantics of this message depend on the original protocol. HTTP/1.1 upgrades apply to the entire connection. +Description {gun_upgrade, ConnPid, StreamRef, Protocols, Headers} ConnPid :: pid() StreamRef :: reference() Protocols :: [&lt;&lt;"websocket"&gt;&gt;] Headers :: [{binary(), binary()}] Successful protocol upgrade. +This message informs the relevant process that the server accepted to upgrade to one or more protocols given in the original request. +The exact semantics of this message depend on the original protocol. HTTP/1.1 upgrades apply to the entire connection. HTTP/2 uses a different mechanism which allows switching specific streams to a different protocol. @@ -6676,10 +7034,10 @@ https://ninenines.eu/docs/en/gun/1.0/manual/gun_ws/ Name gun_ws - Websocket frame - Description {gun_ws, ConnPid, StreamRef, Frame} ConnPid :: pid() StreamRef :: reference() Frame :: close | {text | binary | close, binary()} | {close, non_neg_integer(), binary()} Websocket frame. - This message informs the relevant process that the server sent the enclosed frame. - This message can only be sent on streams that were upgraded to the Websocket protocol. - Elements ConnPid The pid of the Gun connection process. +Description {gun_ws, ConnPid, StreamRef, Frame} ConnPid :: pid() StreamRef :: reference() Frame :: close | {text | binary | close, binary()} | {close, non_neg_integer(), binary()} Websocket frame. +This message informs the relevant process that the server sent the enclosed frame. +This message can only be sent on streams that were upgraded to the Websocket protocol. +Elements ConnPid The pid of the Gun connection process. @@ -6689,9 +7047,10 @@ https://ninenines.eu/docs/en/ranch/1.2/manual/ranch/ Name ranch - socket acceptor pool - Description The ranch module provides functions for starting and manipulating Ranch listeners. - Types max_conns() = non_neg_integer() | infinity Maximum number of connections allowed on this listener. - This is a soft limit. The actual number of connections might be slightly above the limit due to concurrency when accepting new connections. Some connections may also be removed from this count explicitly by the user code. +Description The ranch module provides functions for starting and manipulating Ranch listeners. +Types max_conns() = non_neg_integer() | infinity Maximum number of connections allowed on this listener. +This is a soft limit. The actual number of connections might be slightly above the limit due to concurrency when accepting new connections. Some connections may also be removed from this count explicitly by the user code. +opt() opt() = {ack_timeout, timeout()} | {connection_type, worker | supervisor} | {max_connections, max_conns()} | {shutdown, timeout() | brutal_kill} | {socket, any()} Ranch-specific transport options. @@ -6701,9 +7060,10 @@ https://ninenines.eu/docs/en/ranch/1.3/manual/ranch/ Name ranch - socket acceptor pool - Description The ranch module provides functions for starting and manipulating Ranch listeners. - Types max_conns() = non_neg_integer() | infinity Maximum number of connections allowed on this listener. - This is a soft limit. The actual number of connections might be slightly above the limit due to concurrency when accepting new connections. Some connections may also be removed from this count explicitly by the user code. +Description The ranch module provides functions for starting and manipulating Ranch listeners. +Types max_conns() = non_neg_integer() | infinity Maximum number of connections allowed on this listener. +This is a soft limit. The actual number of connections might be slightly above the limit due to concurrency when accepting new connections. Some connections may also be removed from this count explicitly by the user code. +opt() opt() = {ack_timeout, timeout()} | {connection_type, worker | supervisor} | {max_connections, max_conns()} | {shutdown, timeout() | brutal_kill} | {socket, any()} Ranch-specific transport options. @@ -6713,9 +7073,23 @@ https://ninenines.eu/docs/en/ranch/1.4/manual/ranch/ Name ranch - socket acceptor pool - Description The ranch module provides functions for starting and manipulating Ranch listeners. - Types max_conns() = non_neg_integer() | infinity Maximum number of connections allowed on this listener. - This is a soft limit. The actual number of connections might be slightly above the limit due to concurrency when accepting new connections. Some connections may also be removed from this count explicitly by the user code. +Description The ranch module provides functions for starting and manipulating Ranch listeners. +Types max_conns() = non_neg_integer() | infinity Maximum number of connections allowed on this listener. +This is a soft limit. The actual number of connections might be slightly above the limit due to concurrency when accepting new connections. Some connections may also be removed from this count explicitly by the user code. +opt() opt() = {ack_timeout, timeout()} | {connection_type, worker | supervisor} | {max_connections, max_conns()} | {num_acceptors, pos_integer()} | {shutdown, timeout() | brutal_kill} | {socket, any()} Ranch-specific transport options. + + + + ranch(3) + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch/ + Name ranch - socket acceptor pool +Description The ranch module provides functions for starting and manipulating Ranch listeners. +Types max_conns() = non_neg_integer() | infinity Maximum number of connections allowed on this listener. +This is a soft limit. The actual number of connections might be slightly above the limit due to concurrency when accepting new connections. Some connections may also be removed from this count explicitly by the user code. +opt() opt() = {ack_timeout, timeout()} | {connection_type, worker | supervisor} | {max_connections, max_conns()} | {num_acceptors, pos_integer()} | {shutdown, timeout() | brutal_kill} | {socket, any()} Ranch-specific transport options. @@ -6725,10 +7099,11 @@ https://ninenines.eu/docs/en/ranch/1.2/manual/ranch_app/ Name ranch - Socket acceptor pool for TCP protocols. - Dependencies The ranch application has no particular dependency required to start. - It has optional dependencies that are only required when listening for SSL connections. The dependencies are crypto, asn1, public_key and ssl. They are started automatically if they weren&#8217;t before. - Environment The ranch application defines one application environment configuration parameter. - profile (false) When enabled, Ranch will start eprof profiling automatically. +Dependencies The ranch application has no particular dependency required to start. +It has optional dependencies that are only required when listening for SSL connections. The dependencies are crypto, asn1, public_key and ssl. They are started automatically if they weren&apos;t before. +Environment The ranch application defines one application environment configuration parameter. +profile (false) When enabled, Ranch will start eprof profiling automatically. + You can use the ranch_app:profile_output/0 function to stop profiling and output the results to the files procs. @@ -6738,9 +7113,10 @@ https://ninenines.eu/docs/en/ranch/1.3/manual/ranch_app/ Name ranch - Socket acceptor pool for TCP protocols. - Dependencies The ranch application depends on the ssl application to start. It is used for handling secure connections, when the transport is ranch_ssl. It can be disabled if SSL is not used. - Environment The ranch application defines one application environment configuration parameter. - profile (false) When enabled, Ranch will start eprof profiling automatically. +Dependencies The ranch application depends on the ssl application to start. It is used for handling secure connections, when the transport is ranch_ssl. It can be disabled if SSL is not used. +Environment The ranch application defines one application environment configuration parameter. +profile (false) When enabled, Ranch will start eprof profiling automatically. + You can use the ranch_app:profile_output/0 function to stop profiling and output the results to the files procs. @@ -6750,9 +7126,23 @@ https://ninenines.eu/docs/en/ranch/1.4/manual/ranch_app/ Name ranch - Socket acceptor pool for TCP protocols. - Dependencies The ranch application depends on the ssl application to start. It is used for handling secure connections, when the transport is ranch_ssl. It can be disabled if SSL is not used. - Environment The ranch application defines one application environment configuration parameter. - profile (false) When enabled, Ranch will start eprof profiling automatically. +Dependencies The ranch application depends on the ssl application to start. It is used for handling secure connections, when the transport is ranch_ssl. It can be disabled if SSL is not used. +Environment The ranch application defines one application environment configuration parameter. +profile (false) When enabled, Ranch will start eprof profiling automatically. + You can use the ranch_app:profile_output/0 function to stop profiling and output the results to the files procs. + + + + ranch(7) + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_app/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_app/ + Name ranch - Socket acceptor pool for TCP protocols. +Dependencies The ranch application depends on the ssl application to start. It is used for handling secure connections, when the transport is ranch_ssl. It can be disabled if SSL is not used. +Environment The ranch application defines one application environment configuration parameter. +profile (false) When enabled, Ranch will start eprof profiling automatically. + You can use the ranch_app:profile_output/0 function to stop profiling and output the results to the files procs. @@ -6762,9 +7152,13 @@ https://ninenines.eu/docs/en/ranch/1.2/manual/ranch_protocol/ Name ranch_protocol - behaviour for protocol modules - Description The ranch_protocol behaviour defines the interface used by Ranch protocols. - Types None. - Callbacks start_link(Ref, Socket, Transport, ProtoOpts) &#8594; {ok, pid()} | {ok, pid(), pid()} Ref = ranch:ref() Listener name. Socket = any() Socket for this connection. Transport = module() Transport module for this socket. +Description The ranch_protocol behaviour defines the interface used by Ranch protocols. +Types None. +Callbacks start_link(Ref, Socket, Transport, ProtoOpts) -&gt; {ok, pid()} | {ok, pid(), pid()} Ref = ranch:ref() Listener name. + Socket = any() Socket for this connection. + Transport = module() Transport module for this socket. + ProtoOpts = any() Protocol options. + Start a new connection process for the given socket. @@ -6774,9 +7168,13 @@ https://ninenines.eu/docs/en/ranch/1.3/manual/ranch_protocol/ Name ranch_protocol - behaviour for protocol modules - Description The ranch_protocol behaviour defines the interface used by Ranch protocols. - Types None. - Callbacks start_link(Ref, Socket, Transport, ProtoOpts) &#8594; {ok, pid()} | {ok, pid(), pid()} Ref = ranch:ref() Listener name. Socket = any() Socket for this connection. Transport = module() Transport module for this socket. +Description The ranch_protocol behaviour defines the interface used by Ranch protocols. +Types None. +Callbacks start_link(Ref, Socket, Transport, ProtoOpts) -&gt; {ok, pid()} | {ok, pid(), pid()} Ref = ranch:ref() Listener name. + Socket = any() Socket for this connection. + Transport = module() Transport module for this socket. + ProtoOpts = any() Protocol options. + Start a new connection process for the given socket. @@ -6786,9 +7184,29 @@ https://ninenines.eu/docs/en/ranch/1.4/manual/ranch_protocol/ Name ranch_protocol - behaviour for protocol modules - Description The ranch_protocol behaviour defines the interface used by Ranch protocols. - Types None. - Callbacks start_link(Ref, Socket, Transport, ProtoOpts) &#8594; {ok, pid()} | {ok, pid(), pid()} Ref = ranch:ref() Listener name. Socket = any() Socket for this connection. Transport = module() Transport module for this socket. +Description The ranch_protocol behaviour defines the interface used by Ranch protocols. +Types None. +Callbacks start_link(Ref, Socket, Transport, ProtoOpts) -&gt; {ok, pid()} | {ok, pid(), pid()} Ref = ranch:ref() Listener name. + Socket = any() Socket for this connection. + Transport = module() Transport module for this socket. + ProtoOpts = any() Protocol options. + Start a new connection process for the given socket. + + + + ranch_protocol(3) + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_protocol/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_protocol/ + Name ranch_protocol - behaviour for protocol modules +Description The ranch_protocol behaviour defines the interface used by Ranch protocols. +Types None. +Callbacks start_link(Ref, Socket, Transport, ProtoOpts) -&gt; {ok, pid()} | {ok, pid(), pid()} Ref = ranch:ref() Listener name. + Socket = any() Socket for this connection. + Transport = module() Transport module for this socket. + ProtoOpts = any() Protocol options. + Start a new connection process for the given socket. @@ -6798,8 +7216,8 @@ https://ninenines.eu/docs/en/ranch/1.2/manual/ranch_ssl/ Name ranch_ssl - SSL transport module - Description The ranch_ssl module implements an SSL Ranch transport. - Types ssl_opt() ssl_opt() = {alpn_preferred_protocols, [binary()]} | {cacertfile, string()} | {cacerts, [public_key:der_encoded()]} | {cert, public_key:der_encoded()} | {certfile, string()} | {ciphers, [ssl:erl_cipher_suite()] | string()} | {client_renegotiation, boolean()} | {crl_cache, {module(), {internal | any(), list()}}} | {crl_check, boolean() | peer | best_effort} | {depth, 0..255} | {dh, public_key:der_encoded()} | {dhfile, string()} | {fail_if_no_peer_cert, boolean()} | {hibernate_after, integer() | undefined} | {honor_cipher_order, boolean()} | {key, {'RSAPrivateKey' | 'DSAPrivateKey' | 'PrivateKeyInfo', public_key:der_encoded()}} | {keyfile, string()} | {log_alert, boolean()} | {next_protocols_advertised, [binary()]} | {partial_chain, fun(([public_key:der_encoded()]) -&gt; {trusted_ca, public_key:der_encoded()} | unknown_ca)} | {password, string()} | {psk_identity, string()} | {reuse_session, fun()} | {reuse_sessions, boolean()} | {secure_renegotiate, boolean()} | {sni_fun, fun()} | {sni_hosts, [{string(), ssl_opt()}]} | {user_lookup_fun, {fun(), any()}} | {verify, ssl:verify_type()} | {verify_fun, {fun(), any()}} | {versions, [atom()]}. +Description The ranch_ssl module implements an SSL Ranch transport. +Types ssl_opt() ssl_opt() = {alpn_preferred_protocols, [binary()]} | {cacertfile, string()} | {cacerts, [public_key:der_encoded()]} | {cert, public_key:der_encoded()} | {certfile, string()} | {ciphers, [ssl:erl_cipher_suite()] | string()} | {client_renegotiation, boolean()} | {crl_cache, {module(), {internal | any(), list()}}} | {crl_check, boolean() | peer | best_effort} | {depth, 0..255} | {dh, public_key:der_encoded()} | {dhfile, string()} | {fail_if_no_peer_cert, boolean()} | {hibernate_after, integer() | undefined} | {honor_cipher_order, boolean()} | {key, {'RSAPrivateKey' | 'DSAPrivateKey' | 'PrivateKeyInfo', public_key:der_encoded()}} | {keyfile, string()} | {log_alert, boolean()} | {next_protocols_advertised, [binary()]} | {partial_chain, fun(([public_key:der_encoded()]) -&gt; {trusted_ca, public_key:der_encoded()} | unknown_ca)} | {password, string()} | {psk_identity, string()} | {reuse_session, fun()} | {reuse_sessions, boolean()} | {secure_renegotiate, boolean()} | {sni_fun, fun()} | {sni_hosts, [{string(), ssl_opt()}]} | {user_lookup_fun, {fun(), any()}} | {verify, ssl:verify_type()} | {verify_fun, {fun(), any()}} | {versions, [atom()]}. @@ -6809,8 +7227,8 @@ https://ninenines.eu/docs/en/ranch/1.3/manual/ranch_ssl/ Name ranch_ssl - SSL transport module - Description The ranch_ssl module implements an SSL Ranch transport. - Types ssl_opt() ssl_opt() = {alpn_preferred_protocols, [binary()]} | {beast_mitigation, one_n_minus_one | zero_n | disabled} | {cacertfile, string()} | {cacerts, [public_key:der_encoded()]} | {cert, public_key:der_encoded()} | {certfile, string()} | {ciphers, [ssl:erl_cipher_suite()] | string()} | {client_renegotiation, boolean()} | {crl_cache, {module(), {internal | any(), list()}}} | {crl_check, boolean() | peer | best_effort} | {depth, 0. +Description The ranch_ssl module implements an SSL Ranch transport. +Types ssl_opt() ssl_opt() = {alpn_preferred_protocols, [binary()]} | {beast_mitigation, one_n_minus_one | zero_n | disabled} | {cacertfile, string()} | {cacerts, [public_key:der_encoded()]} | {cert, public_key:der_encoded()} | {certfile, string()} | {ciphers, [ssl:erl_cipher_suite()] | string()} | {client_renegotiation, boolean()} | {crl_cache, {module(), {internal | any(), list()}}} | {crl_check, boolean() | peer | best_effort} | {depth, 0..255} | {dh, public_key:der_encoded()} | {dhfile, string()} | {fail_if_no_peer_cert, boolean()} | {hibernate_after, integer() | undefined} | {honor_cipher_order, boolean()} | {key, {'RSAPrivateKey' | 'DSAPrivateKey' | 'PrivateKeyInfo', public_key:der_encoded()}} | {keyfile, string()} | {log_alert, boolean()} | {next_protocols_advertised, [binary()]} | {padding_check, boolean()} | {partial_chain, fun(([public_key:der_encoded()]) -&gt; {trusted_ca, public_key:der_encoded()} | unknown_ca)} | {password, string()} | {psk_identity, string()} | {reuse_session, fun()} | {reuse_sessions, boolean()} | {secure_renegotiate, boolean()} | {signature_algs, [{atom(), atom()}]} | {sni_fun, fun()} | {sni_hosts, [{string(), ssl_opt()}]} | {user_lookup_fun, {fun(), any()}} | {v2_hello_compatible, boolean()} | {verify, ssl:verify_type()} | {verify_fun, {fun(), any()}} | {versions, [atom()]}. @@ -6820,8 +7238,19 @@ https://ninenines.eu/docs/en/ranch/1.4/manual/ranch_ssl/ Name ranch_ssl - SSL transport module - Description The ranch_ssl module implements an SSL Ranch transport. - Types ssl_opt() ssl_opt() = {alpn_preferred_protocols, [binary()]} | {beast_mitigation, one_n_minus_one | zero_n | disabled} | {cacertfile, string()} | {cacerts, [public_key:der_encoded()]} | {cert, public_key:der_encoded()} | {certfile, string()} | {ciphers, [ssl:erl_cipher_suite()] | string()} | {client_renegotiation, boolean()} | {crl_cache, {module(), {internal | any(), list()}}} | {crl_check, boolean() | peer | best_effort} | {depth, 0. +Description The ranch_ssl module implements an SSL Ranch transport. +Types ssl_opt() ssl_opt() = {alpn_preferred_protocols, [binary()]} | {beast_mitigation, one_n_minus_one | zero_n | disabled} | {cacertfile, string()} | {cacerts, [public_key:der_encoded()]} | {cert, public_key:der_encoded()} | {certfile, string()} | {ciphers, [ssl:erl_cipher_suite()] | string()} | {client_renegotiation, boolean()} | {crl_cache, {module(), {internal | any(), list()}}} | {crl_check, boolean() | peer | best_effort} | {depth, 0..255} | {dh, public_key:der_encoded()} | {dhfile, string()} | {fail_if_no_peer_cert, boolean()} | {hibernate_after, integer() | undefined} | {honor_cipher_order, boolean()} | {key, {'RSAPrivateKey' | 'DSAPrivateKey' | 'PrivateKeyInfo', public_key:der_encoded()}} | {keyfile, string()} | {log_alert, boolean()} | {next_protocols_advertised, [binary()]} | {padding_check, boolean()} | {partial_chain, fun(([public_key:der_encoded()]) -&gt; {trusted_ca, public_key:der_encoded()} | unknown_ca)} | {password, string()} | {psk_identity, string()} | {reuse_session, fun()} | {reuse_sessions, boolean()} | {secure_renegotiate, boolean()} | {signature_algs, [{atom(), atom()}]} | {sni_fun, fun()} | {sni_hosts, [{string(), ssl_opt()}]} | {user_lookup_fun, {fun(), any()}} | {v2_hello_compatible, boolean()} | {verify, ssl:verify_type()} | {verify_fun, {fun(), any()}} | {versions, [atom()]}. + + + + ranch_ssl(3) + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_ssl/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_ssl/ + Name ranch_ssl - SSL transport module +Description The ranch_ssl module implements an SSL Ranch transport. +Types ssl_opt() ssl_opt() = {alpn_preferred_protocols, [binary()]} | {beast_mitigation, one_n_minus_one | zero_n | disabled} | {cacertfile, string()} | {cacerts, [public_key:der_encoded()]} | {cert, public_key:der_encoded()} | {certfile, string()} | {ciphers, [ssl:erl_cipher_suite()] | string()} | {client_renegotiation, boolean()} | {crl_cache, {module(), {internal | any(), list()}}} | {crl_check, boolean() | peer | best_effort} | {depth, 0..255} | {dh, public_key:der_encoded()} | {dhfile, string()} | {fail_if_no_peer_cert, boolean()} | {hibernate_after, integer() | undefined} | {honor_cipher_order, boolean()} | {key, {'RSAPrivateKey' | 'DSAPrivateKey' | 'PrivateKeyInfo', public_key:der_encoded()}} | {keyfile, string()} | {log_alert, boolean()} | {next_protocols_advertised, [binary()]} | {padding_check, boolean()} | {partial_chain, fun(([public_key:der_encoded()]) -&gt; {trusted_ca, public_key:der_encoded()} | unknown_ca)} | {password, string()} | {psk_identity, string()} | {reuse_session, fun()} | {reuse_sessions, boolean()} | {secure_renegotiate, boolean()} | {signature_algs, [{atom(), atom()}]} | {sni_fun, fun()} | {sni_hosts, [{string(), ssl_opt()}]} | {user_lookup_fun, {fun(), any()}} | {v2_hello_compatible, boolean()} | {verify, ssl:verify_type()} | {verify_fun, {fun(), any()}} | {versions, [atom()]}. @@ -6831,9 +7260,9 @@ https://ninenines.eu/docs/en/ranch/1.2/manual/ranch_tcp/ Name ranch_tcp - TCP transport module - Description The ranch_tcp module implements a TCP Ranch transport. - Note that due to bugs in OTP up to at least R16B02, it is recommended to disable async threads when using the sendfile function of this transport, as it can make the threads stuck indefinitely. - Types opt() opt() = {backlog, non_neg_integer()} | {buffer, non_neg_integer()} | {delay_send, boolean()} | {dontroute, boolean()} | {exit_on_close, boolean()} | {fd, non_neg_integer()} | {high_msgq_watermark, non_neg_integer()} | {high_watermark, non_neg_integer()} | inet | inet6 | {ip, inet:ip_address()} | {keepalive, boolean()} | {linger, {boolean(), non_neg_integer()}} | {low_msgq_watermark, non_neg_integer()} | {low_watermark, non_neg_integer()} | {nodelay, boolean()} | {port, inet:port_number()} | {priority, integer()} | {raw, non_neg_integer(), non_neg_integer(), binary()} | {recbuf, non_neg_integer()} | {send_timeout, timeout()} | {send_timeout_close, boolean()} | {sndbuf, non_neg_integer()} | {tos, integer()} Listen options. +Description The ranch_tcp module implements a TCP Ranch transport. +Note that due to bugs in OTP up to at least R16B02, it is recommended to disable async threads when using the sendfile function of this transport, as it can make the threads stuck indefinitely. +Types opt() opt() = {backlog, non_neg_integer()} | {buffer, non_neg_integer()} | {delay_send, boolean()} | {dontroute, boolean()} | {exit_on_close, boolean()} | {fd, non_neg_integer()} | {high_msgq_watermark, non_neg_integer()} | {high_watermark, non_neg_integer()} | inet | inet6 | {ip, inet:ip_address()} | {keepalive, boolean()} | {linger, {boolean(), non_neg_integer()}} | {low_msgq_watermark, non_neg_integer()} | {low_watermark, non_neg_integer()} | {nodelay, boolean()} | {port, inet:port_number()} | {priority, integer()} | {raw, non_neg_integer(), non_neg_integer(), binary()} | {recbuf, non_neg_integer()} | {send_timeout, timeout()} | {send_timeout_close, boolean()} | {sndbuf, non_neg_integer()} | {tos, integer()} Listen options. @@ -6843,9 +7272,9 @@ https://ninenines.eu/docs/en/ranch/1.3/manual/ranch_tcp/ Name ranch_tcp - TCP transport module - Description The ranch_tcp module implements a TCP Ranch transport. - Note that due to bugs in OTP up to at least R16B02, it is recommended to disable async threads when using the sendfile function of this transport, as it can make the threads stuck indefinitely. - Types opt() opt() = {backlog, non_neg_integer()} | {buffer, non_neg_integer()} | {delay_send, boolean()} | {dontroute, boolean()} | {exit_on_close, boolean()} | {fd, non_neg_integer()} | {high_msgq_watermark, non_neg_integer()} | {high_watermark, non_neg_integer()} | inet | inet6 | {ip, inet:ip_address()} | {ipv6_v6only, boolean()} | {keepalive, boolean()} | {linger, {boolean(), non_neg_integer()}} | {low_msgq_watermark, non_neg_integer()} | {low_watermark, non_neg_integer()} | {nodelay, boolean()} | {port, inet:port_number()} | {priority, integer()} | {raw, non_neg_integer(), non_neg_integer(), binary()} | {recbuf, non_neg_integer()} | {send_timeout, timeout()} | {send_timeout_close, boolean()} | {sndbuf, non_neg_integer()} | {tos, integer()} Listen options. +Description The ranch_tcp module implements a TCP Ranch transport. +Note that due to bugs in OTP up to at least R16B02, it is recommended to disable async threads when using the sendfile function of this transport, as it can make the threads stuck indefinitely. +Types opt() opt() = {backlog, non_neg_integer()} | {buffer, non_neg_integer()} | {delay_send, boolean()} | {dontroute, boolean()} | {exit_on_close, boolean()} | {fd, non_neg_integer()} | {high_msgq_watermark, non_neg_integer()} | {high_watermark, non_neg_integer()} | inet | inet6 | {ip, inet:ip_address()} | {ipv6_v6only, boolean()} | {keepalive, boolean()} | {linger, {boolean(), non_neg_integer()}} | {low_msgq_watermark, non_neg_integer()} | {low_watermark, non_neg_integer()} | {nodelay, boolean()} | {port, inet:port_number()} | {priority, integer()} | {raw, non_neg_integer(), non_neg_integer(), binary()} | {recbuf, non_neg_integer()} | {send_timeout, timeout()} | {send_timeout_close, boolean()} | {sndbuf, non_neg_integer()} | {tos, integer()} Listen options. @@ -6855,9 +7284,21 @@ https://ninenines.eu/docs/en/ranch/1.4/manual/ranch_tcp/ Name ranch_tcp - TCP transport module - Description The ranch_tcp module implements a TCP Ranch transport. - Note that due to bugs in OTP up to at least R16B02, it is recommended to disable async threads when using the sendfile function of this transport, as it can make the threads stuck indefinitely. - Types opt() opt() = {backlog, non_neg_integer()} | {buffer, non_neg_integer()} | {delay_send, boolean()} | {dontroute, boolean()} | {exit_on_close, boolean()} | {fd, non_neg_integer()} | {high_msgq_watermark, non_neg_integer()} | {high_watermark, non_neg_integer()} | inet | inet6 | {ip, inet:ip_address()} | {ipv6_v6only, boolean()} | {keepalive, boolean()} | {linger, {boolean(), non_neg_integer()}} | {low_msgq_watermark, non_neg_integer()} | {low_watermark, non_neg_integer()} | {nodelay, boolean()} | {port, inet:port_number()} | {priority, integer()} | {raw, non_neg_integer(), non_neg_integer(), binary()} | {recbuf, non_neg_integer()} | {send_timeout, timeout()} | {send_timeout_close, boolean()} | {sndbuf, non_neg_integer()} | {tos, integer()} Listen options. +Description The ranch_tcp module implements a TCP Ranch transport. +Note that due to bugs in OTP up to at least R16B02, it is recommended to disable async threads when using the sendfile function of this transport, as it can make the threads stuck indefinitely. +Types opt() opt() = {backlog, non_neg_integer()} | {buffer, non_neg_integer()} | {delay_send, boolean()} | {dontroute, boolean()} | {exit_on_close, boolean()} | {fd, non_neg_integer()} | {high_msgq_watermark, non_neg_integer()} | {high_watermark, non_neg_integer()} | inet | inet6 | {ip, inet:ip_address()} | {ipv6_v6only, boolean()} | {keepalive, boolean()} | {linger, {boolean(), non_neg_integer()}} | {low_msgq_watermark, non_neg_integer()} | {low_watermark, non_neg_integer()} | {nodelay, boolean()} | {port, inet:port_number()} | {priority, integer()} | {raw, non_neg_integer(), non_neg_integer(), binary()} | {recbuf, non_neg_integer()} | {send_timeout, timeout()} | {send_timeout_close, boolean()} | {sndbuf, non_neg_integer()} | {tos, integer()} Listen options. + + + + ranch_tcp(3) + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_tcp/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_tcp/ + Name ranch_tcp - TCP transport module +Description The ranch_tcp module implements a TCP Ranch transport. +Note that due to bugs in OTP up to at least R16B02, it is recommended to disable async threads when using the sendfile function of this transport, as it can make the threads stuck indefinitely. +Types opt() opt() = {backlog, non_neg_integer()} | {buffer, non_neg_integer()} | {delay_send, boolean()} | {dontroute, boolean()} | {exit_on_close, boolean()} | {fd, non_neg_integer()} | {high_msgq_watermark, non_neg_integer()} | {high_watermark, non_neg_integer()} | inet | inet6 | {ip, inet:ip_address()} | {ipv6_v6only, boolean()} | {keepalive, boolean()} | {linger, {boolean(), non_neg_integer()}} | {low_msgq_watermark, non_neg_integer()} | {low_watermark, non_neg_integer()} | {nodelay, boolean()} | {port, inet:port_number()} | {priority, integer()} | {raw, non_neg_integer(), non_neg_integer(), binary()} | {recbuf, non_neg_integer()} | {send_timeout, timeout()} | {send_timeout_close, boolean()} | {sndbuf, non_neg_integer()} | {tos, integer()} Listen options. @@ -6867,10 +7308,12 @@ https://ninenines.eu/docs/en/ranch/1.2/manual/ranch_transport/ Name ranch_transport - behaviour for transport modules - Description The ranch_transport behaviour defines the interface used by Ranch transports. - Types sendfile_opts() = [{chunk_size, non_neg_integer()}] Options used by the sendfile function and callbacks. - Allows configuring the chunk size, in bytes. Defaults to 8191 bytes. - Callbacks accept(LSocket, Timeout) &#8594; {ok, CSocket} | {error, closed | timeout | atom()} LSocket = CSocket = any() Listening socket. +Description The ranch_transport behaviour defines the interface used by Ranch transports. +Types sendfile_opts() = [{chunk_size, non_neg_integer()}] Options used by the sendfile function and callbacks. +Allows configuring the chunk size, in bytes. Defaults to 8191 bytes. +Callbacks accept(LSocket, Timeout) -&gt; {ok, CSocket} | {error, closed | timeout | atom()} LSocket = CSocket = any() Listening socket. + Timeout = timeout() Accept timeout. + Accept a connection on the given listening socket. @@ -6880,10 +7323,12 @@ https://ninenines.eu/docs/en/ranch/1.3/manual/ranch_transport/ Name ranch_transport - behaviour for transport modules - Description The ranch_transport behaviour defines the interface used by Ranch transports. - Types sendfile_opts() = [{chunk_size, non_neg_integer()}] Options used by the sendfile function and callbacks. - Allows configuring the chunk size, in bytes. Defaults to 8191 bytes. - Callbacks accept(LSocket, Timeout) &#8594; {ok, CSocket} | {error, closed | timeout | atom()} LSocket = CSocket = any() Listening socket. +Description The ranch_transport behaviour defines the interface used by Ranch transports. +Types sendfile_opts() = [{chunk_size, non_neg_integer()}] Options used by the sendfile function and callbacks. +Allows configuring the chunk size, in bytes. Defaults to 8191 bytes. +Callbacks accept(LSocket, Timeout) -&gt; {ok, CSocket} | {error, closed | timeout | atom()} LSocket = CSocket = any() Listening socket. + Timeout = timeout() Accept timeout. + Accept a connection on the given listening socket. @@ -6893,10 +7338,27 @@ https://ninenines.eu/docs/en/ranch/1.4/manual/ranch_transport/ Name ranch_transport - behaviour for transport modules - Description The ranch_transport behaviour defines the interface used by Ranch transports. - Types sendfile_opts() = [{chunk_size, non_neg_integer()}] Options used by the sendfile function and callbacks. - Allows configuring the chunk size, in bytes. Defaults to 8191 bytes. - Callbacks accept(LSocket, Timeout) &#8594; {ok, CSocket} | {error, closed | timeout | atom()} LSocket = CSocket = any() Listening socket. +Description The ranch_transport behaviour defines the interface used by Ranch transports. +Types sendfile_opts() = [{chunk_size, non_neg_integer()}] Options used by the sendfile function and callbacks. +Allows configuring the chunk size, in bytes. Defaults to 8191 bytes. +Callbacks accept(LSocket, Timeout) -&gt; {ok, CSocket} | {error, closed | timeout | atom()} LSocket = CSocket = any() Listening socket. + Timeout = timeout() Accept timeout. + Accept a connection on the given listening socket. + + + + ranch_transport(3) + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_transport/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_transport/ + Name ranch_transport - behaviour for transport modules +Description The ranch_transport behaviour defines the interface used by Ranch transports. +Types sendfile_opts() = [{chunk_size, non_neg_integer()}] Options used by the sendfile function and callbacks. +Allows configuring the chunk size, in bytes. Defaults to 8191 bytes. +Callbacks accept(LSocket, Timeout) -&gt; {ok, CSocket} | {error, closed | timeout | atom()} LSocket = CSocket = any() Listening socket. + Timeout = timeout() Accept timeout. + Accept a connection on the given listening socket. diff --git a/donate/index.html b/donate/index.html index 92004639..3ced6f38 100644 --- a/donate/index.html +++ b/donate/index.html @@ -62,10 +62,8 @@

    Services

    -
    -

    Like my work? Donate!

    -

    Donate to Loïc Hoguin because his work on Cowboy -and Erlang.mk is fantastic:

    +

    Like my work? Donate!

    +

    Donate to Loïc Hoguin because his work on Cowboy and Erlang.mk is fantastic:

    @@ -77,7 +75,6 @@ and Erlang.mk is fantastic:

    - @@ -518,10 +515,24 @@ and Erlang.mk is fantastic:

    -
    -

    Like my work? Donate!

    -

    Donate to Loïc Hoguin because his work on Cowboy -and Erlang.mk is fantastic:

    + + + + + + + + + + + + + + + + +

    Like my work? Donate!

    +

    Donate to Loïc Hoguin because his work on Cowboy and Erlang.mk is fantastic:

    @@ -533,7 +544,22 @@ and Erlang.mk is fantastic:

    - + + + + + + + + + + + + + + + + diff --git a/index.html b/index.html index 0f8c1d9c..56e2c701 100644 --- a/index.html +++ b/index.html @@ -219,10 +219,10 @@ Source Code - User Guide + User Guide - Manual + Manual

    @@ -237,7 +237,7 @@
    -
    +
    @@ -678,9 +678,24 @@ -

    Feeling generous? Love reading?
    -Crowdfund my salary -or buy The Erlanger Playbook

    + + + + + + + + + + + + + + + + +

    Feeling generous? Love reading?
    Crowdfund my salary or buy The Erlanger Playbook

    + @@ -1514,7 +1529,23 @@ or buy The Erlanger Playbook

    -
    + + + + + + + + + + + + + + + + +
    diff --git a/index.xml b/index.xml index 5fb53320..2250e51e 100644 --- a/index.xml +++ b/index.xml @@ -18,8 +18,9 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/installation/ On Unix Erlang.mk requires GNU Make to be installed. While it will currently work with GNU Make 3.81, support for this version is deprecated and will be removed in 2017. We recommend GNU Make 4.1 or later. - Git and Erlang/OTP must also be installed. - Some functionality requires that Autoconf 2.59 or later be installed, in order to compile Erlang/OTP. Erlang/OTP may have further requirements depending on your needs. +Git and Erlang/OTP must also be installed. +Some functionality requires that Autoconf 2.59 or later be installed, in order to compile Erlang/OTP. Erlang/OTP may have further requirements depending on your needs. +Some packages may require additional libraries. @@ -29,11 +30,12 @@ https://ninenines.eu/docs/en/gun/1.0/guide/introduction/ Gun is an HTTP client for Erlang/OTP. - Gun supports the HTTP/2, HTTP/1.1 and Websocket protocols. - Prerequisites Knowledge of Erlang, but also of the HTTP/1.1, HTTP/2 and Websocket protocols is required in order to read this guide. - Supported platforms Gun is tested and supported on Linux, FreeBSD, Windows and OSX. - Gun is developed for Erlang/OTP 19.0 and newer. - License Gun uses the ISC License. +Gun supports the HTTP/2, HTTP/1.1 and Websocket protocols. +Prerequisites Knowledge of Erlang, but also of the HTTP/1.1, HTTP/2 and Websocket protocols is required in order to read this guide. +Supported platforms Gun is tested and supported on Linux, FreeBSD, Windows and OSX. +Gun is developed for Erlang/OTP 19.0 and newer. +License Gun uses the ISC License. +Copyright (c) 2013-2018, Loïc Hoguin &lt;essen@ninenines.eu&gt; Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. @@ -43,9 +45,9 @@ https://ninenines.eu/docs/en/ranch/1.2/guide/introduction/ Ranch is a socket acceptor pool for TCP protocols. - Ranch aims to provide everything you need to accept TCP connections with a small code base and low latency while being easy to use directly as an application or to embed into your own. - Prerequisites It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols. - Supported platforms Ranch is tested and supported on Linux. +Ranch aims to provide everything you need to accept TCP connections with a small code base and low latency while being easy to use directly as an application or to embed into your own. +Prerequisites It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols. +Supported platforms Ranch is tested and supported on Linux. @@ -55,9 +57,9 @@ https://ninenines.eu/docs/en/ranch/1.3/guide/introduction/ Ranch is a socket acceptor pool for TCP protocols. - Ranch aims to provide everything you need to accept TCP connections with a small code base and low latency while being easy to use directly as an application or to embed into your own. - Prerequisites It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols. - Supported platforms Ranch is tested and supported on Linux, FreeBSD, OSX and Windows. +Ranch aims to provide everything you need to accept TCP connections with a small code base and low latency while being easy to use directly as an application or to embed into your own. +Prerequisites It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols. +Supported platforms Ranch is tested and supported on Linux, FreeBSD, OSX and Windows. @@ -67,9 +69,21 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/introduction/ Ranch is a socket acceptor pool for TCP protocols. - Ranch aims to provide everything you need to accept TCP connections with a small code base and low latency while being easy to use directly as an application or to embed into your own. - Prerequisites It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols. - Supported platforms Ranch is tested and supported on Linux, FreeBSD, OSX and Windows. +Ranch aims to provide everything you need to accept TCP connections with a small code base and low latency while being easy to use directly as an application or to embed into your own. +Prerequisites It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols. +Supported platforms Ranch is tested and supported on Linux, FreeBSD, OSX and Windows. + + + + Introduction + https://ninenines.eu/docs/en/ranch/1.5/guide/introduction/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/guide/introduction/ + Ranch is a socket acceptor pool for TCP protocols. +Ranch aims to provide everything you need to accept TCP connections with a small code base and low latency while being easy to use directly as an application or to embed into your own. +Prerequisites It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols. +Supported platforms Ranch is tested and supported on Linux, FreeBSD, OSX and Windows. @@ -79,8 +93,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/modern_web/ Cowboy is a server for the modern Web. This chapter explains what it means and details all the standards involved. - Cowboy supports all the standards listed in this document. - HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. +Cowboy supports all the standards listed in this document. +HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. The protocol is binary, greatly reducing the resources needed to parse it. @@ -90,8 +104,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/modern_web/ Cowboy is a server for the modern Web. This chapter explains what it means and details all the standards involved. - Cowboy supports all the standards listed in this document. - HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. +Cowboy supports all the standards listed in this document. +HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. The protocol is binary, greatly reducing the resources needed to parse it. @@ -101,8 +115,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/modern_web/ Cowboy is a server for the modern Web. This chapter explains what it means and details all the standards involved. - Cowboy supports all the standards listed in this document. - HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. +Cowboy supports all the standards listed in this document. +HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. The protocol is binary, greatly reducing the resources needed to parse it. @@ -112,8 +126,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/modern_web/ Cowboy is a server for the modern Web. This chapter explains what it means and details all the standards involved. - Cowboy supports all the standards listed in this document. - HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. +Cowboy supports all the standards listed in this document. +HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. The protocol is binary, greatly reducing the resources needed to parse it. @@ -123,8 +137,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/modern_web/ Cowboy is a server for the modern Web. This chapter explains what it means and details all the standards involved. - Cowboy supports all the standards listed in this document. - HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. +Cowboy supports all the standards listed in this document. +HTTP/2 HTTP/2 is the most efficient protocol for consuming Web services. It enables clients to keep a connection open for long periods of time; to send requests concurrently; to reduce the size of requests through HTTP headers compression; and more. The protocol is binary, greatly reducing the resources needed to parse it. @@ -134,7 +148,7 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/erlang_web/ Erlang is the ideal platform for writing Web applications. Its features are a perfect match for the requirements of modern Web applications. - The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. +The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. @@ -144,7 +158,7 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/erlang_web/ Erlang is the ideal platform for writing Web applications. Its features are a perfect match for the requirements of modern Web applications. - The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. +The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. @@ -154,7 +168,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/erlang_web/ Erlang is the ideal platform for writing Web applications. Its features are a perfect match for the requirements of modern Web applications. - The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. +The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. @@ -164,7 +178,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/erlang_web/ Erlang is the ideal platform for writing Web applications. Its features are a perfect match for the requirements of modern Web applications. - The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. +The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. @@ -174,7 +188,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/erlang_web/ Erlang is the ideal platform for writing Web applications. Its features are a perfect match for the requirements of modern Web applications. - The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. +The Web is concurrent When you access a website there is little concurrency involved. A few connections are opened and requests are sent through these connections. Then the web page is displayed on your screen. Your browser will only open up to 4 or 8 connections to the server, depending on your settings. @@ -184,8 +198,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/getting_started/ This chapter explains how to get started using Erlang.mk. - Creating a folder for your project The first step is always to create a new folder that will contain your project. - $ mkdir hello_joe $ cd hello_joe Most people tend to put all their projects side by side in a common folder. We recommend keeping an organization similar to your remote repositories. For example, for GitHub users, put all your projects in a common folder with the same name as your username. +Creating a folder for your project The first step is always to create a new folder that will contain your project. +$ mkdir hello_joe $ cd hello_joe Most people tend to put all their projects side by side in a common folder. We recommend keeping an organization similar to your remote repositories. For example, for GitHub users, put all your projects in a common folder with the same name as your username. @@ -195,7 +209,7 @@ https://ninenines.eu/docs/en/ranch/1.2/guide/listeners/ A listener is a set of processes whose role is to listen on a port for new connections. It manages a pool of acceptor processes, each of them indefinitely accepting connections. When it does, it starts a new process executing the protocol handler code. All the socket programming is abstracted through the user of transport handlers. - The listener takes care of supervising all the acceptor and connection processes, allowing developers to focus on building their application. +The listener takes care of supervising all the acceptor and connection processes, allowing developers to focus on building their application. @@ -205,7 +219,7 @@ https://ninenines.eu/docs/en/ranch/1.3/guide/listeners/ A listener is a set of processes whose role is to listen on a port for new connections. It manages a pool of acceptor processes, each of them indefinitely accepting connections. When it does, it starts a new process executing the protocol handler code. All the socket programming is abstracted through the use of transport handlers. - The listener takes care of supervising all the acceptor and connection processes, allowing developers to focus on building their application. +The listener takes care of supervising all the acceptor and connection processes, allowing developers to focus on building their application. @@ -215,7 +229,17 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/listeners/ A listener is a set of processes whose role is to listen on a port for new connections. It manages a pool of acceptor processes, each of them indefinitely accepting connections. When it does, it starts a new process executing the protocol handler code. All the socket programming is abstracted through the use of transport handlers. - The listener takes care of supervising all the acceptor and connection processes, allowing developers to focus on building their application. +The listener takes care of supervising all the acceptor and connection processes, allowing developers to focus on building their application. + + + + Listeners + https://ninenines.eu/docs/en/ranch/1.5/guide/listeners/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/guide/listeners/ + A listener is a set of processes whose role is to listen on a port for new connections. It manages a pool of acceptor processes, each of them indefinitely accepting connections. When it does, it starts a new process executing the protocol handler code. All the socket programming is abstracted through the use of transport handlers. +The listener takes care of supervising all the acceptor and connection processes, allowing developers to focus on building their application. @@ -225,9 +249,10 @@ https://ninenines.eu/docs/en/gun/1.0/guide/start/ This chapter describes how to start and stop the Gun application. - Setting up Specify Gun as a dependency to your application in your favorite build tool. - With Erlang.mk this is done by adding gun to the DEPS variable in your Makefile. - Adding Gun as an Erlang.mk dependency DEPS = gun Starting Gun is an OTP application. It needs to be started before you can use it. +Setting up Specify Gun as a dependency to your application in your favorite build tool. +With Erlang.mk this is done by adding gun to the DEPS variable in your Makefile. +Adding Gun as an Erlang.mk dependency DEPS = gun Starting Gun is an OTP application. It needs to be started before you can use it. +Starting Gun in an Erlang shell 1&gt; application:ensure_all_started(gun). @@ -237,9 +262,9 @@ https://ninenines.eu/docs/en/gun/1.0/guide/protocols/ This chapter describes the protocols supported and the operations available to them. - HTTP/1.1 HTTP/1.1 is a text request-response protocol. The client sends a request, the server sends back a response. - Gun provides convenience functions for performing GET, HEAD, OPTIONS, POST, PATCH, PUT, and DELETE requests. All these functions are aliases of gun:request/4,5,6 for the respective methods. Gun also provides a gun:data/4 function for streaming the request body. - Gun will send a gun_inform message for every intermediate informational responses received. +HTTP/1.1 HTTP/1.1 is a text request-response protocol. The client sends a request, the server sends back a response. +Gun provides convenience functions for performing GET, HEAD, OPTIONS, POST, PATCH, PUT, and DELETE requests. All these functions are aliases of gun:request/4,5,6 for the respective methods. Gun also provides a gun:data/4 function for streaming the request body. +Gun will send a gun_inform message for every intermediate informational responses received. @@ -249,9 +274,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/introduction/ Cowboy is a small, fast and modern HTTP server for Erlang/OTP. - Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. - Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. - Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. +Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. +Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. +Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. @@ -261,9 +286,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/introduction/ Cowboy is a small, fast and modern HTTP server for Erlang/OTP. - Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. - Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. - Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. +Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. +Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. +Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. @@ -273,9 +298,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/introduction/ Cowboy is a small, fast and modern HTTP server for Erlang/OTP. - Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. - Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. - Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. +Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. +Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. +Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. @@ -285,9 +310,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/introduction/ Cowboy is a small, fast and modern HTTP server for Erlang/OTP. - Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. - Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. - Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. +Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. +Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. +Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. @@ -297,9 +322,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/introduction/ Cowboy is a small, fast and modern HTTP server for Erlang/OTP. - Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. - Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. - Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. +Cowboy aims to provide a complete modern Web stack. This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and Webmachine-based REST. +Cowboy comes with functions for introspection and tracing, enabling developers to know precisely what is happening at any time. Its modular design also easily enable developers to add instrumentation. +Cowboy is a high quality project. It has a small code base, is very efficient (both in latency and memory use) and can easily be embedded in another application. @@ -309,9 +334,9 @@ https://ninenines.eu/docs/en/ranch/1.2/guide/transports/ A transport defines the interface to interact with a socket. - Transports can be used for connecting, listening and accepting connections, but also for receiving and sending data. Both passive and active mode are supported, although all sockets are initialized as passive. - TCP transport The TCP transport is a thin wrapper around gen_tcp. - SSL transport The SSL transport is a thin wrapper around ssl. It requires the crypto, asn1, public_key and ssl applications to be started. +Transports can be used for connecting, listening and accepting connections, but also for receiving and sending data. Both passive and active mode are supported, although all sockets are initialized as passive. +TCP transport The TCP transport is a thin wrapper around gen_tcp. +SSL transport The SSL transport is a thin wrapper around ssl. It requires the crypto, asn1, public_key and ssl applications to be started. @@ -321,10 +346,10 @@ https://ninenines.eu/docs/en/ranch/1.3/guide/transports/ A transport defines the interface to interact with a socket. - Transports can be used for connecting, listening and accepting connections, but also for receiving and sending data. Both passive and active mode are supported, although all sockets are initialized as passive. - TCP transport The TCP transport is a thin wrapper around gen_tcp. - SSL transport The SSL transport is a thin wrapper around ssl. - Ranch depends on ssl by default so any necessary dependencies will start when Ranch is started. +Transports can be used for connecting, listening and accepting connections, but also for receiving and sending data. Both passive and active mode are supported, although all sockets are initialized as passive. +TCP transport The TCP transport is a thin wrapper around gen_tcp. +SSL transport The SSL transport is a thin wrapper around ssl. +Ranch depends on ssl by default so any necessary dependencies will start when Ranch is started. @@ -334,10 +359,23 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/transports/ A transport defines the interface to interact with a socket. - Transports can be used for connecting, listening and accepting connections, but also for receiving and sending data. Both passive and active mode are supported, although all sockets are initialized as passive. - TCP transport The TCP transport is a thin wrapper around gen_tcp. - SSL transport The SSL transport is a thin wrapper around ssl. - Ranch depends on ssl by default so any necessary dependencies will start when Ranch is started. +Transports can be used for connecting, listening and accepting connections, but also for receiving and sending data. Both passive and active mode are supported, although all sockets are initialized as passive. +TCP transport The TCP transport is a thin wrapper around gen_tcp. +SSL transport The SSL transport is a thin wrapper around ssl. +Ranch depends on ssl by default so any necessary dependencies will start when Ranch is started. + + + + Transports + https://ninenines.eu/docs/en/ranch/1.5/guide/transports/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/guide/transports/ + A transport defines the interface to interact with a socket. +Transports can be used for connecting, listening and accepting connections, but also for receiving and sending data. Both passive and active mode are supported, although all sockets are initialized as passive. +TCP transport The TCP transport is a thin wrapper around gen_tcp. +SSL transport The SSL transport is a thin wrapper around ssl. +Ranch depends on ssl by default so any necessary dependencies will start when Ranch is started. @@ -346,9 +384,9 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/erlang.mk/1/guide/overview/ - Now that you know how to get started, let&#8217;s take a look at what Erlang.mk can do for you. - Building your project Erlang.mk is first and foremost a build tool. It is especially tailored for Erlang developers and follows widely accepted practices in the Erlang community. - Erlang.mk will happily build all Erlang-specific files you throw at it. Other kinds of files too, like C or C++ code when you are working on a NIF or a port driver. + Now that you know how to get started, let&apos;s take a look at what Erlang.mk can do for you. +Building your project Erlang.mk is first and foremost a build tool. It is especially tailored for Erlang developers and follows widely accepted practices in the Erlang community. +Erlang.mk will happily build all Erlang-specific files you throw at it. Other kinds of files too, like C or C++ code when you are working on a NIF or a port driver. @@ -358,8 +396,8 @@ https://ninenines.eu/docs/en/gun/1.0/guide/connect/ This chapter describes how to open, monitor and close a connection using the Gun client. - Gun connections Gun is designed with the HTTP/2 and Websocket protocols in mind. They are built for long-running connections that allow concurrent exchange of data, either in the form of request/responses for HTTP/2 or in the form of messages for Websocket. - A Gun connection is an Erlang process that manages a socket to a remote endpoint. +Gun connections Gun is designed with the HTTP/2 and Websocket protocols in mind. They are built for long-running connections that allow concurrent exchange of data, either in the form of request/responses for HTTP/2 or in the form of messages for Websocket. +A Gun connection is an Erlang process that manages a socket to a remote endpoint. @@ -369,7 +407,7 @@ https://ninenines.eu/docs/en/ranch/1.2/guide/protocols/ A protocol handler starts a connection process and defines the protocol logic executed in this process. - Writing a protocol handler All protocol handlers must implement the ranch_protocol behavior which defines a single callback, start_link/4. This callback is responsible for spawning a new process for handling the connection. It receives four arguments: the name of the listener, the socket, the transport handler being used and the protocol options defined in the call to ranch:start_listener/6. +Writing a protocol handler All protocol handlers must implement the ranch_protocol behavior which defines a single callback, start_link/4. This callback is responsible for spawning a new process for handling the connection. It receives four arguments: the name of the listener, the socket, the transport handler being used and the protocol options defined in the call to ranch:start_listener/6. @@ -379,7 +417,7 @@ https://ninenines.eu/docs/en/ranch/1.3/guide/protocols/ A protocol handler starts a connection process and defines the protocol logic executed in this process. - Writing a protocol handler All protocol handlers must implement the ranch_protocol behavior which defines a single callback, start_link/4. This callback is responsible for spawning a new process for handling the connection. It receives four arguments: the name of the listener, the socket, the transport handler being used and the protocol options defined in the call to ranch:start_listener/6. +Writing a protocol handler All protocol handlers must implement the ranch_protocol behavior which defines a single callback, start_link/4. This callback is responsible for spawning a new process for handling the connection. It receives four arguments: the name of the listener, the socket, the transport handler being used and the protocol options defined in the call to ranch:start_listener/6. @@ -389,7 +427,17 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/protocols/ A protocol handler starts a connection process and defines the protocol logic executed in this process. - Writing a protocol handler All protocol handlers must implement the ranch_protocol behavior which defines a single callback, start_link/4. This callback is responsible for spawning a new process for handling the connection. It receives four arguments: the name of the listener, the socket, the transport handler being used and the protocol options defined in the call to ranch:start_listener/5. +Writing a protocol handler All protocol handlers must implement the ranch_protocol behavior which defines a single callback, start_link/4. This callback is responsible for spawning a new process for handling the connection. It receives four arguments: the name of the listener, the socket, the transport handler being used and the protocol options defined in the call to ranch:start_listener/5. + + + + Protocols + https://ninenines.eu/docs/en/ranch/1.5/guide/protocols/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/guide/protocols/ + A protocol handler starts a connection process and defines the protocol logic executed in this process. +Writing a protocol handler All protocol handlers must implement the ranch_protocol behavior which defines a single callback, start_link/4. This callback is responsible for spawning a new process for handling the connection. It receives four arguments: the name of the listener, the socket, the transport handler being used and the protocol options defined in the call to ranch:start_listener/5. @@ -399,7 +447,7 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/getting_started/ Erlang is more than a language, it is also an operating system for your applications. Erlang developers rarely write standalone modules, they write libraries or applications, and then bundle those into what is called a release. A release contains the Erlang VM plus all applications required to run the node, so it can be pushed to production directly. - This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. +This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. @@ -409,7 +457,7 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/getting_started/ Erlang is more than a language, it is also an operating system for your applications. Erlang developers rarely write standalone modules, they write libraries or applications, and then bundle those into what is called a release. A release contains the Erlang VM plus all applications required to run the node, so it can be pushed to production directly. - This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. +This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. @@ -419,7 +467,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/getting_started/ Erlang is more than a language, it is also an operating system for your applications. Erlang developers rarely write standalone modules, they write libraries or applications, and then bundle those into what is called a release. A release contains the Erlang VM plus all applications required to run the node, so it can be pushed to production directly. - This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. +This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. @@ -429,7 +477,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/getting_started/ Erlang is more than a language, it is also an operating system for your applications. Erlang developers rarely write standalone modules, they write libraries or applications, and then bundle those into what is called a release. A release contains the Erlang VM plus all applications required to run the node, so it can be pushed to production directly. - This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. +This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. @@ -439,7 +487,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/getting_started/ Erlang is more than a language, it is also an operating system for your applications. Erlang developers rarely write standalone modules, they write libraries or applications, and then bundle those into what is called a release. A release contains the Erlang VM plus all applications required to run the node, so it can be pushed to production directly. - This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. +This chapter walks you through all the steps of setting up Cowboy, writing your first application and generating your first release. @@ -449,8 +497,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/updating/ This chapter describes how to update the erlang.mk file in your repository. - Initial bootstrap The first time you use Erlang.mk, it will bootstrap itself. It always uses the most recent version for this, so you don&#8217;t have to update after creating your project. - Updating Later on though, updating becomes a necessity. Erlang.mk developers and contributors relentlessly improve the project and add new features; it would be a waste not to benefit from this. +Initial bootstrap The first time you use Erlang.mk, it will bootstrap itself. It always uses the most recent version for this, so you don&apos;t have to update after creating your project. +Updating Later on though, updating becomes a necessity. Erlang.mk developers and contributors relentlessly improve the project and add new features; it would be a waste not to benefit from this. @@ -460,9 +508,9 @@ https://ninenines.eu/docs/en/gun/1.0/guide/http/ This chapter describes how to use the Gun client for communicating with an HTTP/1.1 or HTTP/2 server. - Streams Every time a request is initiated, Gun creates a stream. A stream reference uniquely identifies a set of request and response and must be used to perform additional operations with a stream or to identify its messages. - Stream references use the Erlang reference data type and are therefore unique. - Streams can be canceled at any time. +Streams Every time a request is initiated, Gun creates a stream. A stream reference uniquely identifies a set of request and response and must be used to perform additional operations with a stream or to identify its messages. +Stream references use the Erlang reference data type and are therefore unique. +Streams can be canceled at any time. @@ -472,7 +520,7 @@ https://ninenines.eu/docs/en/ranch/1.2/guide/embedded/ Embedded mode allows you to insert Ranch listeners directly in your supervision tree. This allows for greater fault tolerance control by permitting the shutdown of a listener due to the failure of another part of the application and vice versa. - Embedding To embed Ranch in your application you can simply add the child specs to your supervision tree. This can all be done in the init/1 function of one of your application supervisors. +Embedding To embed Ranch in your application you can simply add the child specs to your supervision tree. This can all be done in the init/1 function of one of your application supervisors. @@ -482,7 +530,7 @@ https://ninenines.eu/docs/en/ranch/1.3/guide/embedded/ Embedded mode allows you to insert Ranch listeners directly in your supervision tree. This allows for greater fault tolerance control by permitting the shutdown of a listener due to the failure of another part of the application and vice versa. - Embedding To embed Ranch in your application you can simply add the child specs to your supervision tree. This can all be done in the init/1 function of one of your application supervisors. +Embedding To embed Ranch in your application you can simply add the child specs to your supervision tree. This can all be done in the init/1 function of one of your application supervisors. @@ -492,7 +540,17 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/embedded/ Embedded mode allows you to insert Ranch listeners directly in your supervision tree. This allows for greater fault tolerance control by permitting the shutdown of a listener due to the failure of another part of the application and vice versa. - Embedding To embed Ranch in your application you can simply add the child specs to your supervision tree. This can all be done in the init/1 function of one of your application supervisors. +Embedding To embed Ranch in your application you can simply add the child specs to your supervision tree. This can all be done in the init/1 function of one of your application supervisors. + + + + Embedded mode + https://ninenines.eu/docs/en/ranch/1.5/guide/embedded/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/guide/embedded/ + Embedded mode allows you to insert Ranch listeners directly in your supervision tree. This allows for greater fault tolerance control by permitting the shutdown of a listener due to the failure of another part of the application and vice versa. +Embedding To embed Ranch in your application you can simply add the child specs to your supervision tree. This can all be done in the init/1 function of one of your application supervisors. @@ -502,9 +560,10 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/limitations/ No software is perfect. - It&#8217;s very important, when evaluating and when using a tool, to understand its limitations, so as to avoid making mistakes and wasting valuable time. - This chapter lists all known limitations of Erlang.mk. - Erlang must be available Currently Erlang.mk requires you to install Erlang beforehand. Installing Erlang is not always easy, particularly if you need a specific version of Erlang for a specific project. +It&apos;s very important, when evaluating and when using a tool, to understand its limitations, so as to avoid making mistakes and wasting valuable time. +This chapter lists all known limitations of Erlang.mk. +Erlang must be available Currently Erlang.mk requires you to install Erlang beforehand. Installing Erlang is not always easy, particularly if you need a specific version of Erlang for a specific project. +In addition, the Erlang being used must be in your $PATH before you use Erlang. @@ -514,8 +573,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/flow_diagram/ Cowboy is a lightweight HTTP server with support for HTTP/1.1, HTTP/2 and Websocket. - It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. - Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. +Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +After Ranch accepts a new connection, whether it is an HTTP/1. @@ -525,8 +585,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/flow_diagram/ Cowboy is a lightweight HTTP server with support for HTTP/1.1, HTTP/2 and Websocket. - It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. - Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. +Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +After Ranch accepts a new connection, whether it is an HTTP/1. @@ -536,8 +597,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/flow_diagram/ Cowboy is a lightweight HTTP server with support for HTTP/1.1, HTTP/2 and Websocket. - It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. - Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. +Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +After Ranch accepts a new connection, whether it is an HTTP/1. @@ -547,8 +609,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/flow_diagram/ Cowboy is a lightweight HTTP server with support for HTTP/1.1, HTTP/2 and Websocket. - It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. - Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. +Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +After Ranch accepts a new connection, whether it is an HTTP/1. @@ -558,8 +621,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/flow_diagram/ Cowboy is a lightweight HTTP server with support for HTTP/1.1, HTTP/2 and Websocket. - It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. - Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +It is built on top of Ranch. Please see the Ranch guide for more information about how the network connections are handled. +Overview As you can see on the diagram, the client begins by connecting to the server. This step is handled by a Ranch acceptor, which is a process dedicated to accepting new connections. +After Ranch accepts a new connection, whether it is an HTTP/1. @@ -569,8 +633,8 @@ https://ninenines.eu/docs/en/gun/1.0/guide/websocket/ This chapter describes how to use the Gun client for communicating with a Websocket server. - HTTP upgrade Websocket is a protocol built on top of HTTP. To use Websocket, you must first request for the connection to be upgraded. Only HTTP/1.1 connections can be upgraded to Websocket, so you might need to restrict the protocol to HTTP/1.1 if you are planning to use Websocket over TLS. - You must use the gun:ws_upgrade/2,3,4 function to upgrade to Websocket. +HTTP upgrade Websocket is a protocol built on top of HTTP. To use Websocket, you must first request for the connection to be upgraded. Only HTTP/1.1 connections can be upgraded to Websocket, so you might need to restrict the protocol to HTTP/1.1 if you are planning to use Websocket over TLS. +You must use the gun:ws_upgrade/2,3,4 function to upgrade to Websocket. @@ -580,8 +644,8 @@ https://ninenines.eu/docs/en/ranch/1.2/guide/parsers/ There are three kinds of protocols: - Text protocols Schema-less binary protocols Schema-based binary protocols This chapter introduces the first two kinds. It will not cover more advanced topics such as continuations or parser generators. - This chapter isn&#8217;t specifically about Ranch, we assume here that you know how to read data from the socket. The data you read and the data that hasn&#8217;t been parsed is saved in a buffer. +Text protocols Schema-less binary protocols Schema-based binary protocols This chapter introduces the first two kinds. It will not cover more advanced topics such as continuations or parser generators. +This chapter isn&apos;t specifically about Ranch, we assume here that you know how to read data from the socket. The data you read and the data that hasn&apos;t been parsed is saved in a buffer. @@ -591,8 +655,8 @@ https://ninenines.eu/docs/en/ranch/1.3/guide/parsers/ There are three kinds of protocols: - Text protocols Schema-less binary protocols Schema-based binary protocols This chapter introduces the first two kinds. It will not cover more advanced topics such as continuations or parser generators. - This chapter isn&#8217;t specifically about Ranch, we assume here that you know how to read data from the socket. The data you read and the data that hasn&#8217;t been parsed is saved in a buffer. +Text protocols Schema-less binary protocols Schema-based binary protocols This chapter introduces the first two kinds. It will not cover more advanced topics such as continuations or parser generators. +This chapter isn&apos;t specifically about Ranch, we assume here that you know how to read data from the socket. The data you read and the data that hasn&apos;t been parsed is saved in a buffer. @@ -602,8 +666,19 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/parsers/ There are three kinds of protocols: - Text protocols Schema-less binary protocols Schema-based binary protocols This chapter introduces the first two kinds. It will not cover more advanced topics such as continuations or parser generators. - This chapter isn&#8217;t specifically about Ranch, we assume here that you know how to read data from the socket. The data you read and the data that hasn&#8217;t been parsed is saved in a buffer. +Text protocols Schema-less binary protocols Schema-based binary protocols This chapter introduces the first two kinds. It will not cover more advanced topics such as continuations or parser generators. +This chapter isn&apos;t specifically about Ranch, we assume here that you know how to read data from the socket. The data you read and the data that hasn&apos;t been parsed is saved in a buffer. + + + + Writing parsers + https://ninenines.eu/docs/en/ranch/1.5/guide/parsers/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/guide/parsers/ + There are three kinds of protocols: +Text protocols Schema-less binary protocols Schema-based binary protocols This chapter introduces the first two kinds. It will not cover more advanced topics such as continuations or parser generators. +This chapter isn&apos;t specifically about Ranch, we assume here that you know how to read data from the socket. The data you read and the data that hasn&apos;t been parsed is saved in a buffer. @@ -613,9 +688,9 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/app/ Erlang.mk can do a lot of things, but it is, first and foremost, a build tool. In this chapter we will cover the basics of building a project with Erlang.mk. - For most of this chapter, we will assume that you are using a project generated by Erlang.mk. - How to build To build a project, all you have to do is type make: - $ make It will work regardless of your project: OTP applications, library applications, NIFs, port drivers or even releases. +For most of this chapter, we will assume that you are using a project generated by Erlang.mk. +How to build To build a project, all you have to do is type make: +$ make It will work regardless of your project: OTP applications, library applications, NIFs, port drivers or even releases. @@ -625,8 +700,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/listeners/ A listener is a set of processes that listens on a port for new connections. Incoming connections get handled by Cowboy. Depending on the connection handshake, one or another protocol may be used. - This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. - Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. +This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. +Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. Both of them support the HTTP/1. @@ -636,8 +711,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/listeners/ A listener is a set of processes that listens on a port for new connections. Incoming connections get handled by Cowboy. Depending on the connection handshake, one or another protocol may be used. - This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. - Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. +This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. +Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. Both of them support the HTTP/1. @@ -647,8 +722,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/listeners/ A listener is a set of processes that listens on a port for new connections. Incoming connections get handled by Cowboy. Depending on the connection handshake, one or another protocol may be used. - This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. - Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. +This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. +Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. Both of them support the HTTP/1. @@ -658,8 +733,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/listeners/ A listener is a set of processes that listens on a port for new connections. Incoming connections get handled by Cowboy. Depending on the connection handshake, one or another protocol may be used. - This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. - Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. +This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. +Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. Both of them support the HTTP/1. @@ -669,8 +744,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/listeners/ A listener is a set of processes that listens on a port for new connections. Incoming connections get handled by Cowboy. Depending on the connection handshake, one or another protocol may be used. - This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. - Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. +This chapter is specific to Cowboy. Please refer to the Ranch User Guide for more information about listeners. +Cowboy provides two types of listeners: one listening for clear TCP connections, and one listening for secure TLS connections. Both of them support the HTTP/1. @@ -680,7 +755,7 @@ https://ninenines.eu/docs/en/ranch/1.2/guide/ssl_auth/ Purpose SSL client authentication is a mechanism allowing applications to identify certificates. This allows your application to make sure that the client is an authorized certificate, but makes no claim about whether the user can be trusted. This can be combined with a password based authentication to attain greater security. - The server only needs to retain the certificate serial number and the certificate issuer to authenticate the certificate. Together, they can be used to uniquely identify a certicate. +The server only needs to retain the certificate serial number and the certificate issuer to authenticate the certificate. Together, they can be used to uniquely identify a certicate. @@ -690,7 +765,7 @@ https://ninenines.eu/docs/en/ranch/1.3/guide/ssl_auth/ Purpose SSL client authentication is a mechanism allowing applications to identify certificates. This allows your application to make sure that the client is an authorized certificate, but makes no claim about whether the user can be trusted. This can be combined with a password based authentication to attain greater security. - The server only needs to retain the certificate serial number and the certificate issuer to authenticate the certificate. Together, they can be used to uniquely identify a certicate. +The server only needs to retain the certificate serial number and the certificate issuer to authenticate the certificate. Together, they can be used to uniquely identify a certicate. @@ -700,7 +775,17 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/ssl_auth/ Purpose SSL client authentication is a mechanism allowing applications to identify certificates. This allows your application to make sure that the client is an authorized certificate, but makes no claim about whether the user can be trusted. This can be combined with a password based authentication to attain greater security. - The server only needs to retain the certificate serial number and the certificate issuer to authenticate the certificate. Together, they can be used to uniquely identify a certicate. +The server only needs to retain the certificate serial number and the certificate issuer to authenticate the certificate. Together, they can be used to uniquely identify a certicate. + + + + SSL client authentication + https://ninenines.eu/docs/en/ranch/1.5/guide/ssl_auth/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/guide/ssl_auth/ + Purpose SSL client authentication is a mechanism allowing applications to identify certificates. This allows your application to make sure that the client is an authorized certificate, but makes no claim about whether the user can be trusted. This can be combined with a password based authentication to attain greater security. +The server only needs to retain the certificate serial number and the certificate issuer to authenticate the certificate. Together, they can be used to uniquely identify a certicate. @@ -710,8 +795,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/deps/ Erlang.mk can fetch and compile the dependencies that your project requires. Erlang.mk improves upon the concepts introduced by Rebar, so they should be familiar to many seasoned Erlang developers. - Erlang.mk is not a package manager, nor is it trying to be, but it does include an index of Erlang packages to make discovering useful projects easier. - This chapter will explain how to use packages, add dependencies to your project or bundle them directly in a single repository. +Erlang.mk is not a package manager, nor is it trying to be, but it does include an index of Erlang packages to make discovering useful projects easier. +This chapter will explain how to use packages, add dependencies to your project or bundle them directly in a single repository. @@ -721,9 +806,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/routing/ Cowboy does nothing by default. - To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. - When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&#8217;s a match, the route&#8217;s associated handler is executed. - Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. +To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. +When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&apos;s a match, the route&apos;s associated handler is executed. +Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. @@ -733,9 +818,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/routing/ Cowboy does nothing by default. - To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. - When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&#8217;s a match, the route&#8217;s associated handler is executed. - Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. +To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. +When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&apos;s a match, the route&apos;s associated handler is executed. +Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. @@ -745,9 +830,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/routing/ Cowboy does nothing by default. - To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. - When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&#8217;s a match, the route&#8217;s associated handler is executed. - Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. +To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. +When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&apos;s a match, the route&apos;s associated handler is executed. +Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. @@ -757,9 +842,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/routing/ Cowboy does nothing by default. - To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. - When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&#8217;s a match, the route&#8217;s associated handler is executed. - Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. +To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. +When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&apos;s a match, the route&apos;s associated handler is executed. +Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. @@ -769,9 +854,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/routing/ Cowboy does nothing by default. - To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. - When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&#8217;s a match, the route&#8217;s associated handler is executed. - Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. +To make Cowboy useful, you need to map URIs to Erlang modules that will handle the requests. This is called routing. +When Cowboy receives a request, it tries to match the requested host and path to the configured routes. When there&apos;s a match, the route&apos;s associated handler is executed. +Routes need to be compiled before they can be used by Cowboy. The result of the compilation is the dispatch rules. @@ -781,8 +866,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/ports/ Erlang.mk can not only build Erlang projects, but also the C code that some projects come with, like NIFs and port drivers. - There are two ways to build the C code: using a custom Makefile, or making Erlang.mk do it directly. The C code will be built as needed when you run make. - C source code location and Erlang environment The C source code should be located in the $(C_SRC_DIR) directory. +There are two ways to build the C code: using a custom Makefile, or making Erlang.mk do it directly. The C code will be built as needed when you run make. +C source code location and Erlang environment The C source code should be located in the $(C_SRC_DIR) directory. @@ -792,7 +877,7 @@ https://ninenines.eu/docs/en/ranch/1.2/guide/internals/ This chapter may not apply to embedded Ranch as embedding allows you to use an architecture specific to your application, which may or may not be compatible with the description of the Ranch application. - Note that for everything related to efficiency and performance, you should perform the benchmarks yourself to get the numbers that matter to you. Generic benchmarks found on the web may or may not be of use to you, you can never know until you benchmark your own system. +Note that for everything related to efficiency and performance, you should perform the benchmarks yourself to get the numbers that matter to you. Generic benchmarks found on the web may or may not be of use to you, you can never know until you benchmark your own system. @@ -802,7 +887,7 @@ https://ninenines.eu/docs/en/ranch/1.3/guide/internals/ This chapter may not apply to embedded Ranch as embedding allows you to use an architecture specific to your application, which may or may not be compatible with the description of the Ranch application. - Note that for everything related to efficiency and performance, you should perform the benchmarks yourself to get the numbers that matter to you. Generic benchmarks found on the web may or may not be of use to you, you can never know until you benchmark your own system. +Note that for everything related to efficiency and performance, you should perform the benchmarks yourself to get the numbers that matter to you. Generic benchmarks found on the web may or may not be of use to you, you can never know until you benchmark your own system. @@ -812,7 +897,17 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/internals/ This chapter may not apply to embedded Ranch as embedding allows you to use an architecture specific to your application, which may or may not be compatible with the description of the Ranch application. - Note that for everything related to efficiency and performance, you should perform the benchmarks yourself to get the numbers that matter to you. Generic benchmarks found on the web may or may not be of use to you, you can never know until you benchmark your own system. +Note that for everything related to efficiency and performance, you should perform the benchmarks yourself to get the numbers that matter to you. Generic benchmarks found on the web may or may not be of use to you, you can never know until you benchmark your own system. + + + + Internals + https://ninenines.eu/docs/en/ranch/1.5/guide/internals/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/guide/internals/ + This chapter may not apply to embedded Ranch as embedding allows you to use an architecture specific to your application, which may or may not be compatible with the description of the Ranch application. +Note that for everything related to efficiency and performance, you should perform the benchmarks yourself to get the numbers that matter to you. Generic benchmarks found on the web may or may not be of use to you, you can never know until you benchmark your own system. @@ -822,9 +917,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/constraints/ Constraints are validation and conversion functions applied to user input. - They are used in various places in Cowboy, including the router and the cowboy_req match functions. - Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. - A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. +They are used in various places in Cowboy, including the router and the cowboy_req match functions. +Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. +A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. @@ -834,9 +929,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/constraints/ Constraints are validation and conversion functions applied to user input. - They are used in various places in Cowboy, including the router and the cowboy_req match functions. - Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. - A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. +They are used in various places in Cowboy, including the router and the cowboy_req match functions. +Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. +A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. @@ -846,9 +941,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/constraints/ Constraints are validation and conversion functions applied to user input. - They are used in various places in Cowboy, including the router and the cowboy_req match functions. - Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. - A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. +They are used in various places in Cowboy, including the router and the cowboy_req match functions. +Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. +A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. @@ -858,9 +953,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/constraints/ Constraints are validation and conversion functions applied to user input. - They are used in various places in Cowboy, including the router and the cowboy_req match functions. - Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. - A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. +They are used in various places in Cowboy, including the router and the cowboy_req match functions. +Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. +A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. @@ -870,9 +965,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/constraints/ Constraints are validation and conversion functions applied to user input. - They are used in various places in Cowboy, including the router and the cowboy_req match functions. - Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. - A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. +They are used in various places in Cowboy, including the router and the cowboy_req match functions. +Syntax Constraints are provided as a list of fields. For each field in the list, specific constraints can be applied, as well as a default value if the field is missing. +A field can take the form of an atom field, a tuple with constraints {field, Constraints} or a tuple with constraints and a default value {field, Constraints, Default}. @@ -882,8 +977,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/releases/ Erlang.mk relies on Relx for generating releases. This chapter covers the Erlang.mk-specific bits. Consult the Relx website for more information. - Setup Erlang.mk will create a release if it detects a Relx configuration file in the $(RELX_CONFIG) location. This defaults to $(CURDIR)/relx.config. You can override it by defining the variable before including Erlang.mk: - RELX_CONFIG = $(CURDIR)/webchat.config Relx does not need to be installed. Erlang.mk will download and build it automatically. +Setup Erlang.mk will create a release if it detects a Relx configuration file in the $(RELX_CONFIG) location. This defaults to $(CURDIR)/relx.config. You can override it by defining the variable before including Erlang.mk: +RELX_CONFIG = $(CURDIR)/webchat.config Relx does not need to be installed. Erlang.mk will download and build it automatically. @@ -893,9 +988,9 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/sfx/ Erlang.mk allows you to package Relx releases as self-extracting archives. These archives contain all the files in the release and come in the form of a script that will extract and run the release automatically. - This allows you to package the release as a single file that can then be executed. - This feature is currently experimental. Feedback is much appreciated. - Generating the self-extracting archive To generate a self-extracting release, all you need to do is pass the SFX=1 variable to Make when you build the release: +This allows you to package the release as a single file that can then be executed. +This feature is currently experimental. Feedback is much appreciated. +Generating the self-extracting archive To generate a self-extracting release, all you need to do is pass the SFX=1 variable to Make when you build the release: @@ -905,10 +1000,10 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/handlers/ Handlers are Erlang modules that handle HTTP requests. - Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. - This callback receives the Req object and the initial state defined in the router configuration. - A handler that does nothing would look like this: - init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. +Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. +This callback receives the Req object and the initial state defined in the router configuration. +A handler that does nothing would look like this: +init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. @@ -918,10 +1013,10 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/handlers/ Handlers are Erlang modules that handle HTTP requests. - Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. - This callback receives the Req object and the initial state defined in the router configuration. - A handler that does nothing would look like this: - init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. +Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. +This callback receives the Req object and the initial state defined in the router configuration. +A handler that does nothing would look like this: +init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. @@ -931,10 +1026,10 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/handlers/ Handlers are Erlang modules that handle HTTP requests. - Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. - This callback receives the Req object and the initial state defined in the router configuration. - A handler that does nothing would look like this: - init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. +Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. +This callback receives the Req object and the initial state defined in the router configuration. +A handler that does nothing would look like this: +init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. @@ -944,10 +1039,10 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/handlers/ Handlers are Erlang modules that handle HTTP requests. - Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. - This callback receives the Req object and the initial state defined in the router configuration. - A handler that does nothing would look like this: - init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. +Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. +This callback receives the Req object and the initial state defined in the router configuration. +A handler that does nothing would look like this: +init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. @@ -957,10 +1052,10 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/handlers/ Handlers are Erlang modules that handle HTTP requests. - Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. - This callback receives the Req object and the initial state defined in the router configuration. - A handler that does nothing would look like this: - init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. +Plain HTTP handlers The most basic handler in Cowboy implements the mandatory init/2 callback, manipulates the request, optionally sends a response and then returns. +This callback receives the Req object and the initial state defined in the router configuration. +A handler that does nothing would look like this: +init(Req, State) -&gt; {ok, Req, State}. Despite sending no reply, a 204 No Content response will be sent to the client, as Cowboy makes sure that a response is sent for every request. @@ -970,9 +1065,9 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/escripts/ Escripts are an alternative to release. They are meant to be used for small command line executables written in Erlang. - They are not self-contained, unlike releases. Erlang must be installed for them to run. This however means that they are fairly small compared to releases. - For self-contained executables, check self-extracting releases. - Requirements Erlang.mk uses p7zip by default to generate the escript archive. Make sure it is installed. On most systems the package is named p7zip; on Ubuntu you need p7zip-full. +They are not self-contained, unlike releases. Erlang must be installed for them to run. This however means that they are fairly small compared to releases. +For self-contained executables, check self-extracting releases. +Requirements Erlang.mk uses p7zip by default to generate the escript archive. Make sure it is installed. On most systems the package is named p7zip; on Ubuntu you need p7zip-full. @@ -982,7 +1077,7 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/loop_handlers/ Loop handlers are a special kind of HTTP handlers used when the response can not be sent right away. The handler enters instead a receive loop waiting for the right message before it can send a response. - Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. +Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. @@ -992,7 +1087,7 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/loop_handlers/ Loop handlers are a special kind of HTTP handlers used when the response can not be sent right away. The handler enters instead a receive loop waiting for the right message before it can send a response. - Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. +Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. @@ -1002,7 +1097,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/loop_handlers/ Loop handlers are a special kind of HTTP handlers used when the response can not be sent right away. The handler enters instead a receive loop waiting for the right message before it can send a response. - Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. +Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. @@ -1012,7 +1107,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/loop_handlers/ Loop handlers are a special kind of HTTP handlers used when the response can not be sent right away. The handler enters instead a receive loop waiting for the right message before it can send a response. - Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. +Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. @@ -1022,7 +1117,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/loop_handlers/ Loop handlers are a special kind of HTTP handlers used when the response can not be sent right away. The handler enters instead a receive loop waiting for the right message before it can send a response. - Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. +Loop handlers are used for requests where a response might not be immediately available, but where you would like to keep the connection open for a while in case the response arrives. The most known example of such practice is known as long polling. @@ -1032,7 +1127,7 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/kerl/ Erlang.mk comes with integrated support for Kerl, a shell script that automates the downloading, building and installing of Erlang/OTP. It can be used to easily build a specific Erlang/OTP version (with or without custom build options) or maintain different versions side by side. - Erlang versions Erlang.mk uses the Git tags from Erlang/OTP to identify OTP versions. The most recent tag at the time of writing is OTP-20.0.4, which is a patch release of OTP-20. +Erlang versions Erlang.mk uses the Git tags from Erlang/OTP to identify OTP versions. The most recent tag at the time of writing is OTP-20.0.4, which is a patch release of OTP-20. @@ -1042,8 +1137,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/static_files/ Cowboy comes with a ready to use handler for serving static files. It is provided as a convenience for serving files during development. - For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. - The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. +For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. +The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. @@ -1053,8 +1148,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/static_files/ Cowboy comes with a ready to use handler for serving static files. It is provided as a convenience for serving files during development. - For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. - The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. +For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. +The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. @@ -1064,8 +1159,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/static_files/ Cowboy comes with a ready to use handler for serving static files. It is provided as a convenience for serving files during development. - For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. - The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. +For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. +The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. @@ -1075,8 +1170,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/static_files/ Cowboy comes with a ready to use handler for serving static files. It is provided as a convenience for serving files during development. - For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. - The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. +For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. +The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. @@ -1086,8 +1181,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/static_files/ Cowboy comes with a ready to use handler for serving static files. It is provided as a convenience for serving files during development. - For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. - The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. +For systems in production, consider using one of the many Content Distribution Network (CDN) available on the market, as they are the best solution for serving files. +The static handler can serve either one file or all files from a given directory. The etag generation and mime types can be configured. @@ -1097,7 +1192,7 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/compat/ Erlang.mk tries its best to be compatible with the other Erlang build tools. It can use dependencies written with other build tools in mind, and can also make your projects usable by those build tools as well. Erlang.mk is like the cool kid that gets along with everybody. - In this chapter I will use the term Rebar project to refer to a project built using Rebar 2, Rebar 3 or Mad. +In this chapter I will use the term Rebar project to refer to a project built using Rebar 2, Rebar 3 or Mad. @@ -1107,8 +1202,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/asciidoc/ Erlang.mk provides rules for generating documentation from AsciiDoc files. It can automatically build a user guide PDF, chunked HTML documentation and Unix manual pages. - Requirements It is necessary to have AsciiDoc, xsltproc and dblatex installed on your system for Erlang.mk to generate documentation from AsciiDoc sources. - Writing AsciiDoc documentation AsciiDoc is a text document format for writing notes, documentation, articles, books, ebooks, slideshows, web pages, man pages and blogs. +Requirements It is necessary to have AsciiDoc, xsltproc and dblatex installed on your system for Erlang.mk to generate documentation from AsciiDoc sources. +Writing AsciiDoc documentation AsciiDoc is a text document format for writing notes, documentation, articles, books, ebooks, slideshows, web pages, man pages and blogs. AsciiDoc files can be translated to many formats including HTML, PDF, EPUB, man page. @@ -1118,8 +1213,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/req/ The Req object is a variable used for obtaining information about a request, read its body or send a response. - It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. - The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. +It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. +The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. @@ -1129,8 +1224,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/req/ The Req object is a variable used for obtaining information about a request, read its body or send a response. - It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. - The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. +It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. +The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. @@ -1140,8 +1235,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/req/ The Req object is a variable used for obtaining information about a request, read its body or send a response. - It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. - The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. +It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. +The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. @@ -1151,8 +1246,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/req/ The Req object is a variable used for obtaining information about a request, read its body or send a response. - It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. - The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. +It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. +The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. @@ -1162,8 +1257,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/req/ The Req object is a variable used for obtaining information about a request, read its body or send a response. - It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. - The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. +It is not really an object in the object-oriented sense. It is a simple map that can be directly accessed or used when calling functions from the cowboy_req module. +The Req object is the subject of a few different chapters. In this chapter we will learn about the Req object and look at how to retrieve information about the request. @@ -1173,9 +1268,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/req_body/ The request body can be read using the Req object. - Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. - Cowboy will not cache the body, it is therefore only possible to read it once. - You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. +Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. +Cowboy will not cache the body, it is therefore only possible to read it once. +You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. @@ -1185,9 +1280,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/req_body/ The request body can be read using the Req object. - Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. - Cowboy will not cache the body, it is therefore only possible to read it once. - You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. +Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. +Cowboy will not cache the body, it is therefore only possible to read it once. +You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. @@ -1197,9 +1292,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/req_body/ The request body can be read using the Req object. - Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. - Cowboy will not cache the body, it is therefore only possible to read it once. - You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. +Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. +Cowboy will not cache the body, it is therefore only possible to read it once. +You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. @@ -1209,9 +1304,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/req_body/ The request body can be read using the Req object. - Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. - Cowboy will not cache the body, it is therefore only possible to read it once. - You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. +Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. +Cowboy will not cache the body, it is therefore only possible to read it once. +You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. @@ -1221,9 +1316,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/req_body/ The request body can be read using the Req object. - Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. - Cowboy will not cache the body, it is therefore only possible to read it once. - You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. +Cowboy will not attempt to read the body until requested. You need to call the body reading functions in order to retrieve it. +Cowboy will not cache the body, it is therefore only possible to read it once. +You are not required to read it, however. If a body is present and was not read, Cowboy will either cancel or skip its download, depending on the protocol. @@ -1233,9 +1328,9 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/edoc/ Erlang.mk provides a thin wrapper on top of EDoc, an application that generates documentation based on comments found in modules. - Writing EDoc comments The EDoc user guide explains everything you need to know about EDoc comments. - Configuration The EDOC_OPTS variable allows you to specify additional EDoc options. Options are documented in the EDoc manual. - A common use for this variable is to enable Markdown in doc comments, using the edown application: +Writing EDoc comments The EDoc user guide explains everything you need to know about EDoc comments. +Configuration The EDOC_OPTS variable allows you to specify additional EDoc options. Options are documented in the EDoc manual. +A common use for this variable is to enable Markdown in doc comments, using the edown application: @@ -1245,8 +1340,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/sphinx/ Erlang.mk includes targets for running the Sphinx documentation generator, which can produce documentation in various formats, like HTML, man pages, Texinfo, LaTeX, and others. - Writing Sphinx documentation Sphinx generates documentation from a set of reST documents. There is a quick start guide on Sphinx' website. For Erlang.mk, we&#8217;ll set up a minimal environment instead. - Basic setup By default, Erlang.mk expects Sphinx documentation to be placed in the doc directory, with doc/conf. +Writing Sphinx documentation Sphinx generates documentation from a set of reST documents. There is a quick start guide on Sphinx&apos; website. For Erlang.mk, we&apos;ll set up a minimal environment instead. +Basic setup By default, Erlang.mk expects Sphinx documentation to be placed in the doc directory, with doc/conf. @@ -1256,8 +1351,9 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/resp/ The response must be sent using the Req object. - Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. - Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. +Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +While only one response is allowed for every request, HTTP/2 introduced a mechanism that allows the server to push additional resources related to the response. @@ -1267,8 +1363,9 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/resp/ The response must be sent using the Req object. - Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. - Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. +Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +While only one response is allowed for every request, HTTP/2 introduced a mechanism that allows the server to push additional resources related to the response. @@ -1278,8 +1375,9 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/resp/ The response must be sent using the Req object. - Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. - Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. +Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +While only one response is allowed for every request, HTTP/2 introduced a mechanism that allows the server to push additional resources related to the response. @@ -1289,8 +1387,9 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/resp/ The response must be sent using the Req object. - Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. - Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. +Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +While only one response is allowed for every request, HTTP/2 introduced a mechanism that allows the server to push additional resources related to the response. @@ -1300,8 +1399,9 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/resp/ The response must be sent using the Req object. - Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. - Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +Cowboy provides two different ways of sending responses: either directly or by streaming the body. Response headers and body may be set in advance. The response is sent as soon as one of the reply or stream reply function is called. +Cowboy also provides a simplified interface for sending files. It can also send only specific parts of a file. +While only one response is allowed for every request, HTTP/2 introduced a mechanism that allows the server to push additional resources related to the response. @@ -1311,8 +1411,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/shell/ Erlang.mk provides a convenient target for starting a shell with all the paths set properly to experiment with your code. - Configuration The SHELL_DEPS variable can be used to define dependencies that are only to be used when the make shell command is called. For example, if you want to use kjell as your shell: - SHELL_DEPS = kjell Dependencies are downloaded and compiled the first time you run the make shell command. +Configuration The SHELL_DEPS variable can be used to define dependencies that are only to be used when the make shell command is called. For example, if you want to use kjell as your shell: +SHELL_DEPS = kjell Dependencies are downloaded and compiled the first time you run the make shell command. @@ -1322,7 +1422,7 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/cookies/ Cookies are a mechanism allowing applications to maintain state on top of the stateless HTTP protocol. - Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). +Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). @@ -1332,7 +1432,7 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/cookies/ Cookies are a mechanism allowing applications to maintain state on top of the stateless HTTP protocol. - Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). +Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). @@ -1342,7 +1442,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/cookies/ Cookies are a mechanism allowing applications to maintain state on top of the stateless HTTP protocol. - Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). +Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). @@ -1352,7 +1452,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/cookies/ Cookies are a mechanism allowing applications to maintain state on top of the stateless HTTP protocol. - Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). +Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). @@ -1362,7 +1462,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/cookies/ Cookies are a mechanism allowing applications to maintain state on top of the stateless HTTP protocol. - Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). +Cookies are a name/value store where the names and values are stored in plain text. They expire either after a delay or when the browser closes. They can be configured on a specific domain name or path, and restricted to secure resources (sent or downloaded over HTTPS), or restricted to the server (disallowing access from client-side scripts). @@ -1372,8 +1472,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/eunit/ EUnit is the tool of choice for unit testing. Erlang.mk automates a few things on top of EUnit, including the discovery and running of unit tests. - Writing tests The EUnit user guide is the best place to learn how to write tests. Of note is that all functions ending with _test or _test_ will be picked up as EUnit test cases. - Erlang.mk will automatically pick up tests found in any of the Erlang modules of your application. +Writing tests The EUnit user guide is the best place to learn how to write tests. Of note is that all functions ending with _test or _test_ will be picked up as EUnit test cases. +Erlang.mk will automatically pick up tests found in any of the Erlang modules of your application. @@ -1383,8 +1483,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/multipart/ Multipart originates from MIME, an Internet standard that extends the format of emails. - A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. - In the context of HTTP, multipart is most often used with the multipart/form-data media type. +A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. +In the context of HTTP, multipart is most often used with the multipart/form-data media type. @@ -1394,8 +1494,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/multipart/ Multipart originates from MIME, an Internet standard that extends the format of emails. - A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. - In the context of HTTP, multipart is most often used with the multipart/form-data media type. +A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. +In the context of HTTP, multipart is most often used with the multipart/form-data media type. @@ -1405,8 +1505,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/multipart/ Multipart originates from MIME, an Internet standard that extends the format of emails. - A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. - In the context of HTTP, multipart is most often used with the multipart/form-data media type. +A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. +In the context of HTTP, multipart is most often used with the multipart/form-data media type. @@ -1416,8 +1516,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/multipart/ Multipart originates from MIME, an Internet standard that extends the format of emails. - A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. - In the context of HTTP, multipart is most often used with the multipart/form-data media type. +A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. +In the context of HTTP, multipart is most often used with the multipart/form-data media type. @@ -1427,8 +1527,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/multipart/ Multipart originates from MIME, an Internet standard that extends the format of emails. - A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. - In the context of HTTP, multipart is most often used with the multipart/form-data media type. +A multipart message is a list of parts. A part contains headers and a body. The body of the parts may be of any media type, and contain text or binary data. It is possible for parts to contain a multipart media type. +In the context of HTTP, multipart is most often used with the multipart/form-data media type. @@ -1437,9 +1537,9 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/erlang.mk/1/guide/common_test/ - Common Test is Erlang&#8217;s functional testing framework. Erlang.mk automates the discovery and running of Common Test suites. - Writing tests The Common Test user guide is the best place to learn how to write tests. Erlang.mk requires that file names for test suites end with _SUITE.erl and that the files be located in the $(TEST_DIR) directory. This defaults to test/. - Configuration The CT_OPTS variable allows you to set extra Common Test options. + Common Test is Erlang&apos;s functional testing framework. Erlang.mk automates the discovery and running of Common Test suites. +Writing tests The Common Test user guide is the best place to learn how to write tests. Erlang.mk requires that file names for test suites end with _SUITE.erl and that the files be located in the $(TEST_DIR) directory. This defaults to test/. +Configuration The CT_OPTS variable allows you to set extra Common Test options. @@ -1449,8 +1549,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/rest_principles/ This chapter will attempt to define the concepts behind REST and explain what makes a service RESTful. - REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&#8217;s highly misguided at best. - We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. +REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&apos;s highly misguided at best. +We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. @@ -1460,8 +1560,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/rest_principles/ This chapter will attempt to define the concepts behind REST and explain what makes a service RESTful. - REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&#8217;s highly misguided at best. - We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. +REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&apos;s highly misguided at best. +We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. @@ -1471,8 +1571,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/rest_principles/ This chapter will attempt to define the concepts behind REST and explain what makes a service RESTful. - REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&#8217;s highly misguided at best. - We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. +REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&apos;s highly misguided at best. +We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. @@ -1482,8 +1582,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/rest_principles/ This chapter will attempt to define the concepts behind REST and explain what makes a service RESTful. - REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&#8217;s highly misguided at best. - We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. +REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&apos;s highly misguided at best. +We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. @@ -1493,8 +1593,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/rest_principles/ This chapter will attempt to define the concepts behind REST and explain what makes a service RESTful. - REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&#8217;s highly misguided at best. - We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. +REST is often confused with performing a distinct operation depending on the HTTP method, while using more than the GET and POST methods. That&apos;s highly misguided at best. +We will first attempt to define REST and will look at what it means in the context of HTTP and the Web. For a more in-depth explanation of REST, you can read Roy T. @@ -1504,12 +1604,12 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/triq/ Triq is a QuickCheck-like library for property-based testing. Erlang.mk automates discovery and checking of Triq properties. - To run all tests (including Triq): - $ make tests To run all tests and static checks (including Triq): - $ make check You can also run Triq separately: - $ make triq To check properties from a single module: - $ make triq t=foo_tests To check a single property: - $ make triq t=foo_tests:bar +To run all tests (including Triq): +$ make tests To run all tests and static checks (including Triq): +$ make check You can also run Triq separately: +$ make triq To check properties from a single module: +$ make triq t=foo_tests To check a single property: +$ make triq t=foo_tests:bar @@ -1518,9 +1618,10 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.0/guide/rest_handlers/ - REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&#8217;s behavior. - The REST handler is the recommended way to handle HTTP requests. - Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. + REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&apos;s behavior. +The REST handler is the recommended way to handle HTTP requests. +Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. +init(Req, State) -&gt; {cowboy_rest, Req, State}. @@ -1529,9 +1630,10 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.1/guide/rest_handlers/ - REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&#8217;s behavior. - The REST handler is the recommended way to handle HTTP requests. - Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. + REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&apos;s behavior. +The REST handler is the recommended way to handle HTTP requests. +Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. +init(Req, State) -&gt; {cowboy_rest, Req, State}. @@ -1540,9 +1642,10 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.2/guide/rest_handlers/ - REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&#8217;s behavior. - The REST handler is the recommended way to handle HTTP requests. - Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. + REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&apos;s behavior. +The REST handler is the recommended way to handle HTTP requests. +Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. +init(Req, State) -&gt; {cowboy_rest, Req, State}. @@ -1551,9 +1654,10 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.3/guide/rest_handlers/ - REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&#8217;s behavior. - The REST handler is the recommended way to handle HTTP requests. - Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. + REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&apos;s behavior. +The REST handler is the recommended way to handle HTTP requests. +Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. +init(Req, State) -&gt; {cowboy_rest, Req, State}. @@ -1562,9 +1666,10 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.4/guide/rest_handlers/ - REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&#8217;s behavior. - The REST handler is the recommended way to handle HTTP requests. - Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. + REST is implemented in Cowboy as a sub protocol. The request is handled as a state machine with many optional callbacks describing the resource and modifying the machine&apos;s behavior. +The REST handler is the recommended way to handle HTTP requests. +Initialization First, the init/2 callback is called. This callback is common to all handlers. To use REST for the current request, this function must return a cowboy_rest tuple. +init(Req, State) -&gt; {cowboy_rest, Req, State}. @@ -1573,8 +1678,7 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/erlang.mk/1/guide/coverage/ - Placeholder chapter. - + Placeholder chapter. @@ -1584,7 +1688,7 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/ci/ Erlang.mk comes with some support for continuous integration, aimed at open source projects that need to support more than one specific Erlang/OTP release. (If you target one specific release, check the OTP version pinning section of the OTP version management chapter.) - Configuring Erlang/OTP versions to test To use the CI plugin you must first configure which versions of Erlang/OTP will be used. Erlang.mk provides three separate configuration variables depending on whether you need a normal OTP release, a HiPE-enabled release or an ErLLVM-enabled release. +Configuring Erlang/OTP versions to test To use the CI plugin you must first configure which versions of Erlang/OTP will be used. Erlang.mk provides three separate configuration variables depending on whether you need a normal OTP release, a HiPE-enabled release or an ErLLVM-enabled release. @@ -1594,8 +1698,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/rest_flowcharts/ This chapter will explain the REST handler state machine through a number of different diagrams. - There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. - All paths start with the "Start" diagram, and all paths excluding the OPTIONS path go through the "Content negotiation" +There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. +All paths start with the &quot;Start&quot; diagram, and all paths excluding the OPTIONS path go through the &quot;Content negotiation&quot; diagram and optionally the &quot;Conditional requests&quot; diagram if the resource exists. @@ -1605,8 +1709,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/rest_flowcharts/ This chapter will explain the REST handler state machine through a number of different diagrams. - There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. - All paths start with the "Start" diagram, and all paths excluding the OPTIONS path go through the "Content negotiation" +There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. +All paths start with the &quot;Start&quot; diagram, and all paths excluding the OPTIONS path go through the &quot;Content negotiation&quot; diagram and optionally the &quot;Conditional requests&quot; diagram if the resource exists. @@ -1616,8 +1720,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/rest_flowcharts/ This chapter will explain the REST handler state machine through a number of different diagrams. - There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. - All paths start with the "Start" diagram, and all paths excluding the OPTIONS path go through the "Content negotiation" +There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. +All paths start with the &quot;Start&quot; diagram, and all paths excluding the OPTIONS path go through the &quot;Content negotiation&quot; diagram and optionally the &quot;Conditional requests&quot; diagram if the resource exists. @@ -1627,8 +1731,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/rest_flowcharts/ This chapter will explain the REST handler state machine through a number of different diagrams. - There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. - All paths start with the "Start" diagram, and all paths excluding the OPTIONS path go through the "Content negotiation" +There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. +All paths start with the &quot;Start&quot; diagram, and all paths excluding the OPTIONS path go through the &quot;Content negotiation&quot; diagram and optionally the &quot;Conditional requests&quot; diagram if the resource exists. @@ -1638,8 +1742,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/rest_flowcharts/ This chapter will explain the REST handler state machine through a number of different diagrams. - There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. - All paths start with the "Start" diagram, and all paths excluding the OPTIONS path go through the "Content negotiation" +There are four main paths that requests may follow. One for the method OPTIONS; one for the methods GET and HEAD; one for the methods PUT, POST and PATCH; and one for the method DELETE. +All paths start with the &quot;Start&quot; diagram, and all paths excluding the OPTIONS path go through the &quot;Content negotiation&quot; diagram and optionally the &quot;Conditional requests&quot; diagram if the resource exists. @@ -1649,8 +1753,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/dialyzer/ Dialyzer is a tool that will detect discrepancies in your program. It does so using a technique known as success typing analysis which has the advantage of providing no false positives. Dialyzer is able to detect type errors, dead code and more. - Erlang.mk provides a wrapper around Dialyzer. - How it works Dialyzer requires a PLT file to work. The PLT file contains the analysis information from all applications which are not expected to change, or rarely do. +Erlang.mk provides a wrapper around Dialyzer. +How it works Dialyzer requires a PLT file to work. The PLT file contains the analysis information from all applications which are not expected to change, or rarely do. @@ -1660,7 +1764,7 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/resource_design/ This chapter aims to provide you with a list of questions you must answer in order to write a good resource handler. It is meant to be usable as a step by step guide. - The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. +The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. @@ -1670,7 +1774,7 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/resource_design/ This chapter aims to provide you with a list of questions you must answer in order to write a good resource handler. It is meant to be usable as a step by step guide. - The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. +The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. @@ -1680,7 +1784,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/resource_design/ This chapter aims to provide you with a list of questions you must answer in order to write a good resource handler. It is meant to be usable as a step by step guide. - The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. +The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. @@ -1690,7 +1794,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/resource_design/ This chapter aims to provide you with a list of questions you must answer in order to write a good resource handler. It is meant to be usable as a step by step guide. - The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. +The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. @@ -1700,7 +1804,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/resource_design/ This chapter aims to provide you with a list of questions you must answer in order to write a good resource handler. It is meant to be usable as a step by step guide. - The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. +The service Can the service become unavailable, and when it does, can we detect it? For example, database connectivity problems may be detected early. We may also have planned outages of all or parts of the system. @@ -1709,8 +1813,7 @@ Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/erlang.mk/1/guide/xref/ - Placeholder chapter. - + Placeholder chapter. @@ -1720,8 +1823,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/external_plugins/ It is often convenient to be able to keep the build files used by all your projects in one place. Those files could be Makefiles, configuration files, templates and more. - Erlang.mk allows you to automatically load plugins from dependencies. Plugins can do anything, including defining new variables, defining file templates, hooking themselves inside the normal Erlang.mk processing or even adding new rules. - You can load plugins using one of two methods. +Erlang.mk allows you to automatically load plugins from dependencies. Plugins can do anything, including defining new variables, defining file templates, hooking themselves inside the normal Erlang.mk processing or even adding new rules. +You can load plugins using one of two methods. @@ -1731,8 +1834,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/ws_protocol/ This chapter explains what Websocket is and why it is a vital component of soft realtime Web applications. - Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. - Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). +Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. +Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). @@ -1742,8 +1845,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/ws_protocol/ This chapter explains what Websocket is and why it is a vital component of soft realtime Web applications. - Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. - Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). +Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. +Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). @@ -1753,8 +1856,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/ws_protocol/ This chapter explains what Websocket is and why it is a vital component of soft realtime Web applications. - Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. - Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). +Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. +Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). @@ -1764,8 +1867,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/ws_protocol/ This chapter explains what Websocket is and why it is a vital component of soft realtime Web applications. - Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. - Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). +Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. +Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). @@ -1775,8 +1878,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/ws_protocol/ This chapter explains what Websocket is and why it is a vital component of soft realtime Web applications. - Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. - Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). +Description Websocket is an extension to HTTP that emulates plain TCP connections between the client, typically a Web browser, and the server. It uses the HTTP Upgrade mechanism to establish the connection. +Websocket connections are fully asynchronous, unlike HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the server can only initiate streams in response to requests). @@ -1786,10 +1889,11 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/external_plugins_list/ This is a non-exhaustive list of Erlang.mk plugins, sorted alphabetically. - efene.mk An Efene plugin for Erlang.mk. Efene is an alternative language for the BEAM. - elixir.mk An Elixir plugin for Erlang.mk. Elixir is an alternative language for the BEAM. - elvis.mk An Elvis plugin for Erlang.mk. Elvis is an Erlang style reviewer. - geas Geas gives aggregated information on a project and its dependencies, and is available as an Erlang. +efene.mk An Efene plugin for Erlang.mk. Efene is an alternative language for the BEAM. +elixir.mk An Elixir plugin for Erlang.mk. Elixir is an alternative language for the BEAM. +elvis.mk An Elvis plugin for Erlang.mk. Elvis is an Erlang style reviewer. +geas Geas gives aggregated information on a project and its dependencies, and is available as an Erlang.mk plugin. +hexer.mk An Hex plugin for Erlang. @@ -1799,7 +1903,7 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/ws_handlers/ Websocket handlers provide an interface for upgrading HTTP/1.1 connections to Websocket and sending or receiving frames on the Websocket connection. - As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. +As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. @@ -1809,7 +1913,7 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/ws_handlers/ Websocket handlers provide an interface for upgrading HTTP/1.1 connections to Websocket and sending or receiving frames on the Websocket connection. - As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. +As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. @@ -1819,7 +1923,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/ws_handlers/ Websocket handlers provide an interface for upgrading HTTP/1.1 connections to Websocket and sending or receiving frames on the Websocket connection. - As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. +As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. @@ -1829,7 +1933,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/ws_handlers/ Websocket handlers provide an interface for upgrading HTTP/1.1 connections to Websocket and sending or receiving frames on the Websocket connection. - As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. +As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. @@ -1839,7 +1943,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/ws_handlers/ Websocket handlers provide an interface for upgrading HTTP/1.1 connections to Websocket and sending or receiving frames on the Websocket connection. - As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. +As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection. @@ -1849,8 +1953,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/streams/ A stream is the set of messages that form an HTTP request/response pair. - The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. - All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. +The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. +All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. @@ -1860,8 +1964,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/streams/ A stream is the set of messages that form an HTTP request/response pair. - The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. - All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. +The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. +All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. @@ -1871,8 +1975,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/streams/ A stream is the set of messages that form an HTTP request/response pair. - The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. - All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. +The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. +All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. @@ -1882,8 +1986,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/streams/ A stream is the set of messages that form an HTTP request/response pair. - The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. - All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. +The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. +All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. @@ -1893,8 +1997,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/streams/ A stream is the set of messages that form an HTTP request/response pair. - The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. - All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. +The term stream comes from HTTP/2. In Cowboy, it is also used when talking about HTTP/1.1 or HTTP/1.0. It should not be confused with streaming the request or response body. +All versions of HTTP allow clients to initiate streams. HTTP/2 is the only one also allowing servers, through its server push feature. Both client and server-initiated streams go through the same process in Cowboy. @@ -1904,9 +2008,9 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/why/ Why would you choose Erlang.mk, if not for its many features? This chapter will attempt to answer that. - Erlang.mk is fast Erlang.mk is as fast as it gets. - Erlang.mk will group the compilation of files so as to avoid running the BEAM more than necessary. This saves many seconds compared to traditional Makefiles, even on small projects. - Erlang.mk will not try to be too smart. It provides a simple solution that works for most people, and gives additional options for projects that run into edge cases, often in the form of extra variables or rules to be defined. +Erlang.mk is fast Erlang.mk is as fast as it gets. +Erlang.mk will group the compilation of files so as to avoid running the BEAM more than necessary. This saves many seconds compared to traditional Makefiles, even on small projects. +Erlang.mk will not try to be too smart. It provides a simple solution that works for most people, and gives additional options for projects that run into edge cases, often in the form of extra variables or rules to be defined. @@ -1916,8 +2020,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/middlewares/ Cowboy delegates the request processing to middleware components. By default, two middlewares are defined, for the routing and handling of the request, as is detailed in most of this guide. - Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. - Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. +Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. +Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. @@ -1927,8 +2031,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/middlewares/ Cowboy delegates the request processing to middleware components. By default, two middlewares are defined, for the routing and handling of the request, as is detailed in most of this guide. - Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. - Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. +Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. +Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. @@ -1938,8 +2042,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/middlewares/ Cowboy delegates the request processing to middleware components. By default, two middlewares are defined, for the routing and handling of the request, as is detailed in most of this guide. - Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. - Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. +Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. +Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. @@ -1949,8 +2053,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/middlewares/ Cowboy delegates the request processing to middleware components. By default, two middlewares are defined, for the routing and handling of the request, as is detailed in most of this guide. - Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. - Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. +Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. +Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. @@ -1960,8 +2064,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/middlewares/ Cowboy delegates the request processing to middleware components. By default, two middlewares are defined, for the routing and handling of the request, as is detailed in most of this guide. - Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. - Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. +Middlewares give you complete control over how requests are to be processed. You can add your own middlewares to the mix or completely change the chain of middlewares as needed. +Cowboy will execute all middlewares in the given order, unless one of them decides to stop processing. @@ -1971,8 +2075,8 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/history/ This chapter aims to be a brief record of the life of the Erlang.mk project. - Before Erlang.mk Erlang.mk originates from the Cowboy project. Cowboy started as a Rebar project and I, Loïc Hoguin, was very happy with it for a couple years. Over time however I started getting annoyed and frustrated by a number of things, including bad defaults, changing defaults and overall slowness. - In particular, at the time I gave up on Rebar, the Cowboy test suite was taking about five minutes to run. +Before Erlang.mk Erlang.mk originates from the Cowboy project. Cowboy started as a Rebar project and I, Loïc Hoguin, was very happy with it for a couple years. Over time however I started getting annoyed and frustrated by a number of things, including bad defaults, changing defaults and overall slowness. +In particular, at the time I gave up on Rebar, the Cowboy test suite was taking about five minutes to run. @@ -1982,9 +2086,10 @@ https://ninenines.eu/docs/en/erlang.mk/1/guide/contributing/ You are welcome and encouraged to contribute. - This is how. - Priorities From the most important to the least important: - Bugs Package issues/additions Refactoring Features Bugs If you have found a bug, you should open a ticket. Include everything relevant including the command you used, output, a link to the code that triggers the issue, why you think this is a bug, etc. +This is how. +Priorities From the most important to the least important: +Bugs Package issues/additions Refactoring Features Bugs If you have found a bug, you should open a ticket. Include everything relevant including the command you used, output, a link to the code that triggers the issue, why you think this is a bug, etc. +If you think you have found a bug but you are not sure, you should open a ticket as previously explained. @@ -1994,7 +2099,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/migrating_from_2.2/ The following patch versions were released since Cowboy 2.2: - Cowboy 2.2.2 While fixing the miscount in the previous patch release an issue was introduced where HTTP/2 bodies could be sent out of orders when using iolists. This has been corrected. Cowboy 2.2.1 Colons are now allowed within path segments in routes provided to cowboy_router:compile/1 as long as they are not the first character of the path segment. +Cowboy 2.2.2 While fixing the miscount in the previous patch release an issue was introduced where HTTP/2 bodies could be sent out of orders when using iolists. This has been corrected. Cowboy 2.2.1 Colons are now allowed within path segments in routes provided to cowboy_router:compile/1 as long as they are not the first character of the path segment. The cowboy_req:delete_resp_header/2 function will no longer crash when no response header was set before calling it. @@ -2004,8 +2109,8 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/migrating_from_1.0/ A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req interface in particular has seen a massive revamp. Hooks are gone, their functionality can now be achieved via stream handlers. - The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. - Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. +The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. +Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. Erlang/OTP 19. @@ -2015,7 +2120,7 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/migrating_from_2.0/ Cowboy 2.1 focused on adding features that were temporarily removed in Cowboy 2.0. A number of bugs found in the 2.0 release were also fixed. - Features added It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object. Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response. +Features added It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object. Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response. The expect: 100-continue header is now handled automatically. @@ -2025,7 +2130,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/migrating_from_2.2/ Cowboy 2.3 focused on making the Cowboy processes behave properly according to OTP principles. This version is a very good milestone toward that goal and most of everything should now work. Release upgrades and a few details will be improved in future versions. - Features added Add support for all functions from the module sys. Note that Cowboy currently does not implement the sys debugging mechanisms as tracing is recommended instead. +Features added Add support for all functions from the module sys. Note that Cowboy currently does not implement the sys debugging mechanisms as tracing is recommended instead. Add a max_frame_size option for Websocket handlers to close the connection when the client attempts to send a frame that&apos;s too large. @@ -2035,7 +2140,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/migrating_from_2.3/ Cowboy 2.4 focused on improving the HTTP/2 implementation. All existing tests from RFC7540 and the h2spec test suite now all pass. Numerous options have been added to control SETTINGS and related behavior. In addition experimental support for Websocket over HTTP/2 was added. - Features added Add experimental support for Websocket over HTTP/2. You can use the enable_connect_protocol option to enable. It implements the following draft: https://tools.ietf.org/html/draft-ietf-httpbis-h2-websockets-01 Add options max_decode_table_size and max_encode_table_size to restrict the size of the HPACK compression dictionary. +Features added Add experimental support for Websocket over HTTP/2. You can use the enable_connect_protocol option to enable. It implements the following draft: https://tools.ietf.org/html/draft-ietf-httpbis-h2-websockets-01 Add options max_decode_table_size and max_encode_table_size to restrict the size of the HPACK compression dictionary. @@ -2045,7 +2150,7 @@ https://ninenines.eu/docs/en/cowboy/2.0/guide/specs/ This chapter intends to list all the specification documents for or related to HTTP. - HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload REST: Fielding&#8217;s Dissertation RFC 1945: HTTP/1. +HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload REST: Fielding&apos;s Dissertation RFC 1945: HTTP/1. @@ -2055,8 +2160,8 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/migrating_from_1.0/ A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req interface in particular has seen a massive revamp. Hooks are gone, their functionality can now be achieved via stream handlers. - The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. - Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. +The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. +Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. Erlang/OTP 19. @@ -2066,7 +2171,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/migrating_from_2.1/ Cowboy 2.2 focused on adding features required for writing gRPC servers and on completing test suites for the core HTTP RFCs, fixing many bugs along the way. - Features added Add support for sending trailers at the end of response bodies. Trailers are additional header fields that may be sent after the body to add more information to the response. Their usage is required in gRPC servers. They are optional and may be discarded in other scenarios (for example if the request goes through an HTTP/1. +Features added Add support for sending trailers at the end of response bodies. Trailers are additional header fields that may be sent after the body to add more information to the response. Their usage is required in gRPC servers. They are optional and may be discarded in other scenarios (for example if the request goes through an HTTP/1. @@ -2076,7 +2181,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/migrating_from_2.1/ Cowboy 2.2 focused on adding features required for writing gRPC servers and on completing test suites for the core HTTP RFCs, fixing many bugs along the way. - Features added Add support for sending trailers at the end of response bodies. Trailers are additional header fields that may be sent after the body to add more information to the response. Their usage is required in gRPC servers. They are optional and may be discarded in other scenarios (for example if the request goes through an HTTP/1. +Features added Add support for sending trailers at the end of response bodies. Trailers are additional header fields that may be sent after the body to add more information to the response. Their usage is required in gRPC servers. They are optional and may be discarded in other scenarios (for example if the request goes through an HTTP/1. @@ -2086,7 +2191,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/migrating_from_2.2/ Cowboy 2.3 focused on making the Cowboy processes behave properly according to OTP principles. This version is a very good milestone toward that goal and most of everything should now work. Release upgrades and a few details will be improved in future versions. - Features added Add support for all functions from the module sys. Note that Cowboy currently does not implement the sys debugging mechanisms as tracing is recommended instead. +Features added Add support for all functions from the module sys. Note that Cowboy currently does not implement the sys debugging mechanisms as tracing is recommended instead. Add a max_frame_size option for Websocket handlers to close the connection when the client attempts to send a frame that&apos;s too large. @@ -2096,7 +2201,7 @@ https://ninenines.eu/docs/en/cowboy/2.1/guide/specs/ This chapter intends to list all the specification documents for or related to HTTP. - HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload REST: Fielding&#8217;s Dissertation RFC 1945: HTTP/1. +HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload REST: Fielding&apos;s Dissertation RFC 1945: HTTP/1. @@ -2106,7 +2211,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/migrating_from_2.0/ Cowboy 2.1 focused on adding features that were temporarily removed in Cowboy 2.0. A number of bugs found in the 2.0 release were also fixed. - Features added It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object. Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response. +Features added It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object. Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response. The expect: 100-continue header is now handled automatically. @@ -2116,7 +2221,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/migrating_from_2.0/ Cowboy 2.1 focused on adding features that were temporarily removed in Cowboy 2.0. A number of bugs found in the 2.0 release were also fixed. - Features added It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object. Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response. +Features added It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object. Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response. The expect: 100-continue header is now handled automatically. @@ -2126,7 +2231,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/migrating_from_2.1/ Cowboy 2.2 focused on adding features required for writing gRPC servers and on completing test suites for the core HTTP RFCs, fixing many bugs along the way. - Features added Add support for sending trailers at the end of response bodies. Trailers are additional header fields that may be sent after the body to add more information to the response. Their usage is required in gRPC servers. They are optional and may be discarded in other scenarios (for example if the request goes through an HTTP/1. +Features added Add support for sending trailers at the end of response bodies. Trailers are additional header fields that may be sent after the body to add more information to the response. Their usage is required in gRPC servers. They are optional and may be discarded in other scenarios (for example if the request goes through an HTTP/1. @@ -2136,8 +2241,8 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/migrating_from_1.0/ A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req interface in particular has seen a massive revamp. Hooks are gone, their functionality can now be achieved via stream handlers. - The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. - Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. +The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. +Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. Erlang/OTP 19. @@ -2147,8 +2252,8 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/migrating_from_1.0/ A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req interface in particular has seen a massive revamp. Hooks are gone, their functionality can now be achieved via stream handlers. - The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. - Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. +The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. +Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. Erlang/OTP 19. @@ -2158,7 +2263,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/migrating_from_2.0/ Cowboy 2.1 focused on adding features that were temporarily removed in Cowboy 2.0. A number of bugs found in the 2.0 release were also fixed. - Features added It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object. Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response. +Features added It is now possible to obtain the client TLS certificate and the local IP/port for the connection from the Req object. Informational responses (1XX responses) can now be sent. They must be sent before initiating the final response. The expect: 100-continue header is now handled automatically. @@ -2168,7 +2273,7 @@ https://ninenines.eu/docs/en/cowboy/2.2/guide/specs/ This chapter intends to list all the specification documents for or related to HTTP. - HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload REST: Fielding&#8217;s Dissertation RFC 1945: HTTP/1. +HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload REST: Fielding&apos;s Dissertation RFC 1945: HTTP/1. @@ -2178,7 +2283,7 @@ https://ninenines.eu/docs/en/cowboy/2.3/guide/specs/ This chapter intends to list all the specification documents for or related to HTTP. - HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload PROXY: The PROXY protocol REST: Fielding&#8217;s Dissertation RFC 1945: HTTP/1. +HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload PROXY: The PROXY protocol REST: Fielding&apos;s Dissertation RFC 1945: HTTP/1. @@ -2188,8 +2293,8 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/migrating_from_1.0/ A lot has changed between Cowboy 1.0 and 2.0. The cowboy_req interface in particular has seen a massive revamp. Hooks are gone, their functionality can now be achieved via stream handlers. - The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. - Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. +The documentation has seen great work, in particular the manual. Each module and each function now has its own dedicated manual page with full details and examples. +Compatibility Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. Erlang/OTP 19. @@ -2199,7 +2304,7 @@ https://ninenines.eu/docs/en/cowboy/2.4/guide/specs/ This chapter intends to list all the specification documents for or related to HTTP. - HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload PROXY: The PROXY protocol REST: Fielding&#8217;s Dissertation RFC 1945: HTTP/1. +HTTP IANA Registries HTTP Method Registry HTTP Status Code Registry Message Headers HTTP Parameters HTTP Alt-Svc Parameter Registry HTTP Authentication Scheme Registry HTTP Cache Directive Registry HTTP Digest Algorithm Values HTTP Origin-Bound Authentication Device Identifier Types HTTP Upgrade Token Registry HTTP Warn Codes HTTP/2 Parameters WebSocket Protocol Registries Current CORS: Cross-Origin Resource Sharing CSP2: Content Security Policy Level 2 DNT: Tracking Preference Expression (DNT) eventsource: Server-Sent Events Form content types: Form content types Preload: Preload PROXY: The PROXY protocol REST: Fielding&apos;s Dissertation RFC 1945: HTTP/1. @@ -2209,9 +2314,9 @@ https://ninenines.eu/articles/gun-1.0.0-rc.1/ Gun 1.0.0-rc.1 has been released! - Gun is an HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP. - Gun provides an asynchronous interface and will keep the connection open to the server, reconnecting as necessary. - Gun has existed for many years as the test client for Cowboy and is now mature enough to receive a proper version. Gun is battle tested by customers and other users but is not the most well tested client there is. +Gun is an HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP. +Gun provides an asynchronous interface and will keep the connection open to the server, reconnecting as necessary. +Gun has existed for many years as the test client for Cowboy and is now mature enough to receive a proper version. Gun is battle tested by customers and other users but is not the most well tested client there is. @@ -2221,8 +2326,8 @@ https://ninenines.eu/articles/cowboy-2.4.0/ Cowboy 2.4.0 has been released! - Numerous HTTP/2 options have been added to control the HTTP/2 SETTINGS and general behavior of HTTP/2 connections. The options for initial window sizes, maximum frame sizes or compression table sizes might be of interest for optimizing the performance of HTTP/2 connections. - Experimental support for Websocket over HTTP/2 was added. Note that browsers do not currently support it. The only browser with partial support is Google Chrome 67 (dev build) started with a specific flag. +Numerous HTTP/2 options have been added to control the HTTP/2 SETTINGS and general behavior of HTTP/2 connections. The options for initial window sizes, maximum frame sizes or compression table sizes might be of interest for optimizing the performance of HTTP/2 connections. +Experimental support for Websocket over HTTP/2 was added. Note that browsers do not currently support it. The only browser with partial support is Google Chrome 67 (dev build) started with a specific flag. @@ -2232,9 +2337,10 @@ https://ninenines.eu/articles/cowboy-2.3.0/ Cowboy 2.3.0 has been released! - This release focused on adding support for the functions from the sys module for introspecting Cowboy processes. - Many bugs have also been fixed. A more complete list of changes can be found in the migration guide: Migrating from Cowboy 2.2 to 2.3. - You can donate to this project via BountySource because I need to eat snacks when I write code. Thanks in advance! +This release focused on adding support for the functions from the sys module for introspecting Cowboy processes. +Many bugs have also been fixed. A more complete list of changes can be found in the migration guide: Migrating from Cowboy 2.2 to 2.3. +You can donate to this project via BountySource because I need to eat snacks when I write code. Thanks in advance! +As usual, feedback is appreciated, and issues should be reported by opening a ticket. @@ -2244,8 +2350,8 @@ https://ninenines.eu/articles/cowboy-2.2.0/ Cowboy 2.2.0 has been released! - This release focused on adding features required for writing gRPC servers and on completing test suites for the core HTTP RFCs. - The cowboy_req:stream_trailers/2 function has been added. It terminates the streamed response by adding some trailer field values. This feature is required for gRPC. The max_skip_body_length option was added. It controls how much of the request body we are willing to skip to get to the next request for HTTP/1. +This release focused on adding features required for writing gRPC servers and on completing test suites for the core HTTP RFCs. +The cowboy_req:stream_trailers/2 function has been added. It terminates the streamed response by adding some trailer field values. This feature is required for gRPC. The max_skip_body_length option was added. It controls how much of the request body we are willing to skip to get to the next request for HTTP/1. @@ -2255,8 +2361,8 @@ https://ninenines.eu/articles/cowboy-2.1.0/ Cowboy 2.1.0 has been released! - This release focused on adding features that were temporarily removed during the 2.0 release process: - The client TLS certificate can now be obtained. The 100 Continue response is now sent automatically again when necessary. NEW: It is now possible to send informational responses (1XX) directly from user code via the cowboy_req:inform/2,3 functions. NEW: cowboy_rest handlers can now switch to any other type of handler from almost any callback. +This release focused on adding features that were temporarily removed during the 2.0 release process: +The client TLS certificate can now be obtained. The 100 Continue response is now sent automatically again when necessary. NEW: It is now possible to send informational responses (1XX) directly from user code via the cowboy_req:inform/2,3 functions. NEW: cowboy_rest handlers can now switch to any other type of handler from almost any callback. @@ -2266,9 +2372,9 @@ https://ninenines.eu/articles/cowboy-2.0.0/ Cowboy 2.0.0 has been released! - This is the new stable version of Cowboy. There are no new releases planned for the 1.x version of Cowboy. - The highlights from the release are: - HTTP/2 support! Websocket compression! Much simpler, cleaner interface. No more weird errors just because you discard the Req object. A new low-level interface that receives all events from every set of request and response. +This is the new stable version of Cowboy. There are no new releases planned for the 1.x version of Cowboy. +The highlights from the release are: +HTTP/2 support! Websocket compression! Much simpler, cleaner interface. No more weird errors just because you discard the Req object. A new low-level interface that receives all events from every set of request and response. This replaces the awkward hooks from 1. @@ -2278,9 +2384,9 @@ https://ninenines.eu/articles/cowboy-2.0.0-rc.2/ Cowboy 2.0.0-rc.2 has been released! - This is the new recommended version of Cowboy. Its API should not change before release. While you probably should not use it in production yet, many do successfully. Use at your own risk. - This new version contains fixes for the following issues: - HTTP/2 server push was using the wrong header compression context. HTTP/2 flow control could end up queueing data in the wrong order when resuming the sending of data. +This is the new recommended version of Cowboy. Its API should not change before release. While you probably should not use it in production yet, many do successfully. Use at your own risk. +This new version contains fixes for the following issues: +HTTP/2 server push was using the wrong header compression context. HTTP/2 flow control could end up queueing data in the wrong order when resuming the sending of data. @@ -2290,8 +2396,8 @@ https://ninenines.eu/articles/cowboy-2.0.0-rc.1/ Cowboy 2.0.0-rc.1 has been released! - This is the new recommended version of Cowboy. Its API should not change before release. While you probably should not use it in production yet, many do successfully. Use at your own risk. - The plan is to have a new RC version every couple weeks until the summer ends or later if there are still blocking issues open. Only issues that can&#8217;t be fixed without making breaking changes to the interface may block the release. +This is the new recommended version of Cowboy. Its API should not change before release. While you probably should not use it in production yet, many do successfully. Use at your own risk. +The plan is to have a new RC version every couple weeks until the summer ends or later if there are still blocking issues open. Only issues that can&apos;t be fixed without making breaking changes to the interface may block the release. @@ -2301,7 +2407,7 @@ https://ninenines.eu/articles/the-elephant-in-the-room/ Have you ever tried telling someone why they should use Erlang? You boast the smaller code size, the auto healing mechanisms, the distribution and they seem really excited. They wonder why they never heard about Erlang before. And then you show them what the code looks like. All excitement goes away. The smiles disappear. Their face starts becoming really serious. - You lost them. You know you lost them. They comment on the syntax, or perhaps you do, already admitting defeat. +You lost them. You know you lost them. They comment on the syntax, or perhaps you do, already admitting defeat. @@ -2310,8 +2416,8 @@ Sun, 22 Jan 2017 00:00:00 +0100 https://ninenines.eu/articles/dont-let-it-crash/ - We have a specific mindset when writing Erlang programs. We focus on the normal execution of the program and don&#8217;t handle most of the errors that may occur. We sometimes call this normal execution the happy path. - The general pattern behind writing only for the happy path, letting the VM catch errors (writing them to a log for future consumption) and then having a supervisor restart the processes that failed from a clean state, has a name. + We have a specific mindset when writing Erlang programs. We focus on the normal execution of the program and don&apos;t handle most of the errors that may occur. We sometimes call this normal execution the happy path. +The general pattern behind writing only for the happy path, letting the VM catch errors (writing them to a log for future consumption) and then having a supervisor restart the processes that failed from a clean state, has a name. @@ -2321,9 +2427,9 @@ https://ninenines.eu/articles/cowboy-2.0.0-pre.4/ Cowboy 2.0.0-pre.4 has been released! - This is the new recommended version of Cowboy. While I would not recommend putting it in production just yet, I do recommend you start writing new applications with this Cowboy version. - The most significant changes in the pre-release are: - A new architecture: there now is one process per connection and one process per request. This was done because HTTP/2 allows running requests concurrently. +This is the new recommended version of Cowboy. While I would not recommend putting it in production just yet, I do recommend you start writing new applications with this Cowboy version. +The most significant changes in the pre-release are: +A new architecture: there now is one process per connection and one process per request. This was done because HTTP/2 allows running requests concurrently. Stream handlers. @@ -2333,8 +2439,9 @@ https://ninenines.eu/articles/ranch-1.3/ Ranch 1.3.0 has been released! - This release fixes a number of long standing issues and adds a small number of features: - The ssl application has been added to the list of dependencies. If you don&#8217;t need it, you can remove it automatically when fetching Ranch or when building the release. If you do need it, you will no longer have issues shutting down a node because of Ranch. +This release fixes a number of long standing issues and adds a small number of features: +The ssl application has been added to the list of dependencies. If you don&apos;t need it, you can remove it automatically when fetching Ranch or when building the release. If you do need it, you will no longer have issues shutting down a node because of Ranch. +The ranch:info/0 and ranch:procs/2 can be used to retrieve information about Ranch&apos;s state. @@ -2344,9 +2451,9 @@ https://ninenines.eu/articles/ml-archives/ The old mailing list archives have been added to the site, mainly for referencing purposes. - The mailing list has been shut down and all personal information has been deleted. - If you need help with a project, consider either opening a ticket on that project&#8217;s issues tracker or going through the community channels (erlang-questions, #ninenines or #erlang on Freenode). - Prefer tickets; often when people have issues it highlights an underlying problem in the project or its documentation. +The mailing list has been shut down and all personal information has been deleted. +If you need help with a project, consider either opening a ticket on that project&apos;s issues tracker or going through the community channels (erlang-questions, #ninenines or #erlang on Freenode). +Prefer tickets; often when people have issues it highlights an underlying problem in the project or its documentation. @@ -2356,8 +2463,8 @@ https://ninenines.eu/articles/website-update/ Last week-end I updated the Nine Nines website. - I switched to Hugo. The site is now built from Asciidoc documents. You probably saw me switch to Asciidoc for documentation this past year. This is the natural conclusion to that story. The great thing is that with a little bit of Makefile magic I can just copy the documentation files into Hugo and poof, they appear on the website. - I am very happy with that new setup. +I switched to Hugo. The site is now built from Asciidoc documents. You probably saw me switch to Asciidoc for documentation this past year. This is the natural conclusion to that story. The great thing is that with a little bit of Makefile magic I can just copy the documentation files into Hugo and poof, they appear on the website. +I am very happy with that new setup. @@ -2367,9 +2474,9 @@ https://ninenines.eu/articles/erlanger-playbook-september-2015-update/ An update to The Erlanger Playbook is now available! - The Erlanger Playbook is a book about software development using Erlang. It currently covers all areas from the conception, design, the writing of code, documentation and tests. - The book is still a work in progress. Future topics will include refactoring, debugging and tracing, benchmarking, releases, community management (for open source projects). - This update fixes a number of things and adds two chapters: IOlists and Erlang building blocks. +The Erlanger Playbook is a book about software development using Erlang. It currently covers all areas from the conception, design, the writing of code, documentation and tests. +The book is still a work in progress. Future topics will include refactoring, debugging and tracing, benchmarking, releases, community management (for open source projects). +This update fixes a number of things and adds two chapters: IOlists and Erlang building blocks. @@ -2379,10 +2486,10 @@ https://ninenines.eu/services/ If you are interested by any of these opportunities, send me an email. - Consulting You can get me, Loïc Hoguin, author of Cowboy, to help you solve a problem or work on a particular project. - My area of expertise is Erlang; HTTP, Websocket and REST APIs; design and implementation of protocols; and messaging systems. - I can also be helpful with testing or code reviews. - I offer both hourly and daily rates: +Consulting You can get me, Loïc Hoguin, author of Cowboy, to help you solve a problem or work on a particular project. +My area of expertise is Erlang; HTTP, Websocket and REST APIs; design and implementation of protocols; and messaging systems. +I can also be helpful with testing or code reviews. +I offer both hourly and daily rates: @@ -2392,8 +2499,7 @@ https://ninenines.eu/docs/ Contribute Do you have examples, tutorials, videos about one or more of my projects? I would happily include them on this page. - Send me an email with the details. - +Send me an email with the details. @@ -2403,7 +2509,7 @@ https://ninenines.eu/donate/ Like my work? Donate! Donate to Loïc Hoguin because his work on Cowboy and Erlang.mk is fantastic: - + @@ -2413,8 +2519,7 @@ https://ninenines.eu/talks/ Talk requests Organizing a conference and in need of a speaker for a talk about Erlang and the Web? Need an introduction to Erlang/OTP for your company? Looking for a cool subject for a user group meeting? - Send me an email with the details. - +Send me an email with the details. @@ -2423,9 +2528,7 @@ Wed, 01 Jul 2015 00:00:00 +0100 https://ninenines.eu/slogan/ - Feeling generous? Love reading? -Crowdfund my salary or buy The Erlanger Playbook - + Feeling generous? Love reading? Crowdfund my salary or buy The Erlanger Playbook @@ -2435,9 +2538,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/articles/erlanger-playbook/ I am proud to announce the pre-release of The Erlanger Playbook. - The Erlanger Playbook is a book about software development using Erlang. It currently covers all areas from the conception, design, the writing of code, documentation and tests. - The book is still a work in progress. Future topics will include refactoring, debugging and tracing, benchmarking, releases, community management (for open source projects). - The following sections are currently available: +The Erlanger Playbook is a book about software development using Erlang. It currently covers all areas from the conception, design, the writing of code, documentation and tests. +The book is still a work in progress. Future topics will include refactoring, debugging and tracing, benchmarking, releases, community management (for open source projects). +The following sections are currently available: +About this book; Changelog; Future additions Erlang: Building blocks; Patterns Workflow: Think; Write; Stay productive Documentation: On documentation; Tutorials; User guide; Manual; README files Design: RESTful APIs; Lessons learned Code: Starting a project; Version control; Project structure; Code style; Best practices; Special processes; IOLists; The process dictionary Tests: On testing; Success typing analysis; Manual testing; Unit testing; Functional testing Selling Erlang: On persuasion; Don&apos;t let it crash Read a preview: Special processes @@ -2447,8 +2551,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/articles/erlang-validate-utf8/ Yesterday I pushed Websocket permessage-deflate to Cowboy master. I also pushed a change in the way the code validates UTF-8 data (required for text and close frames as per the spec). - When looking into why the permessage-deflate tests in autobahntestsuite were taking such a long time, I found that autobahn is using an adaptation of the algorithm named Flexible and Economical UTF-8 Decoder. This is the C99 implementation: - // Copyright (c) 2008-2009 Bjoern Hoehrmann &lt;bjoern@hoehrmann. +When looking into why the permessage-deflate tests in autobahntestsuite were taking such a long time, I found that autobahn is using an adaptation of the algorithm named Flexible and Economical UTF-8 Decoder. This is the C99 implementation: +// Copyright (c) 2008-2009 Bjoern Hoehrmann &lt;bjoern@hoehrmann. @@ -2466,7 +2570,7 @@ Crowdfund my salary or buy The Erlanger Playbook Sat, 23 Aug 2014 00:00:00 +0100 https://ninenines.eu/articles/the-story-so-far/ - As I am away from home with little to do (some call this a vacation) I wanted to reflect a little on the story so far, or how I arrived to Erlang and got to where I am now. The raw personal experience. It&#8217;ll be an article that&#8217;s more about social aspect, communities and marketing a project than technical considerations. As a period piece, it will also allow me to reflect on the evolution of Erlang in recent years. + As I am away from home with little to do (some call this a vacation) I wanted to reflect a little on the story so far, or how I arrived to Erlang and got to where I am now. The raw personal experience. It&apos;ll be an article that&apos;s more about social aspect, communities and marketing a project than technical considerations. As a period piece, it will also allow me to reflect on the evolution of Erlang in recent years. @@ -2476,7 +2580,7 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/articles/cowboy2-qs/ Now that Cowboy 1.0 is out, I can spend some of my time thinking about Cowboy 2.0 that will be released soon after Erlang/OTP 18.0. This entry discusses the proposed changes to query string handling in Cowboy. - Cowboy 2.0 will respond to user wishes by simplifying the interface of the cowboy_req module. Users want two things: less juggling with the Req variable, and more maps. Maps is the only dynamic key/value data structure in Erlang that we can match directly to extract values, allowing users to greatly simplify their code as they don&#8217;t need to call functions to do everything anymore. +Cowboy 2.0 will respond to user wishes by simplifying the interface of the cowboy_req module. Users want two things: less juggling with the Req variable, and more maps. Maps is the only dynamic key/value data structure in Erlang that we can match directly to extract values, allowing users to greatly simplify their code as they don&apos;t need to call functions to do everything anymore. @@ -2486,8 +2590,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/articles/january-2014-status/ I will now be regularly writing posts about project status, plans and hopes for the future. - Before that though, there&#8217;s one important news to share. - Until a year ago all development was financed through consulting and development services. This worked alright but too much time was spent doing things that didn&#8217;t benefit the open source projects. And that didn&#8217;t make me happy at all. Because I like being happy I stopped that for the most part and spent the year figuring things out, experimenting and discussing with people about it. +Before that though, there&apos;s one important news to share. +Until a year ago all development was financed through consulting and development services. This worked alright but too much time was spent doing things that didn&apos;t benefit the open source projects. And that didn&apos;t make me happy at all. Because I like being happy I stopped that for the most part and spent the year figuring things out, experimenting and discussing with people about it. @@ -2496,10 +2600,10 @@ Crowdfund my salary or buy The Erlanger Playbook Thu, 27 Jun 2013 00:00:00 +0100 https://ninenines.eu/articles/farwest-funded/ - This was a triumph! I&#8217;m making a note here: HUGE SUCCESS!! - It&#8217;s hard to overstate my satisfaction. Thanks to everyone who made this possible. - If you have backed this fundraiser, and haven&#8217;t provided your personal details yet, please do so quickly so that your rewards can be sent! - I am hoping that we will be able to make good use of all that money. The details of the expenses will be published regularly on the 2013 Fundraiser wiki page, giving you full disclosure as to how your money is used. + This was a triumph! I&apos;m making a note here: HUGE SUCCESS!! +It&apos;s hard to overstate my satisfaction. Thanks to everyone who made this possible. +If you have backed this fundraiser, and haven&apos;t provided your personal details yet, please do so quickly so that your rewards can be sent! +I am hoping that we will be able to make good use of all that money. The details of the expenses will be published regularly on the 2013 Fundraiser wiki page, giving you full disclosure as to how your money is used. @@ -2508,8 +2612,8 @@ Crowdfund my salary or buy The Erlanger Playbook Tue, 28 May 2013 00:00:00 +0100 https://ninenines.eu/articles/erlang.mk-and-relx/ - Building OTP releases has always been a difficult task. Tools like Reltool or Rebar have made this simpler, but it&#8217;s no panacea. This article will show you an alternative and hopefully much simpler solution. - There is two steps to building a release. First you need to build the various OTP applications you want to include in the release. Once done, you need to create the release itself, by including the Erlang runtime system alongside the applications, a boot script to start the node and all its applications, and some configuration files. + Building OTP releases has always been a difficult task. Tools like Reltool or Rebar have made this simpler, but it&apos;s no panacea. This article will show you an alternative and hopefully much simpler solution. +There is two steps to building a release. First you need to build the various OTP applications you want to include in the release. Once done, you need to create the release itself, by including the Erlang runtime system alongside the applications, a boot script to start the node and all its applications, and some configuration files. @@ -2518,9 +2622,9 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 25 Mar 2013 00:00:00 +0100 https://ninenines.eu/articles/xerl-0.5-intermediate-module/ - Today we will start the work on the intermediate module that will be used to run the code for the expressions found in our file&#8217;s body, replacing our interpreter. - This is what we want to have when all the work is done: - xerl -&gt; tokens -&gt; AST -&gt; intermediate -&gt; cerl Today we will perform this work only on the atomic integer expression however, so we will not build any module at the end. + Today we will start the work on the intermediate module that will be used to run the code for the expressions found in our file&apos;s body, replacing our interpreter. +This is what we want to have when all the work is done: +xerl -&gt; tokens -&gt; AST -&gt; intermediate -&gt; cerl Today we will perform this work only on the atomic integer expression however, so we will not build any module at the end. @@ -2530,9 +2634,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/articles/xerl-0.4-expression-separator/ As promised we are adding an expression separator this time. This will be short and easy. - In the tokenizer we only need to add a line recognizing the comma as a valid token. - , : {token, {',', TokenLine}}. Then we need to change the following lines in the parser: - exprs -&gt; expr : ['$1']. exprs -&gt; expr exprs : ['$1' | '$2']. And add a comma between the expressions on the second line: +In the tokenizer we only need to add a line recognizing the comma as a valid token. +, : {token, {',', TokenLine}}. Then we need to change the following lines in the parser: +exprs -&gt; expr : ['$1']. exprs -&gt; expr exprs : ['$1' | '$2']. And add a comma between the expressions on the second line: @@ -2542,7 +2646,7 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/articles/erlang-scalability/ I would like to share some experience and theories on Erlang scalability. - This will be in the form of a series of hints, which may or may not be accompanied with explanations as to why things are this way, or how they improve or reduce the scalability of a system. I will try to do my best to avoid giving falsehoods, even if that means a few things won&#8217;t be explained. +This will be in the form of a series of hints, which may or may not be accompanied with explanations as to why things are this way, or how they improve or reduce the scalability of a system. I will try to do my best to avoid giving falsehoods, even if that means a few things won&apos;t be explained. @@ -2552,8 +2656,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/articles/xerl-0.3-atomic-expressions/ We will be adding atomic integer expressions to our language. These look as follow in Erlang: - 42. And the result of this expression is of course 42. - We will be running this expression at compile time, since we don&#8217;t have the means to run code at runtime yet. This will of course result in no module being compiled, but that&#8217;s OK, it will allow us to discuss a few important things we&#8217;ll have to plan for later on. +42. And the result of this expression is of course 42. +We will be running this expression at compile time, since we don&apos;t have the means to run code at runtime yet. This will of course result in no module being compiled, but that&apos;s OK, it will allow us to discuss a few important things we&apos;ll have to plan for later on. @@ -2563,10 +2667,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/articles/xerl-0.2-two-modules/ Everything is an expression. - This sentence carries profound meaning. We will invoke it many times over the course of these articles. - If everything is an expression, then the language shouldn&#8217;t have any problem with me defining two modules in the same source file. - mod first_module begin end mod second_module begin end Likewise, it shouldn&#8217;t have any problem with me defining a module inside another module. - mod out_module begin mod in_module begin end end Of course, in the context of the Erlang VM, these two snippets are equivalent; there is nothing preventing you from calling the in_module module from any other module. +This sentence carries profound meaning. We will invoke it many times over the course of these articles. +If everything is an expression, then the language shouldn&apos;t have any problem with me defining two modules in the same source file. +mod first_module begin end mod second_module begin end Likewise, it shouldn&apos;t have any problem with me defining a module inside another module. +mod out_module begin mod in_module begin end end Of course, in the context of the Erlang VM, these two snippets are equivalent; there is nothing preventing you from calling the in_module module from any other module. @@ -2575,9 +2679,9 @@ Crowdfund my salary or buy The Erlanger Playbook Wed, 30 Jan 2013 00:00:00 +0100 https://ninenines.eu/articles/xerl-0.1-empty-modules/ - Let&#8217;s build a programming language. I call it Xerl: eXtended ERLang. It&#8217;ll be an occasion for us to learn a few things, especially me. - Unlike in Erlang, in this language, everything is an expression. This means that modules and functions are expression, and indeed that you can have more than one module per file. - We are just starting, so let&#8217;s no go ahead of ourselves here. We&#8217;ll begin with writing the code allowing us to compile an empty module. + Let&apos;s build a programming language. I call it Xerl: eXtended ERLang. It&apos;ll be an occasion for us to learn a few things, especially me. +Unlike in Erlang, in this language, everything is an expression. This means that modules and functions are expression, and indeed that you can have more than one module per file. +We are just starting, so let&apos;s no go ahead of ourselves here. We&apos;ll begin with writing the code allowing us to compile an empty module. @@ -2587,7 +2691,7 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/articles/ranch-ftp/ Last week I was speaking at the London Erlang Factory Lite where I presented a live demonstration of building an FTP server using Ranch. As there was no slide, you should use this article as a reference instead. - The goal of this article is to showcase how to use Ranch for writing a network protocol implementation, how Ranch gets out of the way to let you write the code that matters, and the common techniques used when writing servers. +The goal of this article is to showcase how to use Ranch for writing a network protocol implementation, how Ranch gets out of the way to let you write the code that matters, and the common techniques used when writing servers. @@ -2597,9 +2701,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/articles/tictactoe/ Everyone knows Tic Tac Toe, right? - Players choose either to be the Xs or the Os, then place their symbol on a 3x3 board one after another, trying to create a line of 3 of them. - Writing an algorithm to check for victory sounds easy, right? It&#8217;s easily tested, considering there&#8217;s only 8 possible winning rows (3 horizontal, 3 vertical and 2 diagonal). - In Erlang though, you probably wouldn&#8217;t want an algorithm. +Players choose either to be the Xs or the Os, then place their symbol on a 3x3 board one after another, trying to create a line of 3 of them. +Writing an algorithm to check for victory sounds easy, right? It&apos;s easily tested, considering there&apos;s only 8 possible winning rows (3 horizontal, 3 vertical and 2 diagonal). +In Erlang though, you probably wouldn&apos;t want an algorithm. @@ -2609,10 +2713,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2622,10 +2726,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2635,10 +2739,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2648,10 +2752,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2661,10 +2765,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2673,7 +2777,7 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.0/guide/ - Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Migrating from Cowboy 1. + Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Migrating from Cowboy 1. @@ -2682,7 +2786,7 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.1/guide/ - Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Migrating from Cowboy 2. + Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Migrating from Cowboy 2. @@ -2691,7 +2795,7 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.2/guide/ - Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Changes since Cowboy 2. + Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Changes since Cowboy 2. @@ -2700,7 +2804,7 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.3/guide/ - Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Migrating from Cowboy 2. + Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Migrating from Cowboy 2. @@ -2709,7 +2813,7 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.4/guide/ - Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Migrating from Cowboy 2. + Rationale The modern Web Erlang and the Web Introduction Introduction Getting started Flow diagram Configuration Listeners Routing Constraints Handlers Handlers Loop handlers Static files Request and response Request details Reading the request body Sending a response Using cookies Multipart REST REST principles Handling REST requests REST flowcharts Designing a resource handler Websocket The Websocket protocol Websocket handlers Advanced Streams Middlewares Additional information Migrating from Cowboy 2. @@ -2718,7 +2822,7 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/erlang.mk/1/guide/ - Installation Getting started Overview Updating Erlang.mk Limitations Code Building Packages and dependencies NIFs and port drivers Releases Self-extracting releases Escripts OTP version management Compatibility with other build tools Documentation Asciidoc documentation EDoc comments Sphinx documentation Tests Erlang shell EUnit Common Test Triq Code coverage Continuous integration Dialyzer Xref Third-party plugins External plugins List of plugins About Erlang. + Installation Getting started Overview Updating Erlang.mk Limitations Code Building Packages and dependencies NIFs and port drivers Releases Self-extracting releases Escripts OTP version management Compatibility with other build tools Documentation Asciidoc documentation EDoc comments Sphinx documentation Tests Erlang shell EUnit Common Test Triq Code coverage Continuous integration Dialyzer Xref Third-party plugins External plugins List of plugins About Erlang. @@ -2728,9 +2832,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/ Name gun - HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP - Description Gun is an HTTP client for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Gun aims to provide an easy to use, asynchronous and always-connected client. It maintains a permanent connection to the server and reconnects automatically when necessary. - Modules gun(3) - Asynchronous HTTP client Dependencies cowlib(7) - Support library for manipulating Web protocols ssl - Secure communication over sockets All these applications must be started before the gun application. +Description Gun is an HTTP client for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Gun aims to provide an easy to use, asynchronous and always-connected client. It maintains a permanent connection to the server and reconnects automatically when necessary. +Modules gun(3) - Asynchronous HTTP client Dependencies cowlib(7) - Support library for manipulating Web protocols ssl - Secure communication over sockets All these applications must be started before the gun application. @@ -2739,7 +2843,7 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/gun/1.0/guide/ - Introduction Starting and stopping Supported protocols Connection Using HTTP Using Websocket + Introduction Starting and stopping Supported protocols Connection Using HTTP Using Websocket @@ -2749,8 +2853,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/http_status_codes/ Name HTTP status codes - status codes used by Cowboy - Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. - 100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. +Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. +100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. This behavior can be disabled using the appropriate body option. @@ -2760,8 +2864,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/http_status_codes/ Name HTTP status codes - status codes used by Cowboy - Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. - 100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. +Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. +100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. This behavior can be disabled using the appropriate body option. @@ -2771,8 +2875,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/http_status_codes/ Name HTTP status codes - status codes used by Cowboy - Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. - 100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. +Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. +100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. This behavior can be disabled using the appropriate body option. @@ -2782,8 +2886,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/http_status_codes/ Name HTTP status codes - status codes used by Cowboy - Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. - 100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. +Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. +100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. This behavior can be disabled using the appropriate body option. @@ -2793,8 +2897,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/http_status_codes/ Name HTTP status codes - status codes used by Cowboy - Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. - 100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. +Description This chapter aims to list all HTTP status codes that Cowboy may return, with details on the reasons why. The list given here only includes the replies that Cowboy sends, not user replies. +100 Continue When the client sends an expect: 100-continue header, Cowboy automatically sends a this status code before trying to read the request body. This behavior can be disabled using the appropriate body option. @@ -2803,7 +2907,7 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/ranch/1.2/manual/ - ranch(7) ranch(3) ranch_protocol(3) ranch_ssl(3) ranch_tcp(3) ranch_transport(3) + ranch(7) ranch(3) ranch_protocol(3) ranch_ssl(3) ranch_tcp(3) ranch_transport(3) @@ -2812,7 +2916,7 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/ranch/1.3/manual/ - ranch(7) ranch(3) ranch_protocol(3) ranch_ssl(3) ranch_tcp(3) ranch_transport(3) + ranch(7) ranch(3) ranch_protocol(3) ranch_ssl(3) ranch_tcp(3) ranch_transport(3) @@ -2821,7 +2925,16 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/ranch/1.4/manual/ - ranch(7) ranch(3) ranch_protocol(3) ranch_ssl(3) ranch_tcp(3) ranch_transport(3) + ranch(7) ranch(3) ranch_protocol(3) ranch_ssl(3) ranch_tcp(3) ranch_transport(3) + + + + Ranch Function Reference + https://ninenines.eu/docs/en/ranch/1.5/manual/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/manual/ + ranch(7) ranch(3) ranch_protocol(3) ranch_ssl(3) ranch_tcp(3) ranch_transport(3) @@ -2830,7 +2943,7 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/ranch/1.2/guide/ - Introduction Listeners Transports Protocols Embedded mode Writing parsers SSL client authentication Internals + Introduction Listeners Transports Protocols Embedded mode Writing parsers SSL client authentication Internals @@ -2839,7 +2952,7 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/ranch/1.3/guide/ - Introduction Listeners Transports Protocols Embedded mode Writing parsers SSL client authentication Internals + Introduction Listeners Transports Protocols Embedded mode Writing parsers SSL client authentication Internals @@ -2848,7 +2961,16 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/ranch/1.4/guide/ - Introduction Listeners Transports Protocols Embedded mode Writing parsers SSL client authentication Internals + Introduction Listeners Transports Protocols Embedded mode Writing parsers SSL client authentication Internals + + + + Ranch User Guide + https://ninenines.eu/docs/en/ranch/1.5/guide/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/guide/ + Introduction Listeners Transports Protocols Embedded mode Writing parsers SSL client authentication Internals @@ -2858,8 +2980,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy/ Name cowboy - HTTP server - Description The module cowboy provides convenience functions for manipulating Ranch listeners. - Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&#8217;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. +Description The module cowboy provides convenience functions for manipulating Ranch listeners. +Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&apos;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. @@ -2869,8 +2991,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy/ Name cowboy - HTTP server - Description The module cowboy provides convenience functions for manipulating Ranch listeners. - Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&#8217;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. +Description The module cowboy provides convenience functions for manipulating Ranch listeners. +Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&apos;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. @@ -2880,8 +3002,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy/ Name cowboy - HTTP server - Description The module cowboy provides convenience functions for manipulating Ranch listeners. - Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&#8217;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. +Description The module cowboy provides convenience functions for manipulating Ranch listeners. +Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&apos;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. @@ -2891,8 +3013,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy/ Name cowboy - HTTP server - Description The module cowboy provides convenience functions for manipulating Ranch listeners. - Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&#8217;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. +Description The module cowboy provides convenience functions for manipulating Ranch listeners. +Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&apos;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. @@ -2902,8 +3024,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy/ Name cowboy - HTTP server - Description The module cowboy provides convenience functions for manipulating Ranch listeners. - Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&#8217;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. +Description The module cowboy provides convenience functions for manipulating Ranch listeners. +Exports cowboy:start_clear(3) - Listen for connections using plain TCP cowboy:start_tls(3) - Listen for connections using TLS cowboy:stop_listener(3) - Stop the given listener cowboy:set_env(3) - Update a listener&apos;s environment value Types fields() fields() :: [Name | {Name, Constraints} | {Name, Constraints, Default}] Name :: atom() Constraints :: Constraint | [Constraint] Constraint :: cowboy_constraints:constraint() Default :: any() Fields description for match operations. @@ -2913,10 +3035,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_app/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2926,10 +3048,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_app/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2939,10 +3061,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_app/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2952,10 +3074,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_app/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2965,10 +3087,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_app/ Name cowboy - Small, fast, modern HTTP server for Erlang/OTP - Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. - Modules Functions: - cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: +Description Cowboy is an HTTP server for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Cowboy aims to provide a complete HTTP stack. This includes the implementation of the HTTP RFCs but also any directly related standards, like Websocket or Server-Sent Events. +Modules Functions: +cowboy(3) - Listener management cowboy_req(3) - Request and response cowboy_router(3) - Router cowboy_constraints(3) - Constraints Protocols: @@ -2977,11 +3099,11 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy.set_env/ - Name cowboy:set_env - Update a listener&#8217;s environment value - Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. - This is most useful for updating the routes dynamically, without having to restart the listener. - The new value will only be available to new connections. Pre-existing connections will still use the old value. - Arguments Name The name of the listener to update. + Name cowboy:set_env - Update a listener&apos;s environment value +Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. +This is most useful for updating the routes dynamically, without having to restart the listener. +The new value will only be available to new connections. Pre-existing connections will still use the old value. +Arguments Name The name of the listener to update. @@ -2990,11 +3112,11 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy.set_env/ - Name cowboy:set_env - Update a listener&#8217;s environment value - Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. - This is most useful for updating the routes dynamically, without having to restart the listener. - The new value will only be available to new connections. Pre-existing connections will still use the old value. - Arguments Name The name of the listener to update. + Name cowboy:set_env - Update a listener&apos;s environment value +Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. +This is most useful for updating the routes dynamically, without having to restart the listener. +The new value will only be available to new connections. Pre-existing connections will still use the old value. +Arguments Name The name of the listener to update. @@ -3003,11 +3125,11 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy.set_env/ - Name cowboy:set_env - Update a listener&#8217;s environment value - Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. - This is most useful for updating the routes dynamically, without having to restart the listener. - The new value will only be available to new connections. Pre-existing connections will still use the old value. - Arguments Name The name of the listener to update. + Name cowboy:set_env - Update a listener&apos;s environment value +Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. +This is most useful for updating the routes dynamically, without having to restart the listener. +The new value will only be available to new connections. Pre-existing connections will still use the old value. +Arguments Name The name of the listener to update. @@ -3016,11 +3138,11 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy.set_env/ - Name cowboy:set_env - Update a listener&#8217;s environment value - Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. - This is most useful for updating the routes dynamically, without having to restart the listener. - The new value will only be available to new connections. Pre-existing connections will still use the old value. - Arguments Name The name of the listener to update. + Name cowboy:set_env - Update a listener&apos;s environment value +Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. +This is most useful for updating the routes dynamically, without having to restart the listener. +The new value will only be available to new connections. Pre-existing connections will still use the old value. +Arguments Name The name of the listener to update. @@ -3029,11 +3151,11 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy.set_env/ - Name cowboy:set_env - Update a listener&#8217;s environment value - Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. - This is most useful for updating the routes dynamically, without having to restart the listener. - The new value will only be available to new connections. Pre-existing connections will still use the old value. - Arguments Name The name of the listener to update. + Name cowboy:set_env - Update a listener&apos;s environment value +Description set_env(Name :: ranch:ref(), Key :: atom(), Value :: any()) -&gt; ok Set or update an environment value for a previously started listener. +This is most useful for updating the routes dynamically, without having to restart the listener. +The new value will only be available to new connections. Pre-existing connections will still use the old value. +Arguments Name The name of the listener to update. @@ -3043,8 +3165,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy.start_clear/ Name cowboy:start_clear - Listen for connections using plain TCP - Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -3054,8 +3177,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy.start_clear/ Name cowboy:start_clear - Listen for connections using plain TCP - Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -3065,8 +3189,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy.start_clear/ Name cowboy:start_clear - Listen for connections using plain TCP - Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -3076,8 +3201,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy.start_clear/ Name cowboy:start_clear - Listen for connections using plain TCP - Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -3087,8 +3213,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy.start_clear/ Name cowboy:start_clear - Listen for connections using plain TCP - Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Description start_clear(Name :: ranch:ref(), TransportOpts :: ranch_tcp:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a clear TCP channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. HTTP/2 has two methods of establishing a connection over a clear TCP channel. Both the upgrade and the prior knowledge methods are supported. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -3098,9 +3225,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy.start_tls/ Name cowboy:start_tls - Listen for connections using TLS - Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. - Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. +Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -3110,9 +3237,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy.start_tls/ Name cowboy:start_tls - Listen for connections using TLS - Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. - Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. +Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -3122,9 +3249,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy.start_tls/ Name cowboy:start_tls - Listen for connections using TLS - Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. - Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. +Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -3134,9 +3261,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy.start_tls/ Name cowboy:start_tls - Listen for connections using TLS - Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. - Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. +Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -3146,9 +3273,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy.start_tls/ Name cowboy:start_tls - Listen for connections using TLS - Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. - Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. - Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. +Description start_tls(Name :: ranch:ref(), TransportOpts :: ranch_ssl:opts(), ProtocolOpts :: opts()) -&gt; {ok, ListenerPid :: pid()} | {error, any()} Start listening for connections over a secure TLS channel. +Both HTTP/1.1 and HTTP/2 are supported on this listener. The ALPN TLS extension must be used to initiate an HTTP/2 connection. +Arguments Name The listener name is used to refer to this listener in future calls, for example when stopping it or when updating the routes defined. @@ -3158,10 +3285,12 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy.stop_listener/ Name cowboy:stop_listener - Stop the given listener - Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. - Alias of ranch:stop_listener(3). - Arguments Name The name of the listener to be stopped. The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. - Return value The atom ok is returned on success. +Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. +Alias of ranch:stop_listener(3). +Arguments Name The name of the listener to be stopped. +The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. + Return value The atom ok is returned on success. +The {error, not_found} tuple is returned when the listener does not exist. @@ -3171,10 +3300,12 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy.stop_listener/ Name cowboy:stop_listener - Stop the given listener - Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. - Alias of ranch:stop_listener(3). - Arguments Name The name of the listener to be stopped. The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. - Return value The atom ok is returned on success. +Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. +Alias of ranch:stop_listener(3). +Arguments Name The name of the listener to be stopped. +The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. + Return value The atom ok is returned on success. +The {error, not_found} tuple is returned when the listener does not exist. @@ -3184,10 +3315,12 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy.stop_listener/ Name cowboy:stop_listener - Stop the given listener - Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. - Alias of ranch:stop_listener(3). - Arguments Name The name of the listener to be stopped. The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. - Return value The atom ok is returned on success. +Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. +Alias of ranch:stop_listener(3). +Arguments Name The name of the listener to be stopped. +The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. + Return value The atom ok is returned on success. +The {error, not_found} tuple is returned when the listener does not exist. @@ -3197,10 +3330,12 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy.stop_listener/ Name cowboy:stop_listener - Stop the given listener - Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. - Alias of ranch:stop_listener(3). - Arguments Name The name of the listener to be stopped. The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. - Return value The atom ok is returned on success. +Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. +Alias of ranch:stop_listener(3). +Arguments Name The name of the listener to be stopped. +The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. + Return value The atom ok is returned on success. +The {error, not_found} tuple is returned when the listener does not exist. @@ -3210,10 +3345,12 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy.stop_listener/ Name cowboy:stop_listener - Stop the given listener - Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. - Alias of ranch:stop_listener(3). - Arguments Name The name of the listener to be stopped. The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. - Return value The atom ok is returned on success. +Description stop_listener(Name :: ranch:ref()) -&gt; ok | {error, not_found}. Stop a previously started listener. +Alias of ranch:stop_listener(3). +Arguments Name The name of the listener to be stopped. +The name of the listener is the first argument given to the cowboy:start_clear(3), cowboy:start_tls(3) or ranch:start_listener(3) function. + Return value The atom ok is returned on success. +The {error, not_found} tuple is returned when the listener does not exist. @@ -3223,10 +3360,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_constraints/ Name cowboy_constraints - Constraints - Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. - Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. - Exports Built-in constraints: - cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. +Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. +Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. +Exports Built-in constraints: +cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. @@ -3236,10 +3373,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_constraints/ Name cowboy_constraints - Constraints - Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. - Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. - Exports Built-in constraints: - cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. +Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. +Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. +Exports Built-in constraints: +cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. @@ -3249,10 +3386,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_constraints/ Name cowboy_constraints - Constraints - Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. - Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. - Exports Built-in constraints: - cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. +Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. +Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. +Exports Built-in constraints: +cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. @@ -3262,10 +3399,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_constraints/ Name cowboy_constraints - Constraints - Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. - Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. - Exports Built-in constraints: - cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. +Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. +Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. +Exports Built-in constraints: +cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. @@ -3275,10 +3412,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_constraints/ Name cowboy_constraints - Constraints - Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. - Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. - Exports Built-in constraints: - cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. +Description The module cowboy_constraints defines the built-in constraints in Cowboy and provides an interface for manipulating these constraints. +Constraints are functions that define what type of input is allowed. They are used throughout Cowboy, from the router to query strings to cookies. +Exports Built-in constraints: +cowboy_constraints:int(3) - Integer constraint cowboy_constraints:nonempty(3) - Non-empty constraint Types constraint() constraint() :: int | nonempty | fun() A constraint function. @@ -3288,10 +3425,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_constraints.int/ Name cowboy_constraints:int - Integer constraint - Description Constraint functions implement a number of different operations. - int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. - int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. - int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. +Description Constraint functions implement a number of different operations. +int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. +int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. +int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. @@ -3301,10 +3438,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_constraints.int/ Name cowboy_constraints:int - Integer constraint - Description Constraint functions implement a number of different operations. - int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. - int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. - int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. +Description Constraint functions implement a number of different operations. +int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. +int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. +int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. @@ -3314,10 +3451,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_constraints.int/ Name cowboy_constraints:int - Integer constraint - Description Constraint functions implement a number of different operations. - int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. - int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. - int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. +Description Constraint functions implement a number of different operations. +int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. +int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. +int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. @@ -3327,10 +3464,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_constraints.int/ Name cowboy_constraints:int - Integer constraint - Description Constraint functions implement a number of different operations. - int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. - int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. - int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. +Description Constraint functions implement a number of different operations. +int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. +int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. +int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. @@ -3340,10 +3477,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_constraints.int/ Name cowboy_constraints:int - Integer constraint - Description Constraint functions implement a number of different operations. - int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. - int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. - int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. +Description Constraint functions implement a number of different operations. +int(forward, Bin) -&gt; {ok, Int} | {error, not_an_integer} Bin :: binary() Int :: integer() Validate and convert the text representation of an integer. +int(reverse, Int) -&gt; {ok, Bin} | {error, not_an_integer} Convert an integer back to its text representation. +int(format_error, Error) -&gt; HumanReadable Error :: {not_an_integer, Bin | Int} HumanReadable :: iolist() Generate a human-readable error message. @@ -3353,11 +3490,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_constraints.nonempty/ Name cowboy_constraints:nonempty - Non-empty constraint - Description Constraint functions implement a number of different operations. - nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. - nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. - nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. - Arguments Arguments vary depending on the operation. +Description Constraint functions implement a number of different operations. +nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. +nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. +nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. +Arguments Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument. @@ -3367,11 +3504,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_constraints.nonempty/ Name cowboy_constraints:nonempty - Non-empty constraint - Description Constraint functions implement a number of different operations. - nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. - nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. - nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. - Arguments Arguments vary depending on the operation. +Description Constraint functions implement a number of different operations. +nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. +nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. +nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. +Arguments Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument. @@ -3381,11 +3518,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_constraints.nonempty/ Name cowboy_constraints:nonempty - Non-empty constraint - Description Constraint functions implement a number of different operations. - nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. - nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. - nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. - Arguments Arguments vary depending on the operation. +Description Constraint functions implement a number of different operations. +nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. +nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. +nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. +Arguments Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument. @@ -3395,11 +3532,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_constraints.nonempty/ Name cowboy_constraints:nonempty - Non-empty constraint - Description Constraint functions implement a number of different operations. - nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. - nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. - nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. - Arguments Arguments vary depending on the operation. +Description Constraint functions implement a number of different operations. +nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. +nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. +nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. +Arguments Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument. @@ -3409,11 +3546,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_constraints.nonempty/ Name cowboy_constraints:nonempty - Non-empty constraint - Description Constraint functions implement a number of different operations. - nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. - nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. - nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. - Arguments Arguments vary depending on the operation. +Description Constraint functions implement a number of different operations. +nonempty(forward | reverse, &lt;&lt;&gt;&gt;) -&gt; {error, empty} Reject empty values. +nonempty(forward | reverse, Bin) -&gt; {ok, Bin} Bin :: binary() Accept any other binary values. +nonempty(format_error, Error) -&gt; HumanReadable Error :: {empty, Bin} HumanReadable :: iolist() Generate a human-readable error message. +Arguments Arguments vary depending on the operation. Constraint functions always take the operation type as first argument, and the value as second argument. @@ -3423,9 +3560,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_handler/ Name cowboy_handler - Plain HTTP handlers - Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. - This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. - This module also defines a callback interface for handling HTTP requests. +Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. +This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. +This module also defines a callback interface for handling HTTP requests. @@ -3435,9 +3572,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_handler/ Name cowboy_handler - Plain HTTP handlers - Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. - This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. - This module also defines a callback interface for handling HTTP requests. +Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. +This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. +This module also defines a callback interface for handling HTTP requests. @@ -3447,9 +3584,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_handler/ Name cowboy_handler - Plain HTTP handlers - Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. - This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. - This module also defines a callback interface for handling HTTP requests. +Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. +This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. +This module also defines a callback interface for handling HTTP requests. @@ -3459,9 +3596,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_handler/ Name cowboy_handler - Plain HTTP handlers - Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. - This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. - This module also defines a callback interface for handling HTTP requests. +Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. +This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. +This module also defines a callback interface for handling HTTP requests. @@ -3471,9 +3608,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_handler/ Name cowboy_handler - Plain HTTP handlers - Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. - This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. - This module also defines a callback interface for handling HTTP requests. +Description The cowboy_handler middleware executes the handler selected by the router or any other preceding middleware. +This middleware takes the handler module and initial state from the handler and handler_opts environment values, respectively. On completion, it adds a result value to the middleware environment, containing the return value of the terminate/3 callback (if defined) and ok otherwise. +This module also defines a callback interface for handling HTTP requests. @@ -3483,9 +3620,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_handler.terminate/ Name cowboy_handler:terminate - Terminate the handler - Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. - Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. - Arguments Reason Reason for termination. PartialReq The Req object. +Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. +Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. +Arguments Reason Reason for termination. + PartialReq The Req object. +It is possible to remove fields from the Req object to save memory when the handler has no concept of requests/responses. @@ -3495,9 +3634,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_handler.terminate/ Name cowboy_handler:terminate - Terminate the handler - Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. - Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. - Arguments Reason Reason for termination. PartialReq The Req object. +Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. +Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. +Arguments Reason Reason for termination. + PartialReq The Req object. +It is possible to remove fields from the Req object to save memory when the handler has no concept of requests/responses. @@ -3507,9 +3648,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_handler.terminate/ Name cowboy_handler:terminate - Terminate the handler - Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. - Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. - Arguments Reason Reason for termination. PartialReq The Req object. +Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. +Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. +Arguments Reason Reason for termination. + PartialReq The Req object. +It is possible to remove fields from the Req object to save memory when the handler has no concept of requests/responses. @@ -3519,9 +3662,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_handler.terminate/ Name cowboy_handler:terminate - Terminate the handler - Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. - Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. - Arguments Reason Reason for termination. PartialReq The Req object. +Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. +Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. +Arguments Reason Reason for termination. + PartialReq The Req object. +It is possible to remove fields from the Req object to save memory when the handler has no concept of requests/responses. @@ -3531,9 +3676,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_handler.terminate/ Name cowboy_handler:terminate - Terminate the handler - Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. - Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. - Arguments Reason Reason for termination. PartialReq The Req object. +Description terminate(Reason, PartialReq, State, Handler) -&gt; ok Reason :: any() PartialReq :: map() State :: any() Handler :: module() Call the optional terminate callback if it is defined. +Make sure to use this function at the end of the execution of modules that implement custom handler behaviors. +Arguments Reason Reason for termination. + PartialReq The Req object. +It is possible to remove fields from the Req object to save memory when the handler has no concept of requests/responses. @@ -3543,8 +3690,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_http/ Name cowboy_http - HTTP/1.1 - Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. +Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. @@ -3554,8 +3701,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_http/ Name cowboy_http - HTTP/1.1 - Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. +Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. @@ -3565,8 +3712,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_http/ Name cowboy_http - HTTP/1.1 - Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), max_skip_body_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. +Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), max_skip_body_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. @@ -3576,8 +3723,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_http/ Name cowboy_http - HTTP/1.1 - Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), max_skip_body_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. +Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), max_skip_body_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. @@ -3587,8 +3734,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_http/ Name cowboy_http - HTTP/1.1 - Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), max_skip_body_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. +Description The module cowboy_http implements HTTP/1.1 and HTTP/1.0 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), idle_timeout =&gt; timeout(), inactivity_timeout =&gt; timeout(), max_empty_lines =&gt; non_neg_integer(), max_header_name_length =&gt; non_neg_integer(), max_header_value_length =&gt; non_neg_integer(), max_headers =&gt; non_neg_integer(), max_keepalive =&gt; non_neg_integer(), max_method_length =&gt; non_neg_integer(), max_request_line_length =&gt; non_neg_integer(), max_skip_body_length =&gt; non_neg_integer(), middlewares =&gt; [module()], request_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/1. @@ -3598,10 +3745,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_http2/ Name cowboy_http2 - HTTP/2 - Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), middlewares =&gt; [module()], preface_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. - This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions. - It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2. +Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), middlewares =&gt; [module()], preface_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. +This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions. +It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2. @@ -3611,10 +3758,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_http2/ Name cowboy_http2 - HTTP/2 - Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), middlewares =&gt; [module()], preface_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. - This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions. - It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2. +Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), middlewares =&gt; [module()], preface_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. +This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions. +It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2. @@ -3624,10 +3771,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_http2/ Name cowboy_http2 - HTTP/2 - Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), middlewares =&gt; [module()], preface_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. - This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions. - It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2. +Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), middlewares =&gt; [module()], preface_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. +This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions. +It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2. @@ -3637,10 +3784,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_http2/ Name cowboy_http2 - HTTP/2 - Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), middlewares =&gt; [module()], preface_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. - This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions. - It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2. +Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), middlewares =&gt; [module()], preface_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. +This configuration is passed to Cowboy when starting listeners using cowboy:start_clear/3 or cowboy:start_tls/3 functions. +It can be updated without restarting listeners using the Ranch functions ranch:get_protocol_options/1 and ranch:set_protocol_options/2. @@ -3650,8 +3797,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_http2/ Name cowboy_http2 - HTTP/2 - Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. - Options opts() :: #{ connection_type =&gt; worker | supervisor, enable_connect_protocol =&gt; boolean(), env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), initial_connection_window_size =&gt; 65535..16#7fffffff, initial_stream_window_size =&gt; 0..16#7fffffff, max_concurrent_streams =&gt; non_neg_integer() | infinity, max_decode_table_size =&gt; non_neg_integer(), max_encode_table_size =&gt; non_neg_integer(), max_frame_size_received =&gt; 16384..16777215, max_frame_size_sent =&gt; 16384..16777215 | infinity, middlewares =&gt; [module()], preface_timeout =&gt; timeout(), settings_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. +Description The module cowboy_http2 implements HTTP/2 as a Ranch protocol. +Options opts() :: #{ connection_type =&gt; worker | supervisor, enable_connect_protocol =&gt; boolean(), env =&gt; cowboy_middleware:env(), inactivity_timeout =&gt; timeout(), initial_connection_window_size =&gt; 65535..16#7fffffff, initial_stream_window_size =&gt; 0..16#7fffffff, max_concurrent_streams =&gt; non_neg_integer() | infinity, max_decode_table_size =&gt; non_neg_integer(), max_encode_table_size =&gt; non_neg_integer(), max_frame_size_received =&gt; 16384..16777215, max_frame_size_sent =&gt; 16384..16777215 | infinity, middlewares =&gt; [module()], preface_timeout =&gt; timeout(), settings_timeout =&gt; timeout(), shutdown_timeout =&gt; timeout(), stream_handlers =&gt; [module()] } Configuration for the HTTP/2 protocol. @@ -3661,10 +3808,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_loop/ Name cowboy_loop - Loop handlers - Description The module cowboy_loop defines a callback interface for long running HTTP connections. - You should switch to this behavior for long polling, server-sent events and similar long-running requests. - There are generally two usage patterns: - Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). +Description The module cowboy_loop defines a callback interface for long running HTTP connections. +You should switch to this behavior for long polling, server-sent events and similar long-running requests. +There are generally two usage patterns: +Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). @@ -3674,10 +3821,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_loop/ Name cowboy_loop - Loop handlers - Description The module cowboy_loop defines a callback interface for long running HTTP connections. - You should switch to this behavior for long polling, server-sent events and similar long-running requests. - There are generally two usage patterns: - Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). +Description The module cowboy_loop defines a callback interface for long running HTTP connections. +You should switch to this behavior for long polling, server-sent events and similar long-running requests. +There are generally two usage patterns: +Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). @@ -3687,10 +3834,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_loop/ Name cowboy_loop - Loop handlers - Description The module cowboy_loop defines a callback interface for long running HTTP connections. - You should switch to this behavior for long polling, server-sent events and similar long-running requests. - There are generally two usage patterns: - Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). +Description The module cowboy_loop defines a callback interface for long running HTTP connections. +You should switch to this behavior for long polling, server-sent events and similar long-running requests. +There are generally two usage patterns: +Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). @@ -3700,10 +3847,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_loop/ Name cowboy_loop - Loop handlers - Description The module cowboy_loop defines a callback interface for long running HTTP connections. - You should switch to this behavior for long polling, server-sent events and similar long-running requests. - There are generally two usage patterns: - Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). +Description The module cowboy_loop defines a callback interface for long running HTTP connections. +You should switch to this behavior for long polling, server-sent events and similar long-running requests. +There are generally two usage patterns: +Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). @@ -3713,10 +3860,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_loop/ Name cowboy_loop - Loop handlers - Description The module cowboy_loop defines a callback interface for long running HTTP connections. - You should switch to this behavior for long polling, server-sent events and similar long-running requests. - There are generally two usage patterns: - Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). +Description The module cowboy_loop defines a callback interface for long running HTTP connections. +You should switch to this behavior for long polling, server-sent events and similar long-running requests. +There are generally two usage patterns: +Loop until receiving a specific message, then send a response and stop execution (for example long polling); Or initiate a response in init/2 and stream the body in info/3 as necessary (for example server-sent events). @@ -3726,10 +3873,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_middleware/ Name cowboy_middleware - Middlewares - Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. - Middlewares process the request sequentially in the order they are configured. - Callbacks Middlewares implement the following interface: - execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. +Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. +Middlewares process the request sequentially in the order they are configured. +Callbacks Middlewares implement the following interface: +execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. It must execute the middleware and return with instructions for Cowboy. @@ -3739,10 +3886,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_middleware/ Name cowboy_middleware - Middlewares - Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. - Middlewares process the request sequentially in the order they are configured. - Callbacks Middlewares implement the following interface: - execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. +Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. +Middlewares process the request sequentially in the order they are configured. +Callbacks Middlewares implement the following interface: +execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. It must execute the middleware and return with instructions for Cowboy. @@ -3752,10 +3899,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_middleware/ Name cowboy_middleware - Middlewares - Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. - Middlewares process the request sequentially in the order they are configured. - Callbacks Middlewares implement the following interface: - execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. +Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. +Middlewares process the request sequentially in the order they are configured. +Callbacks Middlewares implement the following interface: +execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. It must execute the middleware and return with instructions for Cowboy. @@ -3765,10 +3912,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_middleware/ Name cowboy_middleware - Middlewares - Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. - Middlewares process the request sequentially in the order they are configured. - Callbacks Middlewares implement the following interface: - execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. +Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. +Middlewares process the request sequentially in the order they are configured. +Callbacks Middlewares implement the following interface: +execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. It must execute the middleware and return with instructions for Cowboy. @@ -3778,10 +3925,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_middleware/ Name cowboy_middleware - Middlewares - Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. - Middlewares process the request sequentially in the order they are configured. - Callbacks Middlewares implement the following interface: - execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. +Description The module cowboy_middleware defines a callback interface for Cowboy middlewares. +Middlewares process the request sequentially in the order they are configured. +Callbacks Middlewares implement the following interface: +execute(Req, Env) -&gt; {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} Req :: cowboy_req:req() Env :: cowboy_middleware:env() The execute/2 is the only callback that needs to be implemented. It must execute the middleware and return with instructions for Cowboy. @@ -3791,12 +3938,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req/ Name cowboy_req - HTTP request and response - Description The module cowboy_req provides functions to access, manipulate and respond to requests. - There are four types of functions in this module. They can be differentiated by their name and their return type: - Type Name pattern Return type access - no verb, parse_*, match_* - Value - question +Description The module cowboy_req provides functions to access, manipulate and respond to requests. +There are four types of functions in this module. They can be differentiated by their name and their return type: +Type Name pattern Return type access no verb, parse_*, match_* Value question has_* boolean() modification set_* Req action any other verb ok | {Result, Value, Req} Any Req returned must be used in place of the one passed as argument. @@ -3806,12 +3950,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req/ Name cowboy_req - HTTP request and response - Description The module cowboy_req provides functions to access, manipulate and respond to requests. - There are four types of functions in this module. They can be differentiated by their name and their return type: - Type Name pattern Return type access - no verb, parse_*, match_* - Value - question +Description The module cowboy_req provides functions to access, manipulate and respond to requests. +There are four types of functions in this module. They can be differentiated by their name and their return type: +Type Name pattern Return type access no verb, parse_*, match_* Value question has_* boolean() modification set_* Req action any other verb ok | {Result, Value, Req} Any Req returned must be used in place of the one passed as argument. @@ -3821,12 +3962,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req/ Name cowboy_req - HTTP request and response - Description The module cowboy_req provides functions to access, manipulate and respond to requests. - There are four types of functions in this module. They can be differentiated by their name and their return type: - Type Name pattern Return type access - no verb, parse_*, match_* - Value - question +Description The module cowboy_req provides functions to access, manipulate and respond to requests. +There are four types of functions in this module. They can be differentiated by their name and their return type: +Type Name pattern Return type access no verb, parse_*, match_* Value question has_* boolean() modification set_* Req action any other verb ok | {Result, Value, Req} Any Req returned must be used in place of the one passed as argument. @@ -3836,12 +3974,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req/ Name cowboy_req - HTTP request and response - Description The module cowboy_req provides functions to access, manipulate and respond to requests. - There are four types of functions in this module. They can be differentiated by their name and their return type: - Type Name pattern Return type access - no verb, parse_*, match_* - Value - question +Description The module cowboy_req provides functions to access, manipulate and respond to requests. +There are four types of functions in this module. They can be differentiated by their name and their return type: +Type Name pattern Return type access no verb, parse_*, match_* Value question has_* boolean() modification set_* Req action any other verb ok | {Result, Value, Req} Any Req returned must be used in place of the one passed as argument. @@ -3851,12 +3986,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req/ Name cowboy_req - HTTP request and response - Description The module cowboy_req provides functions to access, manipulate and respond to requests. - There are four types of functions in this module. They can be differentiated by their name and their return type: - Type Name pattern Return type access - no verb, parse_*, match_* - Value - question +Description The module cowboy_req provides functions to access, manipulate and respond to requests. +There are four types of functions in this module. They can be differentiated by their name and their return type: +Type Name pattern Return type access no verb, parse_*, match_* Value question has_* boolean() modification set_* Req action any other verb ok | {Result, Value, Req} Any Req returned must be used in place of the one passed as argument. @@ -3866,8 +3998,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.binding/ Name cowboy_req:binding - Access a value bound from the route - Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. - Arguments Name Desired binding name as an atom. Req The Req object. Default Default value returned when the binding is missing. +Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. +Arguments Name Desired binding name as an atom. + Req The Req object. + Default Default value returned when the binding is missing. + Return value By default the value is a case sensitive binary string, however constraints may change the type of this value (for example automatically converting numbers to integer). @@ -3877,8 +4012,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.binding/ Name cowboy_req:binding - Access a value bound from the route - Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. - Arguments Name Desired binding name as an atom. Req The Req object. Default Default value returned when the binding is missing. +Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. +Arguments Name Desired binding name as an atom. + Req The Req object. + Default Default value returned when the binding is missing. + Return value By default the value is a case sensitive binary string, however constraints may change the type of this value (for example automatically converting numbers to integer). @@ -3888,8 +4026,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.binding/ Name cowboy_req:binding - Access a value bound from the route - Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. - Arguments Name Desired binding name as an atom. Req The Req object. Default Default value returned when the binding is missing. +Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. +Arguments Name Desired binding name as an atom. + Req The Req object. + Default Default value returned when the binding is missing. + Return value By default the value is a case sensitive binary string, however constraints may change the type of this value (for example automatically converting numbers to integer). @@ -3899,8 +4040,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.binding/ Name cowboy_req:binding - Access a value bound from the route - Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. - Arguments Name Desired binding name as an atom. Req The Req object. Default Default value returned when the binding is missing. +Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. +Arguments Name Desired binding name as an atom. + Req The Req object. + Default Default value returned when the binding is missing. + Return value By default the value is a case sensitive binary string, however constraints may change the type of this value (for example automatically converting numbers to integer). @@ -3910,8 +4054,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.binding/ Name cowboy_req:binding - Access a value bound from the route - Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. - Arguments Name Desired binding name as an atom. Req The Req object. Default Default value returned when the binding is missing. +Description binding(Name, Req) -&gt; binding(Name, Req, undefined) binding(Name, Req, Default) -&gt; any() | Default Name :: atom() Req :: cowboy_req:req() Default :: any() Return the value for the given binding. +Arguments Name Desired binding name as an atom. + Req The Req object. + Default Default value returned when the binding is missing. + Return value By default the value is a case sensitive binary string, however constraints may change the type of this value (for example automatically converting numbers to integer). @@ -3921,9 +4068,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.bindings/ Name cowboy_req:bindings - Access all values bound from the route - Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. - Arguments Req The Req object. Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). - Changelog 2. +Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. +Arguments Req The Req object. + Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). +Changelog 2.0: Only the values are returned, they are no longer wrapped in a tuple. @@ -3933,9 +4081,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.bindings/ Name cowboy_req:bindings - Access all values bound from the route - Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. - Arguments Req The Req object. Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). - Changelog 2. +Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. +Arguments Req The Req object. + Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). +Changelog 2.0: Only the values are returned, they are no longer wrapped in a tuple. @@ -3945,9 +4094,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.bindings/ Name cowboy_req:bindings - Access all values bound from the route - Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. - Arguments Req The Req object. Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). - Changelog 2. +Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. +Arguments Req The Req object. + Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). +Changelog 2.0: Only the values are returned, they are no longer wrapped in a tuple. @@ -3957,9 +4107,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.bindings/ Name cowboy_req:bindings - Access all values bound from the route - Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. - Arguments Req The Req object. Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). - Changelog 2. +Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. +Arguments Req The Req object. + Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). +Changelog 2.0: Only the values are returned, they are no longer wrapped in a tuple. @@ -3969,9 +4120,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.bindings/ Name cowboy_req:bindings - Access all values bound from the route - Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. - Arguments Req The Req object. Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). - Changelog 2. +Description bindings(Req :: cowboy_req:req()) -&gt; cowboy_router:bindings() Return a map containing all bindings. +Arguments Req The Req object. + Return value By default values are case sensitive binary strings, however constraints may change the type of this value (for example automatically converting numbers to integer). +Changelog 2.0: Only the values are returned, they are no longer wrapped in a tuple. @@ -3981,9 +4133,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.body_length/ Name cowboy_req:body_length - Body length - Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. - The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. - Arguments Req The Req object. Return value The length of the request body, or undefined if it is not known. +Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. +The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. +Arguments Req The Req object. + Return value The length of the request body, or undefined if it is not known. @@ -3993,9 +4146,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.body_length/ Name cowboy_req:body_length - Body length - Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. - The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. - Arguments Req The Req object. Return value The length of the request body, or undefined if it is not known. +Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. +The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. +Arguments Req The Req object. + Return value The length of the request body, or undefined if it is not known. @@ -4005,9 +4159,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.body_length/ Name cowboy_req:body_length - Body length - Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. - The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. - Arguments Req The Req object. Return value The length of the request body, or undefined if it is not known. +Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. +The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. +Arguments Req The Req object. + Return value The length of the request body, or undefined if it is not known. @@ -4017,9 +4172,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.body_length/ Name cowboy_req:body_length - Body length - Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. - The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. - Arguments Req The Req object. Return value The length of the request body, or undefined if it is not known. +Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. +The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. +Arguments Req The Req object. + Return value The length of the request body, or undefined if it is not known. @@ -4029,9 +4185,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.body_length/ Name cowboy_req:body_length - Body length - Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. - The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. - Arguments Req The Req object. Return value The length of the request body, or undefined if it is not known. +Description body_length(Req :: cowboy_req:req()) -&gt; undefined | non_neg_integer() Return the length of the request body. +The length is not always known before reading the body. In those cases Cowboy will return undefined. The body length is available after the body has been fully read. +Arguments Req The Req object. + Return value The length of the request body, or undefined if it is not known. @@ -4041,9 +4198,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.cert/ Name cowboy_req:cert - Client TLS certificate - Description cert(Req :: cowboy_req:req()) -&gt; binary() | undefined Return the peer&#8217;s TLS certificate. - Using the default configuration this function will always return undefined. You need to explicitly configure Cowboy to request the client certificate. To do this you need to set the verify transport option to verify_peer: - {ok, _} = cowboy:start_tls(example, [ {port, 8443}, {cert, "path/to/cert.pem"}, {verify, verify_peer} ], #{ env =&gt; #{dispatch =&gt; Dispatch} }). +Description cert(Req :: cowboy_req:req()) -&gt; binary() | undefined Return the peer&apos;s TLS certificate. +Using the default configuration this function will always return undefined. You need to explicitly configure Cowboy to request the client certificate. To do this you need to set the verify transport option to verify_peer: +{ok, _} = cowboy:start_tls(example, [ {port, 8443}, {cert, "path/to/cert.pem"}, {verify, verify_peer} ], #{ env =&gt; #{dispatch =&gt; Dispatch} }). @@ -4053,9 +4210,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.cert/ Name cowboy_req:cert - Client TLS certificate - Description cert(Req :: cowboy_req:req()) -&gt; binary() | undefined Return the peer&#8217;s TLS certificate. - Using the default configuration this function will always return undefined. You need to explicitly configure Cowboy to request the client certificate. To do this you need to set the verify transport option to verify_peer: - {ok, _} = cowboy:start_tls(example, [ {port, 8443}, {cert, "path/to/cert.pem"}, {verify, verify_peer} ], #{ env =&gt; #{dispatch =&gt; Dispatch} }). +Description cert(Req :: cowboy_req:req()) -&gt; binary() | undefined Return the peer&apos;s TLS certificate. +Using the default configuration this function will always return undefined. You need to explicitly configure Cowboy to request the client certificate. To do this you need to set the verify transport option to verify_peer: +{ok, _} = cowboy:start_tls(example, [ {port, 8443}, {cert, "path/to/cert.pem"}, {verify, verify_peer} ], #{ env =&gt; #{dispatch =&gt; Dispatch} }). @@ -4065,9 +4222,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.cert/ Name cowboy_req:cert - Client TLS certificate - Description cert(Req :: cowboy_req:req()) -&gt; binary() | undefined Return the peer&#8217;s TLS certificate. - Using the default configuration this function will always return undefined. You need to explicitly configure Cowboy to request the client certificate. To do this you need to set the verify transport option to verify_peer: - {ok, _} = cowboy:start_tls(example, [ {port, 8443}, {cert, "path/to/cert.pem"}, {verify, verify_peer} ], #{ env =&gt; #{dispatch =&gt; Dispatch} }). +Description cert(Req :: cowboy_req:req()) -&gt; binary() | undefined Return the peer&apos;s TLS certificate. +Using the default configuration this function will always return undefined. You need to explicitly configure Cowboy to request the client certificate. To do this you need to set the verify transport option to verify_peer: +{ok, _} = cowboy:start_tls(example, [ {port, 8443}, {cert, "path/to/cert.pem"}, {verify, verify_peer} ], #{ env =&gt; #{dispatch =&gt; Dispatch} }). @@ -4077,9 +4234,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.cert/ Name cowboy_req:cert - Client TLS certificate - Description cert(Req :: cowboy_req:req()) -&gt; binary() | undefined Return the peer&#8217;s TLS certificate. - Using the default configuration this function will always return undefined. You need to explicitly configure Cowboy to request the client certificate. To do this you need to set the verify transport option to verify_peer: - {ok, _} = cowboy:start_tls(example, [ {port, 8443}, {cert, "path/to/cert.pem"}, {verify, verify_peer} ], #{ env =&gt; #{dispatch =&gt; Dispatch} }). +Description cert(Req :: cowboy_req:req()) -&gt; binary() | undefined Return the peer&apos;s TLS certificate. +Using the default configuration this function will always return undefined. You need to explicitly configure Cowboy to request the client certificate. To do this you need to set the verify transport option to verify_peer: +{ok, _} = cowboy:start_tls(example, [ {port, 8443}, {cert, "path/to/cert.pem"}, {verify, verify_peer} ], #{ env =&gt; #{dispatch =&gt; Dispatch} }). @@ -4089,9 +4246,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.delete_resp_header/ Name cowboy_req:delete_resp_header - Delete a response header - Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. + Req The Req object. + Return value A new Req object is returned. @@ -4101,9 +4260,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.delete_resp_header/ Name cowboy_req:delete_resp_header - Delete a response header - Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. + Req The Req object. + Return value A new Req object is returned. @@ -4113,9 +4274,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.delete_resp_header/ Name cowboy_req:delete_resp_header - Delete a response header - Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. + Req The Req object. + Return value A new Req object is returned. @@ -4125,9 +4288,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.delete_resp_header/ Name cowboy_req:delete_resp_header - Delete a response header - Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. + Req The Req object. + Return value A new Req object is returned. @@ -4137,9 +4302,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.delete_resp_header/ Name cowboy_req:delete_resp_header - Delete a response header - Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description delete_resp_header(Name, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Delete the given response header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. + Req The Req object. + Return value A new Req object is returned. @@ -4149,9 +4316,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.has_body/ Name cowboy_req:has_body - Is there a request body? - Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. - Arguments Req The Req object. Return value A boolean indicating whether the request has a body. - Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). +Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. +Arguments Req The Req object. + Return value A boolean indicating whether the request has a body. +Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). See also cowboy_req(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3) @@ -4161,9 +4329,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.has_body/ Name cowboy_req:has_body - Is there a request body? - Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. - Arguments Req The Req object. Return value A boolean indicating whether the request has a body. - Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). +Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. +Arguments Req The Req object. + Return value A boolean indicating whether the request has a body. +Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). See also cowboy_req(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3) @@ -4173,9 +4342,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.has_body/ Name cowboy_req:has_body - Is there a request body? - Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. - Arguments Req The Req object. Return value A boolean indicating whether the request has a body. - Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). +Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. +Arguments Req The Req object. + Return value A boolean indicating whether the request has a body. +Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). See also cowboy_req(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3) @@ -4185,9 +4355,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.has_body/ Name cowboy_req:has_body - Is there a request body? - Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. - Arguments Req The Req object. Return value A boolean indicating whether the request has a body. - Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). +Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. +Arguments Req The Req object. + Return value A boolean indicating whether the request has a body. +Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). See also cowboy_req(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3) @@ -4197,9 +4368,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.has_body/ Name cowboy_req:has_body - Is there a request body? - Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. - Arguments Req The Req object. Return value A boolean indicating whether the request has a body. - Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). +Description has_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether the request has a body. +Arguments Req The Req object. + Return value A boolean indicating whether the request has a body. +Changelog 1.0: Function introduced. Examples Ensure the request has a body true = cowboy_req:has_body(Req). See also cowboy_req(3), cowboy_req:body_length(3), cowboy_req:read_body(3), cowboy_req:read_urlencoded_body(3), cowboy_req:read_part(3), cowboy_req:read_part_body(3) @@ -4209,10 +4381,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.has_resp_body/ Name cowboy_req:has_resp_body - Is there a response body? - Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. - Arguments Req The Req object. Return value A boolean indicating whether a response body has been set. - This function will return false when an empty response body has been set. - Changelog 1. +Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. +Arguments Req The Req object. + Return value A boolean indicating whether a response body has been set. +This function will return false when an empty response body has been set. +Changelog 1.0: Function introduced. Examples Check whether a body has been set false = cowboy_req:has_resp_body(Req0), Req1 = cowboy_req:set_resp_body(&lt;&lt;" @@ -4222,10 +4395,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.has_resp_body/ Name cowboy_req:has_resp_body - Is there a response body? - Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. - Arguments Req The Req object. Return value A boolean indicating whether a response body has been set. - This function will return false when an empty response body has been set. - Changelog 1. +Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. +Arguments Req The Req object. + Return value A boolean indicating whether a response body has been set. +This function will return false when an empty response body has been set. +Changelog 1.0: Function introduced. Examples Check whether a body has been set false = cowboy_req:has_resp_body(Req0), Req1 = cowboy_req:set_resp_body(&lt;&lt;" @@ -4235,10 +4409,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.has_resp_body/ Name cowboy_req:has_resp_body - Is there a response body? - Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. - Arguments Req The Req object. Return value A boolean indicating whether a response body has been set. - This function will return false when an empty response body has been set. - Changelog 1. +Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. +Arguments Req The Req object. + Return value A boolean indicating whether a response body has been set. +This function will return false when an empty response body has been set. +Changelog 1.0: Function introduced. Examples Check whether a body has been set false = cowboy_req:has_resp_body(Req0), Req1 = cowboy_req:set_resp_body(&lt;&lt;" @@ -4248,10 +4423,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.has_resp_body/ Name cowboy_req:has_resp_body - Is there a response body? - Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. - Arguments Req The Req object. Return value A boolean indicating whether a response body has been set. - This function will return false when an empty response body has been set. - Changelog 1. +Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. +Arguments Req The Req object. + Return value A boolean indicating whether a response body has been set. +This function will return false when an empty response body has been set. +Changelog 1.0: Function introduced. Examples Check whether a body has been set false = cowboy_req:has_resp_body(Req0), Req1 = cowboy_req:set_resp_body(&lt;&lt;" @@ -4261,10 +4437,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.has_resp_body/ Name cowboy_req:has_resp_body - Is there a response body? - Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. - Arguments Req The Req object. Return value A boolean indicating whether a response body has been set. - This function will return false when an empty response body has been set. - Changelog 1. +Description has_resp_body(Req :: cowboy_req:req()) -&gt; boolean() Return whether a response body has been set. +Arguments Req The Req object. + Return value A boolean indicating whether a response body has been set. +This function will return false when an empty response body has been set. +Changelog 1.0: Function introduced. Examples Check whether a body has been set false = cowboy_req:has_resp_body(Req0), Req1 = cowboy_req:set_resp_body(&lt;&lt;" @@ -4274,9 +4451,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.has_resp_header/ Name cowboy_req:has_resp_header - Is the given response header set? - Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. @@ -4286,9 +4463,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.has_resp_header/ Name cowboy_req:has_resp_header - Is the given response header set? - Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. @@ -4298,9 +4475,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.has_resp_header/ Name cowboy_req:has_resp_header - Is the given response header set? - Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. @@ -4310,9 +4487,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.has_resp_header/ Name cowboy_req:has_resp_header - Is the given response header set? - Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. @@ -4322,9 +4499,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.has_resp_header/ Name cowboy_req:has_resp_header - Is the given response header set? - Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Arguments Name Header name as a lowercase binary string. +Description has_resp_header(Name, Req :: cowboy_req:req()) -&gt; boolean() Name :: binary() %% lowercase; case insensitive Return whether the given response header has been set. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Arguments Name Header name as a lowercase binary string. @@ -4334,8 +4511,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.header/ Name cowboy_req:header - HTTP header - Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Headers can also be obtained using pattern matching: @@ -4345,8 +4523,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.header/ Name cowboy_req:header - HTTP header - Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Headers can also be obtained using pattern matching: @@ -4356,8 +4535,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.header/ Name cowboy_req:header - HTTP header - Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Headers can also be obtained using pattern matching: @@ -4367,8 +4547,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.header/ Name cowboy_req:header - HTTP header - Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Headers can also be obtained using pattern matching: @@ -4378,8 +4559,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.header/ Name cowboy_req:header - HTTP header - Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description header(Name, Req) -&gt; header(Name, Req, undefined) header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Headers can also be obtained using pattern matching: @@ -4389,10 +4571,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.headers/ Name cowboy_req:headers - HTTP headers - Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. - Request headers can also be obtained using pattern matching: - #{headers := Headers} = Req. Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2. +Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. +Request headers can also be obtained using pattern matching: +#{headers := Headers} = Req. Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Only the headers are returned, they are no longer wrapped in a tuple. @@ -4402,10 +4585,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.headers/ Name cowboy_req:headers - HTTP headers - Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. - Request headers can also be obtained using pattern matching: - #{headers := Headers} = Req. Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2. +Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. +Request headers can also be obtained using pattern matching: +#{headers := Headers} = Req. Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Only the headers are returned, they are no longer wrapped in a tuple. @@ -4415,10 +4599,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.headers/ Name cowboy_req:headers - HTTP headers - Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. - Request headers can also be obtained using pattern matching: - #{headers := Headers} = Req. Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2. +Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. +Request headers can also be obtained using pattern matching: +#{headers := Headers} = Req. Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Only the headers are returned, they are no longer wrapped in a tuple. @@ -4428,10 +4613,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.headers/ Name cowboy_req:headers - HTTP headers - Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. - Request headers can also be obtained using pattern matching: - #{headers := Headers} = Req. Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2. +Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. +Request headers can also be obtained using pattern matching: +#{headers := Headers} = Req. Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Only the headers are returned, they are no longer wrapped in a tuple. @@ -4441,10 +4627,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.headers/ Name cowboy_req:headers - HTTP headers - Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. - Request headers can also be obtained using pattern matching: - #{headers := Headers} = Req. Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2. +Description headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all request headers. +Request headers can also be obtained using pattern matching: +#{headers := Headers} = Req. Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Only the headers are returned, they are no longer wrapped in a tuple. @@ -4454,9 +4641,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.host/ Name cowboy_req:host - URI host name - Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. - The host name can also be obtained using pattern matching: - #{host := Host} = Req. Arguments Req The Req object. Return value The host name is returned as a lowercase binary string. It is case insensitive. +Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. +The host name can also be obtained using pattern matching: +#{host := Host} = Req. Arguments Req The Req object. + Return value The host name is returned as a lowercase binary string. It is case insensitive. +Changelog 2.0: Only the host name is returned, it is no longer wrapped in a tuple. @@ -4466,9 +4655,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.host/ Name cowboy_req:host - URI host name - Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. - The host name can also be obtained using pattern matching: - #{host := Host} = Req. Arguments Req The Req object. Return value The host name is returned as a lowercase binary string. It is case insensitive. +Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. +The host name can also be obtained using pattern matching: +#{host := Host} = Req. Arguments Req The Req object. + Return value The host name is returned as a lowercase binary string. It is case insensitive. +Changelog 2.0: Only the host name is returned, it is no longer wrapped in a tuple. @@ -4478,9 +4669,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.host/ Name cowboy_req:host - URI host name - Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. - The host name can also be obtained using pattern matching: - #{host := Host} = Req. Arguments Req The Req object. Return value The host name is returned as a lowercase binary string. It is case insensitive. +Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. +The host name can also be obtained using pattern matching: +#{host := Host} = Req. Arguments Req The Req object. + Return value The host name is returned as a lowercase binary string. It is case insensitive. +Changelog 2.0: Only the host name is returned, it is no longer wrapped in a tuple. @@ -4490,9 +4683,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.host/ Name cowboy_req:host - URI host name - Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. - The host name can also be obtained using pattern matching: - #{host := Host} = Req. Arguments Req The Req object. Return value The host name is returned as a lowercase binary string. It is case insensitive. +Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. +The host name can also be obtained using pattern matching: +#{host := Host} = Req. Arguments Req The Req object. + Return value The host name is returned as a lowercase binary string. It is case insensitive. +Changelog 2.0: Only the host name is returned, it is no longer wrapped in a tuple. @@ -4502,9 +4697,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.host/ Name cowboy_req:host - URI host name - Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. - The host name can also be obtained using pattern matching: - #{host := Host} = Req. Arguments Req The Req object. Return value The host name is returned as a lowercase binary string. It is case insensitive. +Description host(Req :: cowboy_req:req()) -&gt; Host :: binary() Return the host name of the effective request URI. +The host name can also be obtained using pattern matching: +#{host := Host} = Req. Arguments Req The Req object. + Return value The host name is returned as a lowercase binary string. It is case insensitive. +Changelog 2.0: Only the host name is returned, it is no longer wrapped in a tuple. @@ -4513,10 +4710,12 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.host_info/ - Name cowboy_req:host_info - Access the route&#8217;s heading host segments - Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case insensitive binary strings. + Name cowboy_req:host_info - Access the route&apos;s heading host segments +Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case insensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -4525,10 +4724,12 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.host_info/ - Name cowboy_req:host_info - Access the route&#8217;s heading host segments - Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case insensitive binary strings. + Name cowboy_req:host_info - Access the route&apos;s heading host segments +Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case insensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -4537,10 +4738,12 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.host_info/ - Name cowboy_req:host_info - Access the route&#8217;s heading host segments - Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case insensitive binary strings. + Name cowboy_req:host_info - Access the route&apos;s heading host segments +Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case insensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -4549,10 +4752,12 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.host_info/ - Name cowboy_req:host_info - Access the route&#8217;s heading host segments - Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case insensitive binary strings. + Name cowboy_req:host_info - Access the route&apos;s heading host segments +Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case insensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -4561,10 +4766,12 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.host_info/ - Name cowboy_req:host_info - Access the route&#8217;s heading host segments - Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case insensitive binary strings. + Name cowboy_req:host_info - Access the route&apos;s heading host segments +Description host_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the heading host segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case insensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -4574,8 +4781,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.inform/ Name cowboy_req:inform - Send an informational response - Description inform(Status, Req :: cowboy_req:req()) -&gt; inform(StatusCode, #{}, Req) inform(Status, Headers, Req :: cowboy_req:req()) -&gt; ok Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send an informational response. - Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly. +Description inform(Status, Req :: cowboy_req:req()) -&gt; inform(StatusCode, #{}, Req) inform(Status, Headers, Req :: cowboy_req:req()) -&gt; ok Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send an informational response. +Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly. +Any number of informational responses can be sent as long as they are sent before the proper response. @@ -4585,8 +4793,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.inform/ Name cowboy_req:inform - Send an informational response - Description inform(Status, Req :: cowboy_req:req()) -&gt; inform(StatusCode, #{}, Req) inform(Status, Headers, Req :: cowboy_req:req()) -&gt; ok Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send an informational response. - Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly. +Description inform(Status, Req :: cowboy_req:req()) -&gt; inform(StatusCode, #{}, Req) inform(Status, Headers, Req :: cowboy_req:req()) -&gt; ok Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send an informational response. +Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly. +Any number of informational responses can be sent as long as they are sent before the proper response. @@ -4596,8 +4805,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.inform/ Name cowboy_req:inform - Send an informational response - Description inform(Status, Req :: cowboy_req:req()) -&gt; inform(StatusCode, #{}, Req) inform(Status, Headers, Req :: cowboy_req:req()) -&gt; ok Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send an informational response. - Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly. +Description inform(Status, Req :: cowboy_req:req()) -&gt; inform(StatusCode, #{}, Req) inform(Status, Headers, Req :: cowboy_req:req()) -&gt; ok Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send an informational response. +Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly. +Any number of informational responses can be sent as long as they are sent before the proper response. @@ -4607,8 +4817,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.inform/ Name cowboy_req:inform - Send an informational response - Description inform(Status, Req :: cowboy_req:req()) -&gt; inform(StatusCode, #{}, Req) inform(Status, Headers, Req :: cowboy_req:req()) -&gt; ok Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send an informational response. - Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly. +Description inform(Status, Req :: cowboy_req:req()) -&gt; inform(StatusCode, #{}, Req) inform(Status, Headers, Req :: cowboy_req:req()) -&gt; ok Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send an informational response. +Informational responses use a status code between 100 and 199. They cannot include a body. This function will not use any of the previously set headers. All headers to be sent must be given directly. +Any number of informational responses can be sent as long as they are sent before the proper response. @@ -4618,8 +4829,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.match_cookies/ Name cowboy_req:match_cookies - Match cookies against constraints - Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. - Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. +Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. +Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. @@ -4629,8 +4840,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.match_cookies/ Name cowboy_req:match_cookies - Match cookies against constraints - Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. - Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. +Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. +Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. @@ -4640,8 +4851,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.match_cookies/ Name cowboy_req:match_cookies - Match cookies against constraints - Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. - Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. +Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. +Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. @@ -4651,8 +4862,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.match_cookies/ Name cowboy_req:match_cookies - Match cookies against constraints - Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. - Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. +Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. +Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. @@ -4662,8 +4873,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.match_cookies/ Name cowboy_req:match_cookies - Match cookies against constraints - Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. - Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. +Description match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the cookies and match specific values against constraints. +Cowboy will only return the cookie values specified in the fields list, and ignore all others. Fields can be either the name of the cookie requested; the name along with a list of constraints; or the name, a list of constraints and a default value in case the cookie is missing. @@ -4673,8 +4884,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.match_qs/ Name cowboy_req:match_qs - Match the query string against constraints - Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. - Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. +Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. +Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. @@ -4684,8 +4895,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.match_qs/ Name cowboy_req:match_qs - Match the query string against constraints - Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. - Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. +Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. +Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. @@ -4695,8 +4906,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.match_qs/ Name cowboy_req:match_qs - Match the query string against constraints - Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. - Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. +Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. +Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. @@ -4706,8 +4917,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.match_qs/ Name cowboy_req:match_qs - Match the query string against constraints - Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. - Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. +Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. +Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. @@ -4717,8 +4928,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.match_qs/ Name cowboy_req:match_qs - Match the query string against constraints - Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. - Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. +Description match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) -&gt; #{atom() =&gt; any()} Parse the query string and match specific values against constraints. +Cowboy will only return the query string values specified in the fields list, and ignore all others. Fields can be either the key requested; the key along with a list of constraints; or the key, a list of constraints and a default value in case the key is missing. @@ -4728,9 +4939,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.method/ Name cowboy_req:method - HTTP method - Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&#8217;s HTTP method. - The method can also be obtained using pattern matching: - #{method := Method} = Req. Arguments Req The Req object. Return value The request&#8217;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&apos;s HTTP method. +The method can also be obtained using pattern matching: +#{method := Method} = Req. Arguments Req The Req object. + Return value The request&apos;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Changelog 2.0: Only the method is returned, it is no longer wrapped in a tuple. @@ -4740,9 +4953,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.method/ Name cowboy_req:method - HTTP method - Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&#8217;s HTTP method. - The method can also be obtained using pattern matching: - #{method := Method} = Req. Arguments Req The Req object. Return value The request&#8217;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&apos;s HTTP method. +The method can also be obtained using pattern matching: +#{method := Method} = Req. Arguments Req The Req object. + Return value The request&apos;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Changelog 2.0: Only the method is returned, it is no longer wrapped in a tuple. @@ -4752,9 +4967,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.method/ Name cowboy_req:method - HTTP method - Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&#8217;s HTTP method. - The method can also be obtained using pattern matching: - #{method := Method} = Req. Arguments Req The Req object. Return value The request&#8217;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&apos;s HTTP method. +The method can also be obtained using pattern matching: +#{method := Method} = Req. Arguments Req The Req object. + Return value The request&apos;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Changelog 2.0: Only the method is returned, it is no longer wrapped in a tuple. @@ -4764,9 +4981,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.method/ Name cowboy_req:method - HTTP method - Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&#8217;s HTTP method. - The method can also be obtained using pattern matching: - #{method := Method} = Req. Arguments Req The Req object. Return value The request&#8217;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&apos;s HTTP method. +The method can also be obtained using pattern matching: +#{method := Method} = Req. Arguments Req The Req object. + Return value The request&apos;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Changelog 2.0: Only the method is returned, it is no longer wrapped in a tuple. @@ -4776,9 +4995,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.method/ Name cowboy_req:method - HTTP method - Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&#8217;s HTTP method. - The method can also be obtained using pattern matching: - #{method := Method} = Req. Arguments Req The Req object. Return value The request&#8217;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Description method(Req :: cowboy_req:req()) -&gt; Method :: binary() Return the request&apos;s HTTP method. +The method can also be obtained using pattern matching: +#{method := Method} = Req. Arguments Req The Req object. + Return value The request&apos;s HTTP method is returned as a binary string. While methods are case sensitive, standard methods are always uppercase. +Changelog 2.0: Only the method is returned, it is no longer wrapped in a tuple. @@ -4788,11 +5009,12 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.parse_cookies/ Name cowboy_req:parse_cookies - Parse cookie headers - Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. - Alias for cowboy_req:parse_header([cookie], Req). - When the cookie header is missing, [] is returned. - While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. - Arguments Req The Req object. +Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. +Alias for cowboy_req:parse_header(&lt;&lt;&quot;cookie&quot;&gt;&gt;, Req). +When the cookie header is missing, [] is returned. +While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. +Arguments Req The Req object. + Return value The cookies are returned as a list of key/values. @@ -4802,11 +5024,12 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.parse_cookies/ Name cowboy_req:parse_cookies - Parse cookie headers - Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. - Alias for cowboy_req:parse_header([cookie], Req). - When the cookie header is missing, [] is returned. - While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. - Arguments Req The Req object. +Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. +Alias for cowboy_req:parse_header(&lt;&lt;&quot;cookie&quot;&gt;&gt;, Req). +When the cookie header is missing, [] is returned. +While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. +Arguments Req The Req object. + Return value The cookies are returned as a list of key/values. @@ -4816,11 +5039,12 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.parse_cookies/ Name cowboy_req:parse_cookies - Parse cookie headers - Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. - Alias for cowboy_req:parse_header([cookie], Req). - When the cookie header is missing, [] is returned. - While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. - Arguments Req The Req object. +Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. +Alias for cowboy_req:parse_header(&lt;&lt;&quot;cookie&quot;&gt;&gt;, Req). +When the cookie header is missing, [] is returned. +While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. +Arguments Req The Req object. + Return value The cookies are returned as a list of key/values. @@ -4830,11 +5054,12 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.parse_cookies/ Name cowboy_req:parse_cookies - Parse cookie headers - Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. - Alias for cowboy_req:parse_header([cookie], Req). - When the cookie header is missing, [] is returned. - While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. - Arguments Req The Req object. +Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. +Alias for cowboy_req:parse_header(&lt;&lt;&quot;cookie&quot;&gt;&gt;, Req). +When the cookie header is missing, [] is returned. +While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. +Arguments Req The Req object. + Return value The cookies are returned as a list of key/values. @@ -4844,11 +5069,12 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.parse_cookies/ Name cowboy_req:parse_cookies - Parse cookie headers - Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. - Alias for cowboy_req:parse_header([cookie], Req). - When the cookie header is missing, [] is returned. - While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. - Arguments Req The Req object. +Description parse_cookies(Req) -&gt; [{Name, Value}] Name :: binary() %% case sensitive Value :: binary() %% case sensitive Parse cookie headers. +Alias for cowboy_req:parse_header(&lt;&lt;&quot;cookie&quot;&gt;&gt;, Req). +When the cookie header is missing, [] is returned. +While an empty cookie header is not valid, some clients do send it. Cowboy will in this case also return []. +Arguments Req The Req object. + Return value The cookies are returned as a list of key/values. @@ -4858,8 +5084,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.parse_header/ Name cowboy_req:parse_header - Parse the given HTTP header - Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +The type of the parsed value varies depending on the header. @@ -4869,8 +5096,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.parse_header/ Name cowboy_req:parse_header - Parse the given HTTP header - Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +The type of the parsed value varies depending on the header. @@ -4880,8 +5108,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.parse_header/ Name cowboy_req:parse_header - Parse the given HTTP header - Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +The type of the parsed value varies depending on the header. @@ -4891,8 +5120,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.parse_header/ Name cowboy_req:parse_header - Parse the given HTTP header - Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +The type of the parsed value varies depending on the header. @@ -4902,8 +5132,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.parse_header/ Name cowboy_req:parse_header - Parse the given HTTP header - Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description parse_header(Name, Req) -&gt; ParsedValue | Default parse_header(Name, Req, Default) -&gt; ParsedValue | Default Name :: binary() Req :: cowboy_req:req() ParsedValue :: any() Default :: any() Parse the given HTTP header. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +The type of the parsed value varies depending on the header. @@ -4913,8 +5144,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.parse_qs/ Name cowboy_req:parse_qs - Parse the query string - Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. - Arguments Req The Req object. Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. +Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. +Arguments Req The Req object. + Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. Both key and value are case sensitive. @@ -4924,8 +5156,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.parse_qs/ Name cowboy_req:parse_qs - Parse the query string - Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. - Arguments Req The Req object. Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. +Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. +Arguments Req The Req object. + Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. Both key and value are case sensitive. @@ -4935,8 +5168,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.parse_qs/ Name cowboy_req:parse_qs - Parse the query string - Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. - Arguments Req The Req object. Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. +Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. +Arguments Req The Req object. + Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. Both key and value are case sensitive. @@ -4946,8 +5180,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.parse_qs/ Name cowboy_req:parse_qs - Parse the query string - Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. - Arguments Req The Req object. Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. +Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. +Arguments Req The Req object. + Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. Both key and value are case sensitive. @@ -4957,8 +5192,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.parse_qs/ Name cowboy_req:parse_qs - Parse the query string - Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. - Arguments Req The Req object. Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. +Description parse_qs(Req :: cowboy_req:req()) -&gt; [{Key :: binary(), Value :: binary() | true}] Parse the query string as a list of key/value pairs. +Arguments Req The Req object. + Return value The parsed query string is returned as a list of key/value pairs. The key is a binary string. The value is either a binary string, or the atom true. Both key and value are case sensitive. @@ -4968,10 +5204,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.path/ Name cowboy_req:path - URI path - Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. - The path can also be obtained using pattern matching: - #{path := Path} = Req. Arguments Req The Req object. Return value The path is returned as a binary string. It is case sensitive. - Changelog 2. +Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. +The path can also be obtained using pattern matching: +#{path := Path} = Req. Arguments Req The Req object. + Return value The path is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the path is returned, it is no longer wrapped in a tuple. @@ -4981,10 +5218,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.path/ Name cowboy_req:path - URI path - Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. - The path can also be obtained using pattern matching: - #{path := Path} = Req. Arguments Req The Req object. Return value The path is returned as a binary string. It is case sensitive. - Changelog 2. +Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. +The path can also be obtained using pattern matching: +#{path := Path} = Req. Arguments Req The Req object. + Return value The path is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the path is returned, it is no longer wrapped in a tuple. @@ -4994,10 +5232,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.path/ Name cowboy_req:path - URI path - Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. - The path can also be obtained using pattern matching: - #{path := Path} = Req. Arguments Req The Req object. Return value The path is returned as a binary string. It is case sensitive. - Changelog 2. +Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. +The path can also be obtained using pattern matching: +#{path := Path} = Req. Arguments Req The Req object. + Return value The path is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the path is returned, it is no longer wrapped in a tuple. @@ -5007,10 +5246,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.path/ Name cowboy_req:path - URI path - Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. - The path can also be obtained using pattern matching: - #{path := Path} = Req. Arguments Req The Req object. Return value The path is returned as a binary string. It is case sensitive. - Changelog 2. +Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. +The path can also be obtained using pattern matching: +#{path := Path} = Req. Arguments Req The Req object. + Return value The path is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the path is returned, it is no longer wrapped in a tuple. @@ -5020,10 +5260,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.path/ Name cowboy_req:path - URI path - Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. - The path can also be obtained using pattern matching: - #{path := Path} = Req. Arguments Req The Req object. Return value The path is returned as a binary string. It is case sensitive. - Changelog 2. +Description path(Req :: cowboy_req:req()) -&gt; Path :: binary() Return the path of the effective request URI. +The path can also be obtained using pattern matching: +#{path := Path} = Req. Arguments Req The Req object. + Return value The path is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the path is returned, it is no longer wrapped in a tuple. @@ -5032,10 +5273,12 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.path_info/ - Name cowboy_req:path_info - Access the route&#8217;s trailing path segments - Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case sensitive binary strings. + Name cowboy_req:path_info - Access the route&apos;s trailing path segments +Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case sensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -5044,10 +5287,12 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.path_info/ - Name cowboy_req:path_info - Access the route&#8217;s trailing path segments - Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case sensitive binary strings. + Name cowboy_req:path_info - Access the route&apos;s trailing path segments +Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case sensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -5056,10 +5301,12 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.path_info/ - Name cowboy_req:path_info - Access the route&#8217;s trailing path segments - Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case sensitive binary strings. + Name cowboy_req:path_info - Access the route&apos;s trailing path segments +Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case sensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -5068,10 +5315,12 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.path_info/ - Name cowboy_req:path_info - Access the route&#8217;s trailing path segments - Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case sensitive binary strings. + Name cowboy_req:path_info - Access the route&apos;s trailing path segments +Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case sensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -5080,10 +5329,12 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.path_info/ - Name cowboy_req:path_info - Access the route&#8217;s trailing path segments - Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. - This is the part of the host name that was matched using the ... notation. - Arguments Req The Req object. Return value The tokens are returned as a list of case sensitive binary strings. + Name cowboy_req:path_info - Access the route&apos;s trailing path segments +Description path_info(Req :: cowboy_req:req()) -&gt; cowboy_router:tokens() Return the tokens for the trailing path segments. +This is the part of the host name that was matched using the ... notation. +Arguments Req The Req object. + Return value The tokens are returned as a list of case sensitive binary strings. +Changelog 2.0: Only the tokens are returned, they are no longer wrapped in a tuple. @@ -5093,10 +5344,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.peer/ Name cowboy_req:peer - Peer address and port - Description peer(Req :: cowboy_req:req()) -&gt; Peer Peer :: {inet:ip_address(), inet:port_number()} Return the peer&#8217;s IP address and port number. - The peer can also be obtained using pattern matching: - #{peer := {IP, Port}} = Req. Arguments Req The Req object. Return value The peer&#8217;s IP address and port number. - The peer is not necessarily the client&#8217;s IP address and port. +Description peer(Req :: cowboy_req:req()) -&gt; Peer Peer :: {inet:ip_address(), inet:port_number()} Return the peer&apos;s IP address and port number. +The peer can also be obtained using pattern matching: +#{peer := {IP, Port}} = Req. Arguments Req The Req object. + Return value The peer&apos;s IP address and port number. +The peer is not necessarily the client&apos;s IP address and port. It is the IP address of the endpoint connecting directly to the server, which may be a gateway or a proxy. @@ -5106,9 +5358,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.peer/ Name cowboy_req:peer - Peer address and port - Description peer(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the peer&#8217;s IP address and port number. - The peer information can also be obtained using pattern matching: - #{peer := {IP, Port}} = Req. Arguments Req The Req object. Return value The peer&#8217;s IP address and port number. +Description peer(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the peer&apos;s IP address and port number. +The peer information can also be obtained using pattern matching: +#{peer := {IP, Port}} = Req. Arguments Req The Req object. + Return value The peer&apos;s IP address and port number. +The peer is not necessarily the client&apos;s IP address and port. It is the IP address of the endpoint connecting directly to the server, which may be a gateway or a proxy. @@ -5118,9 +5372,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.peer/ Name cowboy_req:peer - Peer address and port - Description peer(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the peer&#8217;s IP address and port number. - The peer information can also be obtained using pattern matching: - #{peer := {IP, Port}} = Req. Arguments Req The Req object. Return value The peer&#8217;s IP address and port number. +Description peer(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the peer&apos;s IP address and port number. +The peer information can also be obtained using pattern matching: +#{peer := {IP, Port}} = Req. Arguments Req The Req object. + Return value The peer&apos;s IP address and port number. +The peer is not necessarily the client&apos;s IP address and port. It is the IP address of the endpoint connecting directly to the server, which may be a gateway or a proxy. @@ -5130,9 +5386,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.peer/ Name cowboy_req:peer - Peer address and port - Description peer(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the peer&#8217;s IP address and port number. - The peer information can also be obtained using pattern matching: - #{peer := {IP, Port}} = Req. Arguments Req The Req object. Return value The peer&#8217;s IP address and port number. +Description peer(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the peer&apos;s IP address and port number. +The peer information can also be obtained using pattern matching: +#{peer := {IP, Port}} = Req. Arguments Req The Req object. + Return value The peer&apos;s IP address and port number. +The peer is not necessarily the client&apos;s IP address and port. It is the IP address of the endpoint connecting directly to the server, which may be a gateway or a proxy. @@ -5142,9 +5400,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.peer/ Name cowboy_req:peer - Peer address and port - Description peer(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the peer&#8217;s IP address and port number. - The peer information can also be obtained using pattern matching: - #{peer := {IP, Port}} = Req. Arguments Req The Req object. Return value The peer&#8217;s IP address and port number. +Description peer(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the peer&apos;s IP address and port number. +The peer information can also be obtained using pattern matching: +#{peer := {IP, Port}} = Req. Arguments Req The Req object. + Return value The peer&apos;s IP address and port number. +The peer is not necessarily the client&apos;s IP address and port. It is the IP address of the endpoint connecting directly to the server, which may be a gateway or a proxy. @@ -5154,10 +5414,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.port/ Name cowboy_req:port - URI port number - Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. - Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. - The port number can also be obtained using pattern matching: - #{port := Port} = Req. +Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. +Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. +The port number can also be obtained using pattern matching: +#{port := Port} = Req. Arguments Req The Req object. @@ -5167,10 +5427,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.port/ Name cowboy_req:port - URI port number - Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. - Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. - The port number can also be obtained using pattern matching: - #{port := Port} = Req. +Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. +Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. +The port number can also be obtained using pattern matching: +#{port := Port} = Req. Arguments Req The Req object. @@ -5180,10 +5440,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.port/ Name cowboy_req:port - URI port number - Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. - Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. - The port number can also be obtained using pattern matching: - #{port := Port} = Req. +Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. +Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. +The port number can also be obtained using pattern matching: +#{port := Port} = Req. Arguments Req The Req object. @@ -5193,10 +5453,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.port/ Name cowboy_req:port - URI port number - Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. - Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. - The port number can also be obtained using pattern matching: - #{port := Port} = Req. +Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. +Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. +The port number can also be obtained using pattern matching: +#{port := Port} = Req. Arguments Req The Req object. @@ -5206,10 +5466,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.port/ Name cowboy_req:port - URI port number - Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. - Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. - The port number can also be obtained using pattern matching: - #{port := Port} = Req. +Description port(Req :: cowboy_req:req()) -&gt; Port :: inet:port_number() Return the port number of the effective request URI. +Note that the port number returned by this function is obtained by parsing the host header. It may be different from the port the peer used to connect to Cowboy. +The port number can also be obtained using pattern matching: +#{port := Port} = Req. Arguments Req The Req object. @@ -5219,8 +5479,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.push/ Name cowboy_req:push - Push a resource to the client - Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. - Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. +Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. +Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. @@ -5230,8 +5490,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.push/ Name cowboy_req:push - Push a resource to the client - Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. - Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. +Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. +Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. @@ -5241,8 +5501,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.push/ Name cowboy_req:push - Push a resource to the client - Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. - Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. +Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. +Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. @@ -5252,8 +5512,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.push/ Name cowboy_req:push - Push a resource to the client - Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. - Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. +Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. +Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. @@ -5263,8 +5523,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.push/ Name cowboy_req:push - Push a resource to the client - Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. - Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. +Description push(Path, Headers, Req :: cowboy_req:req()) -&gt; push(Path, Headers, Req, #{}) push(Path, Headers, Req :: cowboy_req:req(), Opts) -&gt; ok Path :: iodata() %% case sensitive Headers :: cowboy:http_headers() Opts :: cowboy_req:push_opts() Push a resource to the client. +Cowboy handles push requests the same way as if they came from the client, including the creation of a request handling process, routing and middlewares and so on. @@ -5274,9 +5534,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.qs/ Name cowboy_req:qs - URI query string - Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. - The query string can also be obtained using pattern matching: - #{qs := Qs} = Req. Arguments Req The Req object. Return value The query string is returned as a binary string. It is case sensitive. +Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. +The query string can also be obtained using pattern matching: +#{qs := Qs} = Req. Arguments Req The Req object. + Return value The query string is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the query string is returned, it is no longer wrapped in a tuple. @@ -5286,9 +5548,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.qs/ Name cowboy_req:qs - URI query string - Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. - The query string can also be obtained using pattern matching: - #{qs := Qs} = Req. Arguments Req The Req object. Return value The query string is returned as a binary string. It is case sensitive. +Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. +The query string can also be obtained using pattern matching: +#{qs := Qs} = Req. Arguments Req The Req object. + Return value The query string is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the query string is returned, it is no longer wrapped in a tuple. @@ -5298,9 +5562,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.qs/ Name cowboy_req:qs - URI query string - Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. - The query string can also be obtained using pattern matching: - #{qs := Qs} = Req. Arguments Req The Req object. Return value The query string is returned as a binary string. It is case sensitive. +Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. +The query string can also be obtained using pattern matching: +#{qs := Qs} = Req. Arguments Req The Req object. + Return value The query string is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the query string is returned, it is no longer wrapped in a tuple. @@ -5310,9 +5576,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.qs/ Name cowboy_req:qs - URI query string - Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. - The query string can also be obtained using pattern matching: - #{qs := Qs} = Req. Arguments Req The Req object. Return value The query string is returned as a binary string. It is case sensitive. +Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. +The query string can also be obtained using pattern matching: +#{qs := Qs} = Req. Arguments Req The Req object. + Return value The query string is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the query string is returned, it is no longer wrapped in a tuple. @@ -5322,9 +5590,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.qs/ Name cowboy_req:qs - URI query string - Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. - The query string can also be obtained using pattern matching: - #{qs := Qs} = Req. Arguments Req The Req object. Return value The query string is returned as a binary string. It is case sensitive. +Description qs(Req :: cowboy_req:req()) -&gt; Qs :: binary() Return the query string of the effective request URI. +The query string can also be obtained using pattern matching: +#{qs := Qs} = Req. Arguments Req The Req object. + Return value The query string is returned as a binary string. It is case sensitive. +Changelog 2.0: Only the query string is returned, it is no longer wrapped in a tuple. @@ -5334,8 +5604,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.read_body/ Name cowboy_req:read_body - Read the request body - Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. - This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. +Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. +This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. @@ -5345,8 +5615,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.read_body/ Name cowboy_req:read_body - Read the request body - Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. - This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. +Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. +This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. @@ -5356,8 +5626,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.read_body/ Name cowboy_req:read_body - Read the request body - Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. - This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. +Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. +This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. @@ -5367,8 +5637,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.read_body/ Name cowboy_req:read_body - Read the request body - Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. - This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. +Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. +This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. @@ -5378,8 +5648,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.read_body/ Name cowboy_req:read_body - Read the request body - Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. - This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. +Description read_body(Req :: cowboy_req:req()) -&gt; read_body(Req, #{}) read_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the request body. +This function reads a chunk of the request body. A more tuple is returned when more data remains to be read. Call the function repeatedly until an ok tuple is returned to read the entire body. @@ -5389,8 +5659,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.read_part/ Name cowboy_req:read_part - Read the next multipart headers - Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. +Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. @@ -5400,8 +5670,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.read_part/ Name cowboy_req:read_part - Read the next multipart headers - Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. +Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. @@ -5411,8 +5681,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.read_part/ Name cowboy_req:read_part - Read the next multipart headers - Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. +Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. @@ -5422,8 +5692,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.read_part/ Name cowboy_req:read_part - Read the next multipart headers - Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. +Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. @@ -5433,8 +5703,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.read_part/ Name cowboy_req:read_part - Read the next multipart headers - Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. +Description read_part(Req :: cowboy_req:req()) -&gt; read_part(Req, #{}) read_part(Req :: cowboy_req:req(), Opts) -&gt; {ok, Headers, Req} | {done, Req} Opts :: cowboy_req:read_body_opts() Headers :: #{binary() =&gt; binary()} Read the next part of a multipart body. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function parses and returns headers. @@ -5443,9 +5713,9 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.read_part_body/ - Name cowboy_req:read_part_body - Read the current part&#8217;s body - Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. + Name cowboy_req:read_part_body - Read the current part&apos;s body +Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function returns the body of the current part. @@ -5454,9 +5724,9 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.read_part_body/ - Name cowboy_req:read_part_body - Read the current part&#8217;s body - Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. + Name cowboy_req:read_part_body - Read the current part&apos;s body +Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function returns the body of the current part. @@ -5465,9 +5735,9 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.read_part_body/ - Name cowboy_req:read_part_body - Read the current part&#8217;s body - Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. + Name cowboy_req:read_part_body - Read the current part&apos;s body +Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function returns the body of the current part. @@ -5476,9 +5746,9 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.read_part_body/ - Name cowboy_req:read_part_body - Read the current part&#8217;s body - Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. + Name cowboy_req:read_part_body - Read the current part&apos;s body +Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function returns the body of the current part. @@ -5487,9 +5757,9 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.read_part_body/ - Name cowboy_req:read_part_body - Read the current part&#8217;s body - Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. - This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. + Name cowboy_req:read_part_body - Read the current part&apos;s body +Description read_part_body(Req :: cowboy_req:req()) -&gt; read_part_body(Req, #{}) read_part_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Data :: binary(), Req} | {more, Data :: binary(), Req} Opts :: cowboy_req:read_body_opts() Read the body of the current part of the multipart message. +This function reads the request body and parses it as multipart. Each parts of a multipart representation have their own headers and body. This function returns the body of the current part. @@ -5499,9 +5769,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.read_urlencoded_body/ Name cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body - Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. - This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. - The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. +Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. +This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. +The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. @@ -5511,9 +5781,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.read_urlencoded_body/ Name cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body - Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. - This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. - The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. +Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. +This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. +The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. @@ -5523,9 +5793,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.read_urlencoded_body/ Name cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body - Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. - This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. - The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. +Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. +This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. +The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. @@ -5535,9 +5805,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.read_urlencoded_body/ Name cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body - Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. - This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. - The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. +Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. +This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. +The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. @@ -5547,9 +5817,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.read_urlencoded_body/ Name cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body - Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. - This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. - The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. +Description read_urlencoded_body(Req :: cowboy_req:req()) -&gt; read_urlencoded_body(Req, #{}) read_urlencoded_body(Req :: cowboy_req:req(), Opts) -&gt; {ok, Body, Req} Opts :: cowboy_req:read_body_opts() Body :: [{Key :: binary(), Value :: binary() | true}] Read and parse a urlencoded request body. +This function reads the request body and parses it as application/x-www-form-urlencoded. It returns a list of key/values. +The urlencoded media type is used by Web browsers when submitting HTML forms using the POST method. @@ -5559,8 +5829,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.reply/ Name cowboy_req:reply - Send the response - Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5570,8 +5840,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.reply/ Name cowboy_req:reply - Send the response - Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5581,8 +5851,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.reply/ Name cowboy_req:reply - Send the response - Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5592,8 +5862,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.reply/ Name cowboy_req:reply - Send the response - Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5603,8 +5873,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.reply/ Name cowboy_req:reply - Send the response - Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description reply(Status, Req :: cowboy_req:req()) -&gt; reply(StatusCode, #{}, Req) reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req reply(Status, Headers, Body, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Body :: cowboy_req:resp_body() Send the response. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5614,9 +5884,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.resp_header/ Name cowboy_req:resp_header - Response header - Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. - The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. +The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5626,9 +5896,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.resp_header/ Name cowboy_req:resp_header - Response header - Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. - The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. +The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5638,9 +5908,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.resp_header/ Name cowboy_req:resp_header - Response header - Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. - The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. +The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5650,9 +5920,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.resp_header/ Name cowboy_req:resp_header - Response header - Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. - The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. +The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5662,9 +5932,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.resp_header/ Name cowboy_req:resp_header - Response header - Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. - The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description resp_header(Name, Req) -&gt; resp_header(Name, Req, undefined) resp_header(Name, Req, Default) -&gt; binary() | Default Name :: binary() %% lowercase; case insensitive Req :: cowboy_req:req() Default :: any() Return the value for the given response header. +The response header must have been set previously using cowboy_req:set_resp_header(3) or cowboy_req:set_resp_headers(3). +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. @@ -5674,9 +5944,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.resp_headers/ Name cowboy_req:resp_headers - Response headers - Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. - Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). +Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. +Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). See also cowboy_req(3), cowboy_req:resp_header(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3) @@ -5686,9 +5957,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.resp_headers/ Name cowboy_req:resp_headers - Response headers - Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. - Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). +Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. +Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). See also cowboy_req(3), cowboy_req:resp_header(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3) @@ -5698,9 +5970,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.resp_headers/ Name cowboy_req:resp_headers - Response headers - Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. - Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). +Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. +Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). See also cowboy_req(3), cowboy_req:resp_header(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3) @@ -5710,9 +5983,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.resp_headers/ Name cowboy_req:resp_headers - Response headers - Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. - Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). +Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. +Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). See also cowboy_req(3), cowboy_req:resp_header(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3) @@ -5722,9 +5996,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.resp_headers/ Name cowboy_req:resp_headers - Response headers - Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. - Arguments Req The Req object. Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. - Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). +Description resp_headers(Req :: cowboy_req:req()) -&gt; cowboy:http_headers() Return all response headers. +Arguments Req The Req object. + Return value Headers are returned as a map with keys being lowercase binary strings, and values as binary strings. +Changelog 2.0: Function introduced. Examples Get all response headers Headers = cowboy_req:resp_headers(Req). See also cowboy_req(3), cowboy_req:resp_header(3), cowboy_req:set_resp_header(3), cowboy_req:set_resp_headers(3) @@ -5734,10 +6009,12 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.scheme/ Name cowboy_req:scheme - URI scheme - Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. - The scheme can also be obtained using pattern matching: - #{scheme := Scheme} = Req. Arguments Req The Req object. Return value The scheme is returned as a binary. It is case insensitive. - Cowboy will only set the scheme to &lt;&lt;" +Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. +The scheme can also be obtained using pattern matching: +#{scheme := Scheme} = Req. Arguments Req The Req object. + Return value The scheme is returned as a binary. It is case insensitive. +Cowboy will only set the scheme to &lt;&lt;&quot;http&quot;&gt;&gt; or &lt;&lt;&quot;https&quot;&gt;&gt;. +Changelog 2.0: Function introduced. @@ -5747,10 +6024,12 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.scheme/ Name cowboy_req:scheme - URI scheme - Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. - The scheme can also be obtained using pattern matching: - #{scheme := Scheme} = Req. Arguments Req The Req object. Return value The scheme is returned as a binary. It is case insensitive. - Cowboy will only set the scheme to &lt;&lt;" +Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. +The scheme can also be obtained using pattern matching: +#{scheme := Scheme} = Req. Arguments Req The Req object. + Return value The scheme is returned as a binary. It is case insensitive. +Cowboy will only set the scheme to &lt;&lt;&quot;http&quot;&gt;&gt; or &lt;&lt;&quot;https&quot;&gt;&gt;. +Changelog 2.0: Function introduced. @@ -5760,10 +6039,12 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.scheme/ Name cowboy_req:scheme - URI scheme - Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. - The scheme can also be obtained using pattern matching: - #{scheme := Scheme} = Req. Arguments Req The Req object. Return value The scheme is returned as a binary. It is case insensitive. - Cowboy will only set the scheme to &lt;&lt;" +Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. +The scheme can also be obtained using pattern matching: +#{scheme := Scheme} = Req. Arguments Req The Req object. + Return value The scheme is returned as a binary. It is case insensitive. +Cowboy will only set the scheme to &lt;&lt;&quot;http&quot;&gt;&gt; or &lt;&lt;&quot;https&quot;&gt;&gt;. +Changelog 2.0: Function introduced. @@ -5773,10 +6054,12 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.scheme/ Name cowboy_req:scheme - URI scheme - Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. - The scheme can also be obtained using pattern matching: - #{scheme := Scheme} = Req. Arguments Req The Req object. Return value The scheme is returned as a binary. It is case insensitive. - Cowboy will only set the scheme to &lt;&lt;" +Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. +The scheme can also be obtained using pattern matching: +#{scheme := Scheme} = Req. Arguments Req The Req object. + Return value The scheme is returned as a binary. It is case insensitive. +Cowboy will only set the scheme to &lt;&lt;&quot;http&quot;&gt;&gt; or &lt;&lt;&quot;https&quot;&gt;&gt;. +Changelog 2.0: Function introduced. @@ -5786,10 +6069,12 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.scheme/ Name cowboy_req:scheme - URI scheme - Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. - The scheme can also be obtained using pattern matching: - #{scheme := Scheme} = Req. Arguments Req The Req object. Return value The scheme is returned as a binary. It is case insensitive. - Cowboy will only set the scheme to &lt;&lt;" +Description scheme(Req :: cowboy_req:req()) -&gt; Scheme :: binary() Return the scheme of the effective request URI. +The scheme can also be obtained using pattern matching: +#{scheme := Scheme} = Req. Arguments Req The Req object. + Return value The scheme is returned as a binary. It is case insensitive. +Cowboy will only set the scheme to &lt;&lt;&quot;http&quot;&gt;&gt; or &lt;&lt;&quot;https&quot;&gt;&gt;. +Changelog 2.0: Function introduced. @@ -5799,9 +6084,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_body/ Name cowboy_req:set_resp_body - Set the response body - Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. - The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. - This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. +Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. +The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. +This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. @@ -5811,9 +6096,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_body/ Name cowboy_req:set_resp_body - Set the response body - Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. - The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. - This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. +Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. +The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. +This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. @@ -5823,9 +6108,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_body/ Name cowboy_req:set_resp_body - Set the response body - Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. - The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. - This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. +Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. +The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. +This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. @@ -5835,9 +6120,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_body/ Name cowboy_req:set_resp_body - Set the response body - Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. - The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. - This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. +Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. +The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. +This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. @@ -5847,9 +6132,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_body/ Name cowboy_req:set_resp_body - Set the response body - Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. - The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. - This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. +Description set_resp_body(Body, Req :: cowboy_req:req()) -&gt; Req Body :: cowboy_req:resp_body() Set the response body. +The response body will be sent when a reply is initiated. Note that the functions stream_reply/2,3 and reply/4 will override the body set by this function. +This function can also be used to remove a response body that was set previously. To do so, simply call this function with an empty body. @@ -5859,9 +6144,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_cookie/ Name cowboy_req:set_resp_cookie - Set a cookie - Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. - Note that cookie names are case sensitive. - Arguments Name Cookie name. +Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. +Note that cookie names are case sensitive. +Arguments Name Cookie name. + Value Cookie value. + Req The Req object. @@ -5871,9 +6158,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_cookie/ Name cowboy_req:set_resp_cookie - Set a cookie - Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. - Note that cookie names are case sensitive. - Arguments Name Cookie name. +Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. +Note that cookie names are case sensitive. +Arguments Name Cookie name. + Value Cookie value. + Req The Req object. @@ -5883,9 +6172,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_cookie/ Name cowboy_req:set_resp_cookie - Set a cookie - Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. - Note that cookie names are case sensitive. - Arguments Name Cookie name. +Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. +Note that cookie names are case sensitive. +Arguments Name Cookie name. + Value Cookie value. + Req The Req object. @@ -5895,9 +6186,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_cookie/ Name cowboy_req:set_resp_cookie - Set a cookie - Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. - Note that cookie names are case sensitive. - Arguments Name Cookie name. +Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. +Note that cookie names are case sensitive. +Arguments Name Cookie name. + Value Cookie value. + Req The Req object. @@ -5907,9 +6200,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_cookie/ Name cowboy_req:set_resp_cookie - Set a cookie - Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. - Note that cookie names are case sensitive. - Arguments Name Cookie name. +Description set_resp_cookie(Name, Value, Req :: cowboy_req:req()) -&gt; set_resp_cookie(Name, Value, [], Req) set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) -&gt; Req Name :: binary() %% case sensitive Value :: iodata() %% case sensitive Opts :: cow_cookie:cookie_opts() Set a cookie to be sent with the response. +Note that cookie names are case sensitive. +Arguments Name Cookie name. + Value Cookie value. + Req The Req object. @@ -5919,8 +6214,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_header/ Name cowboy_req:set_resp_header - Set a response header - Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. @@ -5930,8 +6226,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_header/ Name cowboy_req:set_resp_header - Set a response header - Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. @@ -5941,8 +6238,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_header/ Name cowboy_req:set_resp_header - Set a response header - Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. @@ -5952,8 +6250,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_header/ Name cowboy_req:set_resp_header - Set a response header - Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. @@ -5963,8 +6262,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_header/ Name cowboy_req:set_resp_header - Set a response header - Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Description set_resp_header(Name, Value, Req :: cowboy_req:req()) -&gt; Req Name :: binary() %% lowercase; case insensitive Value :: iodata() %% case depends on header Set a header to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. @@ -5974,9 +6274,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.set_resp_headers/ Name cowboy_req:set_resp_headers - Set several response headers - Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. +Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. @@ -5986,9 +6286,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.set_resp_headers/ Name cowboy_req:set_resp_headers - Set several response headers - Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. +Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. @@ -5998,9 +6298,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.set_resp_headers/ Name cowboy_req:set_resp_headers - Set several response headers - Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. +Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. @@ -6010,9 +6310,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.set_resp_headers/ Name cowboy_req:set_resp_headers - Set several response headers - Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. +Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. @@ -6022,9 +6322,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.set_resp_headers/ Name cowboy_req:set_resp_headers - Set several response headers - Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. - The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. +Description set_resp_headers(Headers, Req :: cowboy_req:req()) -&gt; Req Headers :: cowboy:http_headers() Set several headers to be sent with the response. +The header name must be given as a lowercase binary string. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may be overwritten by those set from the reply functions. @@ -6034,9 +6334,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.sock/ Name cowboy_req:sock - Socket address and port - Description sock(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the socket&#8217;s IP address and port number. - The socket information can also be obtained using pattern matching: - #{sock := {IP, Port}} = Req. Arguments Req The Req object. Return value The socket&#8217;s local IP address and port number. +Description sock(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the socket&apos;s IP address and port number. +The socket information can also be obtained using pattern matching: +#{sock := {IP, Port}} = Req. Arguments Req The Req object. + Return value The socket&apos;s local IP address and port number. +Changelog 2.1: Function introduced. Examples Get the socket&apos;s IP address and port number. @@ -6046,9 +6348,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.sock/ Name cowboy_req:sock - Socket address and port - Description sock(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the socket&#8217;s IP address and port number. - The socket information can also be obtained using pattern matching: - #{sock := {IP, Port}} = Req. Arguments Req The Req object. Return value The socket&#8217;s local IP address and port number. +Description sock(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the socket&apos;s IP address and port number. +The socket information can also be obtained using pattern matching: +#{sock := {IP, Port}} = Req. Arguments Req The Req object. + Return value The socket&apos;s local IP address and port number. +Changelog 2.1: Function introduced. Examples Get the socket&apos;s IP address and port number. @@ -6058,9 +6362,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.sock/ Name cowboy_req:sock - Socket address and port - Description sock(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the socket&#8217;s IP address and port number. - The socket information can also be obtained using pattern matching: - #{sock := {IP, Port}} = Req. Arguments Req The Req object. Return value The socket&#8217;s local IP address and port number. +Description sock(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the socket&apos;s IP address and port number. +The socket information can also be obtained using pattern matching: +#{sock := {IP, Port}} = Req. Arguments Req The Req object. + Return value The socket&apos;s local IP address and port number. +Changelog 2.1: Function introduced. Examples Get the socket&apos;s IP address and port number. @@ -6070,9 +6376,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.sock/ Name cowboy_req:sock - Socket address and port - Description sock(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the socket&#8217;s IP address and port number. - The socket information can also be obtained using pattern matching: - #{sock := {IP, Port}} = Req. Arguments Req The Req object. Return value The socket&#8217;s local IP address and port number. +Description sock(Req :: cowboy_req:req()) -&gt; Info Info :: {inet:ip_address(), inet:port_number()} Return the socket&apos;s IP address and port number. +The socket information can also be obtained using pattern matching: +#{sock := {IP, Port}} = Req. Arguments Req The Req object. + Return value The socket&apos;s local IP address and port number. +Changelog 2.1: Function introduced. Examples Get the socket&apos;s IP address and port number. @@ -6082,9 +6390,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.stream_body/ Name cowboy_req:stream_body - Stream the response body - Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. - This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. - The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. +Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. +This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. +The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. The final call should use fin (possibly with an empty data value). @@ -6094,9 +6402,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.stream_body/ Name cowboy_req:stream_body - Stream the response body - Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. - This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. - The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. +Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. +This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. +The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. The final call should use fin (possibly with an empty data value). @@ -6106,9 +6414,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.stream_body/ Name cowboy_req:stream_body - Stream the response body - Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. - This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. - The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. +Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. +This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. +The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. The final call should use fin (possibly with an empty data value) or be a call to the cowboy_req:stream_trailers(3) function. @@ -6118,9 +6426,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.stream_body/ Name cowboy_req:stream_body - Stream the response body - Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. - This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. - The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. +Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. +This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. +The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. The final call should use fin (possibly with an empty data value) or be a call to the cowboy_req:stream_trailers(3) function. @@ -6130,9 +6438,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.stream_body/ Name cowboy_req:stream_body - Stream the response body - Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. - This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. - The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. +Description stream_body(Data, IsFin, Req :: cowboy_req:req()) -&gt; ok Data :: iodata() IsFin :: fin | nofin Stream the response body. +This function may be called as many times as needed after initiating a response using the cowboy_req:stream_reply(3) function. +The second argument indicates if this call is the final call. Use the nofin value until you know no more data will be sent. The final call should use fin (possibly with an empty data value) or be a call to the cowboy_req:stream_trailers(3) function. @@ -6142,9 +6450,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.stream_reply/ Name cowboy_req:stream_reply - Send the response headers - Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. +Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3. @@ -6154,9 +6462,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.stream_reply/ Name cowboy_req:stream_reply - Send the response headers - Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. +Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3. @@ -6166,9 +6474,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.stream_reply/ Name cowboy_req:stream_reply - Send the response headers - Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. +Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3. @@ -6178,9 +6486,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.stream_reply/ Name cowboy_req:stream_reply - Send the response headers - Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. +Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3. @@ -6190,9 +6498,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.stream_reply/ Name cowboy_req:stream_reply - Send the response headers - Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. - The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. - Cowboy does not allow duplicate header names. +Description stream_reply(Status, Req :: cowboy_req:req()) -&gt; stream_reply(StatusCode, #{}, Req) stream_reply(Status, Headers, Req :: cowboy_req:req()) -&gt; Req Status :: cowboy:http_status() Headers :: cowboy:http_headers() Send the response headers. +The header names must be given as lowercase binary strings. While header names are case insensitive, Cowboy requires them to be given as lowercase to function properly. +Cowboy does not allow duplicate header names. Headers set by this function may overwrite those set by set_resp_header/3. @@ -6202,9 +6510,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.stream_trailers/ Name cowboy_req:stream_trailers - Send the response trailers - Description stream_trailers(Trailers, Req :: cowboy_req:req()) -&gt; ok Trailers :: cowboy:http_headers() Send the response trailers and terminate the stream. - This function can only be called once, after initiating a response using cowboy_req:stream_reply(3) and sending zero or more body chunks using cowboy_req:stream_body(3) with the nofin argument set. The function stream_trailers/2 implies fin and automatically terminate the response. - You must list all field names sent in trailers in the trailer header, otherwise they might be dropped by intermediaries or clients. +Description stream_trailers(Trailers, Req :: cowboy_req:req()) -&gt; ok Trailers :: cowboy:http_headers() Send the response trailers and terminate the stream. +This function can only be called once, after initiating a response using cowboy_req:stream_reply(3) and sending zero or more body chunks using cowboy_req:stream_body(3) with the nofin argument set. The function stream_trailers/2 implies fin and automatically terminate the response. +You must list all field names sent in trailers in the trailer header, otherwise they might be dropped by intermediaries or clients. @@ -6214,9 +6522,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.stream_trailers/ Name cowboy_req:stream_trailers - Send the response trailers - Description stream_trailers(Trailers, Req :: cowboy_req:req()) -&gt; ok Trailers :: cowboy:http_headers() Send the response trailers and terminate the stream. - This function can only be called once, after initiating a response using cowboy_req:stream_reply(3) and sending zero or more body chunks using cowboy_req:stream_body(3) with the nofin argument set. The function stream_trailers/2 implies fin and automatically terminate the response. - You must list all field names sent in trailers in the trailer header, otherwise they might be dropped by intermediaries or clients. +Description stream_trailers(Trailers, Req :: cowboy_req:req()) -&gt; ok Trailers :: cowboy:http_headers() Send the response trailers and terminate the stream. +This function can only be called once, after initiating a response using cowboy_req:stream_reply(3) and sending zero or more body chunks using cowboy_req:stream_body(3) with the nofin argument set. The function stream_trailers/2 implies fin and automatically terminate the response. +You must list all field names sent in trailers in the trailer header, otherwise they might be dropped by intermediaries or clients. @@ -6226,9 +6534,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.stream_trailers/ Name cowboy_req:stream_trailers - Send the response trailers - Description stream_trailers(Trailers, Req :: cowboy_req:req()) -&gt; ok Trailers :: cowboy:http_headers() Send the response trailers and terminate the stream. - This function can only be called once, after initiating a response using cowboy_req:stream_reply(3) and sending zero or more body chunks using cowboy_req:stream_body(3) with the nofin argument set. The function stream_trailers/2 implies fin and automatically terminate the response. - You must list all field names sent in trailers in the trailer header, otherwise they might be dropped by intermediaries or clients. +Description stream_trailers(Trailers, Req :: cowboy_req:req()) -&gt; ok Trailers :: cowboy:http_headers() Send the response trailers and terminate the stream. +This function can only be called once, after initiating a response using cowboy_req:stream_reply(3) and sending zero or more body chunks using cowboy_req:stream_body(3) with the nofin argument set. The function stream_trailers/2 implies fin and automatically terminate the response. +You must list all field names sent in trailers in the trailer header, otherwise they might be dropped by intermediaries or clients. @@ -6238,8 +6546,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.uri/ Name cowboy_req:uri - Reconstructed URI - Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. - By default Cowboy will build a URI using the components found in the request. +Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. +By default Cowboy will build a URI using the components found in the request. @@ -6249,8 +6557,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.uri/ Name cowboy_req:uri - Reconstructed URI - Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. - By default Cowboy will build a URI using the components found in the request. +Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. +By default Cowboy will build a URI using the components found in the request. @@ -6260,8 +6568,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.uri/ Name cowboy_req:uri - Reconstructed URI - Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. - By default Cowboy will build a URI using the components found in the request. +Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. +By default Cowboy will build a URI using the components found in the request. @@ -6271,8 +6579,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.uri/ Name cowboy_req:uri - Reconstructed URI - Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. - By default Cowboy will build a URI using the components found in the request. +Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. +By default Cowboy will build a URI using the components found in the request. @@ -6282,8 +6590,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.uri/ Name cowboy_req:uri - Reconstructed URI - Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. - By default Cowboy will build a URI using the components found in the request. +Description uri(Req :: cowboy_req:req()) -&gt; uri(Req, #{}) uri(Req :: cowboy_req:req(), Opts) -&gt; URI :: iodata() Opts :: #{ scheme =&gt; iodata() | undefined, host =&gt; iodata() | undefined, port =&gt; inet:port_number() | undefined, path =&gt; iodata() | undefined, qs =&gt; iodata() | undefined, fragment =&gt; iodata() | undefined } Reconstruct the effective request URI, optionally modifying components. +By default Cowboy will build a URI using the components found in the request. @@ -6293,9 +6601,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_req.version/ Name cowboy_req:version - HTTP version - Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. - The version can also be obtained using pattern matching: - #{version := Version} = Req. Arguments Req The Req object. Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. +The version can also be obtained using pattern matching: +#{version := Version} = Req. Arguments Req The Req object. + Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Changelog 2.0: Only the version is returned, it is no longer wrapped in a tuple. @@ -6305,9 +6615,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_req.version/ Name cowboy_req:version - HTTP version - Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. - The version can also be obtained using pattern matching: - #{version := Version} = Req. Arguments Req The Req object. Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. +The version can also be obtained using pattern matching: +#{version := Version} = Req. Arguments Req The Req object. + Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Changelog 2.0: Only the version is returned, it is no longer wrapped in a tuple. @@ -6317,9 +6629,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_req.version/ Name cowboy_req:version - HTTP version - Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. - The version can also be obtained using pattern matching: - #{version := Version} = Req. Arguments Req The Req object. Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. +The version can also be obtained using pattern matching: +#{version := Version} = Req. Arguments Req The Req object. + Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Changelog 2.0: Only the version is returned, it is no longer wrapped in a tuple. @@ -6329,9 +6643,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_req.version/ Name cowboy_req:version - HTTP version - Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. - The version can also be obtained using pattern matching: - #{version := Version} = Req. Arguments Req The Req object. Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. +The version can also be obtained using pattern matching: +#{version := Version} = Req. Arguments Req The Req object. + Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Changelog 2.0: Only the version is returned, it is no longer wrapped in a tuple. @@ -6341,9 +6657,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_req.version/ Name cowboy_req:version - HTTP version - Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. - The version can also be obtained using pattern matching: - #{version := Version} = Req. Arguments Req The Req object. Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Description version(Req :: cowboy_req:req()) -&gt; Version :: cowboy:http_version() Return the HTTP version used for the request. +The version can also be obtained using pattern matching: +#{version := Version} = Req. Arguments Req The Req object. + Return value The HTTP version used for the request is returned as an atom. It is provided for informative purposes only. +Changelog 2.0: Only the version is returned, it is no longer wrapped in a tuple. @@ -6353,10 +6671,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_rest/ Name cowboy_rest - REST handlers - Description The module cowboy_rest implements the HTTP state machine. - Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). - Callbacks REST handlers implement the following interface: - init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. +Description The module cowboy_rest implements the HTTP state machine. +Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). +Callbacks REST handlers implement the following interface: +init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. @@ -6366,10 +6684,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_rest/ Name cowboy_rest - REST handlers - Description The module cowboy_rest implements the HTTP state machine. - Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). - Callbacks REST handlers implement the following interface: - init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} | {{switch_handler, Module}, Req, State} | {{switch_handler, Module, Opts}, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Module :: module() Opts :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. +Description The module cowboy_rest implements the HTTP state machine. +Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). +Callbacks REST handlers implement the following interface: +init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} | {{switch_handler, Module}, Req, State} | {{switch_handler, Module, Opts}, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Module :: module() Opts :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. @@ -6379,10 +6697,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_rest/ Name cowboy_rest - REST handlers - Description The module cowboy_rest implements the HTTP state machine. - Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). - Callbacks REST handlers implement the following interface: - init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} | {{switch_handler, Module}, Req, State} | {{switch_handler, Module, Opts}, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Module :: module() Opts :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. +Description The module cowboy_rest implements the HTTP state machine. +Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). +Callbacks REST handlers implement the following interface: +init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} | {{switch_handler, Module}, Req, State} | {{switch_handler, Module, Opts}, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Module :: module() Opts :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. @@ -6392,10 +6710,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_rest/ Name cowboy_rest - REST handlers - Description The module cowboy_rest implements the HTTP state machine. - Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). - Callbacks REST handlers implement the following interface: - init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} | {{switch_handler, Module}, Req, State} | {{switch_handler, Module, Opts}, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Module :: module() Opts :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. +Description The module cowboy_rest implements the HTTP state machine. +Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). +Callbacks REST handlers implement the following interface: +init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} | {{switch_handler, Module}, Req, State} | {{switch_handler, Module, Opts}, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Module :: module() Opts :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. @@ -6405,10 +6723,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_rest/ Name cowboy_rest - REST handlers - Description The module cowboy_rest implements the HTTP state machine. - Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). - Callbacks REST handlers implement the following interface: - init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} | {{switch_handler, Module}, Req, State} | {{switch_handler, Module, Opts}, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Module :: module() Opts :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. +Description The module cowboy_rest implements the HTTP state machine. +Implementing REST handlers is not enough to provide a REST interface; this interface must also follow the REST constraints including HATEOAS (hypermedia as the engine of application state). +Callbacks REST handlers implement the following interface: +init(Req, State) -&gt; {cowboy_rest, Req, State} Callback(Req, State) -&gt; {Result, Req, State} | {stop, Req, State} | {{switch_handler, Module}, Req, State} | {{switch_handler, Module, Opts}, Req, State} terminate(Reason, Req, State) -&gt; ok %% optional Req :: cowboy_req:req() State :: any() Module :: module() Opts :: any() Reason :: normal | {crash, error | exit | throw, any()} Callback - see below Result - see below Default - see below The init/2 callback is common to all handlers. @@ -6418,9 +6736,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_router/ Name cowboy_router - Router middleware - Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. - The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. - When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. +The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. +When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +The router will stop execution when no route matches. @@ -6430,9 +6749,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_router/ Name cowboy_router - Router middleware - Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. - The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. - When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. +The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. +When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +The router will stop execution when no route matches. @@ -6442,9 +6762,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_router/ Name cowboy_router - Router middleware - Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. - The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. - When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. +The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. +When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +The router will stop execution when no route matches. @@ -6454,9 +6775,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_router/ Name cowboy_router - Router middleware - Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. - The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. - When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. +The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. +When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +The router will stop execution when no route matches. @@ -6466,9 +6788,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_router/ Name cowboy_router - Router middleware - Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. - The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. - When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +Description The cowboy_router middleware maps the requested host and path to the handler to be used for processing the request. +The router takes the dispatch rules as input from the middleware environment. Dispatch rules are generated by calling the cowboy_router:compile(3) function. +When a route matches, the router sets the handler and handler_opts middleware environment values containing the handler module and initial state, respectively. +The router will stop execution when no route matches. @@ -6478,9 +6801,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_router.compile/ Name cowboy_router:compile - Compile routes to the resources - Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. - Takes a human readable list of routes and transforms it into a form more efficient to process. - Arguments Routes Human readable list of routes. Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. +Takes a human readable list of routes and transforms it into a form more efficient to process. +Arguments Routes Human readable list of routes. + Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Changelog 1.0: Function introduced. Examples Compile routes and start a listener Dispatch = cowboy_router:compile([ {'_', [ {" @@ -6490,9 +6815,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_router.compile/ Name cowboy_router:compile - Compile routes to the resources - Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. - Takes a human readable list of routes and transforms it into a form more efficient to process. - Arguments Routes Human readable list of routes. Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. +Takes a human readable list of routes and transforms it into a form more efficient to process. +Arguments Routes Human readable list of routes. + Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Changelog 1.0: Function introduced. Examples Compile routes and start a listener Dispatch = cowboy_router:compile([ {'_', [ {" @@ -6502,9 +6829,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_router.compile/ Name cowboy_router:compile - Compile routes to the resources - Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. - Takes a human readable list of routes and transforms it into a form more efficient to process. - Arguments Routes Human readable list of routes. Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. +Takes a human readable list of routes and transforms it into a form more efficient to process. +Arguments Routes Human readable list of routes. + Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Changelog 1.0: Function introduced. Examples Compile routes and start a listener Dispatch = cowboy_router:compile([ {'_', [ {" @@ -6514,9 +6843,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_router.compile/ Name cowboy_router:compile - Compile routes to the resources - Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. - Takes a human readable list of routes and transforms it into a form more efficient to process. - Arguments Routes Human readable list of routes. Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. +Takes a human readable list of routes and transforms it into a form more efficient to process. +Arguments Routes Human readable list of routes. + Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Changelog 1.0: Function introduced. Examples Compile routes and start a listener Dispatch = cowboy_router:compile([ {'_', [ {" @@ -6526,9 +6857,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_router.compile/ Name cowboy_router:compile - Compile routes to the resources - Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. - Takes a human readable list of routes and transforms it into a form more efficient to process. - Arguments Routes Human readable list of routes. Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Description compile(cowboy_router:routes()) -&gt; cowboy_router:dispatch_rules() Compile routes to the resources. +Takes a human readable list of routes and transforms it into a form more efficient to process. +Arguments Routes Human readable list of routes. + Return value An opaque dispatch rules value is returned. This value must be given to Cowboy as a middleware environment value. +Changelog 1.0: Function introduced. Examples Compile routes and start a listener Dispatch = cowboy_router:compile([ {'_', [ {" @@ -6538,9 +6871,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_static/ Name cowboy_static - Static file handler - Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. - The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. - Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. +Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. +The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. +Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. @@ -6550,9 +6883,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_static/ Name cowboy_static - Static file handler - Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. - The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. - Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. +Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. +The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. +Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. @@ -6562,9 +6895,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_static/ Name cowboy_static - Static file handler - Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. - The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. - Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. +Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. +The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. +Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. @@ -6574,9 +6907,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_static/ Name cowboy_static - Static file handler - Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. - The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. - Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. +Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. +The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. +Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. @@ -6586,9 +6919,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_static/ Name cowboy_static - Static file handler - Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. - The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. - Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. +Description The module cowboy_static implements file serving capabilities using the REST semantics provided by cowboy_rest. +The static file handler is a pre-written handler coming with Cowboy. To serve files, use it in your routes. +Options opts() :: {priv_file, App, Path} | {priv_file, App, Path, Extra} | {file, Path} | {file, Path, Extra} | {priv_dir, App, Path} | {priv_dir, App, Path, Extra} | {dir, Path} | {dir, Path, Extra} App :: atom() Path :: binary() | string() Extra :: [Etag | Mimetypes] Etag :: {etag, module(), function()} | {etag, false} Mimetypes :: {mimetypes, module(), function()} | {mimetypes, binary() | ParsedMime} ParsedMime :: {Type :: binary(), SubType :: binary(), Params} Params :: [{Key :: binary(), Value :: binary()}] Static handler configuration. @@ -6598,9 +6931,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_stream/ Name cowboy_handler - Stream handlers - Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. - An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. - Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. +An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. +Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Extra care must be taken when implementing stream handlers to ensure compatibility. @@ -6610,9 +6944,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_stream/ Name cowboy_handler - Stream handlers - Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. - An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. - Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. +An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. +Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Extra care must be taken when implementing stream handlers to ensure compatibility. @@ -6622,9 +6957,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_stream/ Name cowboy_handler - Stream handlers - Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. - An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. - Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. +An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. +Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Extra care must be taken when implementing stream handlers to ensure compatibility. @@ -6634,9 +6970,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_stream/ Name cowboy_handler - Stream handlers - Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. - An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. - Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. +An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. +Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Extra care must be taken when implementing stream handlers to ensure compatibility. @@ -6646,9 +6983,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_stream/ Name cowboy_handler - Stream handlers - Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. - An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. - Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Description The module cowboy_stream defines a callback interface and a protocol for handling HTTP streams. +An HTTP request and its associated response is called a stream. A connection may have many streams. In HTTP/1.1 they are executed sequentially, while in HTTP/2 they are executed concurrently. +Cowboy calls the stream handler for nearly all events related to a stream. Exceptions vary depending on the protocol. +Extra care must be taken when implementing stream handlers to ensure compatibility. @@ -6658,9 +6996,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.0/manual/cowboy_websocket/ Name cowboy_websocket - Websocket - Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. - Callbacks Websocket handlers must implement the following callback interface: - init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. +Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. +Callbacks Websocket handlers must implement the following callback interface: +init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. @@ -6670,9 +7008,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.1/manual/cowboy_websocket/ Name cowboy_websocket - Websocket - Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. - Callbacks Websocket handlers must implement the following callback interface: - init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. +Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. +Callbacks Websocket handlers must implement the following callback interface: +init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. @@ -6682,9 +7020,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.2/manual/cowboy_websocket/ Name cowboy_websocket - Websocket - Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. - Callbacks Websocket handlers must implement the following callback interface: - init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. +Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. +Callbacks Websocket handlers must implement the following callback interface: +init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. @@ -6694,9 +7032,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.3/manual/cowboy_websocket/ Name cowboy_websocket - Websocket - Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. - Callbacks Websocket handlers must implement the following callback interface: - init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. +Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. +Callbacks Websocket handlers must implement the following callback interface: +init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. @@ -6706,9 +7044,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/cowboy/2.4/manual/cowboy_websocket/ Name cowboy_websocket - Websocket - Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. - Callbacks Websocket handlers must implement the following callback interface: - init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. +Description The module cowboy_websocket implements Websocket as a Ranch protocol. It also defines a callback interface for handling Websocket connections. +Callbacks Websocket handlers must implement the following callback interface: +init(Req, State) -&gt; {cowboy_websocket, Req, State} | {cowboy_websocket, Req, State, Opts} websocket_init(State) -&gt; CallResult %% optional websocket_handle(InFrame, State) -&gt; CallResult websocket_info(Info, State) -&gt; CallResult terminate(Reason, PartialReq, State) -&gt; ok %% optional Req :: cowboy_req:req() PartialReq :: map() State :: any() Opts :: cowboy_websocket:opts() InFrame :: {text | binary | ping | pong, binary()} OutFrame :: cow_ws:frame() %% see types below Info :: any() CallResult :: {ok, State} | {ok, State, hibernate} | {reply, OutFrame | [OutFrame], State} | {reply, OutFrame | [OutFrame], State, hibernate} | {stop, State} Reason :: normal | stop | timeout | remote | {remote, cow_ws:close_code(), binary()} | {error, badencoding | badframe | closed | atom()} | {crash, error | exit | throw, any()} The init/2 callback is common to all handlers. @@ -6718,9 +7056,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun/ Name gun - Asynchronous HTTP client - Description The gun module provides an asynchronous interface for connecting and communicating with Web servers over HTTP, HTTP/2 or Websocket. - Exports Connection: - gun:open(3) - Open a connection to the given host and port gun:open_unix(3) - Open a connection to the given Unix domain socket gun:close(3) - Brutally close the connection gun:info(3) - Obtain information about the connection Requests: +Description The gun module provides an asynchronous interface for connecting and communicating with Web servers over HTTP, HTTP/2 or Websocket. +Exports Connection: +gun:open(3) - Open a connection to the given host and port gun:open_unix(3) - Open a connection to the given Unix domain socket gun:close(3) - Brutally close the connection gun:info(3) - Obtain information about the connection Requests: @@ -6730,9 +7068,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun_app/ Name gun - HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP - Description Gun is an HTTP client for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. - Gun aims to provide an easy to use, asynchronous and always-connected client. It maintains a permanent connection to the server and reconnects automatically when necessary. - Modules gun(3) - Asynchronous HTTP client Dependencies cowlib(7) - Support library for manipulating Web protocols ssl - Secure communication over sockets All these applications must be started before the gun application. +Description Gun is an HTTP client for Erlang/OTP with support for the HTTP/1.1, HTTP/2 and Websocket protocols. +Gun aims to provide an easy to use, asynchronous and always-connected client. It maintains a permanent connection to the server and reconnects automatically when necessary. +Modules gun(3) - Asynchronous HTTP client Dependencies cowlib(7) - Support library for manipulating Web protocols ssl - Secure communication over sockets All these applications must be started before the gun application. @@ -6742,8 +7080,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.await/ Name gun:await - Wait for a response - Description await(ConnPid, StreamRef) -&gt; await(ConnPid, StreamRef, 5000, MonitorRef) await(ConnPid, StreamRef, MonitorRef) -&gt; await(ConnPid, StreamRef, 5000, MonitorRef) await(ConnPid, StreamRef, Timeout) -&gt; await(ConnPid, StreamRef, Timeout, MonitorRef) await(ConnPid, StreamRef, Timeout, MonitorRef) -&gt; Result ConnPid :: pid() StreamRef :: reference() MonitorRef :: reference() Timeout :: timeout() Result :: tuple() - see below Wait for a response. - This function waits for a message from the given stream and returns it as a tuple. +Description await(ConnPid, StreamRef) -&gt; await(ConnPid, StreamRef, 5000, MonitorRef) await(ConnPid, StreamRef, MonitorRef) -&gt; await(ConnPid, StreamRef, 5000, MonitorRef) await(ConnPid, StreamRef, Timeout) -&gt; await(ConnPid, StreamRef, Timeout, MonitorRef) await(ConnPid, StreamRef, Timeout, MonitorRef) -&gt; Result ConnPid :: pid() StreamRef :: reference() MonitorRef :: reference() Timeout :: timeout() Result :: tuple() - see below Wait for a response. +This function waits for a message from the given stream and returns it as a tuple. @@ -6753,7 +7091,7 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.await_body/ Name gun:await_body - Wait for the complete response body - Description await_body(ConnPid, StreamRef) -&gt; await_body(ConnPid, StreamRef, 5000, MonitorRef) await_body(ConnPid, StreamRef, MonitorRef) -&gt; await_body(ConnPid, StreamRef, 5000, MonitorRef) await_body(ConnPid, StreamRef, Timeout) -&gt; await_body(ConnPid, StreamRef, Timeout, MonitorRef) await_body(ConnPid, StreamRef, Timeout, MonitorRef) -&gt; {ok, Body} | {ok, Body, Trailers} | {error, Reason} ConnPid :: pid() StreamRef :: reference() MonitorRef :: reference() Timeout :: timeout() Body :: binary() Trailers :: [{binary(), binary()}] Reason :: timeout | any() Wait for the complete response body. +Description await_body(ConnPid, StreamRef) -&gt; await_body(ConnPid, StreamRef, 5000, MonitorRef) await_body(ConnPid, StreamRef, MonitorRef) -&gt; await_body(ConnPid, StreamRef, 5000, MonitorRef) await_body(ConnPid, StreamRef, Timeout) -&gt; await_body(ConnPid, StreamRef, Timeout, MonitorRef) await_body(ConnPid, StreamRef, Timeout, MonitorRef) -&gt; {ok, Body} | {ok, Body, Trailers} | {error, Reason} ConnPid :: pid() StreamRef :: reference() MonitorRef :: reference() Timeout :: timeout() Body :: binary() Trailers :: [{binary(), binary()}] Reason :: timeout | any() Wait for the complete response body. @@ -6763,8 +7101,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.await_up/ Name gun:await_up - Wait for the connection to be up - Description await_up(ConnPid) -&gt; await_up(ConnPid, 5000, MonitorRef) await_up(ConnPid, MonitorRef) -&gt; await_up(ConnPid, 5000, MonitorRef) await_up(ConnPid, Timeout) -&gt; await_up(ConnPid, Timeout, MonitorRef) await_up(ConnPid, Timeout, MonitorRef) -&gt; {ok, Protocol} | {error, Reason} ConnPid :: pid() MonitorRef :: reference() Timeout :: timeout() Protocol :: http | http2 Reason :: timeout | any() Wait for the connection to be up. - Arguments ConnPid The pid of the Gun connection process. +Description await_up(ConnPid) -&gt; await_up(ConnPid, 5000, MonitorRef) await_up(ConnPid, MonitorRef) -&gt; await_up(ConnPid, 5000, MonitorRef) await_up(ConnPid, Timeout) -&gt; await_up(ConnPid, Timeout, MonitorRef) await_up(ConnPid, Timeout, MonitorRef) -&gt; {ok, Protocol} | {error, Reason} ConnPid :: pid() MonitorRef :: reference() Timeout :: timeout() Protocol :: http | http2 Reason :: timeout | any() Wait for the connection to be up. +Arguments ConnPid The pid of the Gun connection process. @@ -6774,9 +7112,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.cancel/ Name gun:cancel - Cancel the given stream - Description cancel(ConnPid, StreamRef) -&gt; ok ConnPid :: pid() StreamRef :: reference() Cancel the given stream. - The behavior of this function depends on the protocol selected. - HTTP/1.1 does not support this feature. Gun will simply silence the stream and stop relaying messages. Gun may also decide to close the connection if the response body is too large, to avoid wasting time and bandwidth. +Description cancel(ConnPid, StreamRef) -&gt; ok ConnPid :: pid() StreamRef :: reference() Cancel the given stream. +The behavior of this function depends on the protocol selected. +HTTP/1.1 does not support this feature. Gun will simply silence the stream and stop relaying messages. Gun may also decide to close the connection if the response body is too large, to avoid wasting time and bandwidth. @@ -6786,9 +7124,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.close/ Name gun:close - Brutally close the connection - Description close(ConnPid) -&gt; ok ConnPid :: pid() Brutally close the connection. - Arguments ConnPid The pid of the Gun connection process. Return value The atom ok is returned. - Changelog 1.0: Function introduced. Examples Close the connection ok = gun:close(ConnPid). See also gun(3), gun:open(3), gun:open_unix(3) +Description close(ConnPid) -&gt; ok ConnPid :: pid() Brutally close the connection. +Arguments ConnPid The pid of the Gun connection process. + Return value The atom ok is returned. +Changelog 1.0: Function introduced. Examples Close the connection ok = gun:close(ConnPid). See also gun(3), gun:open(3), gun:open_unix(3) @@ -6798,9 +7137,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.data/ Name gun:data - Stream the body of a request - Description data(ConnPid, StreamRef, IsFin, Data) -&gt; ok ConnPid :: pid() StreamRef :: reference() IsFin :: fin | nofin Data :: iodata() Stream the body of a request. - This function can only be used if the original request had headers indicating that a body would be streamed. - All calls to this function must use the nofin flag except for the last which must use fin to indicate the end of the request body. +Description data(ConnPid, StreamRef, IsFin, Data) -&gt; ok ConnPid :: pid() StreamRef :: reference() IsFin :: fin | nofin Data :: iodata() Stream the body of a request. +This function can only be used if the original request had headers indicating that a body would be streamed. +All calls to this function must use the nofin flag except for the last which must use fin to indicate the end of the request body. @@ -6810,8 +7149,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.delete/ Name gun:delete - Delete a resource - Description delete(ConnPid, Path) -&gt; delete(ConnPid, Path, [], #{}). delete(ConnPid, Path, Headers) -&gt; delete(ConnPid, Path, Headers, #{}) delete(ConnPid, Path, Headers, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] ReqOpts :: gun:req_opts() StreamRef :: reference() Delete a resource. - Arguments ConnPid The pid of the Gun connection process. Path Path to the resource. +Description delete(ConnPid, Path) -&gt; delete(ConnPid, Path, [], #{}). delete(ConnPid, Path, Headers) -&gt; delete(ConnPid, Path, Headers, #{}) delete(ConnPid, Path, Headers, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] ReqOpts :: gun:req_opts() StreamRef :: reference() Delete a resource. +Arguments ConnPid The pid of the Gun connection process. + Path Path to the resource. + Headers Additional request headers. + ReqOpts Request options. @@ -6821,9 +7163,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.flush/ Name gun:flush - Flush all messages related to a connection or a stream - Description flush(ConnPid) -&gt; ok flush(StreamRef) -&gt; ok ConnPid :: pid() StreamRef :: reference() Flush all messages related to a connection or a stream. - Arguments Either of these arguments may be provided: - ConnPid The pid of the Gun connection process. StreamRef Identifier of the stream for the original request. +Description flush(ConnPid) -&gt; ok flush(StreamRef) -&gt; ok ConnPid :: pid() StreamRef :: reference() Flush all messages related to a connection or a stream. +Arguments Either of these arguments may be provided: +ConnPid The pid of the Gun connection process. + StreamRef Identifier of the stream for the original request. + Return value The atom ok is returned. @@ -6833,8 +7177,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.get/ Name gun:get - Get a resource representation - Description get(ConnPid, Path) -&gt; get(ConnPid, Path, [], #{}). get(ConnPid, Path, Headers) -&gt; get(ConnPid, Path, Headers, #{}) get(ConnPid, Path, Headers, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] ReqOpts :: gun:req_opts() StreamRef :: reference() Get a resource representation. - Arguments ConnPid The pid of the Gun connection process. Path Path to the resource. +Description get(ConnPid, Path) -&gt; get(ConnPid, Path, [], #{}). get(ConnPid, Path, Headers) -&gt; get(ConnPid, Path, Headers, #{}) get(ConnPid, Path, Headers, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] ReqOpts :: gun:req_opts() StreamRef :: reference() Get a resource representation. +Arguments ConnPid The pid of the Gun connection process. + Path Path to the resource. + Headers Additional request headers. @@ -6844,8 +7190,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.head/ Name gun:head - Get headers of a resource representation - Description head(ConnPid, Path) -&gt; head(ConnPid, Path, [], #{}). head(ConnPid, Path, Headers) -&gt; head(ConnPid, Path, Headers, #{}) head(ConnPid, Path, Headers, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] ReqOpts :: gun:req_opts() StreamRef :: reference() Get headers of a resource representation. - This function performs the same operation as gun:get(3), except the server will not send the resource representation, only the response&#8217;s status code and headers. +Description head(ConnPid, Path) -&gt; head(ConnPid, Path, [], #{}). head(ConnPid, Path, Headers) -&gt; head(ConnPid, Path, Headers, #{}) head(ConnPid, Path, Headers, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] ReqOpts :: gun:req_opts() StreamRef :: reference() Get headers of a resource representation. +This function performs the same operation as gun:get(3), except the server will not send the resource representation, only the response&apos;s status code and headers. @@ -6855,9 +7201,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.info/ Name gun:info - Obtain information about the connection - Description info(ConnPid) -&gt; Info ConnPid :: pid() Info :: #{ sock_ip =&gt; inet:ip_address(), sock_port =&gt; inet:port_number() } Obtain information about the connection. - Arguments ConnPid The pid of the Gun connection process. Return value A map is returned containing various informations about the connection. - Changelog 1. +Description info(ConnPid) -&gt; Info ConnPid :: pid() Info :: #{ sock_ip =&gt; inet:ip_address(), sock_port =&gt; inet:port_number() } Obtain information about the connection. +Arguments ConnPid The pid of the Gun connection process. + Return value A map is returned containing various informations about the connection. +Changelog 1.0: Function introduced. Examples Obtain information about the connection Info = gun:info(ConnPid). See also gun(3), gun:open(3), gun:open_unix(3) @@ -6867,8 +7214,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.open/ Name gun:open - Open a connection to the given host and port - Description open(Host, Port) -&gt; open(Host, Port, #{}) open(Host, Port, Opts) -&gt; {ok, pid()} | {error, any()} Host :: inet:hostname() | inet:ip_address() Port :: inet:port_number() Opts :: gun:opts() Open a connection to the given host and port. - Arguments Host Host or IP address to connect to. Port Port to connect to. +Description open(Host, Port) -&gt; open(Host, Port, #{}) open(Host, Port, Opts) -&gt; {ok, pid()} | {error, any()} Host :: inet:hostname() | inet:ip_address() Port :: inet:port_number() Opts :: gun:opts() Open a connection to the given host and port. +Arguments Host Host or IP address to connect to. + Port Port to connect to. + Opts Options for this connection. @@ -6878,8 +7227,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.open_unix/ Name gun:open_unix - Open a connection to the given Unix domain socket - Description open_unix(SocketPath, Opts) -&gt; {ok, pid()} | {error, any()} SocketPath :: string() Opts :: gun:opts() Open a connection to the given Unix domain socket. - Arguments SocketPath Path to the Unix domain socket to connect to. Opts Options for this connection. Return value The pid of the newly created Gun process is returned. +Description open_unix(SocketPath, Opts) -&gt; {ok, pid()} | {error, any()} SocketPath :: string() Opts :: gun:opts() Open a connection to the given Unix domain socket. +Arguments SocketPath Path to the Unix domain socket to connect to. + Opts Options for this connection. + Return value The pid of the newly created Gun process is returned. Note that this does not indicate that the connection has been successfully opened; the gun_up(3) message will be sent for that. @@ -6889,8 +7240,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.options/ Name gun:options - Query the capabilities of the server or a resource - Description options(ConnPid, Path) -&gt; options(ConnPid, Path, [], #{}). options(ConnPid, Path, Headers) -&gt; options(ConnPid, Path, Headers, #{}) options(ConnPid, Path, Headers, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] ReqOpts :: gun:req_opts() StreamRef :: reference() Query the capabilities of the server or a resource. - The special path "*" can be used to obtain information about the server as a whole. +Description options(ConnPid, Path) -&gt; options(ConnPid, Path, [], #{}). options(ConnPid, Path, Headers) -&gt; options(ConnPid, Path, Headers, #{}) options(ConnPid, Path, Headers, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] ReqOpts :: gun:req_opts() StreamRef :: reference() Query the capabilities of the server or a resource. +The special path &quot;*&quot; can be used to obtain information about the server as a whole. @@ -6900,8 +7251,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.patch/ Name gun:patch - Apply a set of changes to a resource - Description patch(ConnPid, Path, Headers) -&gt; StreamRef patch(ConnPid, Path, Headers, Body) -&gt; patch(ConnPid, Path, Headers, Body, #{}) patch(ConnPid, Path, Headers, Body, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] Body :: iodata() ReqOpts :: gun:req_opts() StreamRef :: reference() Apply a set of changes to a resource. - The behavior of this function varies depending on whether a body is provided. +Description patch(ConnPid, Path, Headers) -&gt; StreamRef patch(ConnPid, Path, Headers, Body) -&gt; patch(ConnPid, Path, Headers, Body, #{}) patch(ConnPid, Path, Headers, Body, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] Body :: iodata() ReqOpts :: gun:req_opts() StreamRef :: reference() Apply a set of changes to a resource. +The behavior of this function varies depending on whether a body is provided. @@ -6910,9 +7261,9 @@ Crowdfund my salary or buy The Erlanger Playbook Mon, 01 Jan 0001 00:00:00 +0000 https://ninenines.eu/docs/en/gun/1.0/manual/gun.post/ - Name gun:post - Process the enclosed representation according to a resource&#8217;s own semantics - Description post(ConnPid, Path, Headers) -&gt; StreamRef post(ConnPid, Path, Headers, Body) -&gt; post(ConnPid, Path, Headers, Body, #{}) post(ConnPid, Path, Headers, Body, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] Body :: iodata() ReqOpts :: gun:req_opts() StreamRef :: reference() Process the enclosed representation according to a resource&#8217;s own semantics. - The behavior of this function varies depending on whether a body is provided. + Name gun:post - Process the enclosed representation according to a resource&apos;s own semantics +Description post(ConnPid, Path, Headers) -&gt; StreamRef post(ConnPid, Path, Headers, Body) -&gt; post(ConnPid, Path, Headers, Body, #{}) post(ConnPid, Path, Headers, Body, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] Body :: iodata() ReqOpts :: gun:req_opts() StreamRef :: reference() Process the enclosed representation according to a resource&apos;s own semantics. +The behavior of this function varies depending on whether a body is provided. @@ -6922,8 +7273,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.put/ Name gun:put - Create or replace a resource - Description put(ConnPid, Path, Headers) -&gt; StreamRef put(ConnPid, Path, Headers, Body) -&gt; put(ConnPid, Path, Headers, Body, #{}) put(ConnPid, Path, Headers, Body, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] Body :: iodata() ReqOpts :: gun:req_opts() StreamRef :: reference() Create or replace a resource. - The behavior of this function varies depending on whether a body is provided. +Description put(ConnPid, Path, Headers) -&gt; StreamRef put(ConnPid, Path, Headers, Body) -&gt; put(ConnPid, Path, Headers, Body, #{}) put(ConnPid, Path, Headers, Body, ReqOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] Body :: iodata() ReqOpts :: gun:req_opts() StreamRef :: reference() Create or replace a resource. +The behavior of this function varies depending on whether a body is provided. +The function put/3 expects either a content-length or content-type header to indicate that a body will be sent afterwards. @@ -6933,8 +7285,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.request/ Name gun:request - Perform the given request - Description request(ConnPid, Method, Path, Headers) -&gt; StreamRef request(ConnPid, Method, Path, Headers, Body) -&gt; request(ConnPid, Method, Path, Headers, Body, #{}) request(ConnPid, Method, Path, Headers, Body, ReqOpts) -&gt; StreamRef ConnPid :: pid() Method :: binary() Path :: iodata() Headers :: [{binary(), iodata()}] Body :: iodata() ReqOpts :: gun:req_opts() StreamRef :: reference() Perform the given request. - This is a general purpose function that should only be used when other method-specific functions do not apply. +Description request(ConnPid, Method, Path, Headers) -&gt; StreamRef request(ConnPid, Method, Path, Headers, Body) -&gt; request(ConnPid, Method, Path, Headers, Body, #{}) request(ConnPid, Method, Path, Headers, Body, ReqOpts) -&gt; StreamRef ConnPid :: pid() Method :: binary() Path :: iodata() Headers :: [{binary(), iodata()}] Body :: iodata() ReqOpts :: gun:req_opts() StreamRef :: reference() Perform the given request. +This is a general purpose function that should only be used when other method-specific functions do not apply. @@ -6944,9 +7296,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.ws_send/ Name gun:ws_send - Send Websocket frames - Description ws_send(ConnPid, Frames) -&gt; ok ConnPid :: pid() Frames :: Frame | [Frame] Frame :: close | ping | pong | {text | binary | close | ping | pong, iodata()} | {close, non_neg_integer(), iodata()} Send Websocket frames. - The connection must first be upgraded to Websocket using the function gun:ws_upgrade(3). - Arguments ConnPid The pid of the Gun connection process. +Description ws_send(ConnPid, Frames) -&gt; ok ConnPid :: pid() Frames :: Frame | [Frame] Frame :: close | ping | pong | {text | binary | close | ping | pong, iodata()} | {close, non_neg_integer(), iodata()} Send Websocket frames. +The connection must first be upgraded to Websocket using the function gun:ws_upgrade(3). +Arguments ConnPid The pid of the Gun connection process. + Frames A Websocket frame. @@ -6956,9 +7309,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun.ws_upgrade/ Name gun:ws_upgrade - Upgrade to Websocket - Description ws_upgrade(ConnPid, Path) -&gt; ws_upgrade(ConnPid, Path, []) ws_upgrade(ConnPid, Path, Headers) -&gt; StreamRef ws_upgrade(ConnPid, Path, Headers, WsOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] WsOpts :: gun:ws_opts StreamRef :: reference() Upgrade to Websocket. - The behavior of this function depends on the protocol selected. - HTTP/1.1 cannot handle Websocket and HTTP requests concurrently. The upgrade, if successful, will result in the complete takeover of the connection. +Description ws_upgrade(ConnPid, Path) -&gt; ws_upgrade(ConnPid, Path, []) ws_upgrade(ConnPid, Path, Headers) -&gt; StreamRef ws_upgrade(ConnPid, Path, Headers, WsOpts) -&gt; StreamRef ConnPid :: pid() Path :: iodata() Headers :: [{binary(), iodata()}] WsOpts :: gun:ws_opts StreamRef :: reference() Upgrade to Websocket. +The behavior of this function depends on the protocol selected. +HTTP/1.1 cannot handle Websocket and HTTP requests concurrently. The upgrade, if successful, will result in the complete takeover of the connection. @@ -6968,10 +7321,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun_data/ Name gun_data - Response body - Description {gun_data, ConnPid, StreamRef, IsFin, Data} ConnPid :: pid() StreamRef :: reference() IsFin :: fin | nofin Data :: binary() Response body. - This message informs the relevant process that the server sent a all or part of the body for the response to the original request. - A data message is always preceded by a response message. - The response body may be terminated either by a data message with the flag fin set or by a gun_trailers(3) message. +Description {gun_data, ConnPid, StreamRef, IsFin, Data} ConnPid :: pid() StreamRef :: reference() IsFin :: fin | nofin Data :: binary() Response body. +This message informs the relevant process that the server sent a all or part of the body for the response to the original request. +A data message is always preceded by a response message. +The response body may be terminated either by a data message with the flag fin set or by a gun_trailers(3) message. @@ -6981,9 +7334,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun_down/ Name gun_down - The connection is down - Description {gun_down, ConnPid, Protocol, Reason, KilledStreams, UnprocessedStreams} ConnPid :: pid() Protocol :: http | http2 | ws Reason :: any() KilledStreams :: [reference()] UnprocessedStreams :: [reference()] The connection is down. - This message informs the owner process that the connection was lost. Depending on the retry and retry_timeout options Gun may automatically attempt to reconnect. - When the connection goes back up, Gun will not attempt to retry requests. +Description {gun_down, ConnPid, Protocol, Reason, KilledStreams, UnprocessedStreams} ConnPid :: pid() Protocol :: http | http2 | ws Reason :: any() KilledStreams :: [reference()] UnprocessedStreams :: [reference()] The connection is down. +This message informs the owner process that the connection was lost. Depending on the retry and retry_timeout options Gun may automatically attempt to reconnect. +When the connection goes back up, Gun will not attempt to retry requests. @@ -6993,8 +7346,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun_error/ Name gun_error - Stream or connection-wide error - Description {gun_error, ConnPid, StreamRef, Reason} {gun_error, ConnPid, Reason} ConnPid :: pid() StreamRef :: reference() Reason :: any() Stream or connection-wide error. - These messages inform the relevant process that an error occurred. A reference is given when the error pertains to a specific stream. Connection-wide errors do not imply that the connection is no longer usable, they are used for all errors that are not specific to a stream. +Description {gun_error, ConnPid, StreamRef, Reason} {gun_error, ConnPid, Reason} ConnPid :: pid() StreamRef :: reference() Reason :: any() Stream or connection-wide error. +These messages inform the relevant process that an error occurred. A reference is given when the error pertains to a specific stream. Connection-wide errors do not imply that the connection is no longer usable, they are used for all errors that are not specific to a stream. @@ -7004,9 +7357,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun_inform/ Name gun_inform - Informational response - Description {gun_inform, ConnPid, StreamRef, Status, Headers} ConnPid :: pid() StreamRef :: reference() Status :: 100..199 Headers :: [{binary(), binary()}] Informational response. - This message informs the relevant process that the server sent an informational response to the original request. - Informational responses are only intermediate responses and provide no guarantees as to what the final response will be. An informational response always precedes the response to the original request. +Description {gun_inform, ConnPid, StreamRef, Status, Headers} ConnPid :: pid() StreamRef :: reference() Status :: 100..199 Headers :: [{binary(), binary()}] Informational response. +This message informs the relevant process that the server sent an informational response to the original request. +Informational responses are only intermediate responses and provide no guarantees as to what the final response will be. An informational response always precedes the response to the original request. @@ -7016,9 +7369,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun_push/ Name gun_push - Server-initiated push - Description {gun_push, ConnPid, StreamRef, NewStreamRef, Method, URI, Headers} ConnPid :: pid() StreamRef :: reference() NewStreamRef :: reference() Method :: binary() URI :: binary() Headers :: [{binary(), binary()}] Server-initiated push. - This message informs the relevant process that the server is pushing a resource related to the effective target URI of the original request. - A server-initiated push message always precedes the response to the original request. +Description {gun_push, ConnPid, StreamRef, NewStreamRef, Method, URI, Headers} ConnPid :: pid() StreamRef :: reference() NewStreamRef :: reference() Method :: binary() URI :: binary() Headers :: [{binary(), binary()}] Server-initiated push. +This message informs the relevant process that the server is pushing a resource related to the effective target URI of the original request. +A server-initiated push message always precedes the response to the original request. @@ -7028,9 +7381,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun_response/ Name gun_response - Response - Description {gun_response, ConnPid, StreamRef, IsFin, Status, Headers} ConnPid :: pid() StreamRef :: reference() IsFin :: fin | nofin Status :: non_neg_integer() Headers :: [{binary(), binary()}] Response. - This message informs the relevant process that the server sent a response to the original request. - Elements ConnPid The pid of the Gun connection process. StreamRef Identifier of the stream for the original request. +Description {gun_response, ConnPid, StreamRef, IsFin, Status, Headers} ConnPid :: pid() StreamRef :: reference() IsFin :: fin | nofin Status :: non_neg_integer() Headers :: [{binary(), binary()}] Response. +This message informs the relevant process that the server sent a response to the original request. +Elements ConnPid The pid of the Gun connection process. + StreamRef Identifier of the stream for the original request. + IsFin Whether this message terminates the response. @@ -7040,10 +7395,12 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun_trailers/ Name gun_trailers - Response trailers - Description {gun_trailers, ConnPid, StreamRef, Headers} ConnPid :: pid() StreamRef :: reference() Headers :: [{binary(), binary()}] Response trailers. - This message informs the relevant process that the server sent response trailers for the response to the original request. - A trailers message terminates the response. - Elements ConnPid The pid of the Gun connection process. StreamRef Identifier of the stream for the original request. +Description {gun_trailers, ConnPid, StreamRef, Headers} ConnPid :: pid() StreamRef :: reference() Headers :: [{binary(), binary()}] Response trailers. +This message informs the relevant process that the server sent response trailers for the response to the original request. +A trailers message terminates the response. +Elements ConnPid The pid of the Gun connection process. + StreamRef Identifier of the stream for the original request. + Headers Trailing headers sent after the response body. @@ -7053,9 +7410,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun_up/ Name gun_up - The connection is up - Description {gun_up, ConnPid, Protocol} ConnPid :: pid() Protocol :: http | http2 The connection is up. - This message informs the owner process that the connection or reconnection completed. - Gun will now start processing the messages it received while waiting for the connection to be up. If this is a reconnection, then this may not be desirable for all requests. +Description {gun_up, ConnPid, Protocol} ConnPid :: pid() Protocol :: http | http2 The connection is up. +This message informs the owner process that the connection or reconnection completed. +Gun will now start processing the messages it received while waiting for the connection to be up. If this is a reconnection, then this may not be desirable for all requests. Those requests should be cancelled when the connection goes down, and any subsequent messages ignored. @@ -7065,9 +7422,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun_upgrade/ Name gun_upgrade - Successful protocol upgrade - Description {gun_upgrade, ConnPid, StreamRef, Protocols, Headers} ConnPid :: pid() StreamRef :: reference() Protocols :: [&lt;&lt;"websocket"&gt;&gt;] Headers :: [{binary(), binary()}] Successful protocol upgrade. - This message informs the relevant process that the server accepted to upgrade to one or more protocols given in the original request. - The exact semantics of this message depend on the original protocol. HTTP/1.1 upgrades apply to the entire connection. +Description {gun_upgrade, ConnPid, StreamRef, Protocols, Headers} ConnPid :: pid() StreamRef :: reference() Protocols :: [&lt;&lt;"websocket"&gt;&gt;] Headers :: [{binary(), binary()}] Successful protocol upgrade. +This message informs the relevant process that the server accepted to upgrade to one or more protocols given in the original request. +The exact semantics of this message depend on the original protocol. HTTP/1.1 upgrades apply to the entire connection. HTTP/2 uses a different mechanism which allows switching specific streams to a different protocol. @@ -7077,10 +7434,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/gun/1.0/manual/gun_ws/ Name gun_ws - Websocket frame - Description {gun_ws, ConnPid, StreamRef, Frame} ConnPid :: pid() StreamRef :: reference() Frame :: close | {text | binary | close, binary()} | {close, non_neg_integer(), binary()} Websocket frame. - This message informs the relevant process that the server sent the enclosed frame. - This message can only be sent on streams that were upgraded to the Websocket protocol. - Elements ConnPid The pid of the Gun connection process. +Description {gun_ws, ConnPid, StreamRef, Frame} ConnPid :: pid() StreamRef :: reference() Frame :: close | {text | binary | close, binary()} | {close, non_neg_integer(), binary()} Websocket frame. +This message informs the relevant process that the server sent the enclosed frame. +This message can only be sent on streams that were upgraded to the Websocket protocol. +Elements ConnPid The pid of the Gun connection process. @@ -7090,9 +7447,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/ranch/1.2/manual/ranch/ Name ranch - socket acceptor pool - Description The ranch module provides functions for starting and manipulating Ranch listeners. - Types max_conns() = non_neg_integer() | infinity Maximum number of connections allowed on this listener. - This is a soft limit. The actual number of connections might be slightly above the limit due to concurrency when accepting new connections. Some connections may also be removed from this count explicitly by the user code. +Description The ranch module provides functions for starting and manipulating Ranch listeners. +Types max_conns() = non_neg_integer() | infinity Maximum number of connections allowed on this listener. +This is a soft limit. The actual number of connections might be slightly above the limit due to concurrency when accepting new connections. Some connections may also be removed from this count explicitly by the user code. +opt() opt() = {ack_timeout, timeout()} | {connection_type, worker | supervisor} | {max_connections, max_conns()} | {shutdown, timeout() | brutal_kill} | {socket, any()} Ranch-specific transport options. @@ -7102,9 +7460,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/ranch/1.3/manual/ranch/ Name ranch - socket acceptor pool - Description The ranch module provides functions for starting and manipulating Ranch listeners. - Types max_conns() = non_neg_integer() | infinity Maximum number of connections allowed on this listener. - This is a soft limit. The actual number of connections might be slightly above the limit due to concurrency when accepting new connections. Some connections may also be removed from this count explicitly by the user code. +Description The ranch module provides functions for starting and manipulating Ranch listeners. +Types max_conns() = non_neg_integer() | infinity Maximum number of connections allowed on this listener. +This is a soft limit. The actual number of connections might be slightly above the limit due to concurrency when accepting new connections. Some connections may also be removed from this count explicitly by the user code. +opt() opt() = {ack_timeout, timeout()} | {connection_type, worker | supervisor} | {max_connections, max_conns()} | {shutdown, timeout() | brutal_kill} | {socket, any()} Ranch-specific transport options. @@ -7114,9 +7473,23 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/ranch/1.4/manual/ranch/ Name ranch - socket acceptor pool - Description The ranch module provides functions for starting and manipulating Ranch listeners. - Types max_conns() = non_neg_integer() | infinity Maximum number of connections allowed on this listener. - This is a soft limit. The actual number of connections might be slightly above the limit due to concurrency when accepting new connections. Some connections may also be removed from this count explicitly by the user code. +Description The ranch module provides functions for starting and manipulating Ranch listeners. +Types max_conns() = non_neg_integer() | infinity Maximum number of connections allowed on this listener. +This is a soft limit. The actual number of connections might be slightly above the limit due to concurrency when accepting new connections. Some connections may also be removed from this count explicitly by the user code. +opt() opt() = {ack_timeout, timeout()} | {connection_type, worker | supervisor} | {max_connections, max_conns()} | {num_acceptors, pos_integer()} | {shutdown, timeout() | brutal_kill} | {socket, any()} Ranch-specific transport options. + + + + ranch(3) + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch/ + Name ranch - socket acceptor pool +Description The ranch module provides functions for starting and manipulating Ranch listeners. +Types max_conns() = non_neg_integer() | infinity Maximum number of connections allowed on this listener. +This is a soft limit. The actual number of connections might be slightly above the limit due to concurrency when accepting new connections. Some connections may also be removed from this count explicitly by the user code. +opt() opt() = {ack_timeout, timeout()} | {connection_type, worker | supervisor} | {max_connections, max_conns()} | {num_acceptors, pos_integer()} | {shutdown, timeout() | brutal_kill} | {socket, any()} Ranch-specific transport options. @@ -7126,10 +7499,11 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/ranch/1.2/manual/ranch_app/ Name ranch - Socket acceptor pool for TCP protocols. - Dependencies The ranch application has no particular dependency required to start. - It has optional dependencies that are only required when listening for SSL connections. The dependencies are crypto, asn1, public_key and ssl. They are started automatically if they weren&#8217;t before. - Environment The ranch application defines one application environment configuration parameter. - profile (false) When enabled, Ranch will start eprof profiling automatically. +Dependencies The ranch application has no particular dependency required to start. +It has optional dependencies that are only required when listening for SSL connections. The dependencies are crypto, asn1, public_key and ssl. They are started automatically if they weren&apos;t before. +Environment The ranch application defines one application environment configuration parameter. +profile (false) When enabled, Ranch will start eprof profiling automatically. + You can use the ranch_app:profile_output/0 function to stop profiling and output the results to the files procs. @@ -7139,9 +7513,10 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/ranch/1.3/manual/ranch_app/ Name ranch - Socket acceptor pool for TCP protocols. - Dependencies The ranch application depends on the ssl application to start. It is used for handling secure connections, when the transport is ranch_ssl. It can be disabled if SSL is not used. - Environment The ranch application defines one application environment configuration parameter. - profile (false) When enabled, Ranch will start eprof profiling automatically. +Dependencies The ranch application depends on the ssl application to start. It is used for handling secure connections, when the transport is ranch_ssl. It can be disabled if SSL is not used. +Environment The ranch application defines one application environment configuration parameter. +profile (false) When enabled, Ranch will start eprof profiling automatically. + You can use the ranch_app:profile_output/0 function to stop profiling and output the results to the files procs. @@ -7151,9 +7526,23 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/ranch/1.4/manual/ranch_app/ Name ranch - Socket acceptor pool for TCP protocols. - Dependencies The ranch application depends on the ssl application to start. It is used for handling secure connections, when the transport is ranch_ssl. It can be disabled if SSL is not used. - Environment The ranch application defines one application environment configuration parameter. - profile (false) When enabled, Ranch will start eprof profiling automatically. +Dependencies The ranch application depends on the ssl application to start. It is used for handling secure connections, when the transport is ranch_ssl. It can be disabled if SSL is not used. +Environment The ranch application defines one application environment configuration parameter. +profile (false) When enabled, Ranch will start eprof profiling automatically. + You can use the ranch_app:profile_output/0 function to stop profiling and output the results to the files procs. + + + + ranch(7) + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_app/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_app/ + Name ranch - Socket acceptor pool for TCP protocols. +Dependencies The ranch application depends on the ssl application to start. It is used for handling secure connections, when the transport is ranch_ssl. It can be disabled if SSL is not used. +Environment The ranch application defines one application environment configuration parameter. +profile (false) When enabled, Ranch will start eprof profiling automatically. + You can use the ranch_app:profile_output/0 function to stop profiling and output the results to the files procs. @@ -7163,9 +7552,13 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/ranch/1.2/manual/ranch_protocol/ Name ranch_protocol - behaviour for protocol modules - Description The ranch_protocol behaviour defines the interface used by Ranch protocols. - Types None. - Callbacks start_link(Ref, Socket, Transport, ProtoOpts) &#8594; {ok, pid()} | {ok, pid(), pid()} Ref = ranch:ref() Listener name. Socket = any() Socket for this connection. Transport = module() Transport module for this socket. +Description The ranch_protocol behaviour defines the interface used by Ranch protocols. +Types None. +Callbacks start_link(Ref, Socket, Transport, ProtoOpts) -&gt; {ok, pid()} | {ok, pid(), pid()} Ref = ranch:ref() Listener name. + Socket = any() Socket for this connection. + Transport = module() Transport module for this socket. + ProtoOpts = any() Protocol options. + Start a new connection process for the given socket. @@ -7175,9 +7568,13 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/ranch/1.3/manual/ranch_protocol/ Name ranch_protocol - behaviour for protocol modules - Description The ranch_protocol behaviour defines the interface used by Ranch protocols. - Types None. - Callbacks start_link(Ref, Socket, Transport, ProtoOpts) &#8594; {ok, pid()} | {ok, pid(), pid()} Ref = ranch:ref() Listener name. Socket = any() Socket for this connection. Transport = module() Transport module for this socket. +Description The ranch_protocol behaviour defines the interface used by Ranch protocols. +Types None. +Callbacks start_link(Ref, Socket, Transport, ProtoOpts) -&gt; {ok, pid()} | {ok, pid(), pid()} Ref = ranch:ref() Listener name. + Socket = any() Socket for this connection. + Transport = module() Transport module for this socket. + ProtoOpts = any() Protocol options. + Start a new connection process for the given socket. @@ -7187,9 +7584,29 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/ranch/1.4/manual/ranch_protocol/ Name ranch_protocol - behaviour for protocol modules - Description The ranch_protocol behaviour defines the interface used by Ranch protocols. - Types None. - Callbacks start_link(Ref, Socket, Transport, ProtoOpts) &#8594; {ok, pid()} | {ok, pid(), pid()} Ref = ranch:ref() Listener name. Socket = any() Socket for this connection. Transport = module() Transport module for this socket. +Description The ranch_protocol behaviour defines the interface used by Ranch protocols. +Types None. +Callbacks start_link(Ref, Socket, Transport, ProtoOpts) -&gt; {ok, pid()} | {ok, pid(), pid()} Ref = ranch:ref() Listener name. + Socket = any() Socket for this connection. + Transport = module() Transport module for this socket. + ProtoOpts = any() Protocol options. + Start a new connection process for the given socket. + + + + ranch_protocol(3) + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_protocol/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_protocol/ + Name ranch_protocol - behaviour for protocol modules +Description The ranch_protocol behaviour defines the interface used by Ranch protocols. +Types None. +Callbacks start_link(Ref, Socket, Transport, ProtoOpts) -&gt; {ok, pid()} | {ok, pid(), pid()} Ref = ranch:ref() Listener name. + Socket = any() Socket for this connection. + Transport = module() Transport module for this socket. + ProtoOpts = any() Protocol options. + Start a new connection process for the given socket. @@ -7199,8 +7616,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/ranch/1.2/manual/ranch_ssl/ Name ranch_ssl - SSL transport module - Description The ranch_ssl module implements an SSL Ranch transport. - Types ssl_opt() ssl_opt() = {alpn_preferred_protocols, [binary()]} | {cacertfile, string()} | {cacerts, [public_key:der_encoded()]} | {cert, public_key:der_encoded()} | {certfile, string()} | {ciphers, [ssl:erl_cipher_suite()] | string()} | {client_renegotiation, boolean()} | {crl_cache, {module(), {internal | any(), list()}}} | {crl_check, boolean() | peer | best_effort} | {depth, 0..255} | {dh, public_key:der_encoded()} | {dhfile, string()} | {fail_if_no_peer_cert, boolean()} | {hibernate_after, integer() | undefined} | {honor_cipher_order, boolean()} | {key, {'RSAPrivateKey' | 'DSAPrivateKey' | 'PrivateKeyInfo', public_key:der_encoded()}} | {keyfile, string()} | {log_alert, boolean()} | {next_protocols_advertised, [binary()]} | {partial_chain, fun(([public_key:der_encoded()]) -&gt; {trusted_ca, public_key:der_encoded()} | unknown_ca)} | {password, string()} | {psk_identity, string()} | {reuse_session, fun()} | {reuse_sessions, boolean()} | {secure_renegotiate, boolean()} | {sni_fun, fun()} | {sni_hosts, [{string(), ssl_opt()}]} | {user_lookup_fun, {fun(), any()}} | {verify, ssl:verify_type()} | {verify_fun, {fun(), any()}} | {versions, [atom()]}. +Description The ranch_ssl module implements an SSL Ranch transport. +Types ssl_opt() ssl_opt() = {alpn_preferred_protocols, [binary()]} | {cacertfile, string()} | {cacerts, [public_key:der_encoded()]} | {cert, public_key:der_encoded()} | {certfile, string()} | {ciphers, [ssl:erl_cipher_suite()] | string()} | {client_renegotiation, boolean()} | {crl_cache, {module(), {internal | any(), list()}}} | {crl_check, boolean() | peer | best_effort} | {depth, 0..255} | {dh, public_key:der_encoded()} | {dhfile, string()} | {fail_if_no_peer_cert, boolean()} | {hibernate_after, integer() | undefined} | {honor_cipher_order, boolean()} | {key, {'RSAPrivateKey' | 'DSAPrivateKey' | 'PrivateKeyInfo', public_key:der_encoded()}} | {keyfile, string()} | {log_alert, boolean()} | {next_protocols_advertised, [binary()]} | {partial_chain, fun(([public_key:der_encoded()]) -&gt; {trusted_ca, public_key:der_encoded()} | unknown_ca)} | {password, string()} | {psk_identity, string()} | {reuse_session, fun()} | {reuse_sessions, boolean()} | {secure_renegotiate, boolean()} | {sni_fun, fun()} | {sni_hosts, [{string(), ssl_opt()}]} | {user_lookup_fun, {fun(), any()}} | {verify, ssl:verify_type()} | {verify_fun, {fun(), any()}} | {versions, [atom()]}. @@ -7210,8 +7627,8 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/ranch/1.3/manual/ranch_ssl/ Name ranch_ssl - SSL transport module - Description The ranch_ssl module implements an SSL Ranch transport. - Types ssl_opt() ssl_opt() = {alpn_preferred_protocols, [binary()]} | {beast_mitigation, one_n_minus_one | zero_n | disabled} | {cacertfile, string()} | {cacerts, [public_key:der_encoded()]} | {cert, public_key:der_encoded()} | {certfile, string()} | {ciphers, [ssl:erl_cipher_suite()] | string()} | {client_renegotiation, boolean()} | {crl_cache, {module(), {internal | any(), list()}}} | {crl_check, boolean() | peer | best_effort} | {depth, 0. +Description The ranch_ssl module implements an SSL Ranch transport. +Types ssl_opt() ssl_opt() = {alpn_preferred_protocols, [binary()]} | {beast_mitigation, one_n_minus_one | zero_n | disabled} | {cacertfile, string()} | {cacerts, [public_key:der_encoded()]} | {cert, public_key:der_encoded()} | {certfile, string()} | {ciphers, [ssl:erl_cipher_suite()] | string()} | {client_renegotiation, boolean()} | {crl_cache, {module(), {internal | any(), list()}}} | {crl_check, boolean() | peer | best_effort} | {depth, 0..255} | {dh, public_key:der_encoded()} | {dhfile, string()} | {fail_if_no_peer_cert, boolean()} | {hibernate_after, integer() | undefined} | {honor_cipher_order, boolean()} | {key, {'RSAPrivateKey' | 'DSAPrivateKey' | 'PrivateKeyInfo', public_key:der_encoded()}} | {keyfile, string()} | {log_alert, boolean()} | {next_protocols_advertised, [binary()]} | {padding_check, boolean()} | {partial_chain, fun(([public_key:der_encoded()]) -&gt; {trusted_ca, public_key:der_encoded()} | unknown_ca)} | {password, string()} | {psk_identity, string()} | {reuse_session, fun()} | {reuse_sessions, boolean()} | {secure_renegotiate, boolean()} | {signature_algs, [{atom(), atom()}]} | {sni_fun, fun()} | {sni_hosts, [{string(), ssl_opt()}]} | {user_lookup_fun, {fun(), any()}} | {v2_hello_compatible, boolean()} | {verify, ssl:verify_type()} | {verify_fun, {fun(), any()}} | {versions, [atom()]}. @@ -7221,8 +7638,19 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/ranch/1.4/manual/ranch_ssl/ Name ranch_ssl - SSL transport module - Description The ranch_ssl module implements an SSL Ranch transport. - Types ssl_opt() ssl_opt() = {alpn_preferred_protocols, [binary()]} | {beast_mitigation, one_n_minus_one | zero_n | disabled} | {cacertfile, string()} | {cacerts, [public_key:der_encoded()]} | {cert, public_key:der_encoded()} | {certfile, string()} | {ciphers, [ssl:erl_cipher_suite()] | string()} | {client_renegotiation, boolean()} | {crl_cache, {module(), {internal | any(), list()}}} | {crl_check, boolean() | peer | best_effort} | {depth, 0. +Description The ranch_ssl module implements an SSL Ranch transport. +Types ssl_opt() ssl_opt() = {alpn_preferred_protocols, [binary()]} | {beast_mitigation, one_n_minus_one | zero_n | disabled} | {cacertfile, string()} | {cacerts, [public_key:der_encoded()]} | {cert, public_key:der_encoded()} | {certfile, string()} | {ciphers, [ssl:erl_cipher_suite()] | string()} | {client_renegotiation, boolean()} | {crl_cache, {module(), {internal | any(), list()}}} | {crl_check, boolean() | peer | best_effort} | {depth, 0..255} | {dh, public_key:der_encoded()} | {dhfile, string()} | {fail_if_no_peer_cert, boolean()} | {hibernate_after, integer() | undefined} | {honor_cipher_order, boolean()} | {key, {'RSAPrivateKey' | 'DSAPrivateKey' | 'PrivateKeyInfo', public_key:der_encoded()}} | {keyfile, string()} | {log_alert, boolean()} | {next_protocols_advertised, [binary()]} | {padding_check, boolean()} | {partial_chain, fun(([public_key:der_encoded()]) -&gt; {trusted_ca, public_key:der_encoded()} | unknown_ca)} | {password, string()} | {psk_identity, string()} | {reuse_session, fun()} | {reuse_sessions, boolean()} | {secure_renegotiate, boolean()} | {signature_algs, [{atom(), atom()}]} | {sni_fun, fun()} | {sni_hosts, [{string(), ssl_opt()}]} | {user_lookup_fun, {fun(), any()}} | {v2_hello_compatible, boolean()} | {verify, ssl:verify_type()} | {verify_fun, {fun(), any()}} | {versions, [atom()]}. + + + + ranch_ssl(3) + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_ssl/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_ssl/ + Name ranch_ssl - SSL transport module +Description The ranch_ssl module implements an SSL Ranch transport. +Types ssl_opt() ssl_opt() = {alpn_preferred_protocols, [binary()]} | {beast_mitigation, one_n_minus_one | zero_n | disabled} | {cacertfile, string()} | {cacerts, [public_key:der_encoded()]} | {cert, public_key:der_encoded()} | {certfile, string()} | {ciphers, [ssl:erl_cipher_suite()] | string()} | {client_renegotiation, boolean()} | {crl_cache, {module(), {internal | any(), list()}}} | {crl_check, boolean() | peer | best_effort} | {depth, 0..255} | {dh, public_key:der_encoded()} | {dhfile, string()} | {fail_if_no_peer_cert, boolean()} | {hibernate_after, integer() | undefined} | {honor_cipher_order, boolean()} | {key, {'RSAPrivateKey' | 'DSAPrivateKey' | 'PrivateKeyInfo', public_key:der_encoded()}} | {keyfile, string()} | {log_alert, boolean()} | {next_protocols_advertised, [binary()]} | {padding_check, boolean()} | {partial_chain, fun(([public_key:der_encoded()]) -&gt; {trusted_ca, public_key:der_encoded()} | unknown_ca)} | {password, string()} | {psk_identity, string()} | {reuse_session, fun()} | {reuse_sessions, boolean()} | {secure_renegotiate, boolean()} | {signature_algs, [{atom(), atom()}]} | {sni_fun, fun()} | {sni_hosts, [{string(), ssl_opt()}]} | {user_lookup_fun, {fun(), any()}} | {v2_hello_compatible, boolean()} | {verify, ssl:verify_type()} | {verify_fun, {fun(), any()}} | {versions, [atom()]}. @@ -7232,9 +7660,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/ranch/1.2/manual/ranch_tcp/ Name ranch_tcp - TCP transport module - Description The ranch_tcp module implements a TCP Ranch transport. - Note that due to bugs in OTP up to at least R16B02, it is recommended to disable async threads when using the sendfile function of this transport, as it can make the threads stuck indefinitely. - Types opt() opt() = {backlog, non_neg_integer()} | {buffer, non_neg_integer()} | {delay_send, boolean()} | {dontroute, boolean()} | {exit_on_close, boolean()} | {fd, non_neg_integer()} | {high_msgq_watermark, non_neg_integer()} | {high_watermark, non_neg_integer()} | inet | inet6 | {ip, inet:ip_address()} | {keepalive, boolean()} | {linger, {boolean(), non_neg_integer()}} | {low_msgq_watermark, non_neg_integer()} | {low_watermark, non_neg_integer()} | {nodelay, boolean()} | {port, inet:port_number()} | {priority, integer()} | {raw, non_neg_integer(), non_neg_integer(), binary()} | {recbuf, non_neg_integer()} | {send_timeout, timeout()} | {send_timeout_close, boolean()} | {sndbuf, non_neg_integer()} | {tos, integer()} Listen options. +Description The ranch_tcp module implements a TCP Ranch transport. +Note that due to bugs in OTP up to at least R16B02, it is recommended to disable async threads when using the sendfile function of this transport, as it can make the threads stuck indefinitely. +Types opt() opt() = {backlog, non_neg_integer()} | {buffer, non_neg_integer()} | {delay_send, boolean()} | {dontroute, boolean()} | {exit_on_close, boolean()} | {fd, non_neg_integer()} | {high_msgq_watermark, non_neg_integer()} | {high_watermark, non_neg_integer()} | inet | inet6 | {ip, inet:ip_address()} | {keepalive, boolean()} | {linger, {boolean(), non_neg_integer()}} | {low_msgq_watermark, non_neg_integer()} | {low_watermark, non_neg_integer()} | {nodelay, boolean()} | {port, inet:port_number()} | {priority, integer()} | {raw, non_neg_integer(), non_neg_integer(), binary()} | {recbuf, non_neg_integer()} | {send_timeout, timeout()} | {send_timeout_close, boolean()} | {sndbuf, non_neg_integer()} | {tos, integer()} Listen options. @@ -7244,9 +7672,9 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/ranch/1.3/manual/ranch_tcp/ Name ranch_tcp - TCP transport module - Description The ranch_tcp module implements a TCP Ranch transport. - Note that due to bugs in OTP up to at least R16B02, it is recommended to disable async threads when using the sendfile function of this transport, as it can make the threads stuck indefinitely. - Types opt() opt() = {backlog, non_neg_integer()} | {buffer, non_neg_integer()} | {delay_send, boolean()} | {dontroute, boolean()} | {exit_on_close, boolean()} | {fd, non_neg_integer()} | {high_msgq_watermark, non_neg_integer()} | {high_watermark, non_neg_integer()} | inet | inet6 | {ip, inet:ip_address()} | {ipv6_v6only, boolean()} | {keepalive, boolean()} | {linger, {boolean(), non_neg_integer()}} | {low_msgq_watermark, non_neg_integer()} | {low_watermark, non_neg_integer()} | {nodelay, boolean()} | {port, inet:port_number()} | {priority, integer()} | {raw, non_neg_integer(), non_neg_integer(), binary()} | {recbuf, non_neg_integer()} | {send_timeout, timeout()} | {send_timeout_close, boolean()} | {sndbuf, non_neg_integer()} | {tos, integer()} Listen options. +Description The ranch_tcp module implements a TCP Ranch transport. +Note that due to bugs in OTP up to at least R16B02, it is recommended to disable async threads when using the sendfile function of this transport, as it can make the threads stuck indefinitely. +Types opt() opt() = {backlog, non_neg_integer()} | {buffer, non_neg_integer()} | {delay_send, boolean()} | {dontroute, boolean()} | {exit_on_close, boolean()} | {fd, non_neg_integer()} | {high_msgq_watermark, non_neg_integer()} | {high_watermark, non_neg_integer()} | inet | inet6 | {ip, inet:ip_address()} | {ipv6_v6only, boolean()} | {keepalive, boolean()} | {linger, {boolean(), non_neg_integer()}} | {low_msgq_watermark, non_neg_integer()} | {low_watermark, non_neg_integer()} | {nodelay, boolean()} | {port, inet:port_number()} | {priority, integer()} | {raw, non_neg_integer(), non_neg_integer(), binary()} | {recbuf, non_neg_integer()} | {send_timeout, timeout()} | {send_timeout_close, boolean()} | {sndbuf, non_neg_integer()} | {tos, integer()} Listen options. @@ -7256,9 +7684,21 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/ranch/1.4/manual/ranch_tcp/ Name ranch_tcp - TCP transport module - Description The ranch_tcp module implements a TCP Ranch transport. - Note that due to bugs in OTP up to at least R16B02, it is recommended to disable async threads when using the sendfile function of this transport, as it can make the threads stuck indefinitely. - Types opt() opt() = {backlog, non_neg_integer()} | {buffer, non_neg_integer()} | {delay_send, boolean()} | {dontroute, boolean()} | {exit_on_close, boolean()} | {fd, non_neg_integer()} | {high_msgq_watermark, non_neg_integer()} | {high_watermark, non_neg_integer()} | inet | inet6 | {ip, inet:ip_address()} | {ipv6_v6only, boolean()} | {keepalive, boolean()} | {linger, {boolean(), non_neg_integer()}} | {low_msgq_watermark, non_neg_integer()} | {low_watermark, non_neg_integer()} | {nodelay, boolean()} | {port, inet:port_number()} | {priority, integer()} | {raw, non_neg_integer(), non_neg_integer(), binary()} | {recbuf, non_neg_integer()} | {send_timeout, timeout()} | {send_timeout_close, boolean()} | {sndbuf, non_neg_integer()} | {tos, integer()} Listen options. +Description The ranch_tcp module implements a TCP Ranch transport. +Note that due to bugs in OTP up to at least R16B02, it is recommended to disable async threads when using the sendfile function of this transport, as it can make the threads stuck indefinitely. +Types opt() opt() = {backlog, non_neg_integer()} | {buffer, non_neg_integer()} | {delay_send, boolean()} | {dontroute, boolean()} | {exit_on_close, boolean()} | {fd, non_neg_integer()} | {high_msgq_watermark, non_neg_integer()} | {high_watermark, non_neg_integer()} | inet | inet6 | {ip, inet:ip_address()} | {ipv6_v6only, boolean()} | {keepalive, boolean()} | {linger, {boolean(), non_neg_integer()}} | {low_msgq_watermark, non_neg_integer()} | {low_watermark, non_neg_integer()} | {nodelay, boolean()} | {port, inet:port_number()} | {priority, integer()} | {raw, non_neg_integer(), non_neg_integer(), binary()} | {recbuf, non_neg_integer()} | {send_timeout, timeout()} | {send_timeout_close, boolean()} | {sndbuf, non_neg_integer()} | {tos, integer()} Listen options. + + + + ranch_tcp(3) + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_tcp/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_tcp/ + Name ranch_tcp - TCP transport module +Description The ranch_tcp module implements a TCP Ranch transport. +Note that due to bugs in OTP up to at least R16B02, it is recommended to disable async threads when using the sendfile function of this transport, as it can make the threads stuck indefinitely. +Types opt() opt() = {backlog, non_neg_integer()} | {buffer, non_neg_integer()} | {delay_send, boolean()} | {dontroute, boolean()} | {exit_on_close, boolean()} | {fd, non_neg_integer()} | {high_msgq_watermark, non_neg_integer()} | {high_watermark, non_neg_integer()} | inet | inet6 | {ip, inet:ip_address()} | {ipv6_v6only, boolean()} | {keepalive, boolean()} | {linger, {boolean(), non_neg_integer()}} | {low_msgq_watermark, non_neg_integer()} | {low_watermark, non_neg_integer()} | {nodelay, boolean()} | {port, inet:port_number()} | {priority, integer()} | {raw, non_neg_integer(), non_neg_integer(), binary()} | {recbuf, non_neg_integer()} | {send_timeout, timeout()} | {send_timeout_close, boolean()} | {sndbuf, non_neg_integer()} | {tos, integer()} Listen options. @@ -7268,10 +7708,12 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/ranch/1.2/manual/ranch_transport/ Name ranch_transport - behaviour for transport modules - Description The ranch_transport behaviour defines the interface used by Ranch transports. - Types sendfile_opts() = [{chunk_size, non_neg_integer()}] Options used by the sendfile function and callbacks. - Allows configuring the chunk size, in bytes. Defaults to 8191 bytes. - Callbacks accept(LSocket, Timeout) &#8594; {ok, CSocket} | {error, closed | timeout | atom()} LSocket = CSocket = any() Listening socket. +Description The ranch_transport behaviour defines the interface used by Ranch transports. +Types sendfile_opts() = [{chunk_size, non_neg_integer()}] Options used by the sendfile function and callbacks. +Allows configuring the chunk size, in bytes. Defaults to 8191 bytes. +Callbacks accept(LSocket, Timeout) -&gt; {ok, CSocket} | {error, closed | timeout | atom()} LSocket = CSocket = any() Listening socket. + Timeout = timeout() Accept timeout. + Accept a connection on the given listening socket. @@ -7281,10 +7723,12 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/ranch/1.3/manual/ranch_transport/ Name ranch_transport - behaviour for transport modules - Description The ranch_transport behaviour defines the interface used by Ranch transports. - Types sendfile_opts() = [{chunk_size, non_neg_integer()}] Options used by the sendfile function and callbacks. - Allows configuring the chunk size, in bytes. Defaults to 8191 bytes. - Callbacks accept(LSocket, Timeout) &#8594; {ok, CSocket} | {error, closed | timeout | atom()} LSocket = CSocket = any() Listening socket. +Description The ranch_transport behaviour defines the interface used by Ranch transports. +Types sendfile_opts() = [{chunk_size, non_neg_integer()}] Options used by the sendfile function and callbacks. +Allows configuring the chunk size, in bytes. Defaults to 8191 bytes. +Callbacks accept(LSocket, Timeout) -&gt; {ok, CSocket} | {error, closed | timeout | atom()} LSocket = CSocket = any() Listening socket. + Timeout = timeout() Accept timeout. + Accept a connection on the given listening socket. @@ -7294,10 +7738,27 @@ Crowdfund my salary or buy The Erlanger Playbook https://ninenines.eu/docs/en/ranch/1.4/manual/ranch_transport/ Name ranch_transport - behaviour for transport modules - Description The ranch_transport behaviour defines the interface used by Ranch transports. - Types sendfile_opts() = [{chunk_size, non_neg_integer()}] Options used by the sendfile function and callbacks. - Allows configuring the chunk size, in bytes. Defaults to 8191 bytes. - Callbacks accept(LSocket, Timeout) &#8594; {ok, CSocket} | {error, closed | timeout | atom()} LSocket = CSocket = any() Listening socket. +Description The ranch_transport behaviour defines the interface used by Ranch transports. +Types sendfile_opts() = [{chunk_size, non_neg_integer()}] Options used by the sendfile function and callbacks. +Allows configuring the chunk size, in bytes. Defaults to 8191 bytes. +Callbacks accept(LSocket, Timeout) -&gt; {ok, CSocket} | {error, closed | timeout | atom()} LSocket = CSocket = any() Listening socket. + Timeout = timeout() Accept timeout. + Accept a connection on the given listening socket. + + + + ranch_transport(3) + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_transport/ + Mon, 01 Jan 0001 00:00:00 +0000 + + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_transport/ + Name ranch_transport - behaviour for transport modules +Description The ranch_transport behaviour defines the interface used by Ranch transports. +Types sendfile_opts() = [{chunk_size, non_neg_integer()}] Options used by the sendfile function and callbacks. +Allows configuring the chunk size, in bytes. Defaults to 8191 bytes. +Callbacks accept(LSocket, Timeout) -&gt; {ok, CSocket} | {error, closed | timeout | atom()} LSocket = CSocket = any() Listening socket. + Timeout = timeout() Accept timeout. + Accept a connection on the given listening socket. diff --git a/services/index.html b/services/index.html index c01c6096..b2afea8c 100644 --- a/services/index.html +++ b/services/index.html @@ -62,107 +62,45 @@

    Services

    -

    If you are interested by any of these opportunities, -send me an email.

    -
    +

    If you are interested by any of these opportunities, send me an email.

    Consulting

    -
    -

    You can get me, Loïc Hoguin, author of Cowboy, to help you -solve a problem or work on a particular project.

    -

    My area of expertise is Erlang; HTTP, Websocket and REST APIs; -design and implementation of protocols; and messaging systems.

    -

    I can also be helpful with testing or code reviews.

    -

    I offer both hourly and daily rates:

    -
      -
    • -

      -200€ hourly rate (remote) -

      +

      You can get me, Loïc Hoguin, author of Cowboy, to help you solve a problem or work on a particular project.

      +

      My area of expertise is Erlang; HTTP, Websocket and REST APIs; design and implementation of protocols; and messaging systems.

      +

      I can also be helpful with testing or code reviews.

      +

      I offer both hourly and daily rates:

      +
      • 200€ hourly rate (remote)
      • -
      • -

        -1000€ daily rate (remote and on-site) -

        +
      • 1000€ daily rate (remote and on-site)
      • -
    -

    For remote consulting, the work can be done by phone, email, -IRC, GitHub and/or any other platform for collaborative work.

    -

    For on-site consulting, the travel expenses and -accomodations are to be paid by the customer. I will also -ask for a higher rate if forced to stay on-site for more -than a week.

    -

    Note that my expertise does not cover all areas where -Erlang is used. My help will be limited in the areas of -distributed databases, or large distributed systems.

    -
    -
    -
    + +

    For remote consulting, the work can be done by phone, email, IRC, GitHub and/or any other platform for collaborative work.

    +

    For on-site consulting, the travel expenses and accomodations are to be paid by the customer. I will also ask for a higher rate if forced to stay on-site for more than a week.

    +

    Note that my expertise does not cover all areas where Erlang is used. My help will be limited in the areas of distributed databases, or large distributed systems.

    Sponsoring

    -
    -

    You can sponsor one of my projects.

    -

    Sponsoring gives you:

    -
      -
    • -

      -a direct, private line of communication -

      +

      You can sponsor one of my projects.

      +

      Sponsoring gives you:

      +
      • a direct, private line of communication
      • -
      • -

        -the power to make me maintain older versions of my projects - (as long as they are sponsoring) -

        +
      • the power to make me maintain older versions of my projects (as long as they are sponsoring)
      • -
      • -

        -priority when adding features or fixing bugs -

        +
      • priority when adding features or fixing bugs
      • -
      • -

        -advertisement space on this website and in the README file - of the project of your choice -

        +
      • advertisement space on this website and in the README file of the project of your choice
      • -
    -

    Sponsors may choose to benefit from any of these perks.

    -

    In exchange sponsors must contribute financially. A minimum -of 200€ per month is required. Sponsors may give as much as -they want. Payment can be monthly or one-time. Invoices are -of course provided.

    -
    -
    -
    + +

    Sponsors may choose to benefit from any of these perks.

    +

    In exchange sponsors must contribute financially. A minimum of 200€ per month is required. Sponsors may give as much as they want. Payment can be monthly or one-time. Invoices are of course provided.

    Erlang beginner training

    -
    -

    I would be happy to introduce more people to Erlang. I have -a 1-day Erlang training readily available for consumption. -The goal of this training is to teach the basics of Erlang -systems and programming. It’s a kind of "Getting started" -for Erlang.

    -

    You can review the training slides.

    -

    This training is meant to be given to a large number of -people interested in Erlang, as part of a public event, -where anyone interested can come.

    -

    Another important aspect of this training is that it is -meant to be affordable. We want the most people to learn -Erlang as possible.

    -

    If you have room, think you can gather 20+ people and -are interested in sponsoring a training session, then -we should talk.

    -
    -
    -
    +

    I would be happy to introduce more people to Erlang. I have a 1-day Erlang training readily available for consumption. The goal of this training is to teach the basics of Erlang systems and programming. It's a kind of "Getting started" for Erlang.

    +

    You can review the training slides.

    +

    This training is meant to be given to a large number of people interested in Erlang, as part of a public event, where anyone interested can come.

    +

    Another important aspect of this training is that it is meant to be affordable. We want the most people to learn Erlang as possible.

    +

    If you have room, think you can gather 20+ people and are interested in sponsoring a training session, then we should talk.

    Custom training

    -
    -

    I can also provide custom training, tailored to your level -and your needs. It can take the form of a class, Q&A or a -code review/writing session. I need to know your expectations -to prepare an appropriate training.

    -

    Custom training rates are the same as consulting rates and -the same restrictions apply.

    -
    -
    +

    I can also provide custom training, tailored to your level and your needs. It can take the form of a class, Q&A or a code review/writing session. I need to know your expectations to prepare an appropriate training.

    +

    Custom training rates are the same as consulting rates and the same restrictions apply.

    + + @@ -603,10 +541,24 @@ the same restrictions apply.

    -
    -

    Like my work? Donate!

    -

    Donate to Loïc Hoguin because his work on Cowboy -and Erlang.mk is fantastic:

    + + + + + + + + + + + + + + + + +

    Like my work? Donate!

    +

    Donate to Loïc Hoguin because his work on Cowboy and Erlang.mk is fantastic:

    @@ -618,7 +570,22 @@ and Erlang.mk is fantastic:

    - + + + + + + + + + + + + + + + + diff --git a/sitemap.xml b/sitemap.xml index 3a256470..e0959b4c 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -22,6 +22,10 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/introduction/ + + https://ninenines.eu/docs/en/ranch/1.5/guide/introduction/ + + https://ninenines.eu/docs/en/cowboy/2.0/guide/modern_web/ @@ -78,6 +82,10 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/listeners/ + + https://ninenines.eu/docs/en/ranch/1.5/guide/listeners/ + + https://ninenines.eu/docs/en/gun/1.0/guide/start/ @@ -118,6 +126,10 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/transports/ + + https://ninenines.eu/docs/en/ranch/1.5/guide/transports/ + + https://ninenines.eu/docs/en/erlang.mk/1/guide/overview/ @@ -138,6 +150,10 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/protocols/ + + https://ninenines.eu/docs/en/ranch/1.5/guide/protocols/ + + https://ninenines.eu/docs/en/cowboy/2.0/guide/getting_started/ @@ -178,6 +194,10 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/embedded/ + + https://ninenines.eu/docs/en/ranch/1.5/guide/embedded/ + + https://ninenines.eu/docs/en/erlang.mk/1/guide/limitations/ @@ -218,6 +238,10 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/parsers/ + + https://ninenines.eu/docs/en/ranch/1.5/guide/parsers/ + + https://ninenines.eu/docs/en/erlang.mk/1/guide/app/ @@ -254,6 +278,10 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/ssl_auth/ + + https://ninenines.eu/docs/en/ranch/1.5/guide/ssl_auth/ + + https://ninenines.eu/docs/en/erlang.mk/1/guide/deps/ @@ -294,6 +322,10 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/internals/ + + https://ninenines.eu/docs/en/ranch/1.5/guide/internals/ + + https://ninenines.eu/docs/en/cowboy/2.0/guide/constraints/ @@ -1088,6 +1120,10 @@ https://ninenines.eu/docs/en/ranch/1.4/manual/ + + https://ninenines.eu/docs/en/ranch/1.5/manual/ + + https://ninenines.eu/docs/en/ranch/1.2/guide/ @@ -1100,6 +1136,10 @@ https://ninenines.eu/docs/en/ranch/1.4/guide/ + + https://ninenines.eu/docs/en/ranch/1.5/guide/ + + https://ninenines.eu/tags/ 0 @@ -2525,6 +2565,10 @@ https://ninenines.eu/docs/en/ranch/1.4/manual/ranch/ + + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch/ + + https://ninenines.eu/docs/en/ranch/1.2/manual/ranch_app/ @@ -2537,6 +2581,10 @@ https://ninenines.eu/docs/en/ranch/1.4/manual/ranch_app/ + + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_app/ + + https://ninenines.eu/docs/en/ranch/1.2/manual/ranch_protocol/ @@ -2549,6 +2597,10 @@ https://ninenines.eu/docs/en/ranch/1.4/manual/ranch_protocol/ + + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_protocol/ + + https://ninenines.eu/docs/en/ranch/1.2/manual/ranch_ssl/ @@ -2561,6 +2613,10 @@ https://ninenines.eu/docs/en/ranch/1.4/manual/ranch_ssl/ + + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_ssl/ + + https://ninenines.eu/docs/en/ranch/1.2/manual/ranch_tcp/ @@ -2573,6 +2629,10 @@ https://ninenines.eu/docs/en/ranch/1.4/manual/ranch_tcp/ + + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_tcp/ + + https://ninenines.eu/docs/en/ranch/1.2/manual/ranch_transport/ @@ -2585,4 +2645,8 @@ https://ninenines.eu/docs/en/ranch/1.4/manual/ranch_transport/ + + https://ninenines.eu/docs/en/ranch/1.5/manual/ranch_transport/ + + \ No newline at end of file diff --git a/slogan/index.html b/slogan/index.html index 1f461b03..5b464449 100644 --- a/slogan/index.html +++ b/slogan/index.html @@ -60,9 +60,8 @@

    -

    Feeling generous? Love reading?
    -Crowdfund my salary -or buy The Erlanger Playbook

    +

    Feeling generous? Love reading?
    Crowdfund my salary or buy The Erlanger Playbook

    +
    diff --git a/talks/index.html b/talks/index.html index 7de3dcd6..1dde6442 100644 --- a/talks/index.html +++ b/talks/index.html @@ -104,14 +104,10 @@
    -

    Talk requests

    -

    Organizing a conference and in need of a speaker for a talk -about Erlang and the Web? Need an introduction to Erlang/OTP -for your company? Looking for a cool subject for a user group -meeting?

    - -
    +

    Organizing a conference and in need of a speaker for a talk about Erlang and the Web? Need an introduction to Erlang/OTP for your company? Looking for a cool subject for a user group meeting?

    +

    Send me an email with the details.

    +
    -- cgit v1.2.3