$ gpg --keyserver hkp://keys.gnupg.net --recv-key 66CCCC8A
From 92b54aacc0de5446dd5497c39897b0bbff72e626 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Lo=C3=AFc=20Hoguin?=
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. -
+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:
+
-Stream handlers. Every request, response and data goes
- through stream handlers. They are meant to replace hooks
- and more. They will be documented in a future pre-release.
- Check cowboy_stream
and cowboy_stream_h
if interested.
-
cowboy_stream
and cowboy_stream_h
if interested.
-Numerous changes to the cowboy_req
interface. This
- is very close to final. Check the manual for what changed.
-
cowboy_req
interface. This is very close to final. Check the manual for what changed.
-The Req object is no longer passed in Websocket callbacks. -
+
-It is now possible to send frames directly from websocket_init/1
.
-
websocket_init/1
.
-SPDY support was removed, now that we have HTTP/2. -
+-Update Ranch to 1.3. We still depend on Cowlib master - for the time being. -
+-A much improved manual. -
+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:
-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 processesRead 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 @@
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 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 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.
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.
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.
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.
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:
+-show your product’s strengths -
+-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.
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.
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.
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.
+-Can we live without expression separators? -
+-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.
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.
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.
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.
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 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.
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 are specified as an atom:
Constraint | -Description | -||||||||
---|---|---|---|---|---|---|---|---|---|
int |
-Converts binary value to integer. |
+
Constraint | +Description | +
---|---|
int | +Converts binary value to integer. |
nonempty |
-Ensures the binary value is non-empty. |
+
nonempty | +Ensures the binary value is non-empty. |
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 @@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.
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.
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 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.
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.
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.
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 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.
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 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.
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.
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 @@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.
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.
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.
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.
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.
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.
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 @@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.
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.
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.
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.
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.
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.
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.
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.
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!
Handlers are Erlang modules that handle HTTP requests.
Handlers are Erlang modules that handle HTTP requests.
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
.
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}.+
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 @@-Introduction -
+-Flow diagram -
+-Listeners -
+-Routing -
+-Constraints -
+-Handlers -
+-Static files -
+-Multipart -
+-Streams -
+-Middlewares -
+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.
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.
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.
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.
-
-
Cowboy uses Semantic Versioning 2.0.0.
Cowboy uses Semantic Versioning 2.0.0.
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 @@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.
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.
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.
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.
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.
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 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.
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}.+
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.
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}.+
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.
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.
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.
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.
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.
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.
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
.
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 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.
-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.
-
cowboy_stream_h
stream handler has been added. It provides most of Cowboy's default behavior.
+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.
+compress
option.
+cowboy_req
functions. Their interface has also been modified to allow for reverse operations and formatting of errors.
+-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. -
-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.
+
-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. -
-cowboy_handler
, cowboy_loop
, cowboy_rest
and cowboy_websocket
.
+init/2
and terminate/3
callbacks. The latter is now optional. The terminate reason has now been documented for all handlers.
+{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.
+halt
or shutdown
tuples as a return value no longer do so. The return value is now a stop
tuple, consistent across Cowboy.
+error
tuple. They have to send the response and return a stop
tuple instead.
+known_content_type
REST handler callback has been removed as it was found unnecessary.
+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_init/1
. The frames will be sent immediately after the handshake.
+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).
+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.
+
-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).
-
cowboy_req:scheme/1
function has been added.
+cowboy_req:uri/1,2
function has been added, replacing the less powerful functions cowboy_req:url/1
and cowboy_req:host_url/1
.
+cowboy_req:match_qs/2
and cowboy_req:match_cookies/2
allow matching query string and cookies against constraints.
+cowboy_req:set_resp_cookie/3
has been added to complement cowboy_req:set_resp_cookie/4
.
+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.
+cowboy_req:set_resp_headers/2
has been added. It allows setting many response headers at once.
+cowboy_req:push/3,4
can be used to push resources for protocols that support it (by default only HTTP/2).
+
-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.
-
cowboy:start_http/4
function was renamed to cowboy:start_clear/3
.
+cowboy:start_https/4
function was renamed to cowboy:start_tls/3
.
+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.
+Opts
argument for cowboy_req:set_resp_cookie/4
has changed to improve consistency. It is now the last argument.
+
-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
.
-
cowboy_req:url/1
and cowboy_req:host_url/1
have been removed in favor of the new function cowboy_req:uri/1,2
.
+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.
+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.
+cowboy_req
, including the functions cowboy_req:get/2
and cowboy_req:set/3
.
+
-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. -
-+
characters.
+.
and ..
.
+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.
+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 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 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 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.
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, 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 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.
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.
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).+
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}).+
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 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.
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.
+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.
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.
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.
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 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.
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.
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">>, []}).+
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 @@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.
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.
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.
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.
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.
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 @@
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.
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.
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.
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.
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.
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
.
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.
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
+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).+
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:
+-Other required headers (for example the date header) -
+-Preset headers -
+-Headers given to the reply function -
+-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).+
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
.
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).+
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 @@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.
All requests start from here.
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.
+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.
This diagram only applies to OPTIONS requests.
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.
+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 applies to all request methods other than -OPTIONS. It is executed right after the "Start" diagram -is completed.
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.
+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 only applies to GET and HEAD requests.
For a description of the cond
step, please see
-the "Conditional requests" diagram.
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.
This diagram only applies to PUT, POST and PATCH requests.
For a description of the cond
step, please see
-the "Conditional requests" diagram.
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.
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.
This diagram only applies to PUT, POST and PATCH requests.
+For a description of the cond
step, please see the "Conditional requests" diagram.
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 DELETE requests.
For a description of the cond
step, please see
-the "Conditional requests" diagram.
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.
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 applies to all request methods other than
-OPTIONS. It is executed right after the resource_exists
-callback, when the resource exists.
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.
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.
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.
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.
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.
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 |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
allow_missing_post |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
charsets_provided |
-skip |
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
content_types_accepted |
-none |
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
content_types_provided |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
delete_completed |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
delete_resource |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
expires |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
forbidden |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
generate_etag |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
is_authorized |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
is_conflict |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
known_methods |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
languages_provided |
-skip |
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
last_modified |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
malformed_request |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
moved_permanently |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
moved_temporarily |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
multiple_choices |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
options |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
previously_existed |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
resource_exists |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
service_available |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
uri_too_long |
-
|
+
Callback name | +Default value | +
---|---|
allowed_methods | +[<<"GET">>, <<"HEAD">>, <<"OPTIONS">>] |
valid_content_headers |
-
|
+
allow_missing_post | +true |
valid_entity_length |
-
|
+
charsets_provided | +skip |
variances |
-
|
+
content_types_accepted | +none |
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.
[{{ <<"text">>, <<"html">>, '*'}, to_html}]
true
false
undefined
false
undefined
true
false
[<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]
undefined
false
false
false
false
ok
false
true
true
false
true
true
[]
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.
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:
+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 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 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 | +
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 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.
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".
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.
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.
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 @@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.
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.
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 = "*".+
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.
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}} -).
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 @@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.
-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 -
--User Interface Security Directives for Content Security Policy -
--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 -
--Beacon -
--File API -
--HTML4.01 -
--HTML5 -
--HTML5.1 -
--HTML5.2 -
--RFC 6690: Constrained RESTful Environments (CoRE) Link Format -
--RFC 7807: Problem Details for HTTP APIs -
--RFC 6906: The profile Link Relation Type -
--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 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 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 -
-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.
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"}}+
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"}}+
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">>, []}}]}}+
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 @@
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 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.
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.
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.
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.
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.+
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}.+
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.
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}.+
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.
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
.
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.
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.
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.
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".
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.
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.
cowboy:set_env - Update a listener’s environment value
cowboy:set_env - Update a listener's environment 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.
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.
-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.
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.
-The key in the environment map. Common keys include dispatch
-and middlewares
.
-
The key in the environment map. Common keys include dispatch
and middlewares
.
-The new value. -
-The type of the value differs depending on the key.
The new value.
+The type of the value differs depending on the key.
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.
-1.0: Function introduced. -
+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(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 - Listen for connections using plain TCP
cowboy:start_clear - Listen for connections using plain TCP
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.
-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
.
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
.
-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.
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.
-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).
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).
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.
-2.0: HTTP/2 support added. -
+
-2.0: Function introduced. Replaces cowboy:start_http/4
.
-
cowboy:start_http/4
.
Dispatch = cowboy_router:compile([ - {'_', [ - {"/", toppage_h, []} +Dispatch = cowboy_router:compile([ + {'_', [ + {"/", toppage_h, []} ]} ]), -{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{ - env => #{dispatch => Dispatch} -}).
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).
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 - Listen for connections using TLS
cowboy:start_tls - Listen for connections using TLS
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.
-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
.
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
.
-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.
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.
-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).
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).
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.
-2.0: HTTP/2 support added. -
+
-2.0: Function introduced. Replaces cowboy:start_https/4
.
-
cowboy:start_https/4
.
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} -}).
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).
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 - Stop the given listener
cowboy:stop_listener - Stop the given listener
stop_listener(Name :: ranch:ref()) - -> ok | {error, not_found}.
Stop a previously started listener.
Alias of ranch:stop_listener(3).
stop_listener(Name :: ranch:ref()) + -> ok | {error, not_found}.+
Stop a previously started listener.
+Alias of ranch:stop_listener(3).
-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.
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.
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.
-1.0: Function introduced. -
+ok = cowboy:stop_listener(example).
ok = cowboy:stop_listener(example).+
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 - HTTP server
cowboy - HTTP server
The module cowboy
provides convenience functions for
-manipulating Ranch listeners.
The module cowboy
provides convenience functions for manipulating Ranch listeners.
-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’s environment value -
+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() :: #{binary() => iodata()}
HTTP headers.
http_headers() :: #{binary() => iodata()}+
HTTP headers.
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/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() :: 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).
cowboy - Small, fast, modern HTTP server for Erlang/OTP
cowboy - Small, fast, modern HTTP server for Erlang/OTP
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.
Functions:
-cowboy(3) - Listener management -
+Functions:
+-cowboy_req(3) - Request and response -
+-cowboy_router(3) - Router -
+-cowboy_constraints(3) - Constraints -
+Protocols:
-cowboy_http(3) - HTTP/1.1 -
+Protocols:
+-cowboy_http2(3) - HTTP/2 -
+-cowboy_websocket(3) - Websocket -
+Handlers:
-cowboy_static(3) - Static file handler -
+Handlers:
+Behaviors:
-cowboy_handler(3) - Plain HTTP handlers -
+Behaviors:
+-cowboy_loop(3) - Loop handlers -
+-cowboy_middleware(3) - Middlewares -
+-cowboy_rest(3) - REST handlers -
+-cowboy_stream(3) - Stream handlers -
+-cowboy_websocket(3) - Websocket handlers -
+Middlewares:
-cowboy_router(3) - Router middleware -
+Middlewares:
+-cowboy_handler(3) - Handler middleware -
+-ranch(7) - Socket acceptor pool for TCP protocols -
+-cowlib(7) - Support library for manipulating Web protocols -
+-ssl - Secure communication over sockets -
+-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).+
The cowboy
application does not define any application
-environment configuration parameters.
The cowboy
application does not define any application environment configuration parameters.
cowboy_constraints:int - Integer constraint
cowboy_constraints:int - Integer constraint
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.
Generate a human-readable error message.
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.
The return value varies depending on the operation.
The return value varies depending on the operation.
-2.0: Interface modified to allow for a variety of operations. -
+-1.0: Constraint introduced. -
+This function is not meant to be called directly.
This function is not meant to be called directly.
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 - Non-empty constraint
cowboy_constraints:nonempty - Non-empty constraint
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.
Generate a human-readable error message.
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.
The return value varies depending on the operation.
The return value varies depending on the operation.
-2.0: Interface modified to allow for a variety of operations. -
+-1.0: Constraint introduced. -
+This function is not meant to be called directly.
This function is not meant to be called directly.
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 - Constraints
cowboy_constraints - Constraints
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.
Built-in constraints:
-cowboy_constraints:int(3) - Integer constraint -
+Built-in constraints:
+-cowboy_constraints:nonempty(3) - Non-empty 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() :: {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.
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 - Terminate the handler
cowboy_handler:terminate - Terminate the handler
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.
-Reason for termination. -
+Reason for termination.
-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.
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.
-Handler state. -
+Handler state.
-Handler module. -
+Handler module.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.0: Function introduced. -
+cowboy_handler:terminate(normal, Req, State, Handler).
cowboy_handler:terminate(normal, Req, State, Handler).+
cowboy_handler - Plain HTTP handlers
cowboy_handler - Plain HTTP handlers
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.
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:
- 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:
+The connection was closed normally.
- 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.
-
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.
The following function should be called by modules implementing -custom handlers to execute the optional terminate callback:
-cowboy_handler:terminate(3) - Terminate the handler -
+The following function should be called by modules implementing custom handlers to execute the optional terminate callback:
+cowboy_http - HTTP/1.1
cowboy_http - HTTP/1.1
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.
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:
- 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:
+Whether the connection process also acts as a supervisor.
- Middleware environment. -
+Middleware environment.
- Time in ms with no data received before Cowboy closes the connection. -
+Time in ms with no data received before Cowboy closes the connection.
- Time in ms with nothing received at all before Cowboy closes the connection. -
+Time in ms with nothing received at all before Cowboy closes the connection.
- Maximum number of empty lines before a request. -
+Maximum number of empty lines before a request.
- Maximum length of header names. -
+Maximum length of header names.
- Maximum length of header values. -
+Maximum length of header values.
- Maximum number of headers allowed per request. -
+Maximum number of headers allowed per request.
- Maximum number of requests allowed per connection. -
+Maximum number of requests allowed per connection.
- Maximum length of the method. -
+Maximum length of the method.
- Maximum length of the request line. -
+Maximum length of the request line.
- Middlewares to run for every request. -
+Middlewares to run for every request.
- Time in ms with no requests before Cowboy closes the connection. -
+Time in ms with no requests before Cowboy closes the connection.
- Time in ms Cowboy will wait for child processes to shut down before killing them. -
+Time in ms Cowboy will wait for child processes to shut down before killing them.
- Ordered list of stream handlers that will handle all stream events. -
+Ordered list of stream handlers that will handle all stream events.
-2.0: The timeout
option was renamed request_timeout
.
-
timeout
option was renamed request_timeout
.
-2.0: The idle_timeout
, inactivity_timeout
and shutdown_timeout
options were added.
-
idle_timeout
, inactivity_timeout
and shutdown_timeout
options were added.
-2.0: The max_method_length
option was added.
-
max_method_length
option was added.
-2.0: The max_request_line_length
default was increased from 4096 to 8000.
-
max_request_line_length
default was increased from 4096 to 8000.
-2.0: The connection_type
option was added.
-
connection_type
option was added.
-2.0: The env
option is now a map instead of a proplist.
-
env
option is now a map instead of a proplist.
-2.0: The stream_handlers
option was added.
-
stream_handlers
option was added.
-2.0: The compress
option was removed in favor of the cowboy_compress_h
stream handler.
-
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: Protocol introduced. Replaces cowboy_protocol
.
-
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 - HTTP/2
cowboy_http2 - HTTP/2
The module cowboy_http2
implements HTTP/2
-as a Ranch protocol.
The module cowboy_http2
implements HTTP/2 as a Ranch protocol.
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:
- 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:
+Whether the connection process also acts as a supervisor.
- Middleware environment. -
+Middleware environment.
- Time in ms with nothing received at all before Cowboy closes the connection. -
+Time in ms with nothing received at all before Cowboy closes the connection.
- Middlewares to run for every request. -
+Middlewares to run for every request.
- Time in ms Cowboy is willing to wait for the connection preface. -
+Time in ms Cowboy is willing to wait for the connection preface.
- Time in ms Cowboy will wait for child processes to shut down before killing them. -
+Time in ms Cowboy will wait for child processes to shut down before killing them.
- Ordered list of stream handlers that will handle all stream events. -
+Ordered list of stream handlers that will handle all stream events.
-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 - Loop handlers
cowboy_loop - Loop handlers
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:
+
-Or initiate a response in init/2
and stream the
- body in info/3
as necessary (for example server-sent events).
-
init/2
and stream the body in info/3
as necessary (for example server-sent events).
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:
- 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:
+The handler requested to close the connection by returning a stop
tuple.
- 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.
-
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.
-2.0: Loop handlers no longer need to handle overflow/timeouts. -
+-1.0: Behavior introduced. -
+cowboy_middleware - Middlewares
cowboy_middleware - Middlewares
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.
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.
-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.
Cowboy should continue processing the request using the returned Req object and environment.
-Cowboy will hibernate the process. When resuming, Cowboy -will apply the returned module, function and arguments. -
+Cowboy will hibernate the process. When resuming, Cowboy will apply the returned module, function and arguments.
-Cowboy will stop middleware execution. No other middleware -will be executed. This effectively ends the processing of -the request. -
+Cowboy will stop middleware execution. No other middleware will be executed. This effectively ends the processing of the request.
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.
-2.0: The env
type is now a map instead of a proplist.
-
env
type is now a map instead of a proplist.
-1.0: Behavior introduced. -
+cowboy_req:binding - Access a value bound from the route
cowboy_req:binding - Access a value bound from the route
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.
-Desired binding name as an atom. -
+Desired binding name as an atom.
-The Req object. -
+The Req object.
-Default value returned when the binding is missing. -
+Default value returned when the binding is missing.
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).
-2.0: Only the value is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+%% Route is "/users/:user" -Username = cowboy_req:binding(user, Req).
%% Route is "/log[/:branch]" -Branch = cowboy_req:binding(branch, Req, <<"master">>)
%% Route is "/log[/:branch]" +Branch = cowboy_req:binding(branch, Req, <<"master">>)+
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 - Access all values bound from the route
cowboy_req:bindings - Access all values bound from the route
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.
-The Req object. -
+The Req object.
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).
-2.0: Only the values are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Bindings = cowboy_req:bindings(Req).
Bindings = cowboy_req:bindings(Req).+
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 - Body length
cowboy_req:body_length - Body length
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.
-The Req object. -
+The Req object.
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.
-2.0: Only the length is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Length = cowboy_req:body_length(Req).
Length = cowboy_req:body_length(Req).+
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 - Delete a response header
cowboy_req:delete_resp_header - Delete a response header
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.
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.
-Header name as a lowercase binary string. -
+Header name as a lowercase binary string.
-The Req object. -
+The Req object.
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.
-1.0: Function introduced. -
+Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),
Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),+
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 - Is there a request body?
cowboy_req:has_body - Is there a request body?
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.
-The Req object. -
+The Req object.
A boolean indicating whether the request has a body.
A boolean indicating whether the request has a body.
-1.0: Function introduced. -
+true = cowboy_req:has_body(Req).
true = cowboy_req:has_body(Req).+
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 - Is there a response body?
cowboy_req:has_resp_body - Is there a response body?
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.
-The Req object. -
+The Req object.
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.
-1.0: Function introduced. -
+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).+
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 - Is the given response header set?
cowboy_req:has_resp_header - Is the given response header set?
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.
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.
-Header name as a lowercase binary string. -
+Header name as a lowercase binary string.
-The Req object. -
+The Req object.
A boolean indicating whether the given response header has been set.
A boolean indicating whether the given response header has been set.
-1.0: Function introduced. -
+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).+
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 - HTTP header
cowboy_req:header - HTTP header
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.
-Desired HTTP header name as a lowercase binary string. -
+Desired HTTP header name as a lowercase binary string.
-The Req object. -
+The Req object.
-Default value returned when the header is missing. -
+Default value returned when the header is missing.
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.
-2.0: Only the header value is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Accept = cowboy_req:header(<<"accept">>, Req).
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).+
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 - HTTP headers
cowboy_req:headers - HTTP headers
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the headers are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Headers = cowboy_req:headers(Req).
Headers = cowboy_req:headers(Req).+
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 - URI host name
cowboy_req:host - URI host name
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the host name is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Host = cowboy_req:host(Req).
Host = cowboy_req:host(Req).+
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 - Access the route’s heading host segments
cowboy_req:host_info - Access the route's heading host segments
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.
-The Req object. -
+The Req object.
The tokens are returned as a list of case insensitive -binary strings.
The tokens are returned as a list of case insensitive binary strings.
-2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+HostInfo = cowboy_req:host_info(Req).
HostInfo = cowboy_req:host_info(Req).+
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 - Match cookies against constraints
cowboy_req:match_cookies - Match cookies against constraints
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.
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.
-2.0: Function introduced. -
+%% ID and Lang are binaries. -#{id := ID, lang := Lang} - = cowboy_req:match_cookies([id, lang], Req).
%% ID is an integer and Lang a non-empty binary. -#{id := ID, lang := Lang} - = cowboy_req:match_cookies([{id, int}, {lang, nonempty}], Req).
#{lang := Lang} - = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
#{lang := Lang} + = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).+
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 - Match the query string against constraints
cowboy_req:match_qs - Match the query string against constraints
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.
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.
-2.0: Function introduced. -
+%% ID and Lang are binaries. -#{id := ID, lang := Lang} - = cowboy_req:match_qs([id, lang], Req).
%% ID is an integer and Lang a non-empty binary. -#{id := ID, lang := Lang} - = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req).
#{lang := Lang} - = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
#{lang := Lang} + = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).+
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 - HTTP method
cowboy_req:method - HTTP method
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the method is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+<<"GET">> = cowboy_req:method(Req).
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.+
cowboy_req:parse_cookies - Parse cookie headers
cowboy_req:parse_cookies - Parse cookie headers
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 []
.
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 []
.
-The Req object. -
+The Req object.
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.
-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
.
-
cookie/2,3
and cookies/1
.
Cookies = cowboy_req:parse_cookies(Req), -{_, Token} = lists:keyfind(token, 1, Cookies).
Cookies = cowboy_req:parse_cookies(Req), +{_, Token} = lists:keyfind(token, 1, Cookies).+
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 - Parse the given HTTP header
cowboy_req:parse_header - Parse the given HTTP 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.
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.
-Desired HTTP header name as a lowercase binary string. -
+Desired HTTP header name as a lowercase binary string.
-The Req object. -
+The Req object.
-Default value returned when the header is missing. -
+Default value returned when the header is missing.
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.
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
:
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
parse_header(Name, Req) -> [{Value, Quality}] - -Name :: <<"accept-charset">> - | <<"accept-encoding">> - | <<"accept-language">> -Value :: binary() %% case insensitive -Quality :: 0..1000
parse_header(<<"authorization">>, Req) - -> {basic, Username :: binary(), Password :: binary()} - | {bearer, Token :: binary()} - | {digest, [{Key :: binary(), Value :: binary()}]}
parse_header(<<"content-length">>, Req) -> non_neg_integer()
When the content-length header is missing, 0
is returned.
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.
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 []
.
parse_header(<<"expect">>, Req) -> continue
parse_header(Name, Req) - -> '*' | [{weak | strong, OpaqueTag}] - -Name :: <<"if-match">> - | <<"if-none-match">> -OpaqueTag :: binary() %% case sensitive
parse_header(Name, Req) -> calendar:datetime()
parse_header(<<"range">>, Req) -> {From, To} | Final - -From :: non_neg_integer() -To :: non_neg_integer() | infinity -Final :: neg_integer()
parse_header(<<"sec-websocket-extensions">>, Req) - -> [{Extension, Params}] - -Extension :: binary() %% case sensitive -Params :: [Key | {Key, Value}] -Key :: binary() %% case sensitive -Value :: binary() %% case sensitive
parse_header(Name, Req) -> [Token] - -Name :: <<"sec-websocket-protocol">> - | <<"upgrade">> -Token :: binary() %% case insensitive
parse_header(<<"x-forwarded-for">>, Req) -> [Token] +parse_header(<<"x-forwarded-for">>, Req) -> [Token] -Token :: binary() %% case sensitive
parse_header(_, Req) -> {undefined, RawValue}
parse_header(_, Req) -> {undefined, RawValue}+
-2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+%% Accept everything when header is missing. -Accept = cowboy_req:parse_header(<<"accept">>, Req, - [{{ <<"*">>, <<"*">>, []}, 1000, []}]).
%% Default content-length is 0. -Length = cowboy_req:header(<<"content-length">>, Req).
%% Default content-length is 0. +Length = cowboy_req:header(<<"content-length">>, Req).+
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 - Parse the query string
cowboy_req:parse_qs - Parse the query string
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.
-The Req object. -
+The Req object.
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
-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: Function introduced. Replaces qs_val/1
and qs_vals/1
.
-
qs_val/1
and qs_vals/1
.
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].+
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 - URI path
cowboy_req:path - URI path
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.+
-The Req object. -
+The Req object.
The path is returned as a binary string. It is case sensitive.
The path is returned as a binary string. It is case sensitive.
-2.0: Only the path is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Path = cowboy_req:path(Req).
Path = cowboy_req:path(Req).+
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 - Access the route’s trailing path segments
cowboy_req:path_info - Access the route's trailing path segments
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.
-The Req object. -
+The Req object.
The tokens are returned as a list of case sensitive -binary strings.
The tokens are returned as a list of case sensitive binary strings.
-2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+PathInfo = cowboy_req:path_info(Req).
PathInfo = cowboy_req:path_info(Req).+
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 - Peer address and port
cowboy_req:peer - Peer address and port
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the peer is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+{IP, Port} = cowboy_req:peer(Req).
{IP, Port} = cowboy_req:peer(Req).+
cowboy_req:port - URI port number
cowboy_req:port - URI port number
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.+
-The Req object. -
+The Req object.
The port number is returned as an integer.
The port number is returned as an integer.
-2.0: Only the port number is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Port = cowboy_req:port(Req).
Port = cowboy_req:port(Req).+
cowboy_req:push - Push a resource to the client
cowboy_req:push - Push a resource to the client
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-The Req object. -
+Header names must be given as lowercase binary strings.
+The Req object.
-Customize the HTTP method or the URI scheme, host, port -or query string. -
+Customize the HTTP method or the URI scheme, host, port or query string.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.0: Function introduced. -
+cowboy_req:push("/static/style.css", #{ - <<"accept">> => <<"text/css">> -}, Req),
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),+
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 - URI query string
cowboy_req:qs - URI query string
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the query string is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Qs = cowboy_req:qs(Req).
Qs = cowboy_req:qs(Req).+
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 - Read the request body
cowboy_req:read_body - Read the request body
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.
-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces body/1,2
.
-
body/1,2
.
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.
cowboy_req:read_body(Req, #{length => 64000}).
cowboy_req:read_body(Req, #{length => 64000}).+
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 - Read the next multipart headers
cowboy_req:read_part - Read the next multipart headers
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.
+-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces part/1,2
.
-
part/1,2
.
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.
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.
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).+
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 - Read the current part’s body
cowboy_req:read_part_body - Read the current part's body
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.
+-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces part_body/1,2
.
-
part_body/1,2
.
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.
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).+
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 - Read and parse a urlencoded request body
cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body
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.
-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces body_qs/1,2
.
-
body_qs/1,2
.
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0), -{_, Lang} = lists:keyfind(<<"lang">>, 1, Body).
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).+
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 - Send the response
cowboy_req:reply - Send the response
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-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.
+The body can be either a binary value, an iolist or a sendfile
tuple telling Cowboy to send the contents of a file.
-The Req object. -
+The Req object.
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.
-2.0: Only the Req is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Req = cowboy_req:reply(404, Req0).
Req = cowboy_req:reply(401, #{ - <<"www-authenticate">> => <<"Basic realm=\"erlang.org\"">> -}, Req0).
Req = cowboy_req:reply(200, #{ - <<"content-type">> => <<"text/plain">> -}, "Hello world!", Req0).
Req = cowboy_req:reply(200, #{ + <<"content-type">> => <<"text/plain">> +}, "Hello world!", Req0).+
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 - Response header
cowboy_req:resp_header - Response header
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.
-Desired response header name as a lowercase binary string. -
+Desired response header name as a lowercase binary string.
-The Req object. -
+The Req object.
-Default value returned when the header is missing. -
+Default value returned when the header is missing.
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.
-2.0: Function introduced. -
+Type = cowboy_req:resp_header(<<"content-type">>, Req).
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).+
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 - Response headers
cowboy_req:resp_headers - Response headers
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.
-The Req object. -
+The Req object.
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.
-2.0: Function introduced. -
+Headers = cowboy_req:resp_headers(Req).
Headers = cowboy_req:resp_headers(Req).+
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 - URI scheme
cowboy_req:scheme - URI scheme
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.+
-The Req object. -
+The Req object.
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">>
.
-2.0: Function introduced. -
+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}.+
cowboy_req:set_resp_body - Set the response body
cowboy_req:set_resp_body - Set the response 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.
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.
-The body can be either a binary value, an iolist or a
-sendfile
tuple telling Cowboy to send the contents of
-a file.
-
The body can be either a binary value, an iolist or a sendfile
tuple telling Cowboy to send the contents of a file.
-The Req object. -
+The Req object.
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.
-2.0: The function now accepts a sendfile
tuple.
-
sendfile
tuple.
-2.0: The set_resp_body_fun/2,3
functions were removed.
-
set_resp_body_fun/2,3
functions were removed.
-1.0: Function introduced. -
+Req = cowboy_req:set_resp_body(<<"Hello world!">>, Req0).
Req = cowboy_req:set_resp_body([ - "<html><head><title>", - page_title(), - "</title></head><body>", - page_body(), - "</body></html>" -], Req0).
{ok, #file_info{size=Size}} = file:read_file_info(Filename), -Req = cowboy_req:set_resp_body({sendfile, 0, Size, Filename}, Req0).
Req = cowboy_req:set_resp_body(<<>>, Req0).
Req = cowboy_req:set_resp_body(<<>>, Req0).+
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 - Set a cookie
cowboy_req:set_resp_cookie - Set a cookie
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.
-Cookie name. -
+Cookie name.
-Cookie value. -
+Cookie value.
-The Req object. -
+The Req object.
-Cookie options. -
+Cookie options.
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.
-2.0: set_resp_cookie/3
introduced as an alias to set_resp_cookie/4
with no options.
-
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()
.
-
binary()
instead of iodata()
.
-1.0: Function introduced. -
+SessionID = base64:encode(crypto:strong_rand_bytes(32)), -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0).
Req = cowboy_req:set_resp_cookie(<<"lang">>, <<"fr-FR">>, - Req0, #{max_age => 3600}).
Req = cowboy_req:set_resp_cookie(<<"sessionid">>, <<>>, - Req0, #{max_age => 0}).
Req = cowboy_req:set_resp_cookie(<<"inaccount">>, <<"1">>, - Req0, #{domain => "my.example.org", path => "/account"}).
SessionID = base64:encode(crypto:strong_rand_bytes(32)), -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, - Req0, #{secure => true}).
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}).+
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 - Set a response header
cowboy_req:set_resp_header - Set a response header
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.
-Header name as a lowercase binary string. -
+Header name as a lowercase binary string.
-Header value. -
+Header value.
-The Req object. -
+The Req object.
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.
-1.0: Function introduced. -
+Req = cowboy_req:set_resp_header(<<"allow">>, "GET", Req0).
Req = cowboy_req:set_resp_header(<<"allow">>, - [allowed_methods(), ", OPTIONS"], Req0).
Req = cowboy_req:set_resp_header(<<"allow">>, + [allowed_methods(), ", OPTIONS"], Req0).+
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 - Set several response headers
cowboy_req:set_resp_headers - Set several response headers
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.
-Headers as a map with keys being lowercase binary strings, -and values as binary strings. -
+Headers as a map with keys being lowercase binary strings, and values as binary strings.
-The Req object. -
+The Req object.
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.
-2.0: Function introduced. -
+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).+
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 - Stream the response body
cowboy_req:stream_body - Stream the response body
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.
-The data to be sent. -
+The data to be sent.
-A flag indicating whether this is the final piece of data -to be sent. -
+A flag indicating whether this is the final piece of data to be sent.
-The Req object. -
+The Req object.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.0: Function introduced. Replaces chunk/2
.
-
chunk/2
.
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).+
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 - Send the response headers
cowboy_req:stream_reply - Send the response headers
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-The Req object. -
+Header names must be given as lowercase binary strings.
+The Req object.
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.
-2.0: Only the Req is returned, it is no longer wrapped in a tuple. -
+
-2.0: Function introduced. Replaces chunked_reply/1,2
.
-
chunked_reply/1,2
.
Req = cowboy_req:stream_reply(200, Req0).
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).+
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 - Reconstructed URI
cowboy_req:uri - Reconstructed URI
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.
-The Req object. -
+The Req object.
-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. -
+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:
+-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 reconstructed URI is returned as an iolist or a binary string.
The reconstructed URI is returned as an iolist or a binary string.
-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: Function introduced. Replaces host_url/1
and url/1
.
-
host_url/1
and url/1
.
With an effective request URI http://example.org/path/to/res?edit=1 -we can have:
%% //example.org/path/to/res?edit=1 -cowboy_req:uri(Req, #{scheme => undefined}).
%% http://example.org -cowboy_req:uri(Req, #{path => undefined, qs => undefined}).
%% /path/to/res?edit=1 -cowboy_req:uri(Req, #{host => undefined}).
%% http://example.org/path/to/res?edit=1#errors -cowboy_req:uri(Req, #{fragment => <<"errors">>}).
%% https://example.org/path/to/res?edit=1 -cowboy_req:uri(Req, #{scheme => <<"https">>}).
iolist_to_binary(cowboy_req:uri(Req)).
iolist_to_binary(cowboy_req:uri(Req)).+
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 - HTTP version
cowboy_req:version - HTTP version
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the version is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Version = cowboy_req:version(Req).
Version = cowboy_req:version(Req).+
cowboy_req - HTTP request and response
cowboy_req - HTTP request and response
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 | +
---|
Type | +Name pattern | +Return type | +
---|---|---|
access | +no verb, parse_*, match_* | +Value |
access |
-no verb, parse_*, match_* |
-
|
+
question | +has_* | +boolean() |
question |
-has_* |
-
|
+
modification | +set_* | +Req |
modification |
-set_* |
-
|
+
action | +any other verb | +ok | {Result, Value, Req} |
action |
-any other verb |
-
|
-
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.
Raw request:
-cowboy_req:method(3) - HTTP method -
--cowboy_req:version(3) - HTTP version -
--cowboy_req:scheme(3) - URI scheme -
--cowboy_req:host(3) - URI host name -
--cowboy_req:port(3) - URI port number -
--cowboy_req:path(3) - URI path -
--cowboy_req:qs(3) - URI query string -
--cowboy_req:uri(3) - Reconstructed URI -
--cowboy_req:header(3) - HTTP header -
--cowboy_req:headers(3) - HTTP headers -
--cowboy_req:peer(3) - Peer address and port -
-Processed request:
-cowboy_req:parse_qs(3) - Parse the query string -
--cowboy_req:match_qs(3) - Match the query string against constraints -
--cowboy_req:parse_header(3) - Parse the given HTTP header -
--cowboy_req:parse_cookies(3) - Parse cookie headers -
--cowboy_req:match_cookies(3) - Match cookies against constraints -
--cowboy_req:binding(3) - Access a value bound from the route -
--cowboy_req:bindings(3) - Access all values bound from the route -
--cowboy_req:host_info(3) - Access the route’s heading host segments -
--cowboy_req:path_info(3) - Access the route’s trailing path segments -
-Request body:
-cowboy_req:has_body(3) - Is there a request body? -
--cowboy_req:body_length(3) - Body length -
--cowboy_req:read_body(3) - Read the request body -
--cowboy_req:read_urlencoded_body(3) - Read and parse a urlencoded request body -
--cowboy_req:read_part(3) - Read the next multipart headers -
--cowboy_req:read_part_body(3) - Read the current part’s body -
-Response:
-cowboy_req:set_resp_cookie(3) - Set a cookie -
--cowboy_req:set_resp_header(3) - Set a response header -
--cowboy_req:set_resp_headers(3) - Set several response headers -
--cowboy_req:has_resp_header(3) - Is the given response header set? -
--cowboy_req:resp_header(3) - Response header -
--cowboy_req:resp_headers(3) - Response headers -
--cowboy_req:delete_resp_header(3) - Delete a response header -
--cowboy_req:set_resp_body(3) - Set the response body -
--cowboy_req:has_resp_body(3) - Is there a response body? -
--cowboy_req:reply(3) - Send the response -
--cowboy_req:stream_reply(3) - Send the response headers -
--cowboy_req:stream_body(3) - Stream the response body -
--cowboy_req:push(3) - Push a resource to the client -
-Raw request:
+Processed request:
+Request body:
+Response:
+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() :: #{ - 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() :: #{ - 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:
Req#{_myapp_auth_method => pubkey}.
Req#{_myapp_auth_method => pubkey}.+
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:
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.
cowboy_rest - REST handlers
cowboy_rest - REST handlers
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).
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:
- 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:
+The handler terminated normally.
- 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.
-
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.
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(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.
Return the list of allowed methods.
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.
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(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(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(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(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.
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(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
.
Delete the resource.
+Cowboy will send an error response when this function returns false
.
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.
Return the resource's expiration date.
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.
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(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.
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(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.
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(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
.
Return whether the PUT request results in a conflict.
+A 409 Conflict response is sent when true
.
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
.
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(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(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.
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(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.
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(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.
Return whether the resource was permanently moved, and what its new location is.
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.
Return whether the resource was temporarily moved, and what its new location is.
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(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(Req, State) -> {Result, Req, State} +previously_existed(Req, State) -> {Result, Req, State} -Result :: boolean() -Default :: false
Return whether the resource existed previously.
Return whether the resource existed previously.
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.
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(Req, State) -> {Result, Req, State} +resource_exists(Req, State) -> {Result, Req, State} -Result :: boolean() -Default :: true
Return whether the resource exists.
Return whether the resource exists.
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
.
Return whether the service is available.
+A 503 Service Unavailable response will be sent when this function returns false
.
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.
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(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.
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(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
.
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(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.
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.
cowboy_router:compile - Compile routes to the resources
cowboy_router:compile - Compile routes to the resources
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.
-Human readable list of routes. -
+Human readable list of routes.
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.
-1.0: Function introduced. -
+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} +}).+
cowboy_router - Router middleware
cowboy_router - Router middleware
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.
-cowboy_router:compile(3) - Compile routes to the resources -
+bindings() :: #{atom() => any()}
Bindings found during routing.
bindings() :: #{atom() => any()}+
Bindings found during routing.
Opaque type containing the compiled routes.
Opaque type containing the compiled 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.
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() :: [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.
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 - Static file handler
cowboy_static - Static file handler
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.
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.
-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.
+Send a file.
+The path is relative to the given application's private directory.
-Send a file. -
-The path is either absolute or relative to the Erlang node’s -current directory.
Send a file.
+The path is either absolute or relative to the Erlang node's current directory.
-Recursively serve files from a directory. -
-The path is relative to the given application’s private -directory.
Recursively serve files from a directory.
+The path is relative to the given application's private directory.
-Recursively serve files from a directory. -
-The path is either absolute or relative to the Erlang node’s -current directory.
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.
-1.0: Handler introduced. -
+generate_etag(Path, Size, Mtime) -> - {strong, integer_to_binary( - erlang:phash2({Path, Size, Mtime}, 16#ffffffff))}.
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.+
cowboy_handler - Stream handlers
cowboy_handler - Stream handlers
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.
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
.
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:
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.
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.
Send data to the client.
{data, fin(), iodata()}
{data, fin(), iodata()}+
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.
The command will be ignored if the protocol does not provide any server push mechanism.
{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.
Inform Cowboy that a process was spawned and should be -supervised.
{spawn, pid(), timeout()}
{spawn, pid(), timeout()}+
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 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 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
.
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.
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.
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.
+ + + + + + + + + + + + + + + + +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.
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.
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.
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.
Same as the switch_protocol command.
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.
The following function should be called by modules implementing -stream handlers to execute the next stream handler in the list:
-cowboy_stream:init(3) - Initialize a stream -
+The following function should be called by modules implementing stream handlers to execute the next stream handler in the list:
+-cowboy_stream:data(3) - Handle data for a stream -
+-cowboy_stream:info(3) - Handle a message for a stream -
+-cowboy_stream:terminate(3) - Terminate a stream -
+-cowboy_stream:early_error(3) - Handle an early error for a stream -
+commands() :: [Command]+
See the list of commands for details.
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.
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() :: 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() :: {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() :: 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.
-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 - Websocket
cowboy_websocket - Websocket
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.
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:
- 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:
+The connection was closed normally before establishing a Websocket connection. This typically happens if an ok
tuple is returned from the init/2
callback.
- The remote endpoint closed the connection without giving any - further details. -
+The remote endpoint closed the connection without giving any further details.
- The remote endpoint closed the connection with the given
- Code
and Payload
as the reason.
-
The remote endpoint closed the connection with the given Code
and Payload
as the reason.
- The handler requested to close the connection, either by returning
- a stop
tuple or by sending a close
frame.
-
The handler requested to close the connection, either by returning a stop
tuple or by sending a close
frame.
- The connection has been closed due to inactivity. The timeout
- value can be configured from init/2
.
-
The connection has been closed due to inactivity. The timeout value can be configured from init/2
.
- 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.
-
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.
- A text frame was sent by the client with invalid encoding. All - text frames must be valid UTF-8. -
+A text frame was sent by the client with invalid encoding. All text frames must be valid UTF-8.
- A protocol error has been detected. -
+A protocol error has been detected.
- The socket has been closed brutally without a close frame being - received first. -
+The socket has been closed brutally without a close frame being received first.
- A socket error ocurred. -
+A socket error ocurred.
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() :: #{ - 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:
- 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:
+Whether to enable the Websocket frame compression extension. Frames will only be compressed for the clients that support this extension.
- Time in milliseconds that Cowboy will keep the - connection open without receiving anything from - the client. -
+Time in milliseconds that Cowboy will keep the connection open without receiving anything from the client.
- 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.
-
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.
-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
.
-
websocket_terminate/3
was removed in favor of terminate/3
.
-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 - status codes used by Cowboy
HTTP status codes - status codes used by Cowboy
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.
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.
This is the status code sent when switching to the -Websocket protocol.
This is the status code sent when switching to the Websocket protocol.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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:
+-The request-line could not be parsed. -
+-Too many headers were sent. -
+-A header name was too long. -
+-A header value was too long. -
+-The host header was missing from an HTTP/1.1 request. -
+-The host header could not be parsed. -
+-The requested host was not found. -
+-The requested path could not be parsed. -
+-The accept header could not be parsed when using REST. -
+-REST under normal conditions. -
+-A Websocket upgrade failed. -
+This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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 - Small, fast, modern HTTP server for Erlang/OTP
cowboy - Small, fast, modern HTTP server for Erlang/OTP
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.
Functions:
-cowboy(3) - Listener management -
+Functions:
+-cowboy_req(3) - Request and response -
+-cowboy_router(3) - Router -
+-cowboy_constraints(3) - Constraints -
+Protocols:
-cowboy_http(3) - HTTP/1.1 -
+Protocols:
+-cowboy_http2(3) - HTTP/2 -
+-cowboy_websocket(3) - Websocket -
+Handlers:
-cowboy_static(3) - Static file handler -
+Handlers:
+Behaviors:
-cowboy_handler(3) - Plain HTTP handlers -
+Behaviors:
+-cowboy_loop(3) - Loop handlers -
+-cowboy_middleware(3) - Middlewares -
+-cowboy_rest(3) - REST handlers -
+-cowboy_stream(3) - Stream handlers -
+-cowboy_websocket(3) - Websocket handlers -
+Middlewares:
-cowboy_router(3) - Router middleware -
+Middlewares:
+-cowboy_handler(3) - Handler middleware -
+-ranch(7) - Socket acceptor pool for TCP protocols -
+-cowlib(7) - Support library for manipulating Web protocols -
+-ssl - Secure communication over sockets -
+-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).+
The cowboy
application does not define any application
-environment configuration parameters.
The cowboy
application does not define any application environment configuration parameters.
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.
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 are specified as an atom:
Constraint | -Description | -||||||||
---|---|---|---|---|---|---|---|---|---|
int |
-Converts binary value to integer. |
+
Constraint | +Description | +
---|---|
int | +Converts binary value to integer. |
nonempty |
-Ensures the binary value is non-empty. |
+
nonempty | +Ensures the binary value is non-empty. |
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 @@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.
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.
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 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.
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.
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.
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 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.
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 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.
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.
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 @@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.
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.
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.
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.
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.
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.
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 @@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.
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.
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.
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.
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.
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.
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.
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.
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!
Handlers are Erlang modules that handle HTTP requests.
Handlers are Erlang modules that handle HTTP requests.
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
.
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}.+
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 @@-Introduction -
+-Flow diagram -
+-Listeners -
+-Routing -
+-Constraints -
+-Handlers -
+-Static files -
+-Multipart -
+-Streams -
+-Middlewares -
+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.
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.
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.
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.
-
-
Cowboy uses Semantic Versioning 2.0.0.
Cowboy uses Semantic Versioning 2.0.0.
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 @@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.
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.
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.
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.
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.
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 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.
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}.+
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.
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}.+
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.
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.
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.
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.
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.
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.
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
.
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 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.
-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.
-
cowboy_stream_h
stream handler has been added. It provides most of Cowboy's default behavior.
+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.
+compress
option.
+cowboy_req
functions. Their interface has also been modified to allow for reverse operations and formatting of errors.
+-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. -
-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.
+
-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. -
-cowboy_handler
, cowboy_loop
, cowboy_rest
and cowboy_websocket
.
+init/2
and terminate/3
callbacks. The latter is now optional. The terminate reason has now been documented for all handlers.
+{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.
+halt
or shutdown
tuples as a return value no longer do so. The return value is now a stop
tuple, consistent across Cowboy.
+error
tuple. They have to send the response and return a stop
tuple instead.
+known_content_type
REST handler callback has been removed as it was found unnecessary.
+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_init/1
. The frames will be sent immediately after the handshake.
+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).
+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.
+
-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).
-
cowboy_req:scheme/1
function has been added.
+cowboy_req:uri/1,2
function has been added, replacing the less powerful functions cowboy_req:url/1
and cowboy_req:host_url/1
.
+cowboy_req:match_qs/2
and cowboy_req:match_cookies/2
allow matching query string and cookies against constraints.
+cowboy_req:set_resp_cookie/3
has been added to complement cowboy_req:set_resp_cookie/4
.
+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.
+cowboy_req:set_resp_headers/2
has been added. It allows setting many response headers at once.
+cowboy_req:push/3,4
can be used to push resources for protocols that support it (by default only HTTP/2).
+
-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.
-
cowboy:start_http/4
function was renamed to cowboy:start_clear/3
.
+cowboy:start_https/4
function was renamed to cowboy:start_tls/3
.
+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.
+Opts
argument for cowboy_req:set_resp_cookie/4
has changed to improve consistency. It is now the last argument.
+
-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
.
-
cowboy_req:url/1
and cowboy_req:host_url/1
have been removed in favor of the new function cowboy_req:uri/1,2
.
+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.
+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.
+cowboy_req
, including the functions cowboy_req:get/2
and cowboy_req:set/3
.
+
-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. -
-+
characters.
+.
and ..
.
+content_types_accepted/2
step in REST handlers.
+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.
+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.
-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. 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.
-
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 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.
+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.
-
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_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.
-
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.
-
stop
as a return value are now explicitly listed in the documentation.
-The function cowboy_req:sock/1
returns the IP/port
- of the local socket.
-
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.
-
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.
-
cowboy_req:inform/2,3
sends an informational response.
-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.
-
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.
-
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.
-
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 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.
-
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. -
+
-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_clock
process is not running. This can happen when Cowboy is being restarted during upgrades, for example.
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 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 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 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.
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, 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 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.
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.
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).+
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}).+
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 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.
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.
+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.
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.
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.
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 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.
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.
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">>, []}).+
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 @@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.
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.
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.
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.
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.
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 @@
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.
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.
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.
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.
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.
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
.
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.
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
+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).+
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:
+-Other required headers (for example the date header) -
+-Preset headers -
+-Headers given to the reply function -
+-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).+
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
.
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).+
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).+
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 @@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.
All requests start from here.
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.
+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.
This diagram only applies to OPTIONS requests.
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.
+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 applies to all request methods other than -OPTIONS. It is executed right after the "Start" diagram -is completed.
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.
+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 only applies to GET and HEAD requests.
For a description of the cond
step, please see
-the "Conditional requests" diagram.
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.
This diagram only applies to PUT, POST and PATCH requests.
For a description of the cond
step, please see
-the "Conditional requests" diagram.
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.
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.
This diagram only applies to PUT, POST and PATCH requests.
+For a description of the cond
step, please see the "Conditional requests" diagram.
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 DELETE requests.
For a description of the cond
step, please see
-the "Conditional requests" diagram.
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.
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 applies to all request methods other than
-OPTIONS. It is executed right after the resource_exists
-callback, when the resource exists.
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.
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.
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.
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.
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.
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 |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
allow_missing_post |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
charsets_provided |
-skip |
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
content_types_accepted |
-none |
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
content_types_provided |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
delete_completed |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
delete_resource |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
expires |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
forbidden |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
generate_etag |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
is_authorized |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
is_conflict |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
known_methods |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
languages_provided |
-skip |
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
last_modified |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
malformed_request |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
moved_permanently |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
moved_temporarily |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
multiple_choices |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
options |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
previously_existed |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
resource_exists |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
service_available |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
uri_too_long |
-
|
+
Callback name | +Default value | +
---|---|
allowed_methods | +[<<"GET">>, <<"HEAD">>, <<"OPTIONS">>] |
valid_content_headers |
-
|
+
allow_missing_post | +true |
valid_entity_length |
-
|
+
charsets_provided | +skip |
variances |
-
|
+
content_types_accepted | +none |
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.
[{{ <<"text">>, <<"html">>, '*'}, to_html}]
true
false
undefined
false
undefined
true
false
[<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]
undefined
false
false
false
false
ok
false
true
true
false
true
true
[]
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.
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:
+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 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 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 | +
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 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.
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".
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.
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.
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 @@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.
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.
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 = "*".+
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.
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}} -).
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 @@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.
-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 -
--User Interface Security Directives for Content Security Policy -
--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 -
--Beacon -
--File API -
--HTML4.01 -
--HTML5 -
--HTML5.1 -
--HTML5.2 -
--RFC 6690: Constrained RESTful Environments (CoRE) Link Format -
--RFC 7807: Problem Details for HTTP APIs -
--RFC 6906: The profile Link Relation Type -
--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 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 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 -
-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.
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"}}+
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"}}+
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">>, []}}]}}+
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 @@
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 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.
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.
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.
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.
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.+
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}.+
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.
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}.+
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.
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
.
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.
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.
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.
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".
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.
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.
cowboy:set_env - Update a listener’s environment value
cowboy:set_env - Update a listener's environment 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.
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.
-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.
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.
-The key in the environment map. Common keys include dispatch
-and middlewares
.
-
The key in the environment map. Common keys include dispatch
and middlewares
.
-The new value. -
-The type of the value differs depending on the key.
The new value.
+The type of the value differs depending on the key.
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.
-1.0: Function introduced. -
+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(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 - Listen for connections using plain TCP
cowboy:start_clear - Listen for connections using plain TCP
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.
-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
.
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
.
-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.
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.
-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).
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).
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.
-2.0: HTTP/2 support added. -
+
-2.0: Function introduced. Replaces cowboy:start_http/4
.
-
cowboy:start_http/4
.
Dispatch = cowboy_router:compile([ - {'_', [ - {"/", toppage_h, []} +Dispatch = cowboy_router:compile([ + {'_', [ + {"/", toppage_h, []} ]} ]), -{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{ - env => #{dispatch => Dispatch} -}).
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).
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 - Listen for connections using TLS
cowboy:start_tls - Listen for connections using TLS
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.
-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
.
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
.
-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.
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.
-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).
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).
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.
-2.0: HTTP/2 support added. -
+
-2.0: Function introduced. Replaces cowboy:start_https/4
.
-
cowboy:start_https/4
.
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} -}).
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).
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 - Stop the given listener
cowboy:stop_listener - Stop the given listener
stop_listener(Name :: ranch:ref()) - -> ok | {error, not_found}.
Stop a previously started listener.
Alias of ranch:stop_listener(3).
stop_listener(Name :: ranch:ref()) + -> ok | {error, not_found}.+
Stop a previously started listener.
+Alias of ranch:stop_listener(3).
-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.
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.
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.
-1.0: Function introduced. -
+ok = cowboy:stop_listener(example).
ok = cowboy:stop_listener(example).+
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 - HTTP server
cowboy - HTTP server
The module cowboy
provides convenience functions for
-manipulating Ranch listeners.
The module cowboy
provides convenience functions for manipulating Ranch listeners.
-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’s environment value -
+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() :: #{binary() => iodata()}
HTTP headers.
http_headers() :: #{binary() => iodata()}+
HTTP headers.
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/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() :: 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).
cowboy - Small, fast, modern HTTP server for Erlang/OTP
cowboy - Small, fast, modern HTTP server for Erlang/OTP
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.
Functions:
-cowboy(3) - Listener management -
+Functions:
+-cowboy_req(3) - Request and response -
+-cowboy_router(3) - Router -
+-cowboy_constraints(3) - Constraints -
+Protocols:
-cowboy_http(3) - HTTP/1.1 -
+Protocols:
+-cowboy_http2(3) - HTTP/2 -
+-cowboy_websocket(3) - Websocket -
+Handlers:
-cowboy_static(3) - Static file handler -
+Handlers:
+Behaviors:
-cowboy_handler(3) - Plain HTTP handlers -
+Behaviors:
+-cowboy_loop(3) - Loop handlers -
+-cowboy_middleware(3) - Middlewares -
+-cowboy_rest(3) - REST handlers -
+-cowboy_stream(3) - Stream handlers -
+-cowboy_websocket(3) - Websocket handlers -
+Middlewares:
-cowboy_router(3) - Router middleware -
+Middlewares:
+-cowboy_handler(3) - Handler middleware -
+-ranch(7) - Socket acceptor pool for TCP protocols -
+-cowlib(7) - Support library for manipulating Web protocols -
+-ssl - Secure communication over sockets -
+-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).+
The cowboy
application does not define any application
-environment configuration parameters.
The cowboy
application does not define any application environment configuration parameters.
cowboy_constraints:int - Integer constraint
cowboy_constraints:int - Integer constraint
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.
Generate a human-readable error message.
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.
The return value varies depending on the operation.
The return value varies depending on the operation.
-2.0: Interface modified to allow for a variety of operations. -
+-1.0: Constraint introduced. -
+This function is not meant to be called directly.
This function is not meant to be called directly.
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 - Non-empty constraint
cowboy_constraints:nonempty - Non-empty constraint
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.
Generate a human-readable error message.
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.
The return value varies depending on the operation.
The return value varies depending on the operation.
-2.0: Interface modified to allow for a variety of operations. -
+-1.0: Constraint introduced. -
+This function is not meant to be called directly.
This function is not meant to be called directly.
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 - Constraints
cowboy_constraints - Constraints
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.
Built-in constraints:
-cowboy_constraints:int(3) - Integer constraint -
+Built-in constraints:
+-cowboy_constraints:nonempty(3) - Non-empty 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() :: {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.
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 - Terminate the handler
cowboy_handler:terminate - Terminate the handler
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.
-Reason for termination. -
+Reason for termination.
-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.
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.
-Handler state. -
+Handler state.
-Handler module. -
+Handler module.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.0: Function introduced. -
+cowboy_handler:terminate(normal, Req, State, Handler).
cowboy_handler:terminate(normal, Req, State, Handler).+
cowboy_handler - Plain HTTP handlers
cowboy_handler - Plain HTTP handlers
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.
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:
- 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:
+The connection was closed normally.
- 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.
-
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.
The following function should be called by modules implementing -custom handlers to execute the optional terminate callback:
-cowboy_handler:terminate(3) - Terminate the handler -
+The following function should be called by modules implementing custom handlers to execute the optional terminate callback:
+cowboy_http - HTTP/1.1
cowboy_http - HTTP/1.1
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.
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:
- 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:
+Whether the connection process also acts as a supervisor.
- Middleware environment. -
+Middleware environment.
- Time in ms with no data received before Cowboy closes the connection. -
+Time in ms with no data received before Cowboy closes the connection.
- Time in ms with nothing received at all before Cowboy closes the connection. -
+Time in ms with nothing received at all before Cowboy closes the connection.
- Maximum number of empty lines before a request. -
+Maximum number of empty lines before a request.
- Maximum length of header names. -
+Maximum length of header names.
- Maximum length of header values. -
+Maximum length of header values.
- Maximum number of headers allowed per request. -
+Maximum number of headers allowed per request.
- Maximum number of requests allowed per connection. -
+Maximum number of requests allowed per connection.
- Maximum length of the method. -
+Maximum length of the method.
- Maximum length of the request line. -
+Maximum length of the request line.
- Middlewares to run for every request. -
+Middlewares to run for every request.
- Time in ms with no requests before Cowboy closes the connection. -
+Time in ms with no requests before Cowboy closes the connection.
- Time in ms Cowboy will wait for child processes to shut down before killing them. -
+Time in ms Cowboy will wait for child processes to shut down before killing them.
- Ordered list of stream handlers that will handle all stream events. -
+Ordered list of stream handlers that will handle all stream events.
-2.0: The timeout
option was renamed request_timeout
.
-
timeout
option was renamed request_timeout
.
-2.0: The idle_timeout
, inactivity_timeout
and shutdown_timeout
options were added.
-
idle_timeout
, inactivity_timeout
and shutdown_timeout
options were added.
-2.0: The max_method_length
option was added.
-
max_method_length
option was added.
-2.0: The max_request_line_length
default was increased from 4096 to 8000.
-
max_request_line_length
default was increased from 4096 to 8000.
-2.0: The connection_type
option was added.
-
connection_type
option was added.
-2.0: The env
option is now a map instead of a proplist.
-
env
option is now a map instead of a proplist.
-2.0: The stream_handlers
option was added.
-
stream_handlers
option was added.
-2.0: The compress
option was removed in favor of the cowboy_compress_h
stream handler.
-
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: Protocol introduced. Replaces cowboy_protocol
.
-
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 - HTTP/2
cowboy_http2 - HTTP/2
The module cowboy_http2
implements HTTP/2
-as a Ranch protocol.
The module cowboy_http2
implements HTTP/2 as a Ranch protocol.
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:
- 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:
+Whether the connection process also acts as a supervisor.
- Middleware environment. -
+Middleware environment.
- Time in ms with nothing received at all before Cowboy closes the connection. -
+Time in ms with nothing received at all before Cowboy closes the connection.
- Middlewares to run for every request. -
+Middlewares to run for every request.
- Time in ms Cowboy is willing to wait for the connection preface. -
+Time in ms Cowboy is willing to wait for the connection preface.
- Time in ms Cowboy will wait for child processes to shut down before killing them. -
+Time in ms Cowboy will wait for child processes to shut down before killing them.
- Ordered list of stream handlers that will handle all stream events. -
+Ordered list of stream handlers that will handle all stream events.
-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 - Loop handlers
cowboy_loop - Loop handlers
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:
+
-Or initiate a response in init/2
and stream the
- body in info/3
as necessary (for example server-sent events).
-
init/2
and stream the body in info/3
as necessary (for example server-sent events).
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:
- 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:
+The handler requested to close the connection by returning a stop
tuple.
- 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.
-
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.
-2.0: Loop handlers no longer need to handle overflow/timeouts. -
+-1.0: Behavior introduced. -
+cowboy_middleware - Middlewares
cowboy_middleware - Middlewares
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.
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.
-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.
Cowboy should continue processing the request using the returned Req object and environment.
-Cowboy will hibernate the process. When resuming, Cowboy -will apply the returned module, function and arguments. -
+Cowboy will hibernate the process. When resuming, Cowboy will apply the returned module, function and arguments.
-Cowboy will stop middleware execution. No other middleware -will be executed. This effectively ends the processing of -the request. -
+Cowboy will stop middleware execution. No other middleware will be executed. This effectively ends the processing of the request.
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.
-2.0: The env
type is now a map instead of a proplist.
-
env
type is now a map instead of a proplist.
-1.0: Behavior introduced. -
+cowboy_req:binding - Access a value bound from the route
cowboy_req:binding - Access a value bound from the route
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.
-Desired binding name as an atom. -
+Desired binding name as an atom.
-The Req object. -
+The Req object.
-Default value returned when the binding is missing. -
+Default value returned when the binding is missing.
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).
-2.0: Only the value is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+%% Route is "/users/:user" -Username = cowboy_req:binding(user, Req).
%% Route is "/log[/:branch]" -Branch = cowboy_req:binding(branch, Req, <<"master">>)
%% Route is "/log[/:branch]" +Branch = cowboy_req:binding(branch, Req, <<"master">>)+
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 - Access all values bound from the route
cowboy_req:bindings - Access all values bound from the route
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.
-The Req object. -
+The Req object.
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).
-2.0: Only the values are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Bindings = cowboy_req:bindings(Req).
Bindings = cowboy_req:bindings(Req).+
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 - Body length
cowboy_req:body_length - Body length
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.
-The Req object. -
+The Req object.
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.
-2.0: Only the length is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Length = cowboy_req:body_length(Req).
Length = cowboy_req:body_length(Req).+
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 - Client TLS certificate
cowboy_req:cert - Client TLS certificate
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.+
-The Req object. -
+The Req object.
The client TLS certificate.
The client TLS certificate.
-2.1: Function introduced. -
+Cert = cowboy_req:cert(Req).
Cert = cowboy_req:cert(Req).+
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 - Delete a response header
cowboy_req:delete_resp_header - Delete a response header
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.
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.
-Header name as a lowercase binary string. -
+Header name as a lowercase binary string.
-The Req object. -
+The Req object.
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.
-1.0: Function introduced. -
+Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),
Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),+
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 - Is there a request body?
cowboy_req:has_body - Is there a request body?
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.
-The Req object. -
+The Req object.
A boolean indicating whether the request has a body.
A boolean indicating whether the request has a body.
-1.0: Function introduced. -
+true = cowboy_req:has_body(Req).
true = cowboy_req:has_body(Req).+
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 - Is there a response body?
cowboy_req:has_resp_body - Is there a response body?
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.
-The Req object. -
+The Req object.
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.
-1.0: Function introduced. -
+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).+
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 - Is the given response header set?
cowboy_req:has_resp_header - Is the given response header set?
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.
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.
-Header name as a lowercase binary string. -
+Header name as a lowercase binary string.
-The Req object. -
+The Req object.
A boolean indicating whether the given response header has been set.
A boolean indicating whether the given response header has been set.
-1.0: Function introduced. -
+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).+
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 - HTTP header
cowboy_req:header - HTTP header
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.
-Desired HTTP header name as a lowercase binary string. -
+Desired HTTP header name as a lowercase binary string.
-The Req object. -
+The Req object.
-Default value returned when the header is missing. -
+Default value returned when the header is missing.
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.
-2.0: Only the header value is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Accept = cowboy_req:header(<<"accept">>, Req).
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).+
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 - HTTP headers
cowboy_req:headers - HTTP headers
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the headers are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Headers = cowboy_req:headers(Req).
Headers = cowboy_req:headers(Req).+
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 - URI host name
cowboy_req:host - URI host name
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the host name is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Host = cowboy_req:host(Req).
Host = cowboy_req:host(Req).+
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 - Access the route’s heading host segments
cowboy_req:host_info - Access the route's heading host segments
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.
-The Req object. -
+The Req object.
The tokens are returned as a list of case insensitive -binary strings.
The tokens are returned as a list of case insensitive binary strings.
-2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+HostInfo = cowboy_req:host_info(Req).
HostInfo = cowboy_req:host_info(Req).+
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 - Send an informational response
cowboy_req:inform - Send an informational response
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-The Req object. -
+Header names must be given as lowercase binary strings.
+The Req object.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.1: Function introduced. -
+Req = cowboy_req:inform(102, Req0).
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).+
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 - Match cookies against constraints
cowboy_req:match_cookies - Match cookies against constraints
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.
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.
-2.0: Function introduced. -
+%% ID and Lang are binaries. -#{id := ID, lang := Lang} - = cowboy_req:match_cookies([id, lang], Req).
%% ID is an integer and Lang a non-empty binary. -#{id := ID, lang := Lang} - = cowboy_req:match_cookies([{id, int}, {lang, nonempty}], Req).
#{lang := Lang} - = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
#{lang := Lang} + = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).+
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 - Match the query string against constraints
cowboy_req:match_qs - Match the query string against constraints
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.
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.
-2.0: Function introduced. -
+%% ID and Lang are binaries. -#{id := ID, lang := Lang} - = cowboy_req:match_qs([id, lang], Req).
%% ID is an integer and Lang a non-empty binary. -#{id := ID, lang := Lang} - = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req).
#{lang := Lang} - = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
#{lang := Lang} + = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).+
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 - HTTP method
cowboy_req:method - HTTP method
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the method is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+<<"GET">> = cowboy_req:method(Req).
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.+
cowboy_req:parse_cookies - Parse cookie headers
cowboy_req:parse_cookies - Parse cookie headers
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 []
.
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 []
.
-The Req object. -
+The Req object.
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.
-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
.
-
cookie/2,3
and cookies/1
.
Cookies = cowboy_req:parse_cookies(Req), -{_, Token} = lists:keyfind(token, 1, Cookies).
Cookies = cowboy_req:parse_cookies(Req), +{_, Token} = lists:keyfind(token, 1, Cookies).+
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 - Parse the given HTTP header
cowboy_req:parse_header - Parse the given HTTP 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.
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.
-Desired HTTP header name as a lowercase binary string. -
+Desired HTTP header name as a lowercase binary string.
-The Req object. -
+The Req object.
-Default value returned when the header is missing. -
+Default value returned when the header is missing.
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.
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
:
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
parse_header(Name, Req) -> [{Value, Quality}] - -Name :: <<"accept-charset">> - | <<"accept-encoding">> - | <<"accept-language">> -Value :: binary() %% case insensitive -Quality :: 0..1000
parse_header(<<"authorization">>, Req) - -> {basic, Username :: binary(), Password :: binary()} - | {bearer, Token :: binary()} - | {digest, [{Key :: binary(), Value :: binary()}]}
parse_header(<<"content-length">>, Req) -> non_neg_integer()
When the content-length header is missing, 0
is returned.
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.
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 []
.
parse_header(<<"expect">>, Req) -> continue
parse_header(Name, Req) - -> '*' | [{weak | strong, OpaqueTag}] - -Name :: <<"if-match">> - | <<"if-none-match">> -OpaqueTag :: binary() %% case sensitive
parse_header(Name, Req) -> calendar:datetime()
parse_header(<<"range">>, Req) -> {From, To} | Final - -From :: non_neg_integer() -To :: non_neg_integer() | infinity -Final :: neg_integer()
parse_header(<<"sec-websocket-extensions">>, Req) - -> [{Extension, Params}] - -Extension :: binary() %% case sensitive -Params :: [Key | {Key, Value}] -Key :: binary() %% case sensitive -Value :: binary() %% case sensitive
parse_header(Name, Req) -> [Token] - -Name :: <<"sec-websocket-protocol">> - | <<"upgrade">> -Token :: binary() %% case insensitive
parse_header(<<"x-forwarded-for">>, Req) -> [Token] +parse_header(<<"x-forwarded-for">>, Req) -> [Token] -Token :: binary() %% case sensitive
parse_header(_, Req) -> {undefined, RawValue}
parse_header(_, Req) -> {undefined, RawValue}+
-2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+%% Accept everything when header is missing. -Accept = cowboy_req:parse_header(<<"accept">>, Req, - [{{ <<"*">>, <<"*">>, []}, 1000, []}]).
%% Default content-length is 0. -Length = cowboy_req:header(<<"content-length">>, Req).
%% Default content-length is 0. +Length = cowboy_req:header(<<"content-length">>, Req).+
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 - Parse the query string
cowboy_req:parse_qs - Parse the query string
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.
-The Req object. -
+The Req object.
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
-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: Function introduced. Replaces qs_val/1
and qs_vals/1
.
-
qs_val/1
and qs_vals/1
.
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].+
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 - URI path
cowboy_req:path - URI path
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.+
-The Req object. -
+The Req object.
The path is returned as a binary string. It is case sensitive.
The path is returned as a binary string. It is case sensitive.
-2.0: Only the path is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Path = cowboy_req:path(Req).
Path = cowboy_req:path(Req).+
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 - Access the route’s trailing path segments
cowboy_req:path_info - Access the route's trailing path segments
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.
-The Req object. -
+The Req object.
The tokens are returned as a list of case sensitive -binary strings.
The tokens are returned as a list of case sensitive binary strings.
-2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+PathInfo = cowboy_req:path_info(Req).
PathInfo = cowboy_req:path_info(Req).+
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 - Peer address and port
cowboy_req:peer - Peer address and port
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the peer is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+{IP, Port} = cowboy_req:peer(Req).
{IP, Port} = cowboy_req:peer(Req).+
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 - URI port number
cowboy_req:port - URI port number
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.+
-The Req object. -
+The Req object.
The port number is returned as an integer.
The port number is returned as an integer.
-2.0: Only the port number is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Port = cowboy_req:port(Req).
Port = cowboy_req:port(Req).+
cowboy_req:push - Push a resource to the client
cowboy_req:push - Push a resource to the client
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-The Req object. -
+Header names must be given as lowercase binary strings.
+The Req object.
-Customize the HTTP method or the URI scheme, host, port -or query string. -
+Customize the HTTP method or the URI scheme, host, port or query string.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.0: Function introduced. -
+cowboy_req:push("/static/style.css", #{ - <<"accept">> => <<"text/css">> -}, Req),
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),+
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 - URI query string
cowboy_req:qs - URI query string
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the query string is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Qs = cowboy_req:qs(Req).
Qs = cowboy_req:qs(Req).+
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 - Read the request body
cowboy_req:read_body - Read the request body
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.
-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces body/1,2
.
-
body/1,2
.
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.
cowboy_req:read_body(Req, #{length => 64000}).
cowboy_req:read_body(Req, #{length => 64000}).+
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 - Read the next multipart headers
cowboy_req:read_part - Read the next multipart headers
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.
+-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces part/1,2
.
-
part/1,2
.
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.
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.
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).+
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 - Read the current part’s body
cowboy_req:read_part_body - Read the current part's body
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.
+-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces part_body/1,2
.
-
part_body/1,2
.
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.
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).+
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 - Read and parse a urlencoded request body
cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body
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.
-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces body_qs/1,2
.
-
body_qs/1,2
.
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0), -{_, Lang} = lists:keyfind(<<"lang">>, 1, Body).
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).+
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 - Send the response
cowboy_req:reply - Send the response
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-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.
+The body can be either a binary value, an iolist or a sendfile
tuple telling Cowboy to send the contents of a file.
-The Req object. -
+The Req object.
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.
-2.0: Only the Req is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Req = cowboy_req:reply(404, Req0).
Req = cowboy_req:reply(401, #{ - <<"www-authenticate">> => <<"Basic realm=\"erlang.org\"">> -}, Req0).
Req = cowboy_req:reply(200, #{ - <<"content-type">> => <<"text/plain">> -}, "Hello world!", Req0).
Req = cowboy_req:reply(200, #{ + <<"content-type">> => <<"text/plain">> +}, "Hello world!", Req0).+
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 - Response header
cowboy_req:resp_header - Response header
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.
-Desired response header name as a lowercase binary string. -
+Desired response header name as a lowercase binary string.
-The Req object. -
+The Req object.
-Default value returned when the header is missing. -
+Default value returned when the header is missing.
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.
-2.0: Function introduced. -
+Type = cowboy_req:resp_header(<<"content-type">>, Req).
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).+
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 - Response headers
cowboy_req:resp_headers - Response headers
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.
-The Req object. -
+The Req object.
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.
-2.0: Function introduced. -
+Headers = cowboy_req:resp_headers(Req).
Headers = cowboy_req:resp_headers(Req).+
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 - URI scheme
cowboy_req:scheme - URI scheme
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.+
-The Req object. -
+The Req object.
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">>
.
-2.0: Function introduced. -
+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}.+
cowboy_req:set_resp_body - Set the response body
cowboy_req:set_resp_body - Set the response 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.
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.
-The body can be either a binary value, an iolist or a
-sendfile
tuple telling Cowboy to send the contents of
-a file.
-
The body can be either a binary value, an iolist or a sendfile
tuple telling Cowboy to send the contents of a file.
-The Req object. -
+The Req object.
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.
-2.0: The function now accepts a sendfile
tuple.
-
sendfile
tuple.
-2.0: The set_resp_body_fun/2,3
functions were removed.
-
set_resp_body_fun/2,3
functions were removed.
-1.0: Function introduced. -
+Req = cowboy_req:set_resp_body(<<"Hello world!">>, Req0).
Req = cowboy_req:set_resp_body([ - "<html><head><title>", - page_title(), - "</title></head><body>", - page_body(), - "</body></html>" -], Req0).
{ok, #file_info{size=Size}} = file:read_file_info(Filename), -Req = cowboy_req:set_resp_body({sendfile, 0, Size, Filename}, Req0).
Req = cowboy_req:set_resp_body(<<>>, Req0).
Req = cowboy_req:set_resp_body(<<>>, Req0).+
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 - Set a cookie
cowboy_req:set_resp_cookie - Set a cookie
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.
-Cookie name. -
+Cookie name.
-Cookie value. -
+Cookie value.
-The Req object. -
+The Req object.
-Cookie options. -
+Cookie options.
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.
-2.0: set_resp_cookie/3
introduced as an alias to set_resp_cookie/4
with no options.
-
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()
.
-
binary()
instead of iodata()
.
-1.0: Function introduced. -
+SessionID = base64:encode(crypto:strong_rand_bytes(32)), -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0).
Req = cowboy_req:set_resp_cookie(<<"lang">>, <<"fr-FR">>, - Req0, #{max_age => 3600}).
Req = cowboy_req:set_resp_cookie(<<"sessionid">>, <<>>, - Req0, #{max_age => 0}).
Req = cowboy_req:set_resp_cookie(<<"inaccount">>, <<"1">>, - Req0, #{domain => "my.example.org", path => "/account"}).
SessionID = base64:encode(crypto:strong_rand_bytes(32)), -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, - Req0, #{secure => true}).
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}).+
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 - Set a response header
cowboy_req:set_resp_header - Set a response header
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.
-Header name as a lowercase binary string. -
+Header name as a lowercase binary string.
-Header value. -
+Header value.
-The Req object. -
+The Req object.
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.
-1.0: Function introduced. -
+Req = cowboy_req:set_resp_header(<<"allow">>, "GET", Req0).
Req = cowboy_req:set_resp_header(<<"allow">>, - [allowed_methods(), ", OPTIONS"], Req0).
Req = cowboy_req:set_resp_header(<<"allow">>, + [allowed_methods(), ", OPTIONS"], Req0).+
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 - Set several response headers
cowboy_req:set_resp_headers - Set several response headers
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.
-Headers as a map with keys being lowercase binary strings, -and values as binary strings. -
+Headers as a map with keys being lowercase binary strings, and values as binary strings.
-The Req object. -
+The Req object.
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.
-2.0: Function introduced. -
+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).+
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 - Socket address and port
cowboy_req:sock - Socket address and port
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.+
-The Req object. -
+The Req object.
The socket’s local IP address and port number.
The socket's local IP address and port number.
-2.1: Function introduced. -
+{IP, Port} = cowboy_req:sock(Req).
{IP, Port} = cowboy_req:sock(Req).+
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 - Stream the response body
cowboy_req:stream_body - Stream the response body
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.
-The data to be sent. -
+The data to be sent.
-A flag indicating whether this is the final piece of data -to be sent. -
+A flag indicating whether this is the final piece of data to be sent.
-The Req object. -
+The Req object.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.0: Function introduced. Replaces chunk/2
.
-
chunk/2
.
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).+
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 - Send the response headers
cowboy_req:stream_reply - Send the response headers
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-The Req object. -
+Header names must be given as lowercase binary strings.
+The Req object.
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.
-2.0: Only the Req is returned, it is no longer wrapped in a tuple. -
+
-2.0: Function introduced. Replaces chunked_reply/1,2
.
-
chunked_reply/1,2
.
Req = cowboy_req:stream_reply(200, Req0).
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).+
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 - Reconstructed URI
cowboy_req:uri - Reconstructed URI
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.
-The Req object. -
+The Req object.
-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. -
+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:
+-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 reconstructed URI is returned as an iolist or a binary string.
The reconstructed URI is returned as an iolist or a binary string.
-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: Function introduced. Replaces host_url/1
and url/1
.
-
host_url/1
and url/1
.
With an effective request URI http://example.org/path/to/res?edit=1 -we can have:
%% //example.org/path/to/res?edit=1 -cowboy_req:uri(Req, #{scheme => undefined}).
%% http://example.org -cowboy_req:uri(Req, #{path => undefined, qs => undefined}).
%% /path/to/res?edit=1 -cowboy_req:uri(Req, #{host => undefined}).
%% http://example.org/path/to/res?edit=1#errors -cowboy_req:uri(Req, #{fragment => <<"errors">>}).
%% https://example.org/path/to/res?edit=1 -cowboy_req:uri(Req, #{scheme => <<"https">>}).
iolist_to_binary(cowboy_req:uri(Req)).
iolist_to_binary(cowboy_req:uri(Req)).+
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 - HTTP version
cowboy_req:version - HTTP version
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the version is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Version = cowboy_req:version(Req).
Version = cowboy_req:version(Req).+
cowboy_req - HTTP request and response
cowboy_req - HTTP request and response
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 | +
---|
Type | +Name pattern | +Return type | +
---|---|---|
access | +no verb, parse_*, match_* | +Value |
access |
-no verb, parse_*, match_* |
-
|
+
question | +has_* | +boolean() |
question |
-has_* |
-
|
+
modification | +set_* | +Req |
modification |
-set_* |
-
|
+
action | +any other verb | +ok | {Result, Value, Req} |
action |
-any other verb |
-
|
-
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.
Connection:
-cowboy_req:peer(3) - Peer address and port -
--cowboy_req:sock(3) - Socket address and port -
--cowboy_req:cert(3) - Client TLS certificate -
-Raw request:
-cowboy_req:method(3) - HTTP method -
--cowboy_req:version(3) - HTTP version -
--cowboy_req:scheme(3) - URI scheme -
--cowboy_req:host(3) - URI host name -
--cowboy_req:port(3) - URI port number -
--cowboy_req:path(3) - URI path -
--cowboy_req:qs(3) - URI query string -
--cowboy_req:uri(3) - Reconstructed URI -
--cowboy_req:header(3) - HTTP header -
--cowboy_req:headers(3) - HTTP headers -
-Processed request:
-cowboy_req:parse_qs(3) - Parse the query string -
--cowboy_req:match_qs(3) - Match the query string against constraints -
--cowboy_req:parse_header(3) - Parse the given HTTP header -
--cowboy_req:parse_cookies(3) - Parse cookie headers -
--cowboy_req:match_cookies(3) - Match cookies against constraints -
--cowboy_req:binding(3) - Access a value bound from the route -
--cowboy_req:bindings(3) - Access all values bound from the route -
--cowboy_req:host_info(3) - Access the route’s heading host segments -
--cowboy_req:path_info(3) - Access the route’s trailing path segments -
-Request body:
-cowboy_req:has_body(3) - Is there a request body? -
--cowboy_req:body_length(3) - Body length -
--cowboy_req:read_body(3) - Read the request body -
--cowboy_req:read_urlencoded_body(3) - Read and parse a urlencoded request body -
--cowboy_req:read_part(3) - Read the next multipart headers -
--cowboy_req:read_part_body(3) - Read the current part’s body -
-Response:
-cowboy_req:set_resp_cookie(3) - Set a cookie -
--cowboy_req:set_resp_header(3) - Set a response header -
--cowboy_req:set_resp_headers(3) - Set several response headers -
--cowboy_req:has_resp_header(3) - Is the given response header set? -
--cowboy_req:resp_header(3) - Response header -
--cowboy_req:resp_headers(3) - Response headers -
--cowboy_req:delete_resp_header(3) - Delete a response header -
--cowboy_req:set_resp_body(3) - Set the response body -
--cowboy_req:has_resp_body(3) - Is there a response body? -
--cowboy_req:inform(3) - Send an informational response -
--cowboy_req:reply(3) - Send the response -
--cowboy_req:stream_reply(3) - Send the response headers -
--cowboy_req:stream_body(3) - Stream the response body -
--cowboy_req:push(3) - Push a resource to the client -
-Connection:
+Raw request:
+Processed request:
+Request body:
+Response:
+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() :: #{ - 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() :: #{ - 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:
Req#{_myapp_auth_method => pubkey}.
Req#{_myapp_auth_method => pubkey}.+
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:
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.
cowboy_rest - REST handlers
cowboy_rest - REST handlers
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).
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:
- 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:
+The handler terminated normally.
- 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.
-
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.
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(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.
Return the list of allowed methods.
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.
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(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(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(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(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.
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(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
.
Delete the resource.
+Cowboy will send an error response when this function returns false
.
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.
Return the resource's expiration date.
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.
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(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.
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(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.
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(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
.
Return whether the PUT request results in a conflict.
+A 409 Conflict response is sent when true
.
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
.
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(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(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.
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(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.
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(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.
Return whether the resource was permanently moved, and what its new location is.
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.
Return whether the resource was temporarily moved, and what its new location is.
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(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(Req, State) -> {Result, Req, State} +previously_existed(Req, State) -> {Result, Req, State} -Result :: boolean() -Default :: false
Return whether the resource existed previously.
Return whether the resource existed previously.
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.
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(Req, State) -> {Result, Req, State} +resource_exists(Req, State) -> {Result, Req, State} -Result :: boolean() -Default :: true
Return whether the resource exists.
Return whether the resource exists.
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
.
Return whether the service is available.
+A 503 Service Unavailable response will be sent when this function returns false
.
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.
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(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.
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(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
.
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(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.
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.
-2.1: The switch_handler
return value was added.
-
switch_handler
return value was added.
-1.0: Behavior introduced. -
+cowboy_router:compile - Compile routes to the resources
cowboy_router:compile - Compile routes to the resources
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.
-Human readable list of routes. -
+Human readable list of routes.
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.
-1.0: Function introduced. -
+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} +}).+
cowboy_router - Router middleware
cowboy_router - Router middleware
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.
-cowboy_router:compile(3) - Compile routes to the resources -
+bindings() :: #{atom() => any()}
Bindings found during routing.
bindings() :: #{atom() => any()}+
Bindings found during routing.
Opaque type containing the compiled routes.
Opaque type containing the compiled 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.
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() :: [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.
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 - Static file handler
cowboy_static - Static file handler
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.
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.
-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.
+Send a file.
+The path is relative to the given application's private directory.
-Send a file. -
-The path is either absolute or relative to the Erlang node’s -current directory.
Send a file.
+The path is either absolute or relative to the Erlang node's current directory.
-Recursively serve files from a directory. -
-The path is relative to the given application’s private -directory.
Recursively serve files from a directory.
+The path is relative to the given application's private directory.
-Recursively serve files from a directory. -
-The path is either absolute or relative to the Erlang node’s -current directory.
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.
-1.0: Handler introduced. -
+generate_etag(Path, Size, Mtime) -> - {strong, integer_to_binary( - erlang:phash2({Path, Size, Mtime}, 16#ffffffff))}.
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.+
cowboy_handler - Stream handlers
cowboy_handler - Stream handlers
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.
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
.
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:
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.
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.
Send data to the client.
{data, fin(), iodata()}
{data, fin(), iodata()}+
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.
The command will be ignored if the protocol does not provide any server push mechanism.
{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.
Inform Cowboy that a process was spawned and should be -supervised.
{spawn, pid(), timeout()}
{spawn, pid(), timeout()}+
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 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 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
.
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.
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.
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.
+ + + + + + + + + + + + + + + + +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.
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.
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.
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.
Same as the switch_protocol command.
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.
The following function should be called by modules implementing -stream handlers to execute the next stream handler in the list:
-cowboy_stream:init(3) - Initialize a stream -
+The following function should be called by modules implementing stream handlers to execute the next stream handler in the list:
+-cowboy_stream:data(3) - Handle data for a stream -
+-cowboy_stream:info(3) - Handle a message for a stream -
+-cowboy_stream:terminate(3) - Terminate a stream -
+-cowboy_stream:early_error(3) - Handle an early error for a stream -
+commands() :: [Command]+
See the list of commands for details.
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.
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() :: 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() :: {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() :: 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.
-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 - Websocket
cowboy_websocket - Websocket
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.
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:
- 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:
+The connection was closed normally before establishing a Websocket connection. This typically happens if an ok
tuple is returned from the init/2
callback.
- The remote endpoint closed the connection without giving any - further details. -
+The remote endpoint closed the connection without giving any further details.
- The remote endpoint closed the connection with the given
- Code
and Payload
as the reason.
-
The remote endpoint closed the connection with the given Code
and Payload
as the reason.
- The handler requested to close the connection, either by returning
- a stop
tuple or by sending a close
frame.
-
The handler requested to close the connection, either by returning a stop
tuple or by sending a close
frame.
- The connection has been closed due to inactivity. The timeout
- value can be configured from init/2
.
-
The connection has been closed due to inactivity. The timeout value can be configured from init/2
.
- 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.
-
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.
- A text frame was sent by the client with invalid encoding. All - text frames must be valid UTF-8. -
+A text frame was sent by the client with invalid encoding. All text frames must be valid UTF-8.
- A protocol error has been detected. -
+A protocol error has been detected.
- The socket has been closed brutally without a close frame being - received first. -
+The socket has been closed brutally without a close frame being received first.
- A socket error ocurred. -
+A socket error ocurred.
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() :: #{ - 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:
- 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:
+Whether to enable the Websocket frame compression extension. Frames will only be compressed for the clients that support this extension.
- Time in milliseconds that Cowboy will keep the - connection open without receiving anything from - the client. -
+Time in milliseconds that Cowboy will keep the connection open without receiving anything from the client.
- 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.
-
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.
-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
.
-
websocket_terminate/3
was removed in favor of terminate/3
.
-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 - status codes used by Cowboy
HTTP status codes - status codes used by Cowboy
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.
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.
This is the status code sent when switching to the -Websocket protocol.
This is the status code sent when switching to the Websocket protocol.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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:
+-The request-line could not be parsed. -
+-Too many headers were sent. -
+-A header name was too long. -
+-A header value was too long. -
+-The host header was missing from an HTTP/1.1 request. -
+-The host header could not be parsed. -
+-The requested host was not found. -
+-The requested path could not be parsed. -
+-The accept header could not be parsed when using REST. -
+-REST under normal conditions. -
+-A Websocket upgrade failed. -
+This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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 - Small, fast, modern HTTP server for Erlang/OTP
cowboy - Small, fast, modern HTTP server for Erlang/OTP
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.
Functions:
-cowboy(3) - Listener management -
+Functions:
+-cowboy_req(3) - Request and response -
+-cowboy_router(3) - Router -
+-cowboy_constraints(3) - Constraints -
+Protocols:
-cowboy_http(3) - HTTP/1.1 -
+Protocols:
+-cowboy_http2(3) - HTTP/2 -
+-cowboy_websocket(3) - Websocket -
+Handlers:
-cowboy_static(3) - Static file handler -
+Handlers:
+Behaviors:
-cowboy_handler(3) - Plain HTTP handlers -
+Behaviors:
+-cowboy_loop(3) - Loop handlers -
+-cowboy_middleware(3) - Middlewares -
+-cowboy_rest(3) - REST handlers -
+-cowboy_stream(3) - Stream handlers -
+-cowboy_websocket(3) - Websocket handlers -
+Middlewares:
-cowboy_router(3) - Router middleware -
+Middlewares:
+-cowboy_handler(3) - Handler middleware -
+-ranch(7) - Socket acceptor pool for TCP protocols -
+-cowlib(7) - Support library for manipulating Web protocols -
+-ssl - Secure communication over sockets -
+-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).+
The cowboy
application does not define any application
-environment configuration parameters.
The cowboy
application does not define any application environment configuration parameters.
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.
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 are specified as an atom:
Constraint | -Description | -||||||||
---|---|---|---|---|---|---|---|---|---|
int |
-Converts binary value to integer. |
+
Constraint | +Description | +
---|---|
int | +Converts binary value to integer. |
nonempty |
-Ensures the binary value is non-empty. |
+
nonempty | +Ensures the binary value is non-empty. |
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 @@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.
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.
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 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.
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.
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.
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 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.
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 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.
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.
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 @@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.
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.
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.
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.
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.
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.
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 @@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.
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.
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.
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.
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.
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.
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.
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.
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!
Handlers are Erlang modules that handle HTTP requests.
Handlers are Erlang modules that handle HTTP requests.
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
.
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}.+
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 @@-Introduction -
+-Flow diagram -
+-Listeners -
+-Routing -
+-Constraints -
+-Handlers -
+-Static files -
+-Multipart -
+-Streams -
+-Middlewares -
+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.
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.
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.
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.
-
-
Cowboy uses Semantic Versioning 2.0.0.
Cowboy uses Semantic Versioning 2.0.0.
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 @@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.
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.
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.
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.
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.
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 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.
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}.+
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.
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}.+
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.
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.
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.
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.
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.
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.
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
.
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 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.
-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.
-
cowboy_stream_h
stream handler has been added. It provides most of Cowboy's default behavior.
+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.
+compress
option.
+cowboy_req
functions. Their interface has also been modified to allow for reverse operations and formatting of errors.
+-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. -
-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.
+
-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. -
-cowboy_handler
, cowboy_loop
, cowboy_rest
and cowboy_websocket
.
+init/2
and terminate/3
callbacks. The latter is now optional. The terminate reason has now been documented for all handlers.
+{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.
+halt
or shutdown
tuples as a return value no longer do so. The return value is now a stop
tuple, consistent across Cowboy.
+error
tuple. They have to send the response and return a stop
tuple instead.
+known_content_type
REST handler callback has been removed as it was found unnecessary.
+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_init/1
. The frames will be sent immediately after the handshake.
+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).
+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.
+
-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).
-
cowboy_req:scheme/1
function has been added.
+cowboy_req:uri/1,2
function has been added, replacing the less powerful functions cowboy_req:url/1
and cowboy_req:host_url/1
.
+cowboy_req:match_qs/2
and cowboy_req:match_cookies/2
allow matching query string and cookies against constraints.
+cowboy_req:set_resp_cookie/3
has been added to complement cowboy_req:set_resp_cookie/4
.
+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.
+cowboy_req:set_resp_headers/2
has been added. It allows setting many response headers at once.
+cowboy_req:push/3,4
can be used to push resources for protocols that support it (by default only HTTP/2).
+
-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.
-
cowboy:start_http/4
function was renamed to cowboy:start_clear/3
.
+cowboy:start_https/4
function was renamed to cowboy:start_tls/3
.
+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.
+Opts
argument for cowboy_req:set_resp_cookie/4
has changed to improve consistency. It is now the last argument.
+
-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
.
-
cowboy_req:url/1
and cowboy_req:host_url/1
have been removed in favor of the new function cowboy_req:uri/1,2
.
+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.
+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.
+cowboy_req
, including the functions cowboy_req:get/2
and cowboy_req:set/3
.
+
-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. -
-+
characters.
+.
and ..
.
+content_types_accepted/2
step in REST handlers.
+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.
+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.
-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. 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.
-
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 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.
+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.
-
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_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.
-
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.
-
stop
as a return value are now explicitly listed in the documentation.
-The function cowboy_req:sock/1
returns the IP/port
- of the local socket.
-
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.
-
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.
-
cowboy_req:inform/2,3
sends an informational response.
-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.
-
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.
-
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.
-
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 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.
-
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. -
+
-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_clock
process is not running. This can happen when Cowboy is being restarted during upgrades, for example.
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.
-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.
-
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 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.
-
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.
-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). -
+-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. -
+-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. -
+-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.
-
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.
-
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. -
+-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. -
+-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. -
+-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. -
+-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. -
+
-A packet could be lost when switching to Websocket or any
- other protocol via the switch_protocol
command. This is
- now fixed.
-
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. -
+
-Both experimental stream handlers cowboy_metrics_h
and
- cowboy_tracer_h
received a number of fixes and improvements.
-
cowboy_metrics_h
and cowboy_tracer_h
received a number of fixes and improvements.
The following patch versions were released since Cowboy 2.2:
The following patch versions were released since Cowboy 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. -
+
-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_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.
-
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. -
+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 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 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 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.
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, 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 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.
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.
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).+
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}).+
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 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.
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.
+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.
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.
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.
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 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.
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.
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">>, []}).+
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 @@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.
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.
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.
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.
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.
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 @@
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.
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.
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.
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.
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.
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
.
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.
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
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).+
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:
+-Other required headers (for example the date header) -
+-Preset headers -
+-Headers given to the reply function -
+-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).+
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
.
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).+
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).+
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 @@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.
All requests start from here.
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.
+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.
This diagram only applies to OPTIONS requests.
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.
+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 applies to all request methods other than -OPTIONS. It is executed right after the "Start" diagram -is completed.
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.
+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 only applies to GET and HEAD requests.
For a description of the cond
step, please see
-the "Conditional requests" diagram.
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.
This diagram only applies to PUT, POST and PATCH requests.
For a description of the cond
step, please see
-the "Conditional requests" diagram.
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.
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.
This diagram only applies to PUT, POST and PATCH requests.
+For a description of the cond
step, please see the "Conditional requests" diagram.
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 DELETE requests.
For a description of the cond
step, please see
-the "Conditional requests" diagram.
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.
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 applies to all request methods other than
-OPTIONS. It is executed right after the resource_exists
-callback, when the resource exists.
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.
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.
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.
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.
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.
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 |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
allow_missing_post |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
charsets_provided |
-skip |
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
content_types_accepted |
-none |
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
content_types_provided |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
delete_completed |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
delete_resource |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
expires |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
forbidden |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
generate_etag |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
is_authorized |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
is_conflict |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
known_methods |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
languages_provided |
-skip |
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
last_modified |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
malformed_request |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
moved_permanently |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
moved_temporarily |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
multiple_choices |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
options |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
previously_existed |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
resource_exists |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
service_available |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
uri_too_long |
-
|
+
Callback name | +Default value | +
---|---|
allowed_methods | +[<<"GET">>, <<"HEAD">>, <<"OPTIONS">>] |
valid_content_headers |
-
|
+
allow_missing_post | +true |
valid_entity_length |
-
|
+
charsets_provided | +skip |
variances |
-
|
+
content_types_accepted | +none |
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.
[{{ <<"text">>, <<"html">>, '*'}, to_html}]
true
false
undefined
false
undefined
true
false
[<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]
undefined
false
false
false
false
ok
false
true
true
false
true
true
[]
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.
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:
+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 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 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 | +
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 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.
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".
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.
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.
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 @@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.
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.
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 = "*".+
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.
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}} -).
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 @@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.
-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 -
--User Interface Security Directives for Content Security Policy -
--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 -
--Beacon -
--File API -
--HTML4.01 -
--HTML5 -
--HTML5.1 -
--HTML5.2 -
--RFC 6690: Constrained RESTful Environments (CoRE) Link Format -
--RFC 7807: Problem Details for HTTP APIs -
--RFC 6906: The profile Link Relation Type -
--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 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 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 -
-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.
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"}}+
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"}}+
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">>, []}}]}}+
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 @@
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 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.
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.
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.
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.
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.+
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}.+
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.
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}.+
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.
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
.
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.
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.
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.
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".
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.
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.
cowboy:set_env - Update a listener’s environment value
cowboy:set_env - Update a listener's environment 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.
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.
-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.
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.
-The key in the environment map. Common keys include dispatch
-and middlewares
.
-
The key in the environment map. Common keys include dispatch
and middlewares
.
-The new value. -
-The type of the value differs depending on the key.
The new value.
+The type of the value differs depending on the key.
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.
-1.0: Function introduced. -
+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(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 - Listen for connections using plain TCP
cowboy:start_clear - Listen for connections using plain TCP
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.
-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
.
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
.
-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.
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.
-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).
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).
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.
-2.0: HTTP/2 support added. -
+
-2.0: Function introduced. Replaces cowboy:start_http/4
.
-
cowboy:start_http/4
.
Dispatch = cowboy_router:compile([ - {'_', [ - {"/", toppage_h, []} +Dispatch = cowboy_router:compile([ + {'_', [ + {"/", toppage_h, []} ]} ]), -{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{ - env => #{dispatch => Dispatch} -}).
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).
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 - Listen for connections using TLS
cowboy:start_tls - Listen for connections using TLS
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.
-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
.
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
.
-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.
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.
-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).
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).
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.
-2.0: HTTP/2 support added. -
+
-2.0: Function introduced. Replaces cowboy:start_https/4
.
-
cowboy:start_https/4
.
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} -}).
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).
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 - Stop the given listener
cowboy:stop_listener - Stop the given listener
stop_listener(Name :: ranch:ref()) - -> ok | {error, not_found}.
Stop a previously started listener.
Alias of ranch:stop_listener(3).
stop_listener(Name :: ranch:ref()) + -> ok | {error, not_found}.+
Stop a previously started listener.
+Alias of ranch:stop_listener(3).
-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.
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.
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.
-1.0: Function introduced. -
+ok = cowboy:stop_listener(example).
ok = cowboy:stop_listener(example).+
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 - HTTP server
cowboy - HTTP server
The module cowboy
provides convenience functions for
-manipulating Ranch listeners.
The module cowboy
provides convenience functions for manipulating Ranch listeners.
-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’s environment value -
+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() :: #{binary() => iodata()}
HTTP headers.
http_headers() :: #{binary() => iodata()}+
HTTP headers.
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/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() :: 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).
cowboy - Small, fast, modern HTTP server for Erlang/OTP
cowboy - Small, fast, modern HTTP server for Erlang/OTP
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.
Functions:
-cowboy(3) - Listener management -
+Functions:
+-cowboy_req(3) - Request and response -
+-cowboy_router(3) - Router -
+-cowboy_constraints(3) - Constraints -
+Protocols:
-cowboy_http(3) - HTTP/1.1 -
+Protocols:
+-cowboy_http2(3) - HTTP/2 -
+-cowboy_websocket(3) - Websocket -
+Handlers:
-cowboy_static(3) - Static file handler -
+Handlers:
+Behaviors:
-cowboy_handler(3) - Plain HTTP handlers -
+Behaviors:
+-cowboy_loop(3) - Loop handlers -
+-cowboy_middleware(3) - Middlewares -
+-cowboy_rest(3) - REST handlers -
+-cowboy_stream(3) - Stream handlers -
+-cowboy_websocket(3) - Websocket handlers -
+Middlewares:
-cowboy_router(3) - Router middleware -
+Middlewares:
+-cowboy_handler(3) - Handler middleware -
+-ranch(7) - Socket acceptor pool for TCP protocols -
+-cowlib(7) - Support library for manipulating Web protocols -
+-ssl - Secure communication over sockets -
+-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).+
The cowboy
application does not define any application
-environment configuration parameters.
The cowboy
application does not define any application environment configuration parameters.
cowboy_constraints:int - Integer constraint
cowboy_constraints:int - Integer constraint
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.
Generate a human-readable error message.
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.
The return value varies depending on the operation.
The return value varies depending on the operation.
-2.0: Interface modified to allow for a variety of operations. -
+-1.0: Constraint introduced. -
+This function is not meant to be called directly.
This function is not meant to be called directly.
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 - Non-empty constraint
cowboy_constraints:nonempty - Non-empty constraint
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.
Generate a human-readable error message.
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.
The return value varies depending on the operation.
The return value varies depending on the operation.
-2.0: Interface modified to allow for a variety of operations. -
+-1.0: Constraint introduced. -
+This function is not meant to be called directly.
This function is not meant to be called directly.
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 - Constraints
cowboy_constraints - Constraints
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.
Built-in constraints:
-cowboy_constraints:int(3) - Integer constraint -
+Built-in constraints:
+-cowboy_constraints:nonempty(3) - Non-empty 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() :: {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.
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 - Terminate the handler
cowboy_handler:terminate - Terminate the handler
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.
-Reason for termination. -
+Reason for termination.
-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.
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.
-Handler state. -
+Handler state.
-Handler module. -
+Handler module.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.0: Function introduced. -
+cowboy_handler:terminate(normal, Req, State, Handler).
cowboy_handler:terminate(normal, Req, State, Handler).+
cowboy_handler - Plain HTTP handlers
cowboy_handler - Plain HTTP handlers
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.
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:
- 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:
+The connection was closed normally.
- 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.
-
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.
The following function should be called by modules implementing -custom handlers to execute the optional terminate callback:
-cowboy_handler:terminate(3) - Terminate the handler -
+The following function should be called by modules implementing custom handlers to execute the optional terminate callback:
+cowboy_http - HTTP/1.1
cowboy_http - HTTP/1.1
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.
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:
- Whether the connection process also acts as a supervisor. -
-- Middleware environment. -
-- Time in ms with no data received before Cowboy closes the connection. -
-- Time in ms with nothing received at all before Cowboy closes the connection. -
-- Maximum number of empty lines before a request. -
-- Maximum length of header names. -
-- Maximum length of header values. -
-- Maximum number of headers allowed per request. -
-- Maximum number of requests allowed per connection. -
-- Maximum length of the method. -
-- Maximum length of the request line. -
-- 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 to run for every request. -
-- Time in ms with no requests before Cowboy closes the connection. -
-- Time in ms Cowboy will wait for child processes to shut down before killing them. -
-- 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:
+Whether the connection process also acts as a supervisor.
+Middleware environment.
+Time in ms with no data received before Cowboy closes the connection.
+Time in ms with nothing received at all before Cowboy closes the connection.
+Maximum number of empty lines before a request.
+Maximum length of header names.
+Maximum length of header values.
+Maximum number of headers allowed per request.
+Maximum number of requests allowed per connection.
+Maximum length of the method.
+Maximum length of the request line.
+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 to run for every request.
+Time in ms with no requests before Cowboy closes the connection.
+Time in ms Cowboy will wait for child processes to shut down before killing them.
+Ordered list of stream handlers that will handle all stream events.
+
-2.2: The max_skip_body_length
option was added.
-
max_skip_body_length
option was added.
-2.0: The timeout
option was renamed request_timeout
.
-
timeout
option was renamed request_timeout
.
-2.0: The idle_timeout
, inactivity_timeout
and shutdown_timeout
options were added.
-
idle_timeout
, inactivity_timeout
and shutdown_timeout
options were added.
-2.0: The max_method_length
option was added.
-
max_method_length
option was added.
-2.0: The max_request_line_length
default was increased from 4096 to 8000.
-
max_request_line_length
default was increased from 4096 to 8000.
-2.0: The connection_type
option was added.
-
connection_type
option was added.
-2.0: The env
option is now a map instead of a proplist.
-
env
option is now a map instead of a proplist.
-2.0: The stream_handlers
option was added.
-
stream_handlers
option was added.
-2.0: The compress
option was removed in favor of the cowboy_compress_h
stream handler.
-
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: Protocol introduced. Replaces cowboy_protocol
.
-
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 - HTTP/2
cowboy_http2 - HTTP/2
The module cowboy_http2
implements HTTP/2
-as a Ranch protocol.
The module cowboy_http2
implements HTTP/2 as a Ranch protocol.
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:
- 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:
+Whether the connection process also acts as a supervisor.
- Middleware environment. -
+Middleware environment.
- Time in ms with nothing received at all before Cowboy closes the connection. -
+Time in ms with nothing received at all before Cowboy closes the connection.
- Middlewares to run for every request. -
+Middlewares to run for every request.
- Time in ms Cowboy is willing to wait for the connection preface. -
+Time in ms Cowboy is willing to wait for the connection preface.
- Time in ms Cowboy will wait for child processes to shut down before killing them. -
+Time in ms Cowboy will wait for child processes to shut down before killing them.
- Ordered list of stream handlers that will handle all stream events. -
+Ordered list of stream handlers that will handle all stream events.
-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 - Loop handlers
cowboy_loop - Loop handlers
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:
+
-Or initiate a response in init/2
and stream the
- body in info/3
as necessary (for example server-sent events).
-
init/2
and stream the body in info/3
as necessary (for example server-sent events).
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:
- 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:
+The handler requested to close the connection by returning a stop
tuple.
- 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.
-
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.
-2.0: Loop handlers no longer need to handle overflow/timeouts. -
+-1.0: Behavior introduced. -
+cowboy_middleware - Middlewares
cowboy_middleware - Middlewares
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.
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.
-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.
Cowboy should continue processing the request using the returned Req object and environment.
-Cowboy will hibernate the process. When resuming, Cowboy -will apply the returned module, function and arguments. -
+Cowboy will hibernate the process. When resuming, Cowboy will apply the returned module, function and arguments.
-Cowboy will stop middleware execution. No other middleware -will be executed. This effectively ends the processing of -the request. -
+Cowboy will stop middleware execution. No other middleware will be executed. This effectively ends the processing of the request.
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.
-2.0: The env
type is now a map instead of a proplist.
-
env
type is now a map instead of a proplist.
-1.0: Behavior introduced. -
+cowboy_req:binding - Access a value bound from the route
cowboy_req:binding - Access a value bound from the route
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.
-Desired binding name as an atom. -
+Desired binding name as an atom.
-The Req object. -
+The Req object.
-Default value returned when the binding is missing. -
+Default value returned when the binding is missing.
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).
-2.0: Only the value is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+%% Route is "/users/:user" -Username = cowboy_req:binding(user, Req).
%% Route is "/log[/:branch]" -Branch = cowboy_req:binding(branch, Req, <<"master">>)
%% Route is "/log[/:branch]" +Branch = cowboy_req:binding(branch, Req, <<"master">>)+
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 - Access all values bound from the route
cowboy_req:bindings - Access all values bound from the route
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.
-The Req object. -
+The Req object.
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).
-2.0: Only the values are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Bindings = cowboy_req:bindings(Req).
Bindings = cowboy_req:bindings(Req).+
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 - Body length
cowboy_req:body_length - Body length
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.
-The Req object. -
+The Req object.
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.
-2.0: Only the length is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Length = cowboy_req:body_length(Req).
Length = cowboy_req:body_length(Req).+
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 - Client TLS certificate
cowboy_req:cert - Client TLS certificate
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.+
-The Req object. -
+The Req object.
The client TLS certificate.
The client TLS certificate.
-2.1: Function introduced. -
+Cert = cowboy_req:cert(Req).
Cert = cowboy_req:cert(Req).+
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 - Delete a response header
cowboy_req:delete_resp_header - Delete a response header
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.
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.
-Header name as a lowercase binary string. -
+Header name as a lowercase binary string.
-The Req object. -
+The Req object.
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.
-1.0: Function introduced. -
+Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),
Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),+
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 - Is there a request body?
cowboy_req:has_body - Is there a request body?
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.
-The Req object. -
+The Req object.
A boolean indicating whether the request has a body.
A boolean indicating whether the request has a body.
-1.0: Function introduced. -
+true = cowboy_req:has_body(Req).
true = cowboy_req:has_body(Req).+
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 - Is there a response body?
cowboy_req:has_resp_body - Is there a response body?
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.
-The Req object. -
+The Req object.
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.
-1.0: Function introduced. -
+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).+
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 - Is the given response header set?
cowboy_req:has_resp_header - Is the given response header set?
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.
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.
-Header name as a lowercase binary string. -
+Header name as a lowercase binary string.
-The Req object. -
+The Req object.
A boolean indicating whether the given response header has been set.
A boolean indicating whether the given response header has been set.
-1.0: Function introduced. -
+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).+
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 - HTTP header
cowboy_req:header - HTTP header
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.
-Desired HTTP header name as a lowercase binary string. -
+Desired HTTP header name as a lowercase binary string.
-The Req object. -
+The Req object.
-Default value returned when the header is missing. -
+Default value returned when the header is missing.
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.
-2.0: Only the header value is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Accept = cowboy_req:header(<<"accept">>, Req).
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).+
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 - HTTP headers
cowboy_req:headers - HTTP headers
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the headers are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Headers = cowboy_req:headers(Req).
Headers = cowboy_req:headers(Req).+
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 - URI host name
cowboy_req:host - URI host name
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the host name is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Host = cowboy_req:host(Req).
Host = cowboy_req:host(Req).+
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 - Access the route’s heading host segments
cowboy_req:host_info - Access the route's heading host segments
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.
-The Req object. -
+The Req object.
The tokens are returned as a list of case insensitive -binary strings.
The tokens are returned as a list of case insensitive binary strings.
-2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+HostInfo = cowboy_req:host_info(Req).
HostInfo = cowboy_req:host_info(Req).+
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 - Send an informational response
cowboy_req:inform - Send an informational response
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-The Req object. -
+Header names must be given as lowercase binary strings.
+The Req object.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.1: Function introduced. -
+Req = cowboy_req:inform(102, Req0).
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).+
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 - Match cookies against constraints
cowboy_req:match_cookies - Match cookies against constraints
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.
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.
-2.0: Function introduced. -
+%% ID and Lang are binaries. -#{id := ID, lang := Lang} - = cowboy_req:match_cookies([id, lang], Req).
%% ID is an integer and Lang a non-empty binary. -#{id := ID, lang := Lang} - = cowboy_req:match_cookies([{id, int}, {lang, nonempty}], Req).
#{lang := Lang} - = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
#{lang := Lang} + = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).+
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 - Match the query string against constraints
cowboy_req:match_qs - Match the query string against constraints
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.
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.
-2.0: Function introduced. -
+%% ID and Lang are binaries. -#{id := ID, lang := Lang} - = cowboy_req:match_qs([id, lang], Req).
%% ID is an integer and Lang a non-empty binary. -#{id := ID, lang := Lang} - = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req).
#{lang := Lang} - = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
#{lang := Lang} + = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).+
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 - HTTP method
cowboy_req:method - HTTP method
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the method is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+<<"GET">> = cowboy_req:method(Req).
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.+
cowboy_req:parse_cookies - Parse cookie headers
cowboy_req:parse_cookies - Parse cookie headers
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 []
.
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 []
.
-The Req object. -
+The Req object.
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.
-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
.
-
cookie/2,3
and cookies/1
.
Cookies = cowboy_req:parse_cookies(Req), -{_, Token} = lists:keyfind(token, 1, Cookies).
Cookies = cowboy_req:parse_cookies(Req), +{_, Token} = lists:keyfind(token, 1, Cookies).+
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 - Parse the given HTTP header
cowboy_req:parse_header - Parse the given HTTP 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.
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.
-Desired HTTP header name as a lowercase binary string. -
+Desired HTTP header name as a lowercase binary string.
-The Req object. -
+The Req object.
-Default value returned when the header is missing. -
+Default value returned when the header is missing.
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.
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
:
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
parse_header(Name, Req) -> [{Value, Quality}] - -Name :: <<"accept-charset">> - | <<"accept-encoding">> - | <<"accept-language">> -Value :: binary() %% case insensitive -Quality :: 0..1000
parse_header(<<"authorization">>, Req) - -> {basic, Username :: binary(), Password :: binary()} - | {bearer, Token :: binary()} - | {digest, [{Key :: binary(), Value :: binary()}]}
parse_header(<<"content-length">>, Req) -> non_neg_integer()
When the content-length header is missing, 0
is returned.
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.
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 []
.
parse_header(<<"expect">>, Req) -> continue
parse_header(Name, Req) - -> '*' | [{weak | strong, OpaqueTag}] - -Name :: <<"if-match">> - | <<"if-none-match">> -OpaqueTag :: binary() %% case sensitive
parse_header(Name, Req) -> calendar:datetime()
parse_header(<<"range">>, Req) -> {From, To} | Final - -From :: non_neg_integer() -To :: non_neg_integer() | infinity -Final :: neg_integer()
parse_header(<<"sec-websocket-extensions">>, Req) - -> [{Extension, Params}] - -Extension :: binary() %% case sensitive -Params :: [Key | {Key, Value}] -Key :: binary() %% case sensitive -Value :: binary() %% case sensitive
parse_header(Name, Req) -> [Token] - -Name :: <<"sec-websocket-protocol">> - | <<"upgrade">> -Token :: binary() %% case insensitive
parse_header(<<"x-forwarded-for">>, Req) -> [Token] +parse_header(<<"x-forwarded-for">>, Req) -> [Token] -Token :: binary() %% case sensitive
parse_header(_, Req) -> {undefined, RawValue}
parse_header(_, Req) -> {undefined, RawValue}+
-2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+%% Accept everything when header is missing. -Accept = cowboy_req:parse_header(<<"accept">>, Req, - [{{ <<"*">>, <<"*">>, []}, 1000, []}]).
%% Default content-length is 0. -Length = cowboy_req:header(<<"content-length">>, Req).
%% Default content-length is 0. +Length = cowboy_req:header(<<"content-length">>, Req).+
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 - Parse the query string
cowboy_req:parse_qs - Parse the query string
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.
-The Req object. -
+The Req object.
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
-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: Function introduced. Replaces qs_val/1
and qs_vals/1
.
-
qs_val/1
and qs_vals/1
.
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].+
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 - URI path
cowboy_req:path - URI path
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.+
-The Req object. -
+The Req object.
The path is returned as a binary string. It is case sensitive.
The path is returned as a binary string. It is case sensitive.
-2.0: Only the path is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Path = cowboy_req:path(Req).
Path = cowboy_req:path(Req).+
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 - Access the route’s trailing path segments
cowboy_req:path_info - Access the route's trailing path segments
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.
-The Req object. -
+The Req object.
The tokens are returned as a list of case sensitive -binary strings.
The tokens are returned as a list of case sensitive binary strings.
-2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+PathInfo = cowboy_req:path_info(Req).
PathInfo = cowboy_req:path_info(Req).+
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 - Peer address and port
cowboy_req:peer - Peer address and port
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the peer is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+{IP, Port} = cowboy_req:peer(Req).
{IP, Port} = cowboy_req:peer(Req).+
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 - URI port number
cowboy_req:port - URI port number
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.+
-The Req object. -
+The Req object.
The port number is returned as an integer.
The port number is returned as an integer.
-2.0: Only the port number is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Port = cowboy_req:port(Req).
Port = cowboy_req:port(Req).+
cowboy_req:push - Push a resource to the client
cowboy_req:push - Push a resource to the client
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-The Req object. -
+Header names must be given as lowercase binary strings.
+The Req object.
-Customize the HTTP method or the URI scheme, host, port -or query string. -
+Customize the HTTP method or the URI scheme, host, port or query string.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.0: Function introduced. -
+cowboy_req:push("/static/style.css", #{ - <<"accept">> => <<"text/css">> -}, Req),
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),+
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 - URI query string
cowboy_req:qs - URI query string
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the query string is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Qs = cowboy_req:qs(Req).
Qs = cowboy_req:qs(Req).+
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 - Read the request body
cowboy_req:read_body - Read the request body
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.
-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces body/1,2
.
-
body/1,2
.
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.
cowboy_req:read_body(Req, #{length => 64000}).
cowboy_req:read_body(Req, #{length => 64000}).+
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 - Read the next multipart headers
cowboy_req:read_part - Read the next multipart headers
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.
+-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces part/1,2
.
-
part/1,2
.
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.
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.
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).+
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 - Read the current part’s body
cowboy_req:read_part_body - Read the current part's body
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.
+-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces part_body/1,2
.
-
part_body/1,2
.
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.
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).+
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 - Read and parse a urlencoded request body
cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body
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.
-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces body_qs/1,2
.
-
body_qs/1,2
.
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0), -{_, Lang} = lists:keyfind(<<"lang">>, 1, Body).
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).+
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 - Send the response
cowboy_req:reply - Send the response
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-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.
+The body can be either a binary value, an iolist or a sendfile
tuple telling Cowboy to send the contents of a file.
-The Req object. -
+The Req object.
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.
-2.0: Only the Req is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Req = cowboy_req:reply(404, Req0).
Req = cowboy_req:reply(401, #{ - <<"www-authenticate">> => <<"Basic realm=\"erlang.org\"">> -}, Req0).
Req = cowboy_req:reply(200, #{ - <<"content-type">> => <<"text/plain">> -}, "Hello world!", Req0).
Req = cowboy_req:reply(200, #{ + <<"content-type">> => <<"text/plain">> +}, "Hello world!", Req0).+
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 - Response header
cowboy_req:resp_header - Response header
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.
-Desired response header name as a lowercase binary string. -
+Desired response header name as a lowercase binary string.
-The Req object. -
+The Req object.
-Default value returned when the header is missing. -
+Default value returned when the header is missing.
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.
-2.0: Function introduced. -
+Type = cowboy_req:resp_header(<<"content-type">>, Req).
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).+
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 - Response headers
cowboy_req:resp_headers - Response headers
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.
-The Req object. -
+The Req object.
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.
-2.0: Function introduced. -
+Headers = cowboy_req:resp_headers(Req).
Headers = cowboy_req:resp_headers(Req).+
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 - URI scheme
cowboy_req:scheme - URI scheme
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.+
-The Req object. -
+The Req object.
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">>
.
-2.0: Function introduced. -
+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}.+
cowboy_req:set_resp_body - Set the response body
cowboy_req:set_resp_body - Set the response 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.
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.
-The body can be either a binary value, an iolist or a
-sendfile
tuple telling Cowboy to send the contents of
-a file.
-
The body can be either a binary value, an iolist or a sendfile
tuple telling Cowboy to send the contents of a file.
-The Req object. -
+The Req object.
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.
-2.0: The function now accepts a sendfile
tuple.
-
sendfile
tuple.
-2.0: The set_resp_body_fun/2,3
functions were removed.
-
set_resp_body_fun/2,3
functions were removed.
-1.0: Function introduced. -
+Req = cowboy_req:set_resp_body(<<"Hello world!">>, Req0).
Req = cowboy_req:set_resp_body([ - "<html><head><title>", - page_title(), - "</title></head><body>", - page_body(), - "</body></html>" -], Req0).
{ok, #file_info{size=Size}} = file:read_file_info(Filename), -Req = cowboy_req:set_resp_body({sendfile, 0, Size, Filename}, Req0).
Req = cowboy_req:set_resp_body(<<>>, Req0).
Req = cowboy_req:set_resp_body(<<>>, Req0).+
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 - Set a cookie
cowboy_req:set_resp_cookie - Set a cookie
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.
-Cookie name. -
+Cookie name.
-Cookie value. -
+Cookie value.
-The Req object. -
+The Req object.
-Cookie options. -
+Cookie options.
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.
-2.0: set_resp_cookie/3
introduced as an alias to set_resp_cookie/4
with no options.
-
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()
.
-
binary()
instead of iodata()
.
-1.0: Function introduced. -
+SessionID = base64:encode(crypto:strong_rand_bytes(32)), -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0).
Req = cowboy_req:set_resp_cookie(<<"lang">>, <<"fr-FR">>, - Req0, #{max_age => 3600}).
Req = cowboy_req:set_resp_cookie(<<"sessionid">>, <<>>, - Req0, #{max_age => 0}).
Req = cowboy_req:set_resp_cookie(<<"inaccount">>, <<"1">>, - Req0, #{domain => "my.example.org", path => "/account"}).
SessionID = base64:encode(crypto:strong_rand_bytes(32)), -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, - Req0, #{secure => true}).
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}).+
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 - Set a response header
cowboy_req:set_resp_header - Set a response header
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.
-Header name as a lowercase binary string. -
+Header name as a lowercase binary string.
-Header value. -
+Header value.
-The Req object. -
+The Req object.
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.
-1.0: Function introduced. -
+Req = cowboy_req:set_resp_header(<<"allow">>, "GET", Req0).
Req = cowboy_req:set_resp_header(<<"allow">>, - [allowed_methods(), ", OPTIONS"], Req0).
Req = cowboy_req:set_resp_header(<<"allow">>, + [allowed_methods(), ", OPTIONS"], Req0).+
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 - Set several response headers
cowboy_req:set_resp_headers - Set several response headers
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.
-Headers as a map with keys being lowercase binary strings, -and values as binary strings. -
+Headers as a map with keys being lowercase binary strings, and values as binary strings.
-The Req object. -
+The Req object.
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.
-2.0: Function introduced. -
+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).+
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 - Socket address and port
cowboy_req:sock - Socket address and port
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.+
-The Req object. -
+The Req object.
The socket’s local IP address and port number.
The socket's local IP address and port number.
-2.1: Function introduced. -
+{IP, Port} = cowboy_req:sock(Req).
{IP, Port} = cowboy_req:sock(Req).+
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 - Stream the response body
cowboy_req:stream_body - Stream the response body
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.
-The data to be sent. -
+The data to be sent.
-A flag indicating whether this is the final piece of data -to be sent. -
+A flag indicating whether this is the final piece of data to be sent.
-The Req object. -
+The Req object.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.0: Function introduced. Replaces chunk/2
.
-
chunk/2
.
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).+
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 - Send the response headers
cowboy_req:stream_reply - Send the response headers
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-The Req object. -
+Header names must be given as lowercase binary strings.
+The Req object.
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.
-2.0: Only the Req is returned, it is no longer wrapped in a tuple. -
+
-2.0: Function introduced. Replaces chunked_reply/1,2
.
-
chunked_reply/1,2
.
Req = cowboy_req:stream_reply(200, Req0).
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).+
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 - Send the response trailers
cowboy_req:stream_trailers - Send the response trailers
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.
-Trailer field values to be sent. -
+Trailer field values to be sent.
-The Req object. -
+The Req object.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.2: Function introduced. -
+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).+
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 - Reconstructed URI
cowboy_req:uri - Reconstructed URI
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.
-The Req object. -
+The Req object.
-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. -
+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:
+-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 reconstructed URI is returned as an iolist or a binary string.
The reconstructed URI is returned as an iolist or a binary string.
-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: Function introduced. Replaces host_url/1
and url/1
.
-
host_url/1
and url/1
.
With an effective request URI http://example.org/path/to/res?edit=1 -we can have:
%% //example.org/path/to/res?edit=1 -cowboy_req:uri(Req, #{scheme => undefined}).
%% http://example.org -cowboy_req:uri(Req, #{path => undefined, qs => undefined}).
%% /path/to/res?edit=1 -cowboy_req:uri(Req, #{host => undefined}).
%% http://example.org/path/to/res?edit=1#errors -cowboy_req:uri(Req, #{fragment => <<"errors">>}).
%% https://example.org/path/to/res?edit=1 -cowboy_req:uri(Req, #{scheme => <<"https">>}).
iolist_to_binary(cowboy_req:uri(Req)).
iolist_to_binary(cowboy_req:uri(Req)).+
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 - HTTP version
cowboy_req:version - HTTP version
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the version is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Version = cowboy_req:version(Req).
Version = cowboy_req:version(Req).+
cowboy_req - HTTP request and response
cowboy_req - HTTP request and response
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_* |
-
|
+
Type | +Name pattern | +Return type | +
---|---|---|
access | +no verb, parse_*, match_* | +Value |
question |
-has_* |
-
|
+
question | +has_* | +boolean() |
modification |
-set_* |
-
|
+
modification | +set_* | +Req |
action |
-any other verb |
-
|
+
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.
Connection:
-cowboy_req:peer(3) - Peer address and port -
--cowboy_req:sock(3) - Socket address and port -
--cowboy_req:cert(3) - Client TLS certificate -
-Raw request:
-cowboy_req:method(3) - HTTP method -
--cowboy_req:version(3) - HTTP version -
--cowboy_req:scheme(3) - URI scheme -
--cowboy_req:host(3) - URI host name -
--cowboy_req:port(3) - URI port number -
--cowboy_req:path(3) - URI path -
--cowboy_req:qs(3) - URI query string -
--cowboy_req:uri(3) - Reconstructed URI -
--cowboy_req:header(3) - HTTP header -
--cowboy_req:headers(3) - HTTP headers -
-Processed request:
-cowboy_req:parse_qs(3) - Parse the query string -
--cowboy_req:match_qs(3) - Match the query string against constraints -
--cowboy_req:parse_header(3) - Parse the given HTTP header -
--cowboy_req:parse_cookies(3) - Parse cookie headers -
--cowboy_req:match_cookies(3) - Match cookies against constraints -
--cowboy_req:binding(3) - Access a value bound from the route -
--cowboy_req:bindings(3) - Access all values bound from the route -
--cowboy_req:host_info(3) - Access the route’s heading host segments -
--cowboy_req:path_info(3) - Access the route’s trailing path segments -
-Request body:
-cowboy_req:has_body(3) - Is there a request body? -
--cowboy_req:body_length(3) - Body length -
--cowboy_req:read_body(3) - Read the request body -
--cowboy_req:read_urlencoded_body(3) - Read and parse a urlencoded request body -
--cowboy_req:read_part(3) - Read the next multipart headers -
--cowboy_req:read_part_body(3) - Read the current part’s body -
-Response:
-cowboy_req:set_resp_cookie(3) - Set a cookie -
--cowboy_req:set_resp_header(3) - Set a response header -
--cowboy_req:set_resp_headers(3) - Set several response headers -
--cowboy_req:has_resp_header(3) - Is the given response header set? -
--cowboy_req:resp_header(3) - Response header -
--cowboy_req:resp_headers(3) - Response headers -
--cowboy_req:delete_resp_header(3) - Delete a response header -
--cowboy_req:set_resp_body(3) - Set the response body -
--cowboy_req:has_resp_body(3) - Is there a response body? -
--cowboy_req:inform(3) - Send an informational response -
--cowboy_req:reply(3) - Send the response -
--cowboy_req:stream_reply(3) - Send the response headers -
--cowboy_req:stream_body(3) - Stream the response body -
--cowboy_req:stream_trailers(3) - Send the response trailers -
--cowboy_req:push(3) - Push a resource to the client -
-Connection:
+Raw request:
+Processed request:
+Request body:
+Response:
+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() :: #{ - 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() :: #{ - 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:
Req#{_myapp_auth_method => pubkey}.
Req#{_myapp_auth_method => pubkey}.+
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:
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.
cowboy_rest - REST handlers
cowboy_rest - REST handlers
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).
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:
- 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:
+The handler terminated normally.
- 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.
-
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.
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(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.
Return the list of allowed methods.
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.
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(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(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(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(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.
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(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
.
Delete the resource.
+Cowboy will send an error response when this function returns false
.
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.
Return the resource's expiration date.
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.
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(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.
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(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.
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(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
.
Return whether the PUT request results in a conflict.
+A 409 Conflict response is sent when true
.
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
.
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(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(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.
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(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.
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(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.
Return whether the resource was permanently moved, and what its new location is.
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.
Return whether the resource was temporarily moved, and what its new location is.
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(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(Req, State) -> {Result, Req, State} +previously_existed(Req, State) -> {Result, Req, State} -Result :: boolean() -Default :: false
Return whether the resource existed previously.
Return whether the resource existed previously.
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.
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(Req, State) -> {Result, Req, State} +resource_exists(Req, State) -> {Result, Req, State} -Result :: boolean() -Default :: true
Return whether the resource exists.
Return whether the resource exists.
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
.
Return whether the service is available.
+A 503 Service Unavailable response will be sent when this function returns false
.
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.
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(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.
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(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
.
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(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.
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.
-2.1: The switch_handler
return value was added.
-
switch_handler
return value was added.
-1.0: Behavior introduced. -
+cowboy_router:compile - Compile routes to the resources
cowboy_router:compile - Compile routes to the resources
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.
-Human readable list of routes. -
+Human readable list of routes.
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.
-1.0: Function introduced. -
+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} +}).+
cowboy_router - Router middleware
cowboy_router - Router middleware
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.
-cowboy_router:compile(3) - Compile routes to the resources -
+bindings() :: #{atom() => any()}
Bindings found during routing.
bindings() :: #{atom() => any()}+
Bindings found during routing.
Opaque type containing the compiled routes.
Opaque type containing the compiled 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.
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() :: [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.
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 - Static file handler
cowboy_static - Static file handler
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.
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.
-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.
+Send a file.
+The path is relative to the given application's private directory.
-Send a file. -
-The path is either absolute or relative to the Erlang node’s -current directory.
Send a file.
+The path is either absolute or relative to the Erlang node's current directory.
-Recursively serve files from a directory. -
-The path is relative to the given application’s private -directory.
Recursively serve files from a directory.
+The path is relative to the given application's private directory.
-Recursively serve files from a directory. -
-The path is either absolute or relative to the Erlang node’s -current directory.
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.
-1.0: Handler introduced. -
+generate_etag(Path, Size, Mtime) -> - {strong, integer_to_binary( - erlang:phash2({Path, Size, Mtime}, 16#ffffffff))}.
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.+
cowboy_handler - Stream handlers
cowboy_handler - Stream handlers
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.
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
.
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:
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.
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.
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.
Send data to the client.
{data, fin(), iodata()}
{data, fin(), iodata()}+
Send response trailers to the client.
{trailers, cowboy:http_headers()}
{trailers, cowboy:http_headers()}+
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.
The command will be ignored if the protocol does not provide any server push mechanism.
{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.
Inform Cowboy that a process was spawned and should be -supervised.
{spawn, pid(), timeout()}
{spawn, pid(), timeout()}+
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 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 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
.
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.
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.
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.
+ + + + + + + + + + + + + + + + +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.
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.
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.
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.
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.
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.
Same as the switch_protocol command.
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.
The following function should be called by modules implementing -stream handlers to execute the next stream handler in the list:
-cowboy_stream:init(3) - Initialize a stream -
+The following function should be called by modules implementing stream handlers to execute the next stream handler in the list:
+-cowboy_stream:data(3) - Handle data for a stream -
+-cowboy_stream:info(3) - Handle a message for a stream -
+-cowboy_stream:terminate(3) - Terminate a stream -
+-cowboy_stream:early_error(3) - Handle an early error for a stream -
+commands() :: [Command]+
See the list of commands for details.
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.
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() :: 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() :: {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() :: 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.
-2.2: The trailers command was 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 - Websocket
cowboy_websocket - Websocket
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.
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:
- 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:
+The connection was closed normally before establishing a Websocket connection. This typically happens if an ok
tuple is returned from the init/2
callback.
- The remote endpoint closed the connection without giving any - further details. -
+The remote endpoint closed the connection without giving any further details.
- The remote endpoint closed the connection with the given
- Code
and Payload
as the reason.
-
The remote endpoint closed the connection with the given Code
and Payload
as the reason.
- The handler requested to close the connection, either by returning
- a stop
tuple or by sending a close
frame.
-
The handler requested to close the connection, either by returning a stop
tuple or by sending a close
frame.
- The connection has been closed due to inactivity. The timeout
- value can be configured from init/2
.
-
The connection has been closed due to inactivity. The timeout value can be configured from init/2
.
- 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.
-
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.
- A text frame was sent by the client with invalid encoding. All - text frames must be valid UTF-8. -
+A text frame was sent by the client with invalid encoding. All text frames must be valid UTF-8.
- A protocol error has been detected. -
+A protocol error has been detected.
- The socket has been closed brutally without a close frame being - received first. -
+The socket has been closed brutally without a close frame being received first.
- A socket error ocurred. -
+A socket error ocurred.
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() :: #{ - 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:
- 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:
+Whether to enable the Websocket frame compression extension. Frames will only be compressed for the clients that support this extension.
- Time in milliseconds that Cowboy will keep the - connection open without receiving anything from - the client. -
+Time in milliseconds that Cowboy will keep the connection open without receiving anything from the client.
- 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.
-
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.
-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
.
-
websocket_terminate/3
was removed in favor of terminate/3
.
-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 - status codes used by Cowboy
HTTP status codes - status codes used by Cowboy
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.
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.
This is the status code sent when switching to the -Websocket protocol.
This is the status code sent when switching to the Websocket protocol.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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:
+-The request-line could not be parsed. -
+-Too many headers were sent. -
+-A header name was too long. -
+-A header value was too long. -
+-The host header was missing from an HTTP/1.1 request. -
+-The host header could not be parsed. -
+-The requested host was not found. -
+-The requested path could not be parsed. -
+-The accept header could not be parsed when using REST. -
+-REST under normal conditions. -
+-A Websocket upgrade failed. -
+This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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 - Small, fast, modern HTTP server for Erlang/OTP
cowboy - Small, fast, modern HTTP server for Erlang/OTP
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.
Functions:
-cowboy(3) - Listener management -
+Functions:
+-cowboy_req(3) - Request and response -
+-cowboy_router(3) - Router -
+-cowboy_constraints(3) - Constraints -
+Protocols:
-cowboy_http(3) - HTTP/1.1 -
+Protocols:
+-cowboy_http2(3) - HTTP/2 -
+-cowboy_websocket(3) - Websocket -
+Handlers:
-cowboy_static(3) - Static file handler -
+Handlers:
+Behaviors:
-cowboy_handler(3) - Plain HTTP handlers -
+Behaviors:
+-cowboy_loop(3) - Loop handlers -
+-cowboy_middleware(3) - Middlewares -
+-cowboy_rest(3) - REST handlers -
+-cowboy_stream(3) - Stream handlers -
+-cowboy_websocket(3) - Websocket handlers -
+Middlewares:
-cowboy_router(3) - Router middleware -
+Middlewares:
+-cowboy_handler(3) - Handler middleware -
+-ranch(7) - Socket acceptor pool for TCP protocols -
+-cowlib(7) - Support library for manipulating Web protocols -
+-ssl - Secure communication over sockets -
+-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).+
The cowboy
application does not define any application
-environment configuration parameters.
The cowboy
application does not define any application environment configuration parameters.
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.
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 are specified as an atom:
Constraint | -Description | -||||||||
---|---|---|---|---|---|---|---|---|---|
int |
-Converts binary value to integer. |
+
Constraint | +Description | +
---|---|
int | +Converts binary value to integer. |
nonempty |
-Ensures the binary value is non-empty. |
+
nonempty | +Ensures the binary value is non-empty. |
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 @@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.
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.
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 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.
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.
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.
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 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.
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 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.
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.
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 @@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.
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.
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.
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.
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.
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.
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 @@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.
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.
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.
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.
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.
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.
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.
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.
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!
Handlers are Erlang modules that handle HTTP requests.
Handlers are Erlang modules that handle HTTP requests.
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
.
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}.+
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 @@-Introduction -
+-Flow diagram -
+-Listeners -
+-Routing -
+-Constraints -
+-Handlers -
+-Static files -
+-Multipart -
+-Streams -
+-Middlewares -
+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.
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.
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.
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.
-
-
Cowboy uses Semantic Versioning 2.0.0.
Cowboy uses Semantic Versioning 2.0.0.
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 @@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.
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.
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.
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.
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.
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 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.
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}.+
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.
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}.+
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.
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.
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.
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.
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.
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.
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
.
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 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.
-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.
-
cowboy_stream_h
stream handler has been added. It provides most of Cowboy's default behavior.
+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.
+compress
option.
+cowboy_req
functions. Their interface has also been modified to allow for reverse operations and formatting of errors.
+-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. -
-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.
+
-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. -
-cowboy_handler
, cowboy_loop
, cowboy_rest
and cowboy_websocket
.
+init/2
and terminate/3
callbacks. The latter is now optional. The terminate reason has now been documented for all handlers.
+{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.
+halt
or shutdown
tuples as a return value no longer do so. The return value is now a stop
tuple, consistent across Cowboy.
+error
tuple. They have to send the response and return a stop
tuple instead.
+known_content_type
REST handler callback has been removed as it was found unnecessary.
+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_init/1
. The frames will be sent immediately after the handshake.
+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).
+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.
+
-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).
-
cowboy_req:scheme/1
function has been added.
+cowboy_req:uri/1,2
function has been added, replacing the less powerful functions cowboy_req:url/1
and cowboy_req:host_url/1
.
+cowboy_req:match_qs/2
and cowboy_req:match_cookies/2
allow matching query string and cookies against constraints.
+cowboy_req:set_resp_cookie/3
has been added to complement cowboy_req:set_resp_cookie/4
.
+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.
+cowboy_req:set_resp_headers/2
has been added. It allows setting many response headers at once.
+cowboy_req:push/3,4
can be used to push resources for protocols that support it (by default only HTTP/2).
+
-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.
-
cowboy:start_http/4
function was renamed to cowboy:start_clear/3
.
+cowboy:start_https/4
function was renamed to cowboy:start_tls/3
.
+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.
+Opts
argument for cowboy_req:set_resp_cookie/4
has changed to improve consistency. It is now the last argument.
+
-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
.
-
cowboy_req:url/1
and cowboy_req:host_url/1
have been removed in favor of the new function cowboy_req:uri/1,2
.
+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.
+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.
+cowboy_req
, including the functions cowboy_req:get/2
and cowboy_req:set/3
.
+
-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. -
-+
characters.
+.
and ..
.
+content_types_accepted/2
step in REST handlers.
+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.
+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.
-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. 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.
-
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 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.
+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.
-
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_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.
-
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.
-
stop
as a return value are now explicitly listed in the documentation.
-The function cowboy_req:sock/1
returns the IP/port
- of the local socket.
-
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.
-
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.
-
cowboy_req:inform/2,3
sends an informational response.
-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.
-
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.
-
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.
-
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 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.
-
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. -
+
-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_clock
process is not running. This can happen when Cowboy is being restarted during upgrades, for example.
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.
-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.
-
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 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.
-
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.
-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). -
+-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. -
+-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. -
+-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.
-
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.
-
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. -
+-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. -
+-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. -
+-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. -
+-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. -
+
-A packet could be lost when switching to Websocket or any
- other protocol via the switch_protocol
command. This is
- now fixed.
-
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. -
+
-Both experimental stream handlers cowboy_metrics_h
and
- cowboy_tracer_h
received a number of fixes and improvements.
-
cowboy_metrics_h
and cowboy_tracer_h
received a number of fixes and improvements.
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.
-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.
-
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.
-
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. -
+-Add support for the 308 status code and a test suite - for RFC7538 where it is defined. -
+
-Ensure timeout options accept the value infinity
as
- documented.
-
infinity
as documented.
-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.
-
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. -
+-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
.
-
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.
-
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.
-
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. -
+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 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 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 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.
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, 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 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.
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.
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).+
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}).+
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 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.
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.
+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.
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.
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.
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 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.
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.
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">>, []}).+
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 @@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.
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.
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.
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.
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.
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 @@
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.
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.
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.
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.
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.
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
.
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.
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
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).+
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:
+-Other required headers (for example the date header) -
+-Preset headers -
+-Headers given to the reply function -
+-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).+
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
.
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).+
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).+
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 @@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.
All requests start from here.
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.
+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.
This diagram only applies to OPTIONS requests.
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.
+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 applies to all request methods other than -OPTIONS. It is executed right after the "Start" diagram -is completed.
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.
+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 only applies to GET and HEAD requests.
For a description of the cond
step, please see
-the "Conditional requests" diagram.
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.
This diagram only applies to PUT, POST and PATCH requests.
For a description of the cond
step, please see
-the "Conditional requests" diagram.
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.
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.
This diagram only applies to PUT, POST and PATCH requests.
+For a description of the cond
step, please see the "Conditional requests" diagram.
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 DELETE requests.
For a description of the cond
step, please see
-the "Conditional requests" diagram.
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.
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 applies to all request methods other than
-OPTIONS. It is executed right after the resource_exists
-callback, when the resource exists.
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.
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.
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.
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.
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.
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 |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
allow_missing_post |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
charsets_provided |
-skip |
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
content_types_accepted |
-none |
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
content_types_provided |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
delete_completed |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
delete_resource |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
expires |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
forbidden |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
generate_etag |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
is_authorized |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
is_conflict |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
known_methods |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
languages_provided |
-skip |
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
last_modified |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
malformed_request |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
moved_permanently |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
moved_temporarily |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
multiple_choices |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
options |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
previously_existed |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
resource_exists |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
service_available |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
uri_too_long |
-
|
+
Callback name | +Default value | +
---|---|
allowed_methods | +[<<"GET">>, <<"HEAD">>, <<"OPTIONS">>] |
valid_content_headers |
-
|
+
allow_missing_post | +true |
valid_entity_length |
-
|
+
charsets_provided | +skip |
variances |
-
|
+
content_types_accepted | +none |
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.
[{{ <<"text">>, <<"html">>, '*'}, to_html}]
true
false
undefined
false
undefined
true
false
[<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]
undefined
false
false
false
false
ok
false
true
true
false
true
true
[]
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.
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:
+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 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 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 | +
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 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.
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".
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.
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.
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 @@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.
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.
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 = "*".+
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.
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}} -).
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 @@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.
-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 -
--User Interface Security Directives for Content Security Policy -
--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 -
--Beacon -
--File API -
--HTML4.01 -
--HTML5 -
--HTML5.1 -
--HTML5.2 -
--RFC 6690: Constrained RESTful Environments (CoRE) Link Format -
--RFC 7807: Problem Details for HTTP APIs -
--RFC 6906: The profile Link Relation Type -
--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 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 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 -
-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.
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"}}+
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"}}+
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">>, []}}]}}+
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 @@
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 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.
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.
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.
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.
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.+
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}.+
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.
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}.+
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.
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
.
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.
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.
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 @@
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.
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".
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.
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.
cowboy:set_env - Update a listener’s environment value
cowboy:set_env - Update a listener's environment 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.
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.
-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.
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.
-The key in the environment map. Common keys include dispatch
-and middlewares
.
-
The key in the environment map. Common keys include dispatch
and middlewares
.
-The new value. -
-The type of the value differs depending on the key.
The new value.
+The type of the value differs depending on the key.
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.
-1.0: Function introduced. -
+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(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 - Listen for connections using plain TCP
cowboy:start_clear - Listen for connections using plain TCP
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.
-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
.
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
.
-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.
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.
-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).
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).
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.
-2.0: HTTP/2 support added. -
+
-2.0: Function introduced. Replaces cowboy:start_http/4
.
-
cowboy:start_http/4
.
Dispatch = cowboy_router:compile([ - {'_', [ - {"/", toppage_h, []} +Dispatch = cowboy_router:compile([ + {'_', [ + {"/", toppage_h, []} ]} ]), -{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{ - env => #{dispatch => Dispatch} -}).
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).
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 - Listen for connections using TLS
cowboy:start_tls - Listen for connections using TLS
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.
-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
.
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
.
-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.
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.
-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).
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).
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.
-2.0: HTTP/2 support added. -
+
-2.0: Function introduced. Replaces cowboy:start_https/4
.
-
cowboy:start_https/4
.
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} -}).
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).
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 - Stop the given listener
cowboy:stop_listener - Stop the given listener
stop_listener(Name :: ranch:ref()) - -> ok | {error, not_found}.
Stop a previously started listener.
Alias of ranch:stop_listener(3).
stop_listener(Name :: ranch:ref()) + -> ok | {error, not_found}.+
Stop a previously started listener.
+Alias of ranch:stop_listener(3).
-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.
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.
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.
-1.0: Function introduced. -
+ok = cowboy:stop_listener(example).
ok = cowboy:stop_listener(example).+
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 - HTTP server
cowboy - HTTP server
The module cowboy
provides convenience functions for
-manipulating Ranch listeners.
The module cowboy
provides convenience functions for manipulating Ranch listeners.
-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’s environment value -
+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() :: #{binary() => iodata()}
HTTP headers.
http_headers() :: #{binary() => iodata()}+
HTTP headers.
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/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() :: 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).
cowboy - Small, fast, modern HTTP server for Erlang/OTP
cowboy - Small, fast, modern HTTP server for Erlang/OTP
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.
Functions:
-cowboy(3) - Listener management -
+Functions:
+-cowboy_req(3) - Request and response -
+-cowboy_router(3) - Router -
+-cowboy_constraints(3) - Constraints -
+Protocols:
-cowboy_http(3) - HTTP/1.1 -
+Protocols:
+-cowboy_http2(3) - HTTP/2 -
+-cowboy_websocket(3) - Websocket -
+Handlers:
-cowboy_static(3) - Static file handler -
+Handlers:
+Behaviors:
-cowboy_handler(3) - Plain HTTP handlers -
+Behaviors:
+-cowboy_loop(3) - Loop handlers -
+-cowboy_middleware(3) - Middlewares -
+-cowboy_rest(3) - REST handlers -
+-cowboy_stream(3) - Stream handlers -
+-cowboy_websocket(3) - Websocket handlers -
+Middlewares:
-cowboy_router(3) - Router middleware -
+Middlewares:
+-cowboy_handler(3) - Handler middleware -
+-ranch(7) - Socket acceptor pool for TCP protocols -
+-cowlib(7) - Support library for manipulating Web protocols -
+-ssl - Secure communication over sockets -
+-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).+
The cowboy
application does not define any application
-environment configuration parameters.
The cowboy
application does not define any application environment configuration parameters.
cowboy_constraints:int - Integer constraint
cowboy_constraints:int - Integer constraint
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.
Generate a human-readable error message.
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.
The return value varies depending on the operation.
The return value varies depending on the operation.
-2.0: Interface modified to allow for a variety of operations. -
+-1.0: Constraint introduced. -
+This function is not meant to be called directly.
This function is not meant to be called directly.
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 - Non-empty constraint
cowboy_constraints:nonempty - Non-empty constraint
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.
Generate a human-readable error message.
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.
The return value varies depending on the operation.
The return value varies depending on the operation.
-2.0: Interface modified to allow for a variety of operations. -
+-1.0: Constraint introduced. -
+This function is not meant to be called directly.
This function is not meant to be called directly.
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 - Constraints
cowboy_constraints - Constraints
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.
Built-in constraints:
-cowboy_constraints:int(3) - Integer constraint -
+Built-in constraints:
+-cowboy_constraints:nonempty(3) - Non-empty 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() :: {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.
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 - Terminate the handler
cowboy_handler:terminate - Terminate the handler
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.
-Reason for termination. -
+Reason for termination.
-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.
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.
-Handler state. -
+Handler state.
-Handler module. -
+Handler module.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.0: Function introduced. -
+cowboy_handler:terminate(normal, Req, State, Handler).
cowboy_handler:terminate(normal, Req, State, Handler).+
cowboy_handler - Plain HTTP handlers
cowboy_handler - Plain HTTP handlers
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.
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:
- 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:
+The connection was closed normally.
- 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.
-
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.
The following function should be called by modules implementing -custom handlers to execute the optional terminate callback:
-cowboy_handler:terminate(3) - Terminate the handler -
+The following function should be called by modules implementing custom handlers to execute the optional terminate callback:
+cowboy_http - HTTP/1.1
cowboy_http - HTTP/1.1
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.
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:
- Whether the connection process also acts as a supervisor. -
-- Middleware environment. -
-- Time in ms with no data received before Cowboy closes the connection. -
-- Time in ms with nothing received at all before Cowboy closes the connection. -
-- Maximum number of empty lines before a request. -
-- Maximum length of header names. -
-- Maximum length of header values. -
-- Maximum number of headers allowed per request. -
-- Maximum number of requests allowed per connection. -
-- Maximum length of the method. -
-- Maximum length of the request line. -
-- 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 to run for every request. -
-- Time in ms with no requests before Cowboy closes the connection. -
-- Time in ms Cowboy will wait for child processes to shut down before killing them. -
-- 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:
+Whether the connection process also acts as a supervisor.
+Middleware environment.
+Time in ms with no data received before Cowboy closes the connection.
+Time in ms with nothing received at all before Cowboy closes the connection.
+Maximum number of empty lines before a request.
+Maximum length of header names.
+Maximum length of header values.
+Maximum number of headers allowed per request.
+Maximum number of requests allowed per connection.
+Maximum length of the method.
+Maximum length of the request line.
+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 to run for every request.
+Time in ms with no requests before Cowboy closes the connection.
+Time in ms Cowboy will wait for child processes to shut down before killing them.
+Ordered list of stream handlers that will handle all stream events.
+
-2.2: The max_skip_body_length
option was added.
-
max_skip_body_length
option was added.
-2.0: The timeout
option was renamed request_timeout
.
-
timeout
option was renamed request_timeout
.
-2.0: The idle_timeout
, inactivity_timeout
and shutdown_timeout
options were added.
-
idle_timeout
, inactivity_timeout
and shutdown_timeout
options were added.
-2.0: The max_method_length
option was added.
-
max_method_length
option was added.
-2.0: The max_request_line_length
default was increased from 4096 to 8000.
-
max_request_line_length
default was increased from 4096 to 8000.
-2.0: The connection_type
option was added.
-
connection_type
option was added.
-2.0: The env
option is now a map instead of a proplist.
-
env
option is now a map instead of a proplist.
-2.0: The stream_handlers
option was added.
-
stream_handlers
option was added.
-2.0: The compress
option was removed in favor of the cowboy_compress_h
stream handler.
-
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: Protocol introduced. Replaces cowboy_protocol
.
-
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 - HTTP/2
cowboy_http2 - HTTP/2
The module cowboy_http2
implements HTTP/2
-as a Ranch protocol.
The module cowboy_http2
implements HTTP/2 as a Ranch protocol.
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:
- 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:
+Whether the connection process also acts as a supervisor.
- Middleware environment. -
+Middleware environment.
- Time in ms with nothing received at all before Cowboy closes the connection. -
+Time in ms with nothing received at all before Cowboy closes the connection.
- Middlewares to run for every request. -
+Middlewares to run for every request.
- Time in ms Cowboy is willing to wait for the connection preface. -
+Time in ms Cowboy is willing to wait for the connection preface.
- Time in ms Cowboy will wait for child processes to shut down before killing them. -
+Time in ms Cowboy will wait for child processes to shut down before killing them.
- Ordered list of stream handlers that will handle all stream events. -
+Ordered list of stream handlers that will handle all stream events.
-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 - Loop handlers
cowboy_loop - Loop handlers
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:
+
-Or initiate a response in init/2
and stream the
- body in info/3
as necessary (for example server-sent events).
-
init/2
and stream the body in info/3
as necessary (for example server-sent events).
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:
- 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:
+The handler requested to close the connection by returning a stop
tuple.
- 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.
-
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.
-2.0: Loop handlers no longer need to handle overflow/timeouts. -
+-1.0: Behavior introduced. -
+cowboy_middleware - Middlewares
cowboy_middleware - Middlewares
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.
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.
-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.
Cowboy should continue processing the request using the returned Req object and environment.
-Cowboy will hibernate the process. When resuming, Cowboy -will apply the returned module, function and arguments. -
+Cowboy will hibernate the process. When resuming, Cowboy will apply the returned module, function and arguments.
-Cowboy will stop middleware execution. No other middleware -will be executed. This effectively ends the processing of -the request. -
+Cowboy will stop middleware execution. No other middleware will be executed. This effectively ends the processing of the request.
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.
-2.0: The env
type is now a map instead of a proplist.
-
env
type is now a map instead of a proplist.
-1.0: Behavior introduced. -
+cowboy_req:binding - Access a value bound from the route
cowboy_req:binding - Access a value bound from the route
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.
-Desired binding name as an atom. -
+Desired binding name as an atom.
-The Req object. -
+The Req object.
-Default value returned when the binding is missing. -
+Default value returned when the binding is missing.
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).
-2.0: Only the value is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+%% Route is "/users/:user" -Username = cowboy_req:binding(user, Req).
%% Route is "/log[/:branch]" -Branch = cowboy_req:binding(branch, Req, <<"master">>)
%% Route is "/log[/:branch]" +Branch = cowboy_req:binding(branch, Req, <<"master">>)+
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 - Access all values bound from the route
cowboy_req:bindings - Access all values bound from the route
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.
-The Req object. -
+The Req object.
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).
-2.0: Only the values are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Bindings = cowboy_req:bindings(Req).
Bindings = cowboy_req:bindings(Req).+
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 - Body length
cowboy_req:body_length - Body length
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.
-The Req object. -
+The Req object.
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.
-2.0: Only the length is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Length = cowboy_req:body_length(Req).
Length = cowboy_req:body_length(Req).+
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 - Client TLS certificate
cowboy_req:cert - Client TLS certificate
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.+
-The Req object. -
+The Req object.
The client TLS certificate.
The client TLS certificate.
-2.1: Function introduced. -
+Cert = cowboy_req:cert(Req).
Cert = cowboy_req:cert(Req).+
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 - Delete a response header
cowboy_req:delete_resp_header - Delete a response header
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.
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.
-Header name as a lowercase binary string. -
+Header name as a lowercase binary string.
-The Req object. -
+The Req object.
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.
-1.0: Function introduced. -
+Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),
Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),+
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 - Is there a request body?
cowboy_req:has_body - Is there a request body?
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.
-The Req object. -
+The Req object.
A boolean indicating whether the request has a body.
A boolean indicating whether the request has a body.
-1.0: Function introduced. -
+true = cowboy_req:has_body(Req).
true = cowboy_req:has_body(Req).+
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 - Is there a response body?
cowboy_req:has_resp_body - Is there a response body?
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.
-The Req object. -
+The Req object.
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.
-1.0: Function introduced. -
+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).+
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 - Is the given response header set?
cowboy_req:has_resp_header - Is the given response header set?
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.
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.
-Header name as a lowercase binary string. -
+Header name as a lowercase binary string.
-The Req object. -
+The Req object.
A boolean indicating whether the given response header has been set.
A boolean indicating whether the given response header has been set.
-1.0: Function introduced. -
+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).+
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 - HTTP header
cowboy_req:header - HTTP header
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.
-Desired HTTP header name as a lowercase binary string. -
+Desired HTTP header name as a lowercase binary string.
-The Req object. -
+The Req object.
-Default value returned when the header is missing. -
+Default value returned when the header is missing.
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.
-2.0: Only the header value is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Accept = cowboy_req:header(<<"accept">>, Req).
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).+
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 - HTTP headers
cowboy_req:headers - HTTP headers
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the headers are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Headers = cowboy_req:headers(Req).
Headers = cowboy_req:headers(Req).+
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 - URI host name
cowboy_req:host - URI host name
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the host name is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Host = cowboy_req:host(Req).
Host = cowboy_req:host(Req).+
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 - Access the route’s heading host segments
cowboy_req:host_info - Access the route's heading host segments
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.
-The Req object. -
+The Req object.
The tokens are returned as a list of case insensitive -binary strings.
The tokens are returned as a list of case insensitive binary strings.
-2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+HostInfo = cowboy_req:host_info(Req).
HostInfo = cowboy_req:host_info(Req).+
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 - Send an informational response
cowboy_req:inform - Send an informational response
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-The Req object. -
+Header names must be given as lowercase binary strings.
+The Req object.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.1: Function introduced. -
+Req = cowboy_req:inform(102, Req0).
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).+
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 - Match cookies against constraints
cowboy_req:match_cookies - Match cookies against constraints
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.
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.
-2.0: Function introduced. -
+%% ID and Lang are binaries. -#{id := ID, lang := Lang} - = cowboy_req:match_cookies([id, lang], Req).
%% ID is an integer and Lang a non-empty binary. -#{id := ID, lang := Lang} - = cowboy_req:match_cookies([{id, int}, {lang, nonempty}], Req).
#{lang := Lang} - = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
#{lang := Lang} + = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).+
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 - Match the query string against constraints
cowboy_req:match_qs - Match the query string against constraints
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.
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.
-2.0: Function introduced. -
+%% ID and Lang are binaries. -#{id := ID, lang := Lang} - = cowboy_req:match_qs([id, lang], Req).
%% ID is an integer and Lang a non-empty binary. -#{id := ID, lang := Lang} - = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req).
#{lang := Lang} - = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
#{lang := Lang} + = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).+
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 - HTTP method
cowboy_req:method - HTTP method
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the method is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+<<"GET">> = cowboy_req:method(Req).
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.+
cowboy_req:parse_cookies - Parse cookie headers
cowboy_req:parse_cookies - Parse cookie headers
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 []
.
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 []
.
-The Req object. -
+The Req object.
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.
-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
.
-
cookie/2,3
and cookies/1
.
Cookies = cowboy_req:parse_cookies(Req), -{_, Token} = lists:keyfind(<<"token">>, 1, Cookies).
Cookies = cowboy_req:parse_cookies(Req), +{_, Token} = lists:keyfind(<<"token">>, 1, Cookies).+
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 - Parse the given HTTP header
cowboy_req:parse_header - Parse the given HTTP 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.
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.
-Desired HTTP header name as a lowercase binary string. -
+Desired HTTP header name as a lowercase binary string.
-The Req object. -
+The Req object.
-Default value returned when the header is missing. -
+Default value returned when the header is missing.
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.
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
:
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
parse_header(Name, Req) -> [{Value, Quality}] - -Name :: <<"accept-charset">> - | <<"accept-encoding">> - | <<"accept-language">> -Value :: binary() %% case insensitive -Quality :: 0..1000
parse_header(<<"authorization">>, Req) - -> {basic, Username :: binary(), Password :: binary()} - | {bearer, Token :: binary()} - | {digest, [{Key :: binary(), Value :: binary()}]}
parse_header(<<"content-length">>, Req) -> non_neg_integer()
When the content-length header is missing, 0
is returned.
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.
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 []
.
parse_header(<<"expect">>, Req) -> continue
parse_header(Name, Req) - -> '*' | [{weak | strong, OpaqueTag}] - -Name :: <<"if-match">> - | <<"if-none-match">> -OpaqueTag :: binary() %% case sensitive
parse_header(Name, Req) -> calendar:datetime()
parse_header(<<"range">>, Req) -> {From, To} | Final - -From :: non_neg_integer() -To :: non_neg_integer() | infinity -Final :: neg_integer()
parse_header(<<"sec-websocket-extensions">>, Req) - -> [{Extension, Params}] - -Extension :: binary() %% case sensitive -Params :: [Key | {Key, Value}] -Key :: binary() %% case sensitive -Value :: binary() %% case sensitive
parse_header(Name, Req) -> [Token] - -Name :: <<"sec-websocket-protocol">> - | <<"upgrade">> -Token :: binary() %% case insensitive
parse_header(<<"x-forwarded-for">>, Req) -> [Token] +parse_header(<<"x-forwarded-for">>, Req) -> [Token] -Token :: binary() %% case sensitive
parse_header(_, Req) -> {undefined, RawValue}
parse_header(_, Req) -> {undefined, RawValue}+
-2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+%% Accept everything when header is missing. -Accept = cowboy_req:parse_header(<<"accept">>, Req, - [{{ <<"*">>, <<"*">>, []}, 1000, []}]).
%% Default content-length is 0. -Length = cowboy_req:header(<<"content-length">>, Req).
%% Default content-length is 0. +Length = cowboy_req:header(<<"content-length">>, Req).+
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 - Parse the query string
cowboy_req:parse_qs - Parse the query string
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.
-The Req object. -
+The Req object.
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
-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: Function introduced. Replaces qs_val/1
and qs_vals/1
.
-
qs_val/1
and qs_vals/1
.
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].+
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 - URI path
cowboy_req:path - URI path
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.+
-The Req object. -
+The Req object.
The path is returned as a binary string. It is case sensitive.
The path is returned as a binary string. It is case sensitive.
-2.0: Only the path is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Path = cowboy_req:path(Req).
Path = cowboy_req:path(Req).+
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 - Access the route’s trailing path segments
cowboy_req:path_info - Access the route's trailing path segments
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.
-The Req object. -
+The Req object.
The tokens are returned as a list of case sensitive -binary strings.
The tokens are returned as a list of case sensitive binary strings.
-2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+PathInfo = cowboy_req:path_info(Req).
PathInfo = cowboy_req:path_info(Req).+
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 - Peer address and port
cowboy_req:peer - Peer address and port
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the peer is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+{IP, Port} = cowboy_req:peer(Req).
{IP, Port} = cowboy_req:peer(Req).+
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 - URI port number
cowboy_req:port - URI port number
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.+
-The Req object. -
+The Req object.
The port number is returned as an integer.
The port number is returned as an integer.
-2.0: Only the port number is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Port = cowboy_req:port(Req).
Port = cowboy_req:port(Req).+
cowboy_req:push - Push a resource to the client
cowboy_req:push - Push a resource to the client
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-The Req object. -
+Header names must be given as lowercase binary strings.
+The Req object.
-Customize the HTTP method or the URI scheme, host, port -or query string. -
+Customize the HTTP method or the URI scheme, host, port or query string.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.0: Function introduced. -
+cowboy_req:push("/static/style.css", #{ - <<"accept">> => <<"text/css">> -}, Req),
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),+
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 - URI query string
cowboy_req:qs - URI query string
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the query string is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Qs = cowboy_req:qs(Req).
Qs = cowboy_req:qs(Req).+
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 - Read the request body
cowboy_req:read_body - Read the request body
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.
-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces body/1,2
.
-
body/1,2
.
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.
cowboy_req:read_body(Req, #{length => 64000}).
cowboy_req:read_body(Req, #{length => 64000}).+
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 - Read the next multipart headers
cowboy_req:read_part - Read the next multipart headers
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.
+-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces part/1,2
.
-
part/1,2
.
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.
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.
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).+
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 - Read the current part’s body
cowboy_req:read_part_body - Read the current part's body
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.
+-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces part_body/1,2
.
-
part_body/1,2
.
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.
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).+
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 - Read and parse a urlencoded request body
cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body
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.
-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces body_qs/1,2
.
-
body_qs/1,2
.
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0), -{_, Lang} = lists:keyfind(<<"lang">>, 1, Body).
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).+
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 - Send the response
cowboy_req:reply - Send the response
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-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.
+The body can be either a binary value, an iolist or a sendfile
tuple telling Cowboy to send the contents of a file.
-The Req object. -
+The Req object.
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.
-2.0: Only the Req is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Req = cowboy_req:reply(404, Req0).
Req = cowboy_req:reply(401, #{ - <<"www-authenticate">> => <<"Basic realm=\"erlang.org\"">> -}, Req0).
Req = cowboy_req:reply(200, #{ - <<"content-type">> => <<"text/plain">> -}, "Hello world!", Req0).
Req = cowboy_req:reply(200, #{ + <<"content-type">> => <<"text/plain">> +}, "Hello world!", Req0).+
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 - Response header
cowboy_req:resp_header - Response header
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.
-Desired response header name as a lowercase binary string. -
+Desired response header name as a lowercase binary string.
-The Req object. -
+The Req object.
-Default value returned when the header is missing. -
+Default value returned when the header is missing.
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.
-2.0: Function introduced. -
+Type = cowboy_req:resp_header(<<"content-type">>, Req).
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).+
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 - Response headers
cowboy_req:resp_headers - Response headers
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.
-The Req object. -
+The Req object.
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.
-2.0: Function introduced. -
+Headers = cowboy_req:resp_headers(Req).
Headers = cowboy_req:resp_headers(Req).+
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 - URI scheme
cowboy_req:scheme - URI scheme
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.+
-The Req object. -
+The Req object.
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">>
.
-2.0: Function introduced. -
+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}.+
cowboy_req:set_resp_body - Set the response body
cowboy_req:set_resp_body - Set the response 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.
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.
-The body can be either a binary value, an iolist or a
-sendfile
tuple telling Cowboy to send the contents of
-a file.
-
The body can be either a binary value, an iolist or a sendfile
tuple telling Cowboy to send the contents of a file.
-The Req object. -
+The Req object.
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.
-2.0: The function now accepts a sendfile
tuple.
-
sendfile
tuple.
-2.0: The set_resp_body_fun/2,3
functions were removed.
-
set_resp_body_fun/2,3
functions were removed.
-1.0: Function introduced. -
+Req = cowboy_req:set_resp_body(<<"Hello world!">>, Req0).
Req = cowboy_req:set_resp_body([ - "<html><head><title>", - page_title(), - "</title></head><body>", - page_body(), - "</body></html>" -], Req0).
{ok, #file_info{size=Size}} = file:read_file_info(Filename), -Req = cowboy_req:set_resp_body({sendfile, 0, Size, Filename}, Req0).
Req = cowboy_req:set_resp_body(<<>>, Req0).
Req = cowboy_req:set_resp_body(<<>>, Req0).+
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 - Set a cookie
cowboy_req:set_resp_cookie - Set a cookie
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.
-Cookie name. -
+Cookie name.
-Cookie value. -
+Cookie value.
-The Req object. -
+The Req object.
-Cookie options. -
+Cookie options.
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.
-2.0: set_resp_cookie/3
introduced as an alias to set_resp_cookie/4
with no options.
-
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()
.
-
binary()
instead of iodata()
.
-1.0: Function introduced. -
+SessionID = base64:encode(crypto:strong_rand_bytes(32)), -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0).
Req = cowboy_req:set_resp_cookie(<<"lang">>, <<"fr-FR">>, - Req0, #{max_age => 3600}).
Req = cowboy_req:set_resp_cookie(<<"sessionid">>, <<>>, - Req0, #{max_age => 0}).
Req = cowboy_req:set_resp_cookie(<<"inaccount">>, <<"1">>, - Req0, #{domain => "my.example.org", path => "/account"}).
SessionID = base64:encode(crypto:strong_rand_bytes(32)), -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, - Req0, #{secure => true}).
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}).+
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 - Set a response header
cowboy_req:set_resp_header - Set a response header
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.
-Header name as a lowercase binary string. -
+Header name as a lowercase binary string.
-Header value. -
+Header value.
-The Req object. -
+The Req object.
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.
-1.0: Function introduced. -
+Req = cowboy_req:set_resp_header(<<"allow">>, "GET", Req0).
Req = cowboy_req:set_resp_header(<<"allow">>, - [allowed_methods(), ", OPTIONS"], Req0).
Req = cowboy_req:set_resp_header(<<"allow">>, + [allowed_methods(), ", OPTIONS"], Req0).+
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 - Set several response headers
cowboy_req:set_resp_headers - Set several response headers
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.
-Headers as a map with keys being lowercase binary strings, -and values as binary strings. -
+Headers as a map with keys being lowercase binary strings, and values as binary strings.
-The Req object. -
+The Req object.
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.
-2.0: Function introduced. -
+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).+
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 - Socket address and port
cowboy_req:sock - Socket address and port
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.+
-The Req object. -
+The Req object.
The socket’s local IP address and port number.
The socket's local IP address and port number.
-2.1: Function introduced. -
+{IP, Port} = cowboy_req:sock(Req).
{IP, Port} = cowboy_req:sock(Req).+
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 - Stream the response body
cowboy_req:stream_body - Stream the response body
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.
-The data to be sent. -
+The data to be sent.
-A flag indicating whether this is the final piece of data -to be sent. -
+A flag indicating whether this is the final piece of data to be sent.
-The Req object. -
+The Req object.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.0: Function introduced. Replaces chunk/2
.
-
chunk/2
.
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).+
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 - Send the response headers
cowboy_req:stream_reply - Send the response headers
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-The Req object. -
+Header names must be given as lowercase binary strings.
+The Req object.
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.
-2.0: Only the Req is returned, it is no longer wrapped in a tuple. -
+
-2.0: Function introduced. Replaces chunked_reply/1,2
.
-
chunked_reply/1,2
.
Req = cowboy_req:stream_reply(200, Req0).
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).+
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 - Send the response trailers
cowboy_req:stream_trailers - Send the response trailers
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.
-Trailer field values to be sent. -
+Trailer field values to be sent.
-The Req object. -
+The Req object.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.2: Function introduced. -
+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).+
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 - Reconstructed URI
cowboy_req:uri - Reconstructed URI
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.
-The Req object. -
+The Req object.
-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. -
+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:
+-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 reconstructed URI is returned as an iolist or a binary string.
The reconstructed URI is returned as an iolist or a binary string.
-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: Function introduced. Replaces host_url/1
and url/1
.
-
host_url/1
and url/1
.
With an effective request URI http://example.org/path/to/res?edit=1 -we can have:
%% //example.org/path/to/res?edit=1 -cowboy_req:uri(Req, #{scheme => undefined}).
%% http://example.org -cowboy_req:uri(Req, #{path => undefined, qs => undefined}).
%% /path/to/res?edit=1 -cowboy_req:uri(Req, #{host => undefined}).
%% http://example.org/path/to/res?edit=1#errors -cowboy_req:uri(Req, #{fragment => <<"errors">>}).
%% https://example.org/path/to/res?edit=1 -cowboy_req:uri(Req, #{scheme => <<"https">>}).
iolist_to_binary(cowboy_req:uri(Req)).
iolist_to_binary(cowboy_req:uri(Req)).+
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 - HTTP version
cowboy_req:version - HTTP version
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the version is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Version = cowboy_req:version(Req).
Version = cowboy_req:version(Req).+
cowboy_req - HTTP request and response
cowboy_req - HTTP request and response
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_* |
-
|
+
Type | +Name pattern | +Return type | +
---|---|---|
access | +no verb, parse_*, match_* | +Value |
question |
-has_* |
-
|
+
question | +has_* | +boolean() |
modification |
-set_* |
-
|
+
modification | +set_* | +Req |
action |
-any other verb |
-
|
+
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.
Connection:
-cowboy_req:peer(3) - Peer address and port -
--cowboy_req:sock(3) - Socket address and port -
--cowboy_req:cert(3) - Client TLS certificate -
-Raw request:
-cowboy_req:method(3) - HTTP method -
--cowboy_req:version(3) - HTTP version -
--cowboy_req:scheme(3) - URI scheme -
--cowboy_req:host(3) - URI host name -
--cowboy_req:port(3) - URI port number -
--cowboy_req:path(3) - URI path -
--cowboy_req:qs(3) - URI query string -
--cowboy_req:uri(3) - Reconstructed URI -
--cowboy_req:header(3) - HTTP header -
--cowboy_req:headers(3) - HTTP headers -
-Processed request:
-cowboy_req:parse_qs(3) - Parse the query string -
--cowboy_req:match_qs(3) - Match the query string against constraints -
--cowboy_req:parse_header(3) - Parse the given HTTP header -
--cowboy_req:parse_cookies(3) - Parse cookie headers -
--cowboy_req:match_cookies(3) - Match cookies against constraints -
--cowboy_req:binding(3) - Access a value bound from the route -
--cowboy_req:bindings(3) - Access all values bound from the route -
--cowboy_req:host_info(3) - Access the route’s heading host segments -
--cowboy_req:path_info(3) - Access the route’s trailing path segments -
-Request body:
-cowboy_req:has_body(3) - Is there a request body? -
--cowboy_req:body_length(3) - Body length -
--cowboy_req:read_body(3) - Read the request body -
--cowboy_req:read_urlencoded_body(3) - Read and parse a urlencoded request body -
--cowboy_req:read_part(3) - Read the next multipart headers -
--cowboy_req:read_part_body(3) - Read the current part’s body -
-Response:
-cowboy_req:set_resp_cookie(3) - Set a cookie -
--cowboy_req:set_resp_header(3) - Set a response header -
--cowboy_req:set_resp_headers(3) - Set several response headers -
--cowboy_req:has_resp_header(3) - Is the given response header set? -
--cowboy_req:resp_header(3) - Response header -
--cowboy_req:resp_headers(3) - Response headers -
--cowboy_req:delete_resp_header(3) - Delete a response header -
--cowboy_req:set_resp_body(3) - Set the response body -
--cowboy_req:has_resp_body(3) - Is there a response body? -
--cowboy_req:inform(3) - Send an informational response -
--cowboy_req:reply(3) - Send the response -
--cowboy_req:stream_reply(3) - Send the response headers -
--cowboy_req:stream_body(3) - Stream the response body -
--cowboy_req:stream_trailers(3) - Send the response trailers -
--cowboy_req:push(3) - Push a resource to the client -
-Connection:
+Raw request:
+Processed request:
+Request body:
+Response:
+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() :: #{ - 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() :: #{ - 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:
Req#{_myapp_auth_method => pubkey}.
Req#{_myapp_auth_method => pubkey}.+
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:
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.
cowboy_rest - REST handlers
cowboy_rest - REST handlers
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).
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:
- 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:
+The handler terminated normally.
- 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.
-
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.
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(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.
Return the list of allowed methods.
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.
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(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(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(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(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.
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(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
.
Delete the resource.
+Cowboy will send an error response when this function returns false
.
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.
Return the resource's expiration date.
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.
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(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.
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(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.
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(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
.
Return whether the PUT request results in a conflict.
+A 409 Conflict response is sent when true
.
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
.
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(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(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.
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(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.
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(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.
Return whether the resource was permanently moved, and what its new location is.
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.
Return whether the resource was temporarily moved, and what its new location is.
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(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(Req, State) -> {Result, Req, State} +previously_existed(Req, State) -> {Result, Req, State} -Result :: boolean() -Default :: false
Return whether the resource existed previously.
Return whether the resource existed previously.
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.
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(Req, State) -> {Result, Req, State} +resource_exists(Req, State) -> {Result, Req, State} -Result :: boolean() -Default :: true
Return whether the resource exists.
Return whether the resource exists.
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
.
Return whether the service is available.
+A 503 Service Unavailable response will be sent when this function returns false
.
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.
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(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.
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(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
.
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(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.
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.
-2.1: The switch_handler
return value was added.
-
switch_handler
return value was added.
-1.0: Behavior introduced. -
+cowboy_router:compile - Compile routes to the resources
cowboy_router:compile - Compile routes to the resources
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.
-Human readable list of routes. -
+Human readable list of routes.
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.
-1.0: Function introduced. -
+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} +}).+
cowboy_router - Router middleware
cowboy_router - Router middleware
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.
-cowboy_router:compile(3) - Compile routes to the resources -
+bindings() :: #{atom() => any()}
Bindings found during routing.
bindings() :: #{atom() => any()}+
Bindings found during routing.
Opaque type containing the compiled routes.
Opaque type containing the compiled 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.
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() :: [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.
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 - Static file handler
cowboy_static - Static file handler
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.
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.
-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.
+Send a file.
+The path is relative to the given application's private directory.
-Send a file. -
-The path is either absolute or relative to the Erlang node’s -current directory.
Send a file.
+The path is either absolute or relative to the Erlang node's current directory.
-Recursively serve files from a directory. -
-The path is relative to the given application’s private -directory.
Recursively serve files from a directory.
+The path is relative to the given application's private directory.
-Recursively serve files from a directory. -
-The path is either absolute or relative to the Erlang node’s -current directory.
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.
-1.0: Handler introduced. -
+generate_etag(Path, Size, Mtime) -> - {strong, integer_to_binary( - erlang:phash2({Path, Size, Mtime}, 16#ffffffff))}.
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.+
cowboy_handler - Stream handlers
cowboy_handler - Stream handlers
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.
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
.
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:
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.
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.
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.
Send data to the client.
{data, fin(), iodata()}
{data, fin(), iodata()}+
Send response trailers to the client.
{trailers, cowboy:http_headers()}
{trailers, cowboy:http_headers()}+
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.
The command will be ignored if the protocol does not provide any server push mechanism.
{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.
Inform Cowboy that a process was spawned and should be -supervised.
{spawn, pid(), timeout()}
{spawn, pid(), timeout()}+
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 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 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
.
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.
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.
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.
+ + + + + + + + + + + + + + + + +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.
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.
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.
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.
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.
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.
Same as the switch_protocol command.
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.
The following function should be called by modules implementing -stream handlers to execute the next stream handler in the list:
-cowboy_stream:init(3) - Initialize a stream -
+The following function should be called by modules implementing stream handlers to execute the next stream handler in the list:
+-cowboy_stream:data(3) - Handle data for a stream -
+-cowboy_stream:info(3) - Handle a message for a stream -
+-cowboy_stream:terminate(3) - Terminate a stream -
+-cowboy_stream:early_error(3) - Handle an early error for a stream -
+commands() :: [Command]+
See the list of commands for details.
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.
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() :: 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() :: {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() :: 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.
-2.2: The trailers command was 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 - Websocket
cowboy_websocket - Websocket
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.
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:
- 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:
+The connection was closed normally before establishing a Websocket connection. This typically happens if an ok
tuple is returned from the init/2
callback.
- The remote endpoint closed the connection without giving any - further details. -
+The remote endpoint closed the connection without giving any further details.
- The remote endpoint closed the connection with the given
- Code
and Payload
as the reason.
-
The remote endpoint closed the connection with the given Code
and Payload
as the reason.
- The handler requested to close the connection, either by returning
- a stop
tuple or by sending a close
frame.
-
The handler requested to close the connection, either by returning a stop
tuple or by sending a close
frame.
- The connection has been closed due to inactivity. The timeout
- value can be configured from init/2
.
-
The connection has been closed due to inactivity. The timeout value can be configured from init/2
.
- 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.
-
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.
- A text frame was sent by the client with invalid encoding. All - text frames must be valid UTF-8. -
+A text frame was sent by the client with invalid encoding. All text frames must be valid UTF-8.
- A protocol error has been detected. -
+A protocol error has been detected.
- The socket has been closed brutally without a close frame being - received first. -
+The socket has been closed brutally without a close frame being received first.
- A socket error ocurred. -
+A socket error ocurred.
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() :: #{ - 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:
- 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:
+Whether to enable the Websocket frame compression extension. Frames will only be compressed for the clients that support this extension.
- Time in milliseconds that Cowboy will keep the - connection open without receiving anything from - the client. -
+Time in milliseconds that Cowboy will keep the connection open without receiving anything from the client.
- 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. -
+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.
- 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.
-
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.
-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
.
-
websocket_terminate/3
was removed in favor of terminate/3
.
-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 - status codes used by Cowboy
HTTP status codes - status codes used by Cowboy
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.
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.
This is the status code sent when switching to the -Websocket protocol.
This is the status code sent when switching to the Websocket protocol.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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:
+-The request-line could not be parsed. -
+-Too many headers were sent. -
+-A header name was too long. -
+-A header value was too long. -
+-The host header was missing from an HTTP/1.1 request. -
+-The host header could not be parsed. -
+-The requested host was not found. -
+-The requested path could not be parsed. -
+-The accept header could not be parsed when using REST. -
+-REST under normal conditions. -
+-A Websocket upgrade failed. -
+This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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 - Small, fast, modern HTTP server for Erlang/OTP
cowboy - Small, fast, modern HTTP server for Erlang/OTP
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.
Functions:
-cowboy(3) - Listener management -
+Functions:
+-cowboy_req(3) - Request and response -
+-cowboy_router(3) - Router -
+-cowboy_constraints(3) - Constraints -
+Protocols:
-cowboy_http(3) - HTTP/1.1 -
+Protocols:
+-cowboy_http2(3) - HTTP/2 -
+-cowboy_websocket(3) - Websocket -
+Handlers:
-cowboy_static(3) - Static file handler -
+Handlers:
+Behaviors:
-cowboy_handler(3) - Plain HTTP handlers -
+Behaviors:
+-cowboy_loop(3) - Loop handlers -
+-cowboy_middleware(3) - Middlewares -
+-cowboy_rest(3) - REST handlers -
+-cowboy_stream(3) - Stream handlers -
+-cowboy_websocket(3) - Websocket handlers -
+Middlewares:
-cowboy_router(3) - Router middleware -
+Middlewares:
+-cowboy_handler(3) - Handler middleware -
+-ranch(7) - Socket acceptor pool for TCP protocols -
+-cowlib(7) - Support library for manipulating Web protocols -
+-ssl - Secure communication over sockets -
+-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).+
The cowboy
application does not define any application
-environment configuration parameters.
The cowboy
application does not define any application environment configuration parameters.
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.
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 are specified as an atom:
Constraint | -Description | -||||||||
---|---|---|---|---|---|---|---|---|---|
int |
-Converts binary value to integer. |
+
Constraint | +Description | +
---|---|
int | +Converts binary value to integer. |
nonempty |
-Ensures the binary value is non-empty. |
+
nonempty | +Ensures the binary value is non-empty. |
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 @@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.
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.
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 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.
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.
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.
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 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.
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 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.
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.
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 @@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.
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.
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.
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.
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.
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.
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 @@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.
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.
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.
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.
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.
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.
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.
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.
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!
Handlers are Erlang modules that handle HTTP requests.
Handlers are Erlang modules that handle HTTP requests.
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
.
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}.+
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 @@-Introduction -
+-Flow diagram -
+-Listeners -
+-Routing -
+-Constraints -
+-Handlers -
+-Static files -
+-Multipart -
+-Streams -
+-Middlewares -
+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.
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.
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.
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.
-
-
Cowboy uses Semantic Versioning 2.0.0.
Cowboy uses Semantic Versioning 2.0.0.
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 @@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.
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.
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.
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.
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.
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 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.
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}.+
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.
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}.+
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.
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.
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.
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.
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.
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.
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
.
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 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.
-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.
-
cowboy_stream_h
stream handler has been added. It provides most of Cowboy's default behavior.
+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.
+compress
option.
+cowboy_req
functions. Their interface has also been modified to allow for reverse operations and formatting of errors.
+-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. -
-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.
+
-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. -
-cowboy_handler
, cowboy_loop
, cowboy_rest
and cowboy_websocket
.
+init/2
and terminate/3
callbacks. The latter is now optional. The terminate reason has now been documented for all handlers.
+{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.
+halt
or shutdown
tuples as a return value no longer do so. The return value is now a stop
tuple, consistent across Cowboy.
+error
tuple. They have to send the response and return a stop
tuple instead.
+known_content_type
REST handler callback has been removed as it was found unnecessary.
+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_init/1
. The frames will be sent immediately after the handshake.
+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).
+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.
+
-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).
-
cowboy_req:scheme/1
function has been added.
+cowboy_req:uri/1,2
function has been added, replacing the less powerful functions cowboy_req:url/1
and cowboy_req:host_url/1
.
+cowboy_req:match_qs/2
and cowboy_req:match_cookies/2
allow matching query string and cookies against constraints.
+cowboy_req:set_resp_cookie/3
has been added to complement cowboy_req:set_resp_cookie/4
.
+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.
+cowboy_req:set_resp_headers/2
has been added. It allows setting many response headers at once.
+cowboy_req:push/3,4
can be used to push resources for protocols that support it (by default only HTTP/2).
+
-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.
-
cowboy:start_http/4
function was renamed to cowboy:start_clear/3
.
+cowboy:start_https/4
function was renamed to cowboy:start_tls/3
.
+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.
+Opts
argument for cowboy_req:set_resp_cookie/4
has changed to improve consistency. It is now the last argument.
+
-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
.
-
cowboy_req:url/1
and cowboy_req:host_url/1
have been removed in favor of the new function cowboy_req:uri/1,2
.
+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.
+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.
+cowboy_req
, including the functions cowboy_req:get/2
and cowboy_req:set/3
.
+
-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. -
-+
characters.
+.
and ..
.
+content_types_accepted/2
step in REST handlers.
+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.
+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.
-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. 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.
-
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 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.
+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.
-
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_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.
-
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.
-
stop
as a return value are now explicitly listed in the documentation.
-The function cowboy_req:sock/1
returns the IP/port
- of the local socket.
-
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.
-
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.
-
cowboy_req:inform/2,3
sends an informational response.
-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.
-
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.
-
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.
-
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 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.
-
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. -
+
-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_clock
process is not running. This can happen when Cowboy is being restarted during upgrades, for example.
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.
-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.
-
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 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.
-
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.
-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). -
+-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. -
+-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. -
+-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.
-
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.
-
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. -
+-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. -
+-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. -
+-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. -
+-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. -
+
-A packet could be lost when switching to Websocket or any
- other protocol via the switch_protocol
command. This is
- now fixed.
-
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. -
+
-Both experimental stream handlers cowboy_metrics_h
and
- cowboy_tracer_h
received a number of fixes and improvements.
-
cowboy_metrics_h
and cowboy_tracer_h
received a number of fixes and improvements.
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.
-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.
-
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.
-
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. -
+-Add support for the 308 status code and a test suite - for RFC7538 where it is defined. -
+
-Ensure timeout options accept the value infinity
as
- documented.
-
infinity
as documented.
-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.
-
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. -
+-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
.
-
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.
-
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.
-
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. -
+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.
-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
-
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.
-
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.
-
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.
-
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.
-
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.
-
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 Cowlib to 2.3.0 -
+-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. -
+-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 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. -
+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 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 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 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.
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, 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 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.
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.
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).+
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}).+
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 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.
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.
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.
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.
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.
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 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.
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.
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">>, []}).+
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 @@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.
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.
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.
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.
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.
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 @@
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.
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.
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.
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.
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.
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
.
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.
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
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).+
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:
+-Other required headers (for example the date header) -
+-Preset headers -
+-Headers given to the reply function -
+-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).+
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
.
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).+
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).+
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 @@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.
All requests start from here.
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.
+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.
This diagram only applies to OPTIONS requests.
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.
+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 applies to all request methods other than -OPTIONS. It is executed right after the "Start" diagram -is completed.
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.
+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 only applies to GET and HEAD requests.
For a description of the cond
step, please see
-the "Conditional requests" diagram.
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.
This diagram only applies to PUT, POST and PATCH requests.
For a description of the cond
step, please see
-the "Conditional requests" diagram.
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.
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.
This diagram only applies to PUT, POST and PATCH requests.
+For a description of the cond
step, please see the "Conditional requests" diagram.
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 DELETE requests.
For a description of the cond
step, please see
-the "Conditional requests" diagram.
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.
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 applies to all request methods other than
-OPTIONS. It is executed right after the resource_exists
-callback, when the resource exists.
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.
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.
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.
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.
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.
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 |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
allow_missing_post |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
charsets_provided |
-skip |
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
content_types_accepted |
-none |
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
content_types_provided |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
delete_completed |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
delete_resource |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
expires |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
forbidden |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
generate_etag |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
is_authorized |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
is_conflict |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
known_methods |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
languages_provided |
-skip |
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
last_modified |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
malformed_request |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
moved_permanently |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
moved_temporarily |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
multiple_choices |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
options |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
previously_existed |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
resource_exists |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
service_available |
-
|
-||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
uri_too_long |
-
|
+
Callback name | +Default value | +
---|---|
allowed_methods | +[<<"GET">>, <<"HEAD">>, <<"OPTIONS">>] |
valid_content_headers |
-
|
+
allow_missing_post | +true |
valid_entity_length |
-
|
+
charsets_provided | +skip |
variances |
-
|
+
content_types_accepted | +none |
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.
[{{ <<"text">>, <<"html">>, '*'}, to_html}]
true
false
undefined
false
undefined
true
false
[<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]
undefined
false
false
false
false
ok
false
true
true
false
true
true
[]
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.
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:
+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 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 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 | +
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 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.
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".
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.
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.
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 @@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.
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.
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 = "*".+
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.
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}} -).
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 @@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.
-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 -
--User Interface Security Directives for Content Security Policy -
--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 -
--Beacon -
--File API -
--HTML4.01 -
--HTML5 -
--HTML5.1 -
--HTML5.2 -
--RFC 6690: Constrained RESTful Environments (CoRE) Link Format -
--RFC 7807: Problem Details for HTTP APIs -
--RFC 6906: The profile Link Relation Type -
--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 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 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 -
-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.
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"}}+
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"}}+
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">>, []}}]}}+
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 @@
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 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.
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.
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.
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.
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.+
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}.+
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.
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}.+
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.
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
.
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.
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.
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 @@
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.
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".
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.
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.
cowboy:set_env - Update a listener’s environment value
cowboy:set_env - Update a listener's environment 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.
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.
-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.
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.
-The key in the environment map. Common keys include dispatch
-and middlewares
.
-
The key in the environment map. Common keys include dispatch
and middlewares
.
-The new value. -
-The type of the value differs depending on the key.
The new value.
+The type of the value differs depending on the key.
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.
-1.0: Function introduced. -
+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(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 - Listen for connections using plain TCP
cowboy:start_clear - Listen for connections using plain TCP
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.
-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
.
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
.
-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.
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.
-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).
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).
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.
-2.0: HTTP/2 support added. -
+
-2.0: Function introduced. Replaces cowboy:start_http/4
.
-
cowboy:start_http/4
.
Dispatch = cowboy_router:compile([ - {'_', [ - {"/", toppage_h, []} +Dispatch = cowboy_router:compile([ + {'_', [ + {"/", toppage_h, []} ]} ]), -{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{ - env => #{dispatch => Dispatch} -}).
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).
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 - Listen for connections using TLS
cowboy:start_tls - Listen for connections using TLS
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.
-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
.
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
.
-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.
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.
-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).
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).
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.
-2.0: HTTP/2 support added. -
+
-2.0: Function introduced. Replaces cowboy:start_https/4
.
-
cowboy:start_https/4
.
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} -}).
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).
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 - Stop the given listener
cowboy:stop_listener - Stop the given listener
stop_listener(Name :: ranch:ref()) - -> ok | {error, not_found}.
Stop a previously started listener.
Alias of ranch:stop_listener(3).
stop_listener(Name :: ranch:ref()) + -> ok | {error, not_found}.+
Stop a previously started listener.
+Alias of ranch:stop_listener(3).
-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.
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.
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.
-1.0: Function introduced. -
+ok = cowboy:stop_listener(example).
ok = cowboy:stop_listener(example).+
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 - HTTP server
cowboy - HTTP server
The module cowboy
provides convenience functions for
-manipulating Ranch listeners.
The module cowboy
provides convenience functions for manipulating Ranch listeners.
-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’s environment value -
+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() :: #{binary() => iodata()}
HTTP headers.
http_headers() :: #{binary() => iodata()}+
HTTP headers.
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/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() :: 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).
cowboy - Small, fast, modern HTTP server for Erlang/OTP
cowboy - Small, fast, modern HTTP server for Erlang/OTP
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.
Functions:
-cowboy(3) - Listener management -
+Functions:
+-cowboy_req(3) - Request and response -
+-cowboy_router(3) - Router -
+-cowboy_constraints(3) - Constraints -
+Protocols:
-cowboy_http(3) - HTTP/1.1 -
+Protocols:
+-cowboy_http2(3) - HTTP/2 -
+-cowboy_websocket(3) - Websocket -
+Handlers:
-cowboy_static(3) - Static file handler -
+Handlers:
+Behaviors:
-cowboy_handler(3) - Plain HTTP handlers -
+Behaviors:
+-cowboy_loop(3) - Loop handlers -
+-cowboy_middleware(3) - Middlewares -
+-cowboy_rest(3) - REST handlers -
+-cowboy_stream(3) - Stream handlers -
+-cowboy_websocket(3) - Websocket handlers -
+Middlewares:
-cowboy_router(3) - Router middleware -
+Middlewares:
+-cowboy_handler(3) - Handler middleware -
+-ranch(7) - Socket acceptor pool for TCP protocols -
+-cowlib(7) - Support library for manipulating Web protocols -
+-ssl - Secure communication over sockets -
+-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).+
The cowboy
application does not define any application
-environment configuration parameters.
The cowboy
application does not define any application environment configuration parameters.
cowboy_constraints:int - Integer constraint
cowboy_constraints:int - Integer constraint
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.
Generate a human-readable error message.
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.
The return value varies depending on the operation.
The return value varies depending on the operation.
-2.0: Interface modified to allow for a variety of operations. -
+-1.0: Constraint introduced. -
+This function is not meant to be called directly.
This function is not meant to be called directly.
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 - Non-empty constraint
cowboy_constraints:nonempty - Non-empty constraint
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.
Generate a human-readable error message.
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.
The return value varies depending on the operation.
The return value varies depending on the operation.
-2.0: Interface modified to allow for a variety of operations. -
+-1.0: Constraint introduced. -
+This function is not meant to be called directly.
This function is not meant to be called directly.
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 - Constraints
cowboy_constraints - Constraints
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.
Built-in constraints:
-cowboy_constraints:int(3) - Integer constraint -
+Built-in constraints:
+-cowboy_constraints:nonempty(3) - Non-empty 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() :: {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.
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 - Terminate the handler
cowboy_handler:terminate - Terminate the handler
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.
-Reason for termination. -
+Reason for termination.
-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.
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.
-Handler state. -
+Handler state.
-Handler module. -
+Handler module.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.0: Function introduced. -
+cowboy_handler:terminate(normal, Req, State, Handler).
cowboy_handler:terminate(normal, Req, State, Handler).+
cowboy_handler - Plain HTTP handlers
cowboy_handler - Plain HTTP handlers
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.
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:
- 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:
+The connection was closed normally.
- 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.
-
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.
The following function should be called by modules implementing -custom handlers to execute the optional terminate callback:
-cowboy_handler:terminate(3) - Terminate the handler -
+The following function should be called by modules implementing custom handlers to execute the optional terminate callback:
+cowboy_http - HTTP/1.1
cowboy_http - HTTP/1.1
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.
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:
- Whether the connection process also acts as a supervisor. -
-- Middleware environment. -
-- Time in ms with no data received before Cowboy closes the connection. -
-- Time in ms with nothing received at all before Cowboy closes the connection. -
-- Maximum number of empty lines before a request. -
-- Maximum length of header names. -
-- Maximum length of header values. -
-- Maximum number of headers allowed per request. -
-- Maximum number of requests allowed per connection. -
-- Maximum length of the method. -
-- Maximum length of the request line. -
-- 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 to run for every request. -
-- Time in ms with no requests before Cowboy closes the connection. -
-- Time in ms Cowboy will wait for child processes to shut down before killing them. -
-- 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:
+Whether the connection process also acts as a supervisor.
+Middleware environment.
+Time in ms with no data received before Cowboy closes the connection.
+Time in ms with nothing received at all before Cowboy closes the connection.
+Maximum number of empty lines before a request.
+Maximum length of header names.
+Maximum length of header values.
+Maximum number of headers allowed per request.
+Maximum number of requests allowed per connection.
+Maximum length of the method.
+Maximum length of the request line.
+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 to run for every request.
+Time in ms with no requests before Cowboy closes the connection.
+Time in ms Cowboy will wait for child processes to shut down before killing them.
+Ordered list of stream handlers that will handle all stream events.
+
-2.2: The max_skip_body_length
option was added.
-
max_skip_body_length
option was added.
-2.0: The timeout
option was renamed request_timeout
.
-
timeout
option was renamed request_timeout
.
-2.0: The idle_timeout
, inactivity_timeout
and shutdown_timeout
options were added.
-
idle_timeout
, inactivity_timeout
and shutdown_timeout
options were added.
-2.0: The max_method_length
option was added.
-
max_method_length
option was added.
-2.0: The max_request_line_length
default was increased from 4096 to 8000.
-
max_request_line_length
default was increased from 4096 to 8000.
-2.0: The connection_type
option was added.
-
connection_type
option was added.
-2.0: The env
option is now a map instead of a proplist.
-
env
option is now a map instead of a proplist.
-2.0: The stream_handlers
option was added.
-
stream_handlers
option was added.
-2.0: The compress
option was removed in favor of the cowboy_compress_h
stream handler.
-
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: Protocol introduced. Replaces cowboy_protocol
.
-
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 - HTTP/2
cowboy_http2 - HTTP/2
The module cowboy_http2
implements HTTP/2
-as a Ranch protocol.
The module cowboy_http2
implements HTTP/2 as a Ranch protocol.
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:
- 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:
+Whether the connection process also acts as a supervisor.
- 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. -
+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.
- Middleware environment. -
+Middleware environment.
- Time in ms with nothing received at all before Cowboy closes the connection. -
+Time in ms with nothing received at all before Cowboy closes the connection.
- 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 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 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 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.
- Maximum number of concurrent streams allowed on the connection. -
+Maximum number of concurrent streams allowed on the connection.
- 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. -
+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.
- 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. -
+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.
- 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. -
+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.
- 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.
-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 to run for every request. -
+Middlewares to run for every request.
- Time in ms Cowboy is willing to wait for the connection preface. -
+Time in ms Cowboy is willing to wait for the connection preface.
- Time in ms Cowboy is willing to wait for a SETTINGS ack. -
+Time in ms Cowboy is willing to wait for a SETTINGS ack.
- Time in ms Cowboy will wait for child processes to shut down before killing them. -
+Time in ms Cowboy will wait for child processes to shut down before killing them.
- Ordered list of stream handlers that will handle all stream events. -
+Ordered list of stream handlers that will handle all stream events.
-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.
-
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
.
-
enable_connect_protocol
.
-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 - Loop handlers
cowboy_loop - Loop handlers
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:
+
-Or initiate a response in init/2
and stream the
- body in info/3
as necessary (for example server-sent events).
-
init/2
and stream the body in info/3
as necessary (for example server-sent events).
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:
- 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:
+The handler requested to close the connection by returning a stop
tuple.
- 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.
-
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.
-2.0: Loop handlers no longer need to handle overflow/timeouts. -
+-1.0: Behavior introduced. -
+cowboy_middleware - Middlewares
cowboy_middleware - Middlewares
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.
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.
-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.
Cowboy should continue processing the request using the returned Req object and environment.
-Cowboy will hibernate the process. When resuming, Cowboy -will apply the returned module, function and arguments. -
+Cowboy will hibernate the process. When resuming, Cowboy will apply the returned module, function and arguments.
-Cowboy will stop middleware execution. No other middleware -will be executed. This effectively ends the processing of -the request. -
+Cowboy will stop middleware execution. No other middleware will be executed. This effectively ends the processing of the request.
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.
-2.0: The env
type is now a map instead of a proplist.
-
env
type is now a map instead of a proplist.
-1.0: Behavior introduced. -
+cowboy_req:binding - Access a value bound from the route
cowboy_req:binding - Access a value bound from the route
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.
-Desired binding name as an atom. -
+Desired binding name as an atom.
-The Req object. -
+The Req object.
-Default value returned when the binding is missing. -
+Default value returned when the binding is missing.
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).
-2.0: Only the value is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+%% Route is "/users/:user" -Username = cowboy_req:binding(user, Req).
%% Route is "/log[/:branch]" -Branch = cowboy_req:binding(branch, Req, <<"master">>)
%% Route is "/log[/:branch]" +Branch = cowboy_req:binding(branch, Req, <<"master">>)+
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 - Access all values bound from the route
cowboy_req:bindings - Access all values bound from the route
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.
-The Req object. -
+The Req object.
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).
-2.0: Only the values are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Bindings = cowboy_req:bindings(Req).
Bindings = cowboy_req:bindings(Req).+
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 - Body length
cowboy_req:body_length - Body length
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.
-The Req object. -
+The Req object.
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.
-2.0: Only the length is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Length = cowboy_req:body_length(Req).
Length = cowboy_req:body_length(Req).+
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 - Client TLS certificate
cowboy_req:cert - Client TLS certificate
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.+
-The Req object. -
+The Req object.
The client TLS certificate.
The client TLS certificate.
-2.1: Function introduced. -
+Cert = cowboy_req:cert(Req).
Cert = cowboy_req:cert(Req).+
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 - Delete a response header
cowboy_req:delete_resp_header - Delete a response header
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.
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.
-Header name as a lowercase binary string. -
+Header name as a lowercase binary string.
-The Req object. -
+The Req object.
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.
-1.0: Function introduced. -
+Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),
Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0),+
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 - Is there a request body?
cowboy_req:has_body - Is there a request body?
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.
-The Req object. -
+The Req object.
A boolean indicating whether the request has a body.
A boolean indicating whether the request has a body.
-1.0: Function introduced. -
+true = cowboy_req:has_body(Req).
true = cowboy_req:has_body(Req).+
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 - Is there a response body?
cowboy_req:has_resp_body - Is there a response body?
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.
-The Req object. -
+The Req object.
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.
-1.0: Function introduced. -
+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).+
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 - Is the given response header set?
cowboy_req:has_resp_header - Is the given response header set?
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.
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.
-Header name as a lowercase binary string. -
+Header name as a lowercase binary string.
-The Req object. -
+The Req object.
A boolean indicating whether the given response header has been set.
A boolean indicating whether the given response header has been set.
-1.0: Function introduced. -
+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).+
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 - HTTP header
cowboy_req:header - HTTP header
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.
-Desired HTTP header name as a lowercase binary string. -
+Desired HTTP header name as a lowercase binary string.
-The Req object. -
+The Req object.
-Default value returned when the header is missing. -
+Default value returned when the header is missing.
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.
-2.0: Only the header value is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Accept = cowboy_req:header(<<"accept">>, Req).
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).
Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>).+
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 - HTTP headers
cowboy_req:headers - HTTP headers
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the headers are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Headers = cowboy_req:headers(Req).
Headers = cowboy_req:headers(Req).+
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 - URI host name
cowboy_req:host - URI host name
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the host name is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Host = cowboy_req:host(Req).
Host = cowboy_req:host(Req).+
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 - Access the route’s heading host segments
cowboy_req:host_info - Access the route's heading host segments
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.
-The Req object. -
+The Req object.
The tokens are returned as a list of case insensitive -binary strings.
The tokens are returned as a list of case insensitive binary strings.
-2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+HostInfo = cowboy_req:host_info(Req).
HostInfo = cowboy_req:host_info(Req).+
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 - Send an informational response
cowboy_req:inform - Send an informational response
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-The Req object. -
+Header names must be given as lowercase binary strings.
+The Req object.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.1: Function introduced. -
+Req = cowboy_req:inform(102, Req0).
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).+
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 - Match cookies against constraints
cowboy_req:match_cookies - Match cookies against constraints
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.
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.
-2.0: Function introduced. -
+%% ID and Lang are binaries. -#{id := ID, lang := Lang} - = cowboy_req:match_cookies([id, lang], Req).
%% ID is an integer and Lang a non-empty binary. -#{id := ID, lang := Lang} - = cowboy_req:match_cookies([{id, int}, {lang, nonempty}], Req).
#{lang := Lang} - = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).
#{lang := Lang} + = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req).+
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 - Match the query string against constraints
cowboy_req:match_qs - Match the query string against constraints
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.
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.
-2.0: Function introduced. -
+%% ID and Lang are binaries. -#{id := ID, lang := Lang} - = cowboy_req:match_qs([id, lang], Req).
%% ID is an integer and Lang a non-empty binary. -#{id := ID, lang := Lang} - = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req).
#{lang := Lang} - = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).
#{lang := Lang} + = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req).+
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 - HTTP method
cowboy_req:method - HTTP method
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the method is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+<<"GET">> = cowboy_req:method(Req).
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.+
cowboy_req:parse_cookies - Parse cookie headers
cowboy_req:parse_cookies - Parse cookie headers
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 []
.
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 []
.
-The Req object. -
+The Req object.
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.
-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
.
-
cookie/2,3
and cookies/1
.
Cookies = cowboy_req:parse_cookies(Req), -{_, Token} = lists:keyfind(<<"token">>, 1, Cookies).
Cookies = cowboy_req:parse_cookies(Req), +{_, Token} = lists:keyfind(<<"token">>, 1, Cookies).+
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 - Parse the given HTTP header
cowboy_req:parse_header - Parse the given HTTP 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.
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.
-Desired HTTP header name as a lowercase binary string. -
+Desired HTTP header name as a lowercase binary string.
-The Req object. -
+The Req object.
-Default value returned when the header is missing. -
+Default value returned when the header is missing.
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.
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
:
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
parse_header(Name, Req) -> [{Value, Quality}] - -Name :: <<"accept-charset">> - | <<"accept-encoding">> - | <<"accept-language">> -Value :: binary() %% case insensitive -Quality :: 0..1000
parse_header(<<"authorization">>, Req) - -> {basic, Username :: binary(), Password :: binary()} - | {bearer, Token :: binary()} - | {digest, [{Key :: binary(), Value :: binary()}]}
parse_header(<<"content-length">>, Req) -> non_neg_integer()
When the content-length header is missing, 0
is returned.
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.
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 []
.
parse_header(<<"expect">>, Req) -> continue
parse_header(Name, Req) - -> '*' | [{weak | strong, OpaqueTag}] - -Name :: <<"if-match">> - | <<"if-none-match">> -OpaqueTag :: binary() %% case sensitive
parse_header(Name, Req) -> calendar:datetime()
parse_header(<<"range">>, Req) -> {From, To} | Final - -From :: non_neg_integer() -To :: non_neg_integer() | infinity -Final :: neg_integer()
parse_header(<<"sec-websocket-extensions">>, Req) - -> [{Extension, Params}] - -Extension :: binary() %% case sensitive -Params :: [Key | {Key, Value}] -Key :: binary() %% case sensitive -Value :: binary() %% case sensitive
parse_header(Name, Req) -> [Token] - -Name :: <<"sec-websocket-protocol">> - | <<"upgrade">> -Token :: binary() %% case insensitive
parse_header(<<"x-forwarded-for">>, Req) -> [Token] +parse_header(<<"x-forwarded-for">>, Req) -> [Token] -Token :: binary() %% case sensitive
parse_header(_, Req) -> {undefined, RawValue}
parse_header(_, Req) -> {undefined, RawValue}+
-2.0: Only the parsed header value is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+%% Accept everything when header is missing. -Accept = cowboy_req:parse_header(<<"accept">>, Req, - [{{ <<"*">>, <<"*">>, []}, 1000, []}]).
%% Default content-length is 0. -Length = cowboy_req:header(<<"content-length">>, Req).
%% Default content-length is 0. +Length = cowboy_req:header(<<"content-length">>, Req).+
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 - Parse the query string
cowboy_req:parse_qs - Parse the query string
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.
-The Req object. -
+The Req object.
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
-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: Function introduced. Replaces qs_val/1
and qs_vals/1
.
-
qs_val/1
and qs_vals/1
.
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].+
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 - URI path
cowboy_req:path - URI path
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.+
-The Req object. -
+The Req object.
The path is returned as a binary string. It is case sensitive.
The path is returned as a binary string. It is case sensitive.
-2.0: Only the path is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Path = cowboy_req:path(Req).
Path = cowboy_req:path(Req).+
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 - Access the route’s trailing path segments
cowboy_req:path_info - Access the route's trailing path segments
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.
-The Req object. -
+The Req object.
The tokens are returned as a list of case sensitive -binary strings.
The tokens are returned as a list of case sensitive binary strings.
-2.0: Only the tokens are returned, they are no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+PathInfo = cowboy_req:path_info(Req).
PathInfo = cowboy_req:path_info(Req).+
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 - Peer address and port
cowboy_req:peer - Peer address and port
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the peer is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+{IP, Port} = cowboy_req:peer(Req).
{IP, Port} = cowboy_req:peer(Req).+
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 - URI port number
cowboy_req:port - URI port number
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.+
-The Req object. -
+The Req object.
The port number is returned as an integer.
The port number is returned as an integer.
-2.0: Only the port number is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Port = cowboy_req:port(Req).
Port = cowboy_req:port(Req).+
cowboy_req:push - Push a resource to the client
cowboy_req:push - Push a resource to the client
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-The Req object. -
+Header names must be given as lowercase binary strings.
+The Req object.
-Customize the HTTP method or the URI scheme, host, port -or query string. -
+Customize the HTTP method or the URI scheme, host, port or query string.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.0: Function introduced. -
+cowboy_req:push("/static/style.css", #{ - <<"accept">> => <<"text/css">> -}, Req),
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),+
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 - URI query string
cowboy_req:qs - URI query string
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the query string is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Qs = cowboy_req:qs(Req).
Qs = cowboy_req:qs(Req).+
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 - Read the request body
cowboy_req:read_body - Read the request body
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.
-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces body/1,2
.
-
body/1,2
.
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.
cowboy_req:read_body(Req, #{length => 64000}).
cowboy_req:read_body(Req, #{length => 64000}).+
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 - Read the next multipart headers
cowboy_req:read_part - Read the next multipart headers
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.
+-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces part/1,2
.
-
part/1,2
.
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.
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.
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).
{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}).+
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 - Read the current part’s body
cowboy_req:read_part_body - Read the current part's body
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.
+-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces part_body/1,2
.
-
part_body/1,2
.
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.
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).
{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}).+
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 - Read and parse a urlencoded request body
cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body
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.
-The Req object. -
+The Req object.
-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.
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.
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.
-2.0: Function introduced. Replaces body_qs/1,2
.
-
body_qs/1,2
.
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0), -{_, Lang} = lists:keyfind(<<"lang">>, 1, Body).
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).
{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}).+
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 - Send the response
cowboy_req:reply - Send the response
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-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.
+The body can be either a binary value, an iolist or a sendfile
tuple telling Cowboy to send the contents of a file.
-The Req object. -
+The Req object.
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.
-2.0: Only the Req is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Req = cowboy_req:reply(404, Req0).
Req = cowboy_req:reply(401, #{ - <<"www-authenticate">> => <<"Basic realm=\"erlang.org\"">> -}, Req0).
Req = cowboy_req:reply(200, #{ - <<"content-type">> => <<"text/plain">> -}, "Hello world!", Req0).
Req = cowboy_req:reply(200, #{ + <<"content-type">> => <<"text/plain">> +}, "Hello world!", Req0).+
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 - Response header
cowboy_req:resp_header - Response header
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.
-Desired response header name as a lowercase binary string. -
+Desired response header name as a lowercase binary string.
-The Req object. -
+The Req object.
-Default value returned when the header is missing. -
+Default value returned when the header is missing.
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.
-2.0: Function introduced. -
+Type = cowboy_req:resp_header(<<"content-type">>, Req).
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).
Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>).+
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 - Response headers
cowboy_req:resp_headers - Response headers
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.
-The Req object. -
+The Req object.
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.
-2.0: Function introduced. -
+Headers = cowboy_req:resp_headers(Req).
Headers = cowboy_req:resp_headers(Req).+
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 - URI scheme
cowboy_req:scheme - URI scheme
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.+
-The Req object. -
+The Req object.
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">>
.
-2.0: Function introduced. -
+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}.+
cowboy_req:set_resp_body - Set the response body
cowboy_req:set_resp_body - Set the response 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.
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.
-The body can be either a binary value, an iolist or a
-sendfile
tuple telling Cowboy to send the contents of
-a file.
-
The body can be either a binary value, an iolist or a sendfile
tuple telling Cowboy to send the contents of a file.
-The Req object. -
+The Req object.
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.
-2.0: The function now accepts a sendfile
tuple.
-
sendfile
tuple.
-2.0: The set_resp_body_fun/2,3
functions were removed.
-
set_resp_body_fun/2,3
functions were removed.
-1.0: Function introduced. -
+Req = cowboy_req:set_resp_body(<<"Hello world!">>, Req0).
Req = cowboy_req:set_resp_body([ - "<html><head><title>", - page_title(), - "</title></head><body>", - page_body(), - "</body></html>" -], Req0).
{ok, #file_info{size=Size}} = file:read_file_info(Filename), -Req = cowboy_req:set_resp_body({sendfile, 0, Size, Filename}, Req0).
Req = cowboy_req:set_resp_body(<<>>, Req0).
Req = cowboy_req:set_resp_body(<<>>, Req0).+
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 - Set a cookie
cowboy_req:set_resp_cookie - Set a cookie
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.
-Cookie name. -
+Cookie name.
-Cookie value. -
+Cookie value.
-The Req object. -
+The Req object.
-Cookie options. -
+Cookie options.
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.
-2.0: set_resp_cookie/3
introduced as an alias to set_resp_cookie/4
with no options.
-
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()
.
-
binary()
instead of iodata()
.
-1.0: Function introduced. -
+SessionID = base64:encode(crypto:strong_rand_bytes(32)), -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0).
Req = cowboy_req:set_resp_cookie(<<"lang">>, <<"fr-FR">>, - Req0, #{max_age => 3600}).
Req = cowboy_req:set_resp_cookie(<<"sessionid">>, <<>>, - Req0, #{max_age => 0}).
Req = cowboy_req:set_resp_cookie(<<"inaccount">>, <<"1">>, - Req0, #{domain => "my.example.org", path => "/account"}).
SessionID = base64:encode(crypto:strong_rand_bytes(32)), -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, - Req0, #{secure => true}).
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}).+
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 - Set a response header
cowboy_req:set_resp_header - Set a response header
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.
-Header name as a lowercase binary string. -
+Header name as a lowercase binary string.
-Header value. -
+Header value.
-The Req object. -
+The Req object.
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.
-1.0: Function introduced. -
+Req = cowboy_req:set_resp_header(<<"allow">>, "GET", Req0).
Req = cowboy_req:set_resp_header(<<"allow">>, - [allowed_methods(), ", OPTIONS"], Req0).
Req = cowboy_req:set_resp_header(<<"allow">>, + [allowed_methods(), ", OPTIONS"], Req0).+
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 - Set several response headers
cowboy_req:set_resp_headers - Set several response headers
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.
-Headers as a map with keys being lowercase binary strings, -and values as binary strings. -
+Headers as a map with keys being lowercase binary strings, and values as binary strings.
-The Req object. -
+The Req object.
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.
-2.0: Function introduced. -
+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).+
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 - Socket address and port
cowboy_req:sock - Socket address and port
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.+
-The Req object. -
+The Req object.
The socket’s local IP address and port number.
The socket's local IP address and port number.
-2.1: Function introduced. -
+{IP, Port} = cowboy_req:sock(Req).
{IP, Port} = cowboy_req:sock(Req).+
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 - Stream the response body
cowboy_req:stream_body - Stream the response body
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.
-The data to be sent. -
+The data to be sent.
-A flag indicating whether this is the final piece of data -to be sent. -
+A flag indicating whether this is the final piece of data to be sent.
-The Req object. -
+The Req object.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.0: Function introduced. Replaces chunk/2
.
-
chunk/2
.
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).+
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 - Send the response headers
cowboy_req:stream_reply - Send the response headers
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.
-The status code for the response. -
+The status code for the response.
-The response headers. -
+The response headers.
Header names must be given as lowercase binary strings.
-The Req object. -
+Header names must be given as lowercase binary strings.
+The Req object.
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.
-2.0: Only the Req is returned, it is no longer wrapped in a tuple. -
+
-2.0: Function introduced. Replaces chunked_reply/1,2
.
-
chunked_reply/1,2
.
Req = cowboy_req:stream_reply(200, Req0).
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).+
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 - Send the response trailers
cowboy_req:stream_trailers - Send the response trailers
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.
-Trailer field values to be sent. -
+Trailer field values to be sent.
-The Req object. -
+The Req object.
The atom ok
is always returned. It can be safely ignored.
The atom ok
is always returned. It can be safely ignored.
-2.2: Function introduced. -
+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).+
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 - Reconstructed URI
cowboy_req:uri - Reconstructed URI
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.
-The Req object. -
+The Req object.
-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. -
+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:
+-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 reconstructed URI is returned as an iolist or a binary string.
The reconstructed URI is returned as an iolist or a binary string.
-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: Function introduced. Replaces host_url/1
and url/1
.
-
host_url/1
and url/1
.
With an effective request URI http://example.org/path/to/res?edit=1 -we can have:
%% //example.org/path/to/res?edit=1 -cowboy_req:uri(Req, #{scheme => undefined}).
%% http://example.org -cowboy_req:uri(Req, #{path => undefined, qs => undefined}).
%% /path/to/res?edit=1 -cowboy_req:uri(Req, #{host => undefined}).
%% http://example.org/path/to/res?edit=1#errors -cowboy_req:uri(Req, #{fragment => <<"errors">>}).
%% https://example.org/path/to/res?edit=1 -cowboy_req:uri(Req, #{scheme => <<"https">>}).
iolist_to_binary(cowboy_req:uri(Req)).
iolist_to_binary(cowboy_req:uri(Req)).+
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 - HTTP version
cowboy_req:version - HTTP version
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.+
-The Req object. -
+The Req object.
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.
-2.0: Only the version is returned, it is no longer wrapped in a tuple. -
+-1.0: Function introduced. -
+Version = cowboy_req:version(Req).
Version = cowboy_req:version(Req).+
cowboy_req - HTTP request and response
cowboy_req - HTTP request and response
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_* |
-
|
+
Type | +Name pattern | +Return type | +
---|---|---|
access | +no verb, parse_*, match_* | +Value |
question |
-has_* |
-
|
+
question | +has_* | +boolean() |
modification |
-set_* |
-
|
+
modification | +set_* | +Req |
action |
-any other verb |
-
|
+
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.
Connection:
-cowboy_req:peer(3) - Peer address and port -
--cowboy_req:sock(3) - Socket address and port -
--cowboy_req:cert(3) - Client TLS certificate -
-Raw request:
-cowboy_req:method(3) - HTTP method -
--cowboy_req:version(3) - HTTP version -
--cowboy_req:scheme(3) - URI scheme -
--cowboy_req:host(3) - URI host name -
--cowboy_req:port(3) - URI port number -
--cowboy_req:path(3) - URI path -
--cowboy_req:qs(3) - URI query string -
--cowboy_req:uri(3) - Reconstructed URI -
--cowboy_req:header(3) - HTTP header -
--cowboy_req:headers(3) - HTTP headers -
-Processed request:
-cowboy_req:parse_qs(3) - Parse the query string -
--cowboy_req:match_qs(3) - Match the query string against constraints -
--cowboy_req:parse_header(3) - Parse the given HTTP header -
--cowboy_req:parse_cookies(3) - Parse cookie headers -
--cowboy_req:match_cookies(3) - Match cookies against constraints -
--cowboy_req:binding(3) - Access a value bound from the route -
--cowboy_req:bindings(3) - Access all values bound from the route -
--cowboy_req:host_info(3) - Access the route’s heading host segments -
--cowboy_req:path_info(3) - Access the route’s trailing path segments -
-Request body:
-cowboy_req:has_body(3) - Is there a request body? -
--cowboy_req:body_length(3) - Body length -
--cowboy_req:read_body(3) - Read the request body -
--cowboy_req:read_urlencoded_body(3) - Read and parse a urlencoded request body -
--cowboy_req:read_part(3) - Read the next multipart headers -
--cowboy_req:read_part_body(3) - Read the current part’s body -
-Response:
-cowboy_req:set_resp_cookie(3) - Set a cookie -
--cowboy_req:set_resp_header(3) - Set a response header -
--cowboy_req:set_resp_headers(3) - Set several response headers -
--cowboy_req:has_resp_header(3) - Is the given response header set? -
--cowboy_req:resp_header(3) - Response header -
--cowboy_req:resp_headers(3) - Response headers -
--cowboy_req:delete_resp_header(3) - Delete a response header -
--cowboy_req:set_resp_body(3) - Set the response body -
--cowboy_req:has_resp_body(3) - Is there a response body? -
--cowboy_req:inform(3) - Send an informational response -
--cowboy_req:reply(3) - Send the response -
--cowboy_req:stream_reply(3) - Send the response headers -
--cowboy_req:stream_body(3) - Stream the response body -
--cowboy_req:stream_trailers(3) - Send the response trailers -
--cowboy_req:push(3) - Push a resource to the client -
-Connection:
+Raw request:
+Processed request:
+Request body:
+Response:
+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() :: #{ - 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() :: #{ - 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:
Req#{_myapp_auth_method => pubkey}.
Req#{_myapp_auth_method => pubkey}.+
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:
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.
cowboy_rest - REST handlers
cowboy_rest - REST handlers
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).
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:
- 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:
+The handler terminated normally.
- 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.
-
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.
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(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.
Return the list of allowed methods.
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.
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(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(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(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(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.
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(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
.
Delete the resource.
+Cowboy will send an error response when this function returns false
.
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.
Return the resource's expiration date.
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.
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(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.
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(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.
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(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
.
Return whether the PUT request results in a conflict.
+A 409 Conflict response is sent when true
.
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
.
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(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(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.
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(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.
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(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.
Return whether the resource was permanently moved, and what its new location is.
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.
Return whether the resource was temporarily moved, and what its new location is.
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(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(Req, State) -> {Result, Req, State} +previously_existed(Req, State) -> {Result, Req, State} -Result :: boolean() -Default :: false
Return whether the resource existed previously.
Return whether the resource existed previously.
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.
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(Req, State) -> {Result, Req, State} +resource_exists(Req, State) -> {Result, Req, State} -Result :: boolean() -Default :: true
Return whether the resource exists.
Return whether the resource exists.
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
.
Return whether the service is available.
+A 503 Service Unavailable response will be sent when this function returns false
.
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.
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(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.
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(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
.
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(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.
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.
-2.1: The switch_handler
return value was added.
-
switch_handler
return value was added.
-1.0: Behavior introduced. -
+cowboy_router:compile - Compile routes to the resources
cowboy_router:compile - Compile routes to the resources
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.
-Human readable list of routes. -
+Human readable list of routes.
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.
-1.0: Function introduced. -
+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} +}).+
cowboy_router - Router middleware
cowboy_router - Router middleware
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.
-cowboy_router:compile(3) - Compile routes to the resources -
+bindings() :: #{atom() => any()}
Bindings found during routing.
bindings() :: #{atom() => any()}+
Bindings found during routing.
Opaque type containing the compiled routes.
Opaque type containing the compiled 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.
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() :: [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.
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 - Static file handler
cowboy_static - Static file handler
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.
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.
-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.
+Send a file.
+The path is relative to the given application's private directory.
-Send a file. -
-The path is either absolute or relative to the Erlang node’s -current directory.
Send a file.
+The path is either absolute or relative to the Erlang node's current directory.
-Recursively serve files from a directory. -
-The path is relative to the given application’s private -directory.
Recursively serve files from a directory.
+The path is relative to the given application's private directory.
-Recursively serve files from a directory. -
-The path is either absolute or relative to the Erlang node’s -current directory.
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.
-1.0: Handler introduced. -
+generate_etag(Path, Size, Mtime) -> - {strong, integer_to_binary( - erlang:phash2({Path, Size, Mtime}, 16#ffffffff))}.
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.+
cowboy_handler - Stream handlers
cowboy_handler - Stream handlers
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.
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
.
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:
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.
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.
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.
Send data to the client.
{data, fin(), iodata()}
{data, fin(), iodata()}+
Send response trailers to the client.
{trailers, cowboy:http_headers()}
{trailers, cowboy:http_headers()}+
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.
The command will be ignored if the protocol does not provide any server push mechanism.
{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.
Inform Cowboy that a process was spawned and should be -supervised.
{spawn, pid(), timeout()}
{spawn, pid(), timeout()}+
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 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 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
.
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.
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.
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.
+ + + + + + + + + + + + + + + + +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.
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.
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.
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.
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.
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.
Same as the switch_protocol command.
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.
The following function should be called by modules implementing -stream handlers to execute the next stream handler in the list:
-cowboy_stream:init(3) - Initialize a stream -
+The following function should be called by modules implementing stream handlers to execute the next stream handler in the list:
+-cowboy_stream:data(3) - Handle data for a stream -
+-cowboy_stream:info(3) - Handle a message for a stream -
+-cowboy_stream:terminate(3) - Terminate a stream -
+-cowboy_stream:early_error(3) - Handle an early error for a stream -
+commands() :: [Command]+
See the list of commands for details.
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.
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() :: 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() :: {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() :: 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.
-2.2: The trailers command was 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 - Websocket
cowboy_websocket - Websocket
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.
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:
- 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:
+The connection was closed normally before establishing a Websocket connection. This typically happens if an ok
tuple is returned from the init/2
callback.
- The remote endpoint closed the connection without giving any - further details. -
+The remote endpoint closed the connection without giving any further details.
- The remote endpoint closed the connection with the given
- Code
and Payload
as the reason.
-
The remote endpoint closed the connection with the given Code
and Payload
as the reason.
- The handler requested to close the connection, either by returning
- a stop
tuple or by sending a close
frame.
-
The handler requested to close the connection, either by returning a stop
tuple or by sending a close
frame.
- The connection has been closed due to inactivity. The timeout
- value can be configured from init/2
.
-
The connection has been closed due to inactivity. The timeout value can be configured from init/2
.
- 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.
-
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.
- A text frame was sent by the client with invalid encoding. All - text frames must be valid UTF-8. -
+A text frame was sent by the client with invalid encoding. All text frames must be valid UTF-8.
- A protocol error has been detected. -
+A protocol error has been detected.
- The socket has been closed brutally without a close frame being - received first. -
+The socket has been closed brutally without a close frame being received first.
- A socket error ocurred. -
+A socket error ocurred.
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() :: #{ - 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:
- 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:
+Whether to enable the Websocket frame compression extension. Frames will only be compressed for the clients that support this extension.
- Time in milliseconds that Cowboy will keep the - connection open without receiving anything from - the client. -
+Time in milliseconds that Cowboy will keep the connection open without receiving anything from the client.
- 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. -
+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.
- 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.
-
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.
-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
.
-
websocket_terminate/3
was removed in favor of terminate/3
.
-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 - status codes used by Cowboy
HTTP status codes - status codes used by Cowboy
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.
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.
This is the status code sent when switching to the -Websocket protocol.
This is the status code sent when switching to the Websocket protocol.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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:
+-The request-line could not be parsed. -
+-Too many headers were sent. -
+-A header name was too long. -
+-A header value was too long. -
+-The host header was missing from an HTTP/1.1 request. -
+-The host header could not be parsed. -
+-The requested host was not found. -
+-The requested path could not be parsed. -
+-The accept header could not be parsed when using REST. -
+-REST under normal conditions. -
+-A Websocket upgrade failed. -
+This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
This status code is sent by cowboy_rest
.
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 - Small, fast, modern HTTP server for Erlang/OTP
cowboy - Small, fast, modern HTTP server for Erlang/OTP
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.
Functions:
-cowboy(3) - Listener management -
+Functions:
+-cowboy_req(3) - Request and response -
+-cowboy_router(3) - Router -
+-cowboy_constraints(3) - Constraints -
+Protocols:
-cowboy_http(3) - HTTP/1.1 -
+Protocols:
+-cowboy_http2(3) - HTTP/2 -
+-cowboy_websocket(3) - Websocket -
+Handlers:
-cowboy_static(3) - Static file handler -
+Handlers:
+Behaviors:
-cowboy_handler(3) - Plain HTTP handlers -
+Behaviors:
+-cowboy_loop(3) - Loop handlers -
+-cowboy_middleware(3) - Middlewares -
+-cowboy_rest(3) - REST handlers -
+-cowboy_stream(3) - Stream handlers -
+-cowboy_websocket(3) - Websocket handlers -
+Middlewares:
-cowboy_router(3) - Router middleware -
+Middlewares:
+-cowboy_handler(3) - Handler middleware -
+-ranch(7) - Socket acceptor pool for TCP protocols -
+-cowlib(7) - Support library for manipulating Web protocols -
+-ssl - Secure communication over sockets -
+-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).+
The cowboy
application does not define any application
-environment configuration parameters.
The cowboy
application does not define any application environment configuration parameters.
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.
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.
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.
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.
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.
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.
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.
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.
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]}]} -]
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+
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 legacy method was used, and the .app.src file contained {id, "git"}
-
{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"},+
Erlang.mk supports a variety of different source file formats. -The following formats are supported natively:
Extension | -Location | -Description | -Output | +
---|
Extension | +Location | +Description | +Output | +
---|---|---|---|
.erl | +src/ | +Erlang source | +ebin/*.beam |
.erl |
-src/ |
-Erlang source |
-ebin/*.beam |
+
.core | +src/ | +Core Erlang source | +ebin/*.beam |
.core |
-src/ |
-Core Erlang source |
-ebin/*.beam |
+
.xrl | +src/ | +Leex source | +src/*.erl |
.xrl |
-src/ |
-Leex source |
-src/*.erl |
+
.yrl | +src/ | +Yecc source | +src/*.erl |
.yrl |
-src/ |
-Yecc source |
-src/*.erl |
+
.asn1 | +asn1/ | +ASN.1 files | +include/*.hrl include/*.asn1db src/*.erl |
.asn1 |
-asn1/ |
-ASN.1 files |
-include/.hrl include/.asn1db src/*.erl |
+
.mib | +mibs/ | +SNMP MIB files | +include/*.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:
+Extension | +Location | +Description | +Output | +
---|---|---|---|
.dtl | +templates/ | +Django templates | +ebin/*.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 |
+
.proto | +src/ | +Protocol buffers | +ebin/*.beam |
.proto |
-src/ |
-Protocol buffers |
-ebin/*.beam |
-
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
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_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
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+
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.
- 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.
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 $@
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.
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.
It is necessary to have AsciiDoc, xsltproc and dblatex installed on your system for Erlang.mk to generate documentation from AsciiDoc sources.
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.
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.
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.
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.)
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.
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+
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.
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.
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/.
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+
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 @@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.
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 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.
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!
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 @@You are welcome and encouraged to contribute.
This is how.
You are welcome and encouraged to contribute.
+This is how.
From the most important to the least important:
-Bugs -
+From the most important to the least important:
+-Package issues/additions -
+-Refactoring -
+-Features -
+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.
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.
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.
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
.
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 @@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 @@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.
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+
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.
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.
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 |
+
Name | +Format | +Description | +
---|---|---|
git | +git repo commit | +Clone the Git repository and checkout the given version |
git-submodule |
-git-submodule |
-Initialize and update the Git submodule |
+
git-submodule | +git-submodule | +Initialize and update the Git submodule |
hg |
-hg repo commit |
-Clone the Mercurial repository and update to the given version |
+
hg | +hg repo commit | +Clone the Mercurial repository and update to the given version |
svn |
-svn repo |
-Checkout the given SVN repository |
+
svn | +svn repo | +Checkout the given SVN repository |
cp |
-cp path/to/repo |
-Recursively copy a local directory |
+
cp | +cp path/to/repo | +Recursively copy a local directory |
ln |
-ln path/to/repo |
-Symbolically link a local directory |
+
ln | +ln path/to/repo | +Symbolically link a local directory |
hex |
-hex version |
-Download the given project version from hex.pm |
+
hex | +hex version | +Download the given project version from hex.pm |
fail |
-N/A |
-Always fail, reserved for internal use |
+
fail | +N/A | +Always fail, reserved for internal use |
legacy |
-N/A |
-Legacy Erlang.mk fetcher, reserved for internal use |
+
legacy | +N/A | +Legacy 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+
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.
Note that, like dependency information, this custom fetch method must be written before including erlang.mk.
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:
-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:
+-Build first dependency -
+-Build Nth dependency -
+-Build last dependency -
+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.
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:
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'
.
-
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.
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 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.
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 autopatched -
+
-They are not deleted on make distclean
-
make distclean
-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+
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.
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:
+
-If it contains a configure.ac or configure.in file, run autoreconf -Wall -vif -I m4
-
autoreconf -Wall -vif -I m4
-If it contains a configure script, run it -
+-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.
+-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. -
+-Projects with no source directory and no Makefile get an -empty Makefile generated, for compatibility purposes. -
+-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+
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:
+
-The dependency directory $(DEPS_DIR) will not be removed on make distclean
-
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 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.
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.
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.
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
.
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.
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.
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}+
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 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.
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+
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+
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.
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
.
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
.
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.
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.
Erlang.mk will automatically recompile your code when you perform a normal build after running tests, and vice versa.
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+
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 @@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.
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.
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+
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.
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
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 @@
This is a non-exhaustive list of Erlang.mk plugins, sorted -alphabetically.
This is a non-exhaustive list of Erlang.mk plugins, sorted alphabetically.
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.
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.
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 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.
An Hex plugin for Erlang.mk
-using the hexer
tool.
An Hex plugin for Erlang.mk using the hexer
tool.
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 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.
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.
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.
A live reload plugin for Erlang.mk.
A live reload plugin for Erlang.mk.
A plugin to build Rust crates and install binaries into priv/
.
This chapter explains how to get started using Erlang.mk.
This chapter explains how to get started using Erlang.mk.
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.
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.
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.
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!
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!
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!
Simple as that!
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.
From that point onward you can create an src/
folder or start using templates.
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.
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!
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!
+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.
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 @@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.
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.
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 @@-Installation -
+-Overview -
+-Limitations -
+-Building -
+-Releases -
+-Escripts -
+-Erlang shell -
+-EUnit -
+-Common Test -
+-Triq -
+-Dialyzer -
+-Xref -
+-Contributing -
+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.
The commands to install packages vary between distributions:
$ 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 comes with binary and source 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.
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:
$ brew install erlang git make
Homebrew installs GNU Make as gmake
. The make
command
-is the one provided by Apple.
$ sudo port install erlang git gmake
$ sudo port install erlang git gmake+
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.
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
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"
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.
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 @@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.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.
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.
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.
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 @@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.
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.
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.
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.
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.
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.
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+
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.
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.
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.
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 @@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
.
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.
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+
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.
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 @@
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.
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.
+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+
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
.
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.
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!
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
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.
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
.
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.
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.
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()'+
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.
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.
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.
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 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.
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:
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 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 @@
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.
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.
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.
All that's left to do is to commit the file!
+Yep, it's that easy.
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.
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 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 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 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 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 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.
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 @@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 @@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 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.
The gun:open/2,3
function must be used to open a connection.
{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.
{ok, ConnPid} = gun:open("example.org", 8443, #{transport => tls}).
{ok, ConnPid} = gun:open("example.org", 8443, #{transport => tls}).+
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.
{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).+
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.
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.
{ok, ConnPid} = gun:open("example.org", 443). -MRef = monitor(process, ConnPid).
This monitor reference can be kept and used until the connection -process exits.
DOWN
messagesreceive - %% 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.
The connection can be stopped abruptly at any time by calling
-the gun:close/1
function.
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 @@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.
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.
gun:cancel(ConnPid, StreamRef).
gun:cancel(ConnPid, StreamRef).+
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.
Use gun:get/2,3,4
to request a resource.
StreamRef = gun:get(ConnPid, "/organizations/ninenines").
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.
StreamRef = gun:head(ConnPid, "/organizations/ninenines").
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.
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.
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.
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.
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.+
Use gun:delete/2,3,4
to delete a resource.
StreamRef = gun:delete(ConnPid, "/organizations/ninenines").
StreamRef = gun:delete(ConnPid, "/organizations/ninenines", [ - {<<"user-agent">>, "revolver/1.0"} -]).
StreamRef = gun:delete(ConnPid, "/organizations/ninenines", [ + {<<"user-agent">>, "revolver/1.0"} +]).+
Use gun:options/2,3
to request information about a resource.
StreamRef = gun:options(ConnPid, "/organizations/ninenines").
StreamRef = gun:options(ConnPid, "/organizations/ninenines", [ - {<<"user-agent">>, "revolver/1.0"} -]).
You can also use this function to request information about -the server itself.
StreamRef = gun:options(ConnPid, "*").
StreamRef = gun:options(ConnPid, "*").+
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.
gun:request(ConnPid, "TRACE", "/", [ - {<<"max-forwards">>, "30"} -]).
gun:request(ConnPid, "TRACE", "/", [ + {<<"max-forwards">>, "30"} +]).+
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.
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.
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.+
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.
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.
{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
.
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.
gun:flush(ConnPid).
gun:flush(StreamRef).
gun:flush(StreamRef).+
Gun allows you to specify which process will handle responses
-to a request via the reply_to
request option.
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 @@
-Introduction -
+-Connection -
+-Using HTTP -
+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.
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.
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.
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.
-
-
Gun uses Semantic Versioning 2.0.0.
Gun uses Semantic Versioning 2.0.0.
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 @@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 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 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 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.
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 | +
---|
Operation | +HTTP/1.1 | +HTTP/2 | +Websocket | +
---|---|---|---|
delete | +yes | +yes | +no |
delete |
-yes |
-yes |
-no |
+
get | +yes | +yes | +no |
get |
-yes |
-yes |
-no |
+
head | +yes | +yes | +no |
head |
-yes |
-yes |
-no |
+
options | +yes | +yes | +no |
options |
-yes |
-yes |
-no |
+
patch | +yes | +yes | +no |
patch |
-yes |
-yes |
-no |
+
post | +yes | +yes | +no |
post |
-yes |
-yes |
-no |
+
put | +yes | +yes | +no |
put |
-yes |
-yes |
-no |
+
request | +yes | +yes | +no |
request |
-yes |
-yes |
-no |
+
data | +yes | +yes | +no |
data |
-yes |
-yes |
-no |
+
await | +yes | +yes | +no |
await |
-yes |
-yes |
-no |
+
await_body | +yes | +yes | +no |
await_body |
-yes |
-yes |
-no |
+
flush | +yes | +yes | +no |
flush |
-yes |
-yes |
-no |
+
cancel | +yes | +yes | +no |
cancel |
-yes |
-yes |
-no |
+
ws_upgrade | +yes | +no | +no |
ws_upgrade |
-yes |
-no |
-no |
+
ws_send | +no | +no | +yes |
ws_send |
-no |
-no |
-yes |
+
Message | +HTTP/1.1 | +HTTP/2 | +Websocket | +
---|---|---|---|
gun_push | +no | +yes | +no |
Message | -HTTP/1.1 | -HTTP/2 | -Websocket | +
---|---|---|---|
gun_inform | +yes | +yes | +no |
gun_push |
-no |
-yes |
-no |
+
gun_response | +yes | +yes | +no |
gun_inform |
-yes |
-yes |
-no |
+
gun_data | +yes | +yes | +no |
gun_response |
-yes |
-yes |
-no |
+
gun_trailers | +yes | +yes | +no |
gun_data |
-yes |
-yes |
-no |
+
gun_error | +yes | +yes | +yes |
gun_trailers |
-yes |
-yes |
-no |
+
gun_upgrade | +yes | +no | +no |
gun_error |
-yes |
-yes |
-yes |
+
gun_ws | +no | +no | +yes |
gun_upgrade |
-yes |
-no |
-no |
-
gun_ws |
-no |
-no |
-yes |
-
This chapter describes how to start and stop the Gun application.
This chapter describes how to start and stop the Gun application.
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.
DEPS = gun
DEPS = gun+
Gun is an OTP application. It needs to be started before you can -use it.
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]}+
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.
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 @@
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.
+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.
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.
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.+
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.
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.
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 - Wait for a response
gun:await - Wait for a response
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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Identifier of the stream for the original request. -
+Identifier of the stream for the original request.
-How long to wait for a message, in milliseconds. -
+How long to wait for a message, in milliseconds.
-Monitor for the Gun connection process. -
-A monitor is automatically created for the duration of this -call when one is not provided.
Monitor for the Gun connection process.
+A monitor is automatically created for the duration of this call when one is not provided.
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:
+-gun_inform(3) - Informational response -
+-gun_response(3) - Response -
+-gun_data(3) - Response body -
+-gun_trailers(3) - Response trailers -
+-1.0: Function introduced. -
+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).+
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 - Wait for the complete response body
gun:await_body - 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.
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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Identifier of the stream for the original request. -
+Identifier of the stream for the original request.
-How long to wait for each message, in milliseconds. -
+How long to wait for each message, in milliseconds.
-Monitor for the Gun connection process. -
-A monitor is automatically created for the duration of this -call when one is not provided.
Monitor for the Gun connection process.
+A monitor is automatically created for the duration of this call when one is not provided.
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.
-1.0: Function introduced. -
+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).+
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 - Wait for the connection to be up
gun:await_up - Wait for the connection to be up
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.
Wait for the connection to be up.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-How long to wait for, in milliseconds. -
+How long to wait for, in milliseconds.
-Monitor for the Gun connection process. -
-A monitor is automatically created for the duration of this -call when one is not provided.
Monitor for the Gun connection process.
+A monitor is automatically created for the duration of this call when one is not provided.
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.
-1.0: Function introduced. -
+{ok, ConnPid} = gun:open("example.org", 443). -{ok, _} = gun:await_up(ConnPid).
{ok, ConnPid} = gun:open("example.org", 443). +{ok, _} = gun:await_up(ConnPid).+
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 - Cancel the given stream
gun:cancel - Cancel the given stream
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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Identifier of the stream for the original request. -
+Identifier of the stream for the original request.
The atom ok
is returned.
The atom ok
is returned.
-1.0: Function introduced. -
+gun:cancel(ConnPid, StreamRef).
gun:cancel(ConnPid, StreamRef).+
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 - Brutally close the connection
gun:close - Brutally close the connection
close(ConnPid) -> ok +close(ConnPid) -> ok -ConnPid :: pid()
Brutally close the connection.
Brutally close the connection.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
The atom ok
is returned.
The atom ok
is returned.
-1.0: Function introduced. -
+ok = gun:close(ConnPid).
ok = gun:close(ConnPid).+
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 - Stream the body of a request
gun:data - Stream the body of a request
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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Identifier of the stream for the original request. -
+Identifier of the stream for the original request.
-Whether this message terminates the request. -
+Whether this message terminates the request.
-All or part of the response body. -
+All or part of the response body.
The atom ok
is returned.
The atom ok
is returned.
-1.0: Function introduced. -
+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">>).+
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 - Delete a resource
gun:delete - 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.
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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Path to the resource. -
+Path to the resource.
-Additional request headers. -
+Additional request headers.
-Request options. -
+Request options.
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.
-1.0: Function introduced. -
+StreamRef = gun:delete(ConnPid, "/drafts/123").
StreamRef = gun:delete(ConnPid, "/drafts/123", [], - #{reply_to => ReplyToPid}).
StreamRef = gun:delete(ConnPid, "/drafts/123", [], + #{reply_to => ReplyToPid}).+
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 - Flush all messages related to a connection or a stream
gun:flush - Flush all messages related to a connection or a stream
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.
Flush all messages related to a connection or a stream.
Either of these arguments may be provided:
-The pid of the Gun connection process. -
+Either of these arguments may be provided:
+The pid of the Gun connection process.
-Identifier of the stream for the original request. -
+Identifier of the stream for the original request.
The atom ok
is returned.
The atom ok
is returned.
-1.0: Function introduced. -
+gun:flush(ConnPid).
gun:flush(StreamRef).
gun:flush(StreamRef).+
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 - Get a resource representation
gun:get - 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.
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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Path to the resource. -
+Path to the resource.
-Additional request headers. -
+Additional request headers.
-Request options. -
+Request options.
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.
-1.0: Function introduced. -
+StreamRef = gun:get(ConnPid, "/articles", [ - {<<"accept">>, <<"text/html;q=1.0, application/xml;q=0.1">>} -]).
StreamRef = gun:get(ConnPid, "/articles", [], #{ - reply_to => ReplyToPid -}).
StreamRef = gun:get(ConnPid, "/articles", [], #{ + reply_to => ReplyToPid +}).+
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 - Get headers of a resource representation
gun:head - Get headers of a resource representation
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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Path to the resource. -
+Path to the resource.
-Additional request headers. -
+Additional request headers.
-Request options. -
+Request options.
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.
-1.0: Function introduced. -
+StreamRef = gun:head(ConnPid, "/articles", [ - {<<"accept">>, <<"text/html;q=1.0, application/xml;q=0.1">>} -]).
StreamRef = gun:head(ConnPid, "/articles", [], #{ - reply_to => ReplyToPid -}).
StreamRef = gun:head(ConnPid, "/articles", [], #{ + reply_to => ReplyToPid +}).+
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 - Obtain information about the connection
gun:info - 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.
info(ConnPid) -> Info + +ConnPid :: pid() +Info :: #{ + sock_ip => inet:ip_address(), + sock_port => inet:port_number() +}+
Obtain information about the connection.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
A map is returned containing various informations about -the connection.
A map is returned containing various informations about the connection.
-1.0: Function introduced. -
+Info = gun:info(ConnPid).
Info = gun:info(ConnPid).+
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 - Open a connection to the given host and port
gun:open - 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.
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.
-Host or IP address to connect to. -
+Host or IP address to connect to.
-Port to connect to. -
+Port to connect to.
-Options for this connection. -
+Options for this connection.
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.
-1.0: Function introduced. -
+{ok, ConnPid} = gun:open("example.org", 443).
{ok, ConnPid} = gun:open("example.org", 443, - #{protocols => [http2]}).
{ok, ConnPid} = gun:open({127,0,0,1}, 443).
{ok, ConnPid} = gun:open({127,0,0,1}, 443).+
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 - Open a connection to the given Unix domain socket
gun:open_unix - Open a connection to the given Unix domain socket
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.
Open a connection to the given Unix domain socket.
-Path to the Unix domain socket to connect to. -
+Path to the Unix domain socket to connect to.
-Options for this connection. -
+Options for this connection.
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.
-1.0: Function introduced. -
+{ok, ConnPid} = gun:open_unix("/var/run/dbus/system_bus_socket", #{}).
{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]}).+
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 - Query the capabilities of the server or a resource
gun:options - Query the capabilities of the server or a resource
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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Path to the resource. -
+Path to the resource.
-Additional request headers. -
+Additional request headers.
-Request options. -
+Request options.
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.
-1.0: Function introduced. -
+StreamRef = gun:options(ConnPid, "*").
StreamRef = gun:options(ConnPid, "/articles").
StreamRef = gun:options(ConnPid, "/articles").+
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 - Apply a set of changes to a resource
gun:patch - Apply a set of changes to a 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.
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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Path to the resource. -
+Path to the resource.
-Additional request headers. -
+Additional request headers.
-Request body. -
+Request body.
-Request options. -
+Request options.
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.
-1.0: Function introduced. -
+StreamRef = gun:patch(ConnPid, "/users/1", - [{<<"content-type">>, <<"application/json-patch+json">>}], - <<"[{\"op\":\"add\",\"path\":\"/baz\",\"value\":\"qux\"}]">>).
StreamRef = gun:patch(ConnPid, "/users/1", [ - {<<"content-type">>, <<"application/json-patch+json">>} -]). -gun:data(ConnPid, StreamRef, fin, - <<"[{\"op\":\"add\",\"path\":\"/baz\",\"value\":\"qux\"}]">>).
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}).+
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 - Process the enclosed representation according to a resource’s own semantics
gun:post - Process the enclosed representation according to a resource's own semantics
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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Path to the resource. -
+Path to the resource.
-Additional request headers. -
+Additional request headers.
-Request body. -
+Request body.
-Request options. -
+Request options.
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.
-1.0: Function introduced. -
+StreamRef = gun:post(ConnPid, "/search", - [{<<"content-type">>, <<"application/x-www-form-urlencoded">>}], - <<"q=nine%20nines">>).
StreamRef = gun:post(ConnPid, "/search", [ - {<<"content-type">>, <<"application/x-www-form-urlencoded">>} -]). -gun:data(ConnPid, StreamRef, fin, <<"q=nine%20nines">>).
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}).+
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 - Create or replace a resource
gun:put - Create or replace a resource
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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Path to the resource. -
+Path to the resource.
-Additional request headers. -
+Additional request headers.
-Request body. -
+Request body.
-Request options. -
+Request options.
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.
-1.0: Function introduced. -
+StreamRef = gun:put(ConnPid, "/lang/fr_FR/hello", - [{<<"content-type">>, <<"text/plain">>}], - <<"Bonjour !">>).
StreamRef = gun:put(ConnPid, "/lang/fr_FR/hello", [ - {<<"content-type">>, <<"text/plain">>} -]). -gun:data(ConnPid, StreamRef, fin, <<"Bonjour !">>).
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}).+
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 - Perform the given request
gun:request - Perform the given request
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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Method to be used for the request. -
+Method to be used for the request.
-Path to the resource. -
+Path to the resource.
-Additional request headers. -
+Additional request headers.
-Request body. -
+Request body.
-Request options. -
+Request options.
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.
-1.0: Function introduced. -
+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 !">>).+
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 - Send Websocket frames
gun:ws_send - Send Websocket frames
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).
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-A Websocket frame. -
+A Websocket frame.
The atom ok
is returned.
The atom ok
is returned.
-1.0: Function introduced. -
+gun:ws_send(ConnPid, {text, <<"Hello world!">>}).
gun:ws_send(ConnPid, {text, <<"Hello world!">>}).+
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 - Upgrade to Websocket
gun:ws_upgrade - Upgrade to Websocket
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
.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Path to the resource. -
+Path to the resource.
-Additional request headers. -
+Additional request headers.
-Configuration for the Websocket protocol. -
+Configuration for the Websocket protocol.
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.
-1.0: Function introduced. -
+StreamRef = gun:ws_upgrade(ConnPid, "/ws", [ - {<<"sec-websocket-protocol">>, <<"chat">>} -]). -receive - {gun_upgrade, ConnPid, StreamRef, [<<"websocket">>], _} -> - ok -after 5000 -> - error(timeout) -end.
StreamRef = gun:ws_upgrade(ConnPid, "/ws", [], #{ - compress => false -}).
StreamRef = gun:ws_upgrade(ConnPid, "/ws", [], #{ + compress => false +}).+
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 - Asynchronous HTTP client
gun - Asynchronous HTTP client
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.
Connection:
-gun:open(3) - Open a connection to the given host and port -
+Connection:
+-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:
-gun:get(3) - Get a resource representation -
+Requests:
+-gun:head(3) - Get headers of a resource representation -
+-gun:options(3) - Query the capabilities of the server or a resource -
+-gun:patch(3) - Apply a set of changes to a resource -
+-gun:post(3) - Process the enclosed representation according to a resource’s own semantics -
+-gun:put(3) - Create or replace a resource -
+-gun:delete(3) - Delete a resource -
+-gun:request(3) - Perform the given request -
+-gun:data(3) - Stream the body of a request -
+Messages:
-gun:await(3) - Wait for a response -
+Messages:
+-gun:await_body(3) - Wait for the complete response body -
+-gun:await(3) - Wait for the connection to be up -
+-gun:flush(3) - Flush all messages related to a connection or a stream -
+Streams:
-gun:cancel(3) - Cancel the given stream -
+Streams:
+Websocket:
-gun:ws_upgrade(3) - Upgrade to Websocket -
+Websocket:
+-gun:ws_send(3) - Send Websocket frames -
+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:
+-gun_down(3) - The connection is down -
+-gun_upgrade(3) - Successful protocol upgrade -
+-gun_error(3) - Stream or connection-wide error -
+Responses:
-gun_push(3) - Server-initiated push -
+Responses:
+-gun_inform(3) - Informational response -
+-gun_response(3) - Response -
+-gun_data(3) - Response body -
+-gun_trailers(3) - Response trailers -
+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.
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:
-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:
+ +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.
-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. -
+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.
'HTTP/1.1'
)
--HTTP version to use. -
+'HTTP/1.1'
)HTTP version to use.
http2_opts() :: #{ - keepalive => timeout() -}
Configuration for the HTTP/2 protocol.
The default value is given next to the option name:
-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:
+ +Time between pings in milliseconds.
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:
-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:
+Connection timeout.
-Options specific to the HTTP protocol. -
+Options specific to the HTTP protocol.
-Options specific to the HTTP/2 protocol. -
+Options specific to the HTTP/2 protocol.
-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
.
-
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
.
-Number of times Gun will try to reconnect on failure before giving up. -
+Number of times Gun will try to reconnect on failure before giving up.
-Time between retries in milliseconds. -
+Time between retries in milliseconds.
-Whether to enable dbg
tracing of the connection process. Should
-only be used during debugging.
-
Whether to enable dbg
tracing of the connection process. Should only be used during debugging.
-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
.
-
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 options. They are TCP options or TLS options depending on -the selected transport. -
+Transport options. They are TCP options or TLS options depending on the selected transport.
-Options specific to the Websocket protocol. -
+Options specific to the Websocket protocol.
req_opts() :: #{ - reply_to => pid() -}
Configuration for a particular request.
The default value is given next to the option name:
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:
+self()
)The pid of the process that will receive the response messages.
ws_opts() :: #{ - compress => boolean() -}
Configuration for the Websocket protocol.
The default value is given next to the option name:
-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:
+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.
gun - HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP
gun - HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP
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.
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).+
The gun
application does not define any application
-environment configuration parameters.
The gun
application does not define any application environment configuration parameters.
gun_data - Response body
gun_data - Response body
{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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Identifier of the stream for the original request. -
+Identifier of the stream for the original request.
-Whether this message terminates the response. -
+Whether this message terminates the response.
-All or part of the response body. -
+All or part of the response body.
-1.0: Message introduced. -
+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}.+
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 - The connection is down
gun_down - The connection is down
{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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-The protocol that was selected for this connection -or upgraded to during the course of the connection. -
+The protocol that was selected for this connection or upgraded to during the course of the connection.
-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.
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.
-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.
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.
-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.
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.
-1.0: Message introduced. -
+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}.+
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 - Stream or connection-wide error
gun_error - Stream or connection-wide error
{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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Identifier of the stream that resulted in an error. -
+Identifier of the stream that resulted in an error.
-The reason for the error. -
-It is present for debugging purposes only. You should not -rely on this value to perform operations programmatically.
The reason for the error.
+It is present for debugging purposes only. You should not rely on this value to perform operations programmatically.
-1.0: Message introduced. -
+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}.+
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 - Informational response
gun_inform - Informational response
{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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Identifier of the stream for the original request. -
+Identifier of the stream for the original request.
-Status code for the informational response. -
+Status code for the informational response.
-Headers sent with the informational response. -
+Headers sent with the informational response.
-1.0: Message introduced. -
+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}.+
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 - Server-initiated push
gun_push - 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.
{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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Identifier of the stream for the original request. -
+Identifier of the stream for the original request.
-Identifier of the stream being pushed. -
+Identifier of the stream being pushed.
-Method of the equivalent HTTP request. -
+Method of the equivalent HTTP request.
-URI of the resource being pushed. -
+URI of the resource being pushed.
-Headers of the equivalent HTTP request. -
+Headers of the equivalent HTTP request.
-1.0: Message introduced. -
+handle_info({gun_push, ConnPid, _StreamRef, - _NewStreamRef, _Method, _URI, _Headers}, - State=#state{conn_pid=ConnPid}) -> - %% Do something. - {noreply, State}.
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}.+
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 - Response
gun_response - Response
{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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Identifier of the stream for the original request. -
+Identifier of the stream for the original request.
-Whether this message terminates the response. -
+Whether this message terminates the response.
-Status code for the response. -
+Status code for the response.
-Headers sent with the response. -
+Headers sent with the response.
-1.0: Message introduced. -
+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}.+
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 - Response trailers
gun_trailers - Response trailers
{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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Identifier of the stream for the original request. -
+Identifier of the stream for the original request.
-Trailing headers sent after the response body. -
+Trailing headers sent after the response body.
-1.0: Message introduced. -
+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}.+
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 - The connection is up
gun_up - The connection is up
{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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-The protocol selected for this connection. It can be used -to determine the capabilities of the server. -
+The protocol selected for this connection. It can be used to determine the capabilities of the server.
-1.0: Message introduced. -
+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}.+
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 - Successful protocol upgrade
gun_upgrade - Successful protocol upgrade
{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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Identifier of the stream that resulted in an upgrade. -
+Identifier of the stream that resulted in an upgrade.
-List of protocols this stream was upgraded to. -
+List of protocols this stream was upgraded to.
-Headers sent with the upgrade response. -
+Headers sent with the upgrade response.
-1.0: Message introduced. -
+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}.+
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 - Websocket frame
gun_ws - Websocket frame
{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.
-The pid of the Gun connection process. -
+The pid of the Gun connection process.
-Identifier of the stream that was upgraded to Websocket. -
+Identifier of the stream that was upgraded to Websocket.
-The Websocket frame in question. -
+The Websocket frame in question.
-1.0: Message introduced. -
+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}.+
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 - HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP
gun - HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP
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.
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).+
The gun
application does not define any application
-environment configuration parameters.
The gun
application does not define any application environment configuration parameters.
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.
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.
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.
-Introduction -
+-Listeners -
+-Transports -
+-Protocols -
+-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.
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.
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.
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.
{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 --> +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.
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.
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.
Ranch uses Semantic Versioning 2.0.0
Ranch uses Semantic Versioning 2.0.0
+ @@ -140,6 +125,8 @@ modifications but there is no guarantee that it will work as expected. +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.
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:
+-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/6
-function. Before doing so however, you must ensure that the ranch
-application is started.
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.
{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:
$ 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.
$ 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.+
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.
ranch:stop_listener(tcp_echo).
ranch:stop_listener(tcp_echo).+
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.
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
.
{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).+
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.
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.
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.
{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
.
{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.
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.
ranch:set_max_connections(tcp_echo, MaxConns).
The change will occur immediately.
ranch:set_max_connections(tcp_echo, MaxConns).+
The change will occur immediately.
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.
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.
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
.
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 --> +
There are three kinds of protocols:
-Text protocols -
+There are three kinds of 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.
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.
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}
.
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.
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.
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.
<< 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. +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.
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.
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/
.
-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.+
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.
-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.
-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}; +%% ...+
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
.
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.
+-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.
You can optionally save the certificate for later use, for example to extract the IssuerID
information as will be detailed later on.
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.
{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.
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.
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.
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.
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.
The TCP transport is a thin wrapper around gen_tcp
.
The TCP transport is a thin wrapper around gen_tcp
.
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.
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.
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:
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.
{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.
{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.
{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.
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:
{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
:
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:
{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).+
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.
ranch_ssl
for an example.<
+ -ranch(7) -
+-ranch(3) -
+-ranch_ssl(3) -
+-ranch_tcp(3) -
+ranch - socket acceptor pool
ranch - socket acceptor pool
The ranch
module provides functions for starting and
-manipulating Ranch listeners.
The ranch
module provides functions for starting and manipulating Ranch listeners.
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.
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() = {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.
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.
+Unique name used to refer to a listener.
None of the options are required.
- Maximum allowed time for the ranch:accept_ack/1
call to finish.
-
- Type of process that will handle the connection. -
-
- Maximum number of active connections. Soft limit. Using infinity
will disable the limit entirely.
-
- Maximum allowed time for children to stop on listener shutdown. -
-
- Listening socket opened externally to be used instead of calling Transport:listen/1
.
-
None of the options are required.
+Maximum allowed time for the ranch:accept_ack/1
call to finish.
Type of process that will handle the connection.
+Maximum number of active connections. Soft limit. Using infinity
will disable the limit entirely.
Maximum allowed time for children to stop on listener shutdown.
+Listening socket opened externally to be used instead of calling Transport:listen/1
.
-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.
-Listener name. -
--Number of acceptor processes. -
--Transport module. -
--Transport options. -
--Protocol module. -
--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.
-Listener name. -
--IP of the interface used by this listener. -
--Port number used by this listener. -
-Return the IP address and port for the given listener.
-Listener name. -
--Current maximum number of connections. -
-Return the max number of connections allowed for the given listener.
-Listener name. -
--Port number used by this listener. -
-Return the port for the given listener.
-Listener name. -
--Current protocol options. -
-Return the protocol options set for the given listener.
-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.
-Listener name. -
--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.
-Listener name. -
--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.
-Listener name. -
--Number of acceptor processes. -
--Transport module. -
--Transport options. -
--Protocol module. -
--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.
-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.
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.
+Listener name.
+Number of acceptor processes.
+Transport module.
+Transport options.
+Protocol module.
+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.
+Listener name.
+IP of the interface used by this listener.
+Port number used by this listener.
+Return the IP address and port for the given listener.
+Listener name.
+Current maximum number of connections.
+Return the max number of connections allowed for the given listener.
+Listener name.
+Port number used by this listener.
+Return the port for the given listener.
+Listener name.
+Current protocol options.
+Return the protocol options set for the given listener.
+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.
+Listener name.
+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.
+Listener name.
+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.
+Listener name.
+Number of acceptor processes.
+Transport module.
+Transport options.
+Protocol module.
+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.
+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. +ranch - Socket acceptor pool for TCP protocols.
ranch - Socket acceptor pool for TCP protocols.
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.
The ranch
application defines one application environment
-configuration parameter.
- When enabled, Ranch will start eprof
profiling automatically.
-
The ranch
application defines one application environment configuration parameter.
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.
ranch_protocol - behaviour for protocol modules
ranch_protocol - behaviour for protocol modules
The ranch_protocol
behaviour defines the interface used
-by Ranch protocols.
The ranch_protocol
behaviour defines the interface used by Ranch protocols.
None.
None.
-Listener name. -
+Listener name.
-Socket for this connection. -
+Socket for this connection.
-Transport module for this socket. -
+Transport module for this socket.
-Protocol options. -
+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. +ranch_ssl - SSL transport module
ranch_ssl - SSL transport module
The ranch_ssl
module implements an SSL Ranch transport.
The ranch_ssl
module implements an SSL Ranch transport.
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.
Listen options.
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.
+Listen options.
+List of listen options.
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.
- Perform Application-Layer Protocol Negotiation with the given list of preferred protocols. -
-- Path to PEM encoded trusted certificates file used to verify peer certificates. -
-- List of DER encoded trusted certificates. -
-- DER encoded user certificate. -
-- Path to the PEM encoded user certificate file. May also contain the private key. -
-- List of ciphers that clients are allowed to use. -
-- Whether to allow client-initiated renegotiation. -
-- Customize the module used to cache Certificate Revocation Lists. -
-- Whether to perform CRL check on all certificates in the chain during validation. -
-- Maximum of intermediate certificates allowed in the certification path. -
-- DER encoded Diffie-Hellman parameters. -
-- Path to the PEM encoded Diffie-Hellman parameters file. -
-- Whether to refuse the connection if the client sends an empty certificate. -
-- Time in ms after which SSL socket processes go into hibernation to reduce memory usage. -
-- If true, use the server’s preference for cipher selection. If false, use the client’s preference. -
-- DER encoded user private key. -
-- Path to the PEM encoded private key file, if different than the certfile. -
-- If false, error reports will not be displayed. -
-- List of protocols to send to the client if it supports the Next Protocol extension. -
-- Whether to enable TCP_NODELAY. -
-- Claim an intermediate CA in the chain as trusted. -
-- Password to the private key file, if password protected. -
-- Provide the given PSK identity hint to the client during the handshake. -
-- Custom policy to decide whether a session should be reused. -
-- Whether to allow session reuse. -
-- Whether to reject renegotiation attempts that do not conform to RFC5746. -
-- Function called when the client requests a host using Server Name Indication. Returns options to apply. -
-- Options to apply for the host that matches what the client requested with Server Name Indication. -
-- Function called to determine the shared secret when using PSK, or provide parameters when using SRP. -
-
- Use verify_peer
to request a certificate from the client.
-
- Custom policy to decide whether a client certificate is valid. -
-- 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.
+Perform Application-Layer Protocol Negotiation with the given list of preferred protocols.
+Path to PEM encoded trusted certificates file used to verify peer certificates.
+List of DER encoded trusted certificates.
+DER encoded user certificate.
+Path to the PEM encoded user certificate file. May also contain the private key.
+List of ciphers that clients are allowed to use.
+Whether to allow client-initiated renegotiation.
+Customize the module used to cache Certificate Revocation Lists.
+Whether to perform CRL check on all certificates in the chain during validation.
+Maximum of intermediate certificates allowed in the certification path.
+DER encoded Diffie-Hellman parameters.
+Path to the PEM encoded Diffie-Hellman parameters file.
+Whether to refuse the connection if the client sends an empty certificate.
+Time in ms after which SSL socket processes go into hibernation to reduce memory usage.
+If true, use the server's preference for cipher selection. If false, use the client's preference.
+DER encoded user private key.
+Path to the PEM encoded private key file, if different than the certfile.
+If false, error reports will not be displayed.
+List of protocols to send to the client if it supports the Next Protocol extension.
+Whether to enable TCP_NODELAY.
+Claim an intermediate CA in the chain as trusted.
+Password to the private key file, if password protected.
+Provide the given PSK identity hint to the client during the handshake.
+Custom policy to decide whether a session should be reused.
+Whether to allow session reuse.
+Whether to reject renegotiation attempts that do not conform to RFC5746.
+Function called when the client requests a host using Server Name Indication. Returns options to apply.
+Options to apply for the host that matches what the client requested with Server Name Indication.
+Function called to determine the shared secret when using PSK, or provide parameters when using SRP.
+Use verify_peer
to request a certificate from the client.
Custom policy to decide whether a client certificate is valid.
+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.
None.
None.
+ @@ -439,6 +248,8 @@ greater control over the client certificate validation. +ranch_tcp - TCP transport module
ranch_tcp - TCP transport module
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.
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.
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.
+List of listen options.
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.
- 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.
Max length of the queue of pending connections.
- Size of the buffer used by the Erlang driver. Default is system-dependent. -
+Size of the buffer used by the Erlang driver. Default is system-dependent.
- Always queue packets before sending, to send fewer, larger packets over the network. -
+Always queue packets before sending, to send fewer, larger packets over the network.
- Don’t send via a gateway, only send to directly connected hosts. -
+Don't send via a gateway, only send to directly connected hosts.
- Disable to allow sending data after a close has been detected. -
+Disable to allow sending data after a close has been detected.
- File descriptor of the socket, if it was opened externally. -
+File descriptor of the socket, if it was opened externally.
- Limit in the amount of data in the socket message queue before the socket queue becomes busy. -
+Limit in the amount of data in the socket message queue before the socket queue becomes busy.
- Limit in the amount of data in the ERTS socket implementation’s queue before the socket becomes busy. -
+Limit in the amount of data in the ERTS socket implementation's queue before the socket becomes busy.
- Set up the socket for IPv4. -
+Set up the socket for IPv4.
- Set up the socket for IPv6. -
+Set up the socket for IPv6.
- Interface to listen on. Listen on all interfaces by default. -
+Interface to listen on. Listen on all interfaces by default.
- Enable sending of keep-alive messages. -
+Enable sending of keep-alive messages.
- Whether to wait and how long to flush data sent before closing the socket. -
+Whether to wait and how long to flush data sent before closing the socket.
- Amount of data in the socket message queue before the socket queue leaves busy state. -
+Amount of data in the socket message queue before the socket queue leaves busy state.
- Amount of data in the ERTS socket implementation’s queue before the socket leaves busy state. -
+Amount of data in the ERTS socket implementation's queue before the socket leaves busy state.
- Whether to enable TCP_NODELAY. -
+Whether to enable TCP_NODELAY.
- TCP port number to listen on. 0 means a random port will be used. -
+TCP port number to listen on. 0 means a random port will be used.
- Priority value for all packets to be sent by this socket. -
+Priority value for all packets to be sent by this socket.
- Minimum size of the socket’s receive buffer. Default is system-dependent. -
+Minimum size of the socket's receive buffer. Default is system-dependent.
- How long the send call may wait for confirmation before returning. -
+How long the send call may wait for confirmation before returning.
- Whether to close the socket when the confirmation wasn’t received. -
+Whether to close the socket when the confirmation wasn't received.
- Minimum size of the socket’s send buffer. Default is system-dependent. -
+Minimum size of the socket's send buffer. Default is system-dependent.
- Value for the IP_TOS IP level option. Use with caution. -
+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.
None.
None.
+ @@ -364,6 +213,8 @@ portable. Use with caution. +ranch_transport - behaviour for transport modules
ranch_transport - behaviour for transport modules
The ranch_transport
behaviour defines the interface used
-by Ranch transports.
The ranch_transport
behaviour defines the interface used by Ranch transports.
Options used by the sendfile function and callbacks.
Allows configuring the chunk size, in bytes. Defaults to 8191 bytes.
Options used by the sendfile function and callbacks.
+Allows configuring the chunk size, in bytes. Defaults to 8191 bytes.
-Listening socket. -
--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.
-Socket for this connection. -
--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.
-Socket opened with listen/1 or accept/2. -
-Close the given socket.
-Socket opened with listen/1 or accept/2. -
--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.
-Transport options. -
--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.
-Tuple names. -
-Return the atoms used to identify messages sent in active mode.
-Transport module name. -
-Return the name of the transport.
-Socket for this connection. -
--IP of the remote endpoint. -
--Port of the remote endpoint. -
-Return the IP and port of the remote endpoint.
-Socket for this connection. -
--Requested length. -
--Receive timeout. -
--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.
-Socket for this connection. -
--Data to be sent. -
-Send data to the given socket.
Alias of ranch_transport:sendfile/5
.
Alias of ranch_transport:sendfile/5
.
-Socket for this connection. -
--Filename or file descriptor for the file to be sent. -
--Begin sending at this position in the file. -
--Send this many bytes. -
--This many bytes were sent. -
--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.
-Socket for this connection. -
--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.
-Socket for this connection. -
--Which side(s) of the socket to close. -
-Immediately close the socket in one or two directions.
-Socket opened with listen/1 or accept/2. -
--IP of the local endpoint. -
--Port of the local endpoint. -
-Return the IP and port of the local endpoint.
Listening socket.
+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.
Socket for this connection.
+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.
+Socket opened with listen/1 or accept/2.
+Close the given socket.
+Socket opened with listen/1 or accept/2.
+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.
+Transport options.
+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.
+Tuple names.
+Return the atoms used to identify messages sent in active mode.
+Transport module name.
+Return the name of the transport.
+Socket for this connection.
+IP of the remote endpoint.
+Port of the remote endpoint.
+Return the IP and port of the remote endpoint.
+Socket for this connection.
+Requested length.
+Receive timeout.
+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.
Socket for this connection.
+Data to be sent.
+Send data to the given socket.
+Alias of ranch_transport:sendfile/5
.
Alias of ranch_transport:sendfile/5
.
Socket for this connection.
+Filename or file descriptor for the file to be sent.
+Begin sending at this position in the file.
+Send this many bytes.
+This many bytes were sent.
+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.
Socket for this connection.
+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.
+Socket for this connection.
+Which side(s) of the socket to close.
+Immediately close the socket in one or two directions.
+Socket opened with listen/1 or accept/2.
+IP of the local endpoint.
+Port of the local endpoint.
+Return the IP and port of the local endpoint.
-Transport module for this socket. -
--Socket for this connection. -
--Filename or file descriptor for the file to be sent. -
--Begin sending at this position in the file. -
--Send this many bytes. -
--This many bytes were sent. -
--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.
Transport module for this socket.
+Socket for this connection.
+Filename or file descriptor for the file to be sent.
+Begin sending at this position in the file.
+Send this many bytes.
+This many bytes were sent.
+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.
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.
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.
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.
-Introduction -
+-Listeners -
+-Transports -
+-Protocols -
+-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.
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.
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.
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.
{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 --> +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.
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.
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.
Ranch uses Semantic Versioning 2.0.0
Ranch uses Semantic Versioning 2.0.0
+ @@ -142,6 +126,8 @@ modifications but there is no guarantee that it will work as expected. +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.
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:
+-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/6
-function. Before doing so however, you must ensure that the ranch
-application is started.
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.
{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:
$ 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.
$ 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.+
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.
ranch:stop_listener(tcp_echo).
ranch:stop_listener(tcp_echo).+
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.
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
.
{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).+
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.
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.
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.
{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
.
{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.
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.
ranch:set_max_connections(tcp_echo, MaxConns).
The change will occur immediately.
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.
+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.
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.
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.
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
.
Opts = ranch:get_protocol_options(tcp_echo).
Opts = ranch:get_protocol_options(tcp_echo).+
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.
ranch:info().
The ranch:procs/2
function will return all acceptor or listener
-processes for a given listener.
ranch:procs(tcp_echo, acceptors).
ranch:procs(tcp_echo, connections).
ranch:procs(tcp_echo, connections).+ + @@ -458,6 +312,8 @@ http://www.gnu.org/software/src-highlite --> +
There are three kinds of protocols:
-Text protocols -
+There are three kinds of 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.
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.
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}
.
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.
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.
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.
<< 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. +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.
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.
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/
.
-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.+
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.
-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.
Check the tcp_reverse
example for a complete example.
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
.
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.
+-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.
You can optionally save the certificate for later use, for example to extract the IssuerID
information as will be detailed later on.
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.
{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.
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.
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.
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.
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.
The TCP transport is a thin wrapper around gen_tcp
.
The TCP transport is a thin wrapper around gen_tcp
.
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.
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:
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.
{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.
{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.
{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.
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:
{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
:
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:
{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).+
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.
ranch_ssl
for an example.<
+ -ranch(7) -
+-ranch(3) -
+-ranch_ssl(3) -
+-ranch_tcp(3) -
+ranch - socket acceptor pool
ranch - socket acceptor pool
The ranch
module provides functions for starting and
-manipulating Ranch listeners.
The ranch
module provides functions for starting and manipulating Ranch listeners.
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.
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() = {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.
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.
+Unique name used to refer to a listener.
None of the options are required.
- Maximum allowed time for the ranch:accept_ack/1
call to finish.
-
- Type of process that will handle the connection. -
-
- Maximum number of active connections. Soft limit. Using infinity
will disable the limit entirely.
-
- Maximum allowed time for children to stop on listener shutdown. -
-
- Listening socket opened externally to be used instead of calling Transport:listen/1
.
-
None of the options are required.
+Maximum allowed time for the ranch:accept_ack/1
call to finish.
Type of process that will handle the connection.
+Maximum number of active connections. Soft limit. Using infinity
will disable the limit entirely.
Maximum allowed time for children to stop on listener shutdown.
+Listening socket opened externally to be used instead of calling Transport:listen/1
.
-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.
-Listener name. -
--Number of acceptor processes. -
--Transport module. -
--Transport options. -
--Protocol module. -
--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.
-Listener name. -
--IP of the interface used by this listener. -
--Port number used by this listener. -
-Return the IP address and port for the given listener.
-Listener name. -
--Current maximum number of connections. -
-Return the max number of connections allowed for the given listener.
-Listener name. -
--Port number used by this listener. -
-Return the port for the given listener.
-Listener name. -
--Current protocol options. -
-Return the protocol options set for the given listener.
-Listener name. -
--Information key. -
--Information value. -
-Return detailed information about all Ranch listeners.
The following keys are defined:
-Pid of the listener’s top-level supervisor. -
--Interface Ranch listens on. -
--Port number Ranch listens on. -
--Number of acceptor processes. -
--Maximum number of connections. -
--Number of active connections. -
--Number of connections, including those removed from the count. -
--Transport module. -
--Transport options. -
--Protocol module. -
--Protocol options. -
--Listener name. -
-Return all acceptor or connection processes for one listener.
-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.
-Listener name. -
--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.
-Listener name. -
--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.
-Listener name. -
--Number of acceptor processes. -
--Transport module. -
--Transport options. -
--Protocol module. -
--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.
-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.
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.
+Listener name.
+Number of acceptor processes.
+Transport module.
+Transport options.
+Protocol module.
+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.
+Listener name.
+IP of the interface used by this listener.
+Port number used by this listener.
+Return the IP address and port for the given listener.
+Listener name.
+Current maximum number of connections.
+Return the max number of connections allowed for the given listener.
+Listener name.
+Port number used by this listener.
+Return the port for the given listener.
+Listener name.
+Current protocol options.
+Return the protocol options set for the given listener.
+Listener name.
+Information key.
+Information value.
+Return detailed information about all Ranch listeners.
+The following keys are defined:
+Pid of the listener's top-level supervisor.
+Interface Ranch listens on.
+Port number Ranch listens on.
+Number of acceptor processes.
+Maximum number of connections.
+Number of active connections.
+Number of connections, including those removed from the count.
+Transport module.
+Transport options.
+Protocol module.
+Protocol options.
+Listener name.
+Return all acceptor or connection processes for one listener.
+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.
+Listener name.
+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.
+Listener name.
+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.
+Listener name.
+Number of acceptor processes.
+Transport module.
+Transport options.
+Protocol module.
+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.
+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. +ranch - Socket acceptor pool for TCP protocols.
ranch - Socket acceptor pool for TCP protocols.
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.
The ranch
application defines one application environment
-configuration parameter.
- When enabled, Ranch will start eprof
profiling automatically.
-
The ranch
application defines one application environment configuration parameter.
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.
ranch_protocol - behaviour for protocol modules
ranch_protocol - behaviour for protocol modules
The ranch_protocol
behaviour defines the interface used
-by Ranch protocols.
The ranch_protocol
behaviour defines the interface used by Ranch protocols.
None.
None.
-Listener name. -
+Listener name.
-Socket for this connection. -
+Socket for this connection.
-Transport module for this socket. -
+Transport module for this socket.
-Protocol options. -
+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. +ranch_ssl - SSL transport module
ranch_ssl - SSL transport module
The ranch_ssl
module implements an SSL Ranch transport.
The ranch_ssl
module implements an SSL Ranch transport.
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.
Listen options.
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.
+Listen options.
+List of listen options.
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.
- Perform Application-Layer Protocol Negotiation with the given list of preferred protocols. -
-- Change the BEAST mitigation strategy for SSL-3.0 and TLS-1.0 to interoperate with legacy software. -
-- Path to PEM encoded trusted certificates file used to verify peer certificates. -
-- List of DER encoded trusted certificates. -
-- DER encoded user certificate. -
-- Path to the PEM encoded user certificate file. May also contain the private key. -
-- List of ciphers that clients are allowed to use. -
-- Whether to allow client-initiated renegotiation. -
-- Customize the module used to cache Certificate Revocation Lists. -
-- Whether to perform CRL check on all certificates in the chain during validation. -
-- Maximum of intermediate certificates allowed in the certification path. -
-- DER encoded Diffie-Hellman parameters. -
-- Path to the PEM encoded Diffie-Hellman parameters file. -
-- Whether to refuse the connection if the client sends an empty certificate. -
-- Time in ms after which SSL socket processes go into hibernation to reduce memory usage. -
-- If true, use the server’s preference for cipher selection. If false, use the client’s preference. -
-- DER encoded user private key. -
-- Path to the PEM encoded private key file, if different than the certfile. -
-- If false, error reports will not be displayed. -
-- List of protocols to send to the client if it supports the Next Protocol extension. -
-- Whether to enable TCP_NODELAY. -
-- Allow disabling the block cipher padding check for TLS-1.0 to be able to interoperate with legacy software. -
-- Claim an intermediate CA in the chain as trusted. -
-- Password to the private key file, if password protected. -
-- Provide the given PSK identity hint to the client during the handshake. -
-- Custom policy to decide whether a session should be reused. -
-- Whether to allow session reuse. -
-- Whether to reject renegotiation attempts that do not conform to RFC5746. -
-- The TLS signature algorithm extension may be used, from TLS 1.2, to negotiate which signature algorithm to use during the TLS handshake. -
-- Function called when the client requests a host using Server Name Indication. Returns options to apply. -
-- Options to apply for the host that matches what the client requested with Server Name Indication. -
-- Function called to determine the shared secret when using PSK, or provide parameters when using SRP. -
-- Accept clients that send hello messages in SSL-2.0 format while offering supported SSL/TLS versions. -
-
- Use verify_peer
to request a certificate from the client.
-
- Custom policy to decide whether a client certificate is valid. -
-- 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.
+Perform Application-Layer Protocol Negotiation with the given list of preferred protocols.
+Change the BEAST mitigation strategy for SSL-3.0 and TLS-1.0 to interoperate with legacy software.
+Path to PEM encoded trusted certificates file used to verify peer certificates.
+List of DER encoded trusted certificates.
+DER encoded user certificate.
+Path to the PEM encoded user certificate file. May also contain the private key.
+List of ciphers that clients are allowed to use.
+Whether to allow client-initiated renegotiation.
+Customize the module used to cache Certificate Revocation Lists.
+Whether to perform CRL check on all certificates in the chain during validation.
+Maximum of intermediate certificates allowed in the certification path.
+DER encoded Diffie-Hellman parameters.
+Path to the PEM encoded Diffie-Hellman parameters file.
+Whether to refuse the connection if the client sends an empty certificate.
+Time in ms after which SSL socket processes go into hibernation to reduce memory usage.
+If true, use the server's preference for cipher selection. If false, use the client's preference.
+DER encoded user private key.
+Path to the PEM encoded private key file, if different than the certfile.
+If false, error reports will not be displayed.
+List of protocols to send to the client if it supports the Next Protocol extension.
+Whether to enable TCP_NODELAY.
+Allow disabling the block cipher padding check for TLS-1.0 to be able to interoperate with legacy software.
+Claim an intermediate CA in the chain as trusted.
+Password to the private key file, if password protected.
+Provide the given PSK identity hint to the client during the handshake.
+Custom policy to decide whether a session should be reused.
+Whether to allow session reuse.
+Whether to reject renegotiation attempts that do not conform to RFC5746.
+The TLS signature algorithm extension may be used, from TLS 1.2, to negotiate which signature algorithm to use during the TLS handshake.
+Function called when the client requests a host using Server Name Indication. Returns options to apply.
+Options to apply for the host that matches what the client requested with Server Name Indication.
+Function called to determine the shared secret when using PSK, or provide parameters when using SRP.
+Accept clients that send hello messages in SSL-2.0 format while offering supported SSL/TLS versions.
+Use verify_peer
to request a certificate from the client.
Custom policy to decide whether a client certificate is valid.
+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.
None.
None.
+ @@ -475,6 +264,8 @@ greater control over the client certificate validation. +ranch_tcp - TCP transport module
ranch_tcp - TCP transport module
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.
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.
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.
+List of listen options.
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.
- 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.
Max length of the queue of pending connections.
- Size of the buffer used by the Erlang driver. Default is system-dependent. -
+Size of the buffer used by the Erlang driver. Default is system-dependent.
- Always queue packets before sending, to send fewer, larger packets over the network. -
+Always queue packets before sending, to send fewer, larger packets over the network.
- Don’t send via a gateway, only send to directly connected hosts. -
+Don't send via a gateway, only send to directly connected hosts.
- Disable to allow sending data after a close has been detected. -
+Disable to allow sending data after a close has been detected.
- File descriptor of the socket, if it was opened externally. -
+File descriptor of the socket, if it was opened externally.
- Limit in the amount of data in the socket message queue before the socket queue becomes busy. -
+Limit in the amount of data in the socket message queue before the socket queue becomes busy.
- Limit in the amount of data in the ERTS socket implementation’s queue before the socket becomes busy. -
+Limit in the amount of data in the ERTS socket implementation's queue before the socket becomes busy.
- Set up the socket for IPv4. -
+Set up the socket for IPv4.
- Set up the socket for IPv6. -
+Set up the socket for IPv6.
- Interface to listen on. Listen on all interfaces by default. -
+Interface to listen on. Listen on all interfaces by default.
- Listen on IPv4 and IPv6 (false) or only on IPv6 (true). Use with inet6. -
+Listen on IPv4 and IPv6 (false) or only on IPv6 (true). Use with inet6.
- Enable sending of keep-alive messages. -
+Enable sending of keep-alive messages.
- Whether to wait and how long to flush data sent before closing the socket. -
+Whether to wait and how long to flush data sent before closing the socket.
- Amount of data in the socket message queue before the socket queue leaves busy state. -
+Amount of data in the socket message queue before the socket queue leaves busy state.
- Amount of data in the ERTS socket implementation’s queue before the socket leaves busy state. -
+Amount of data in the ERTS socket implementation's queue before the socket leaves busy state.
- Whether to enable TCP_NODELAY. -
+Whether to enable TCP_NODELAY.
- TCP port number to listen on. 0 means a random port will be used. -
+TCP port number to listen on. 0 means a random port will be used.
- Priority value for all packets to be sent by this socket. -
+Priority value for all packets to be sent by this socket.
- Minimum size of the socket’s receive buffer. Default is system-dependent. -
+Minimum size of the socket's receive buffer. Default is system-dependent.
- How long the send call may wait for confirmation before returning. -
+How long the send call may wait for confirmation before returning.
- Whether to close the socket when the confirmation wasn’t received. -
+Whether to close the socket when the confirmation wasn't received.
- Minimum size of the socket’s send buffer. Default is system-dependent. -
+Minimum size of the socket's send buffer. Default is system-dependent.
- Value for the IP_TOS IP level option. Use with caution. -
+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.
None.
None.
+ @@ -373,6 +217,8 @@ portable. Use with caution. +ranch_transport - behaviour for transport modules
ranch_transport - behaviour for transport modules
The ranch_transport
behaviour defines the interface used
-by Ranch transports.
The ranch_transport
behaviour defines the interface used by Ranch transports.
Options used by the sendfile function and callbacks.
Allows configuring the chunk size, in bytes. Defaults to 8191 bytes.
Options used by the sendfile function and callbacks.
+Allows configuring the chunk size, in bytes. Defaults to 8191 bytes.
-Listening socket. -
--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.
-Socket for this connection. -
--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.
-Socket opened with listen/1 or accept/2. -
-Close the given socket.
-Socket opened with listen/1 or accept/2. -
--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.
-Transport options. -
--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.
-Tuple names. -
-Return the atoms used to identify messages sent in active mode.
-Transport module name. -
-Return the name of the transport.
-Socket for this connection. -
--IP of the remote endpoint. -
--Port of the remote endpoint. -
-Return the IP and port of the remote endpoint.
-Socket for this connection. -
--Requested length. -
--Receive timeout. -
--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.
-Socket for this connection. -
--Data to be sent. -
-Send data to the given socket.
Alias of ranch_transport:sendfile/5
.
Alias of ranch_transport:sendfile/5
.
-Socket for this connection. -
--Filename or file descriptor for the file to be sent. -
--Begin sending at this position in the file. -
--Send this many bytes. -
--This many bytes were sent. -
--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.
-Socket for this connection. -
--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.
-Socket for this connection. -
--Which side(s) of the socket to close. -
-Immediately close the socket in one or two directions.
-Socket opened with listen/1 or accept/2. -
--IP of the local endpoint. -
--Port of the local endpoint. -
-Return the IP and port of the local endpoint.
Listening socket.
+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.
Socket for this connection.
+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.
+Socket opened with listen/1 or accept/2.
+Close the given socket.
+Socket opened with listen/1 or accept/2.
+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.
+Transport options.
+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.
+Tuple names.
+Return the atoms used to identify messages sent in active mode.
+Transport module name.
+Return the name of the transport.
+Socket for this connection.
+IP of the remote endpoint.
+Port of the remote endpoint.
+Return the IP and port of the remote endpoint.
+Socket for this connection.
+Requested length.
+Receive timeout.
+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.
Socket for this connection.
+Data to be sent.
+Send data to the given socket.
+Alias of ranch_transport:sendfile/5
.
Alias of ranch_transport:sendfile/5
.
Socket for this connection.
+Filename or file descriptor for the file to be sent.
+Begin sending at this position in the file.
+Send this many bytes.
+This many bytes were sent.
+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.
Socket for this connection.
+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.
+Socket for this connection.
+Which side(s) of the socket to close.
+Immediately close the socket in one or two directions.
+Socket opened with listen/1 or accept/2.
+IP of the local endpoint.
+Port of the local endpoint.
+Return the IP and port of the local endpoint.
-Transport module for this socket. -
--Socket for this connection. -
--Filename or file descriptor for the file to be sent. -
--Begin sending at this position in the file. -
--Send this many bytes. -
--This many bytes were sent. -
--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.
Transport module for this socket.
+Socket for this connection.
+Filename or file descriptor for the file to be sent.
+Begin sending at this position in the file.
+Send this many bytes.
+This many bytes were sent.
+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.
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.
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.
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.
-Introduction -
+-Listeners -
+-Transports -
+-Protocols -
+-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.
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.
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.
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.
{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 --> +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.
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.
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.
Ranch uses Semantic Versioning 2.0.0
Ranch uses Semantic Versioning 2.0.0
+ @@ -142,6 +126,8 @@ modifications but there is no guarantee that it will work as expected. +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.
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:
+-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.
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.
{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:
$ 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.
$ 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.+
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.
ranch:stop_listener(tcp_echo).
ranch:stop_listener(tcp_echo).+
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.
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
.
{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).+
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.
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.
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.
{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
.
{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.
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.
ranch:set_max_connections(tcp_echo, MaxConns).
The change will occur immediately.
ranch:set_max_connections(tcp_echo, MaxConns).+
The change will occur immediately.
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.
{ok, _} = ranch:start_listener(tcp_echo, - ranch_tcp, [{port, 5555}, {num_acceptors, 42}], - echo_protocol, [] -).
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.
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.
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.
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.
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
.
Opts = ranch:get_protocol_options(tcp_echo).
Opts = ranch:get_protocol_options(tcp_echo).+
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.
ranch:info().
The ranch:procs/2
function will return all acceptor or listener
-processes for a given listener.
ranch:procs(tcp_echo, acceptors).
ranch:procs(tcp_echo, connections).
ranch:procs(tcp_echo, connections).+ + @@ -479,6 +325,8 @@ http://www.gnu.org/software/src-highlite --> +
There are three kinds of protocols:
-Text protocols -
+There are three kinds of 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.
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.
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}
.
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.
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.
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.
<< 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. +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.
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.
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/
.
-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.+
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.
-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.
Check the tcp_reverse
example for a complete example.
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
.
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.
+-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.
You can optionally save the certificate for later use, for example to extract the IssuerID
information as will be detailed later on.
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.
{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.
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.
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.
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.
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.
The TCP transport is a thin wrapper around gen_tcp
.
The TCP transport is a thin wrapper around gen_tcp
.
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.
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:
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.
{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.
{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.
{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.
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:
{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
:
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:
{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).+
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.
ranch_ssl
for an example.<
+ -ranch(7) -
+-ranch(3) -
+-ranch_ssl(3) -
+-ranch_tcp(3) -
+ranch - socket acceptor pool
ranch - socket acceptor pool
The ranch
module provides functions for starting and
-manipulating Ranch listeners.
The ranch
module provides functions for starting and manipulating Ranch listeners.
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.
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() = {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.
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.
+Unique name used to refer to a listener.
None of the options are required.
- Maximum allowed time for the ranch:accept_ack/1
call to finish.
-
- Type of process that will handle the connection. -
-
- Maximum number of active connections. Soft limit. Using infinity
will disable the limit entirely.
-
- Number of processes that accept connections. -
-- Maximum allowed time for children to stop on listener shutdown. -
-
- Listening socket opened externally to be used instead of calling Transport:listen/1
.
-
None of the options are required.
+Maximum allowed time for the ranch:accept_ack/1
call to finish.
Type of process that will handle the connection.
+Maximum number of active connections. Soft limit. Using infinity
will disable the limit entirely.
Number of processes that accept connections.
+Maximum allowed time for children to stop on listener shutdown.
+Listening socket opened externally to be used instead of calling Transport:listen/1
.
-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.
-Listener name. -
--Number of acceptor processes. -
--Transport module. -
--Transport options. -
--Protocol module. -
--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.
-Listener name. -
--IP of the interface used by this listener. -
--Port number used by this listener. -
-Return the IP address and port for the given listener.
-Listener name. -
--Current maximum number of connections. -
-Return the max number of connections allowed for the given listener.
-Listener name. -
--Port number used by this listener. -
-Return the port for the given listener.
-Listener name. -
--Current protocol options. -
-Return the protocol options set for the given listener.
-Listener name. -
--Information key. -
--Information value. -
-Return detailed information about all Ranch listeners.
The following keys are defined:
-Pid of the listener’s top-level supervisor. -
--Interface Ranch listens on. -
--Port number Ranch listens on. -
--Number of acceptor processes. -
--Maximum number of connections. -
--Number of active connections. -
--Number of connections, including those removed from the count. -
--Transport module. -
--Transport options. -
--Protocol module. -
--Protocol options. -
--Listener name. -
-Return all acceptor or connection processes for one listener.
-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.
-Listener name. -
--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.
-Listener name. -
--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.
-Listener name. -
--Number of acceptor processes. -
--Transport module. -
--Transport options. -
--Protocol module. -
--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.
-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.
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.
+Listener name.
+Number of acceptor processes.
+Transport module.
+Transport options.
+Protocol module.
+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.
+Listener name.
+IP of the interface used by this listener.
+Port number used by this listener.
+Return the IP address and port for the given listener.
+Listener name.
+Current maximum number of connections.
+Return the max number of connections allowed for the given listener.
+Listener name.
+Port number used by this listener.
+Return the port for the given listener.
+Listener name.
+Current protocol options.
+Return the protocol options set for the given listener.
+Listener name.
+Information key.
+Information value.
+Return detailed information about all Ranch listeners.
+The following keys are defined:
+Pid of the listener's top-level supervisor.
+Interface Ranch listens on.
+Port number Ranch listens on.
+Number of acceptor processes.
+Maximum number of connections.
+Number of active connections.
+Number of connections, including those removed from the count.
+Transport module.
+Transport options.
+Protocol module.
+Protocol options.
+Listener name.
+Return all acceptor or connection processes for one listener.
+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.
+Listener name.
+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.
+Listener name.
+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.
+Listener name.
+Number of acceptor processes.
+Transport module.
+Transport options.
+Protocol module.
+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.
+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. +ranch - Socket acceptor pool for TCP protocols.
ranch - Socket acceptor pool for TCP protocols.
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.
The ranch
application defines one application environment
-configuration parameter.
- When enabled, Ranch will start eprof
profiling automatically.
-
The ranch
application defines one application environment configuration parameter.
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.
ranch_protocol - behaviour for protocol modules
ranch_protocol - behaviour for protocol modules
The ranch_protocol
behaviour defines the interface used
-by Ranch protocols.
The ranch_protocol
behaviour defines the interface used by Ranch protocols.
None.
None.
-Listener name. -
+Listener name.
-Socket for this connection. -
+Socket for this connection.
-Transport module for this socket. -
+Transport module for this socket.
-Protocol options. -
+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. +ranch_ssl - SSL transport module
ranch_ssl - SSL transport module
The ranch_ssl
module implements an SSL Ranch transport.
The ranch_ssl
module implements an SSL Ranch transport.
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.
Listen options.
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.
+Listen options.
+List of listen options.
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.
- Perform Application-Layer Protocol Negotiation with the given list of preferred protocols. -
-- Change the BEAST mitigation strategy for SSL-3.0 and TLS-1.0 to interoperate with legacy software. -
-- Path to PEM encoded trusted certificates file used to verify peer certificates. -
-- List of DER encoded trusted certificates. -
-- DER encoded user certificate. -
-- Path to the PEM encoded user certificate file. May also contain the private key. -
-- List of ciphers that clients are allowed to use. -
-- Whether to allow client-initiated renegotiation. -
-- Customize the module used to cache Certificate Revocation Lists. -
-- Whether to perform CRL check on all certificates in the chain during validation. -
-- Maximum of intermediate certificates allowed in the certification path. -
-- DER encoded Diffie-Hellman parameters. -
-- Path to the PEM encoded Diffie-Hellman parameters file. -
-- Whether to refuse the connection if the client sends an empty certificate. -
-- Time in ms after which SSL socket processes go into hibernation to reduce memory usage. -
-- If true, use the server’s preference for cipher selection. If false, use the client’s preference. -
-- DER encoded user private key. -
-- Path to the PEM encoded private key file, if different than the certfile. -
-- If false, error reports will not be displayed. -
-- List of protocols to send to the client if it supports the Next Protocol extension. -
-- Whether to enable TCP_NODELAY. -
-- Allow disabling the block cipher padding check for TLS-1.0 to be able to interoperate with legacy software. -
-- Claim an intermediate CA in the chain as trusted. -
-- Password to the private key file, if password protected. -
-- Provide the given PSK identity hint to the client during the handshake. -
-- Custom policy to decide whether a session should be reused. -
-- Whether to allow session reuse. -
-- Whether to reject renegotiation attempts that do not conform to RFC5746. -
-- The TLS signature algorithm extension may be used, from TLS 1.2, to negotiate which signature algorithm to use during the TLS handshake. -
-- Function called when the client requests a host using Server Name Indication. Returns options to apply. -
-- Options to apply for the host that matches what the client requested with Server Name Indication. -
-- Function called to determine the shared secret when using PSK, or provide parameters when using SRP. -
-- Accept clients that send hello messages in SSL-2.0 format while offering supported SSL/TLS versions. -
-
- Use verify_peer
to request a certificate from the client.
-
- Custom policy to decide whether a client certificate is valid. -
-- 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.
+Perform Application-Layer Protocol Negotiation with the given list of preferred protocols.
+Change the BEAST mitigation strategy for SSL-3.0 and TLS-1.0 to interoperate with legacy software.
+Path to PEM encoded trusted certificates file used to verify peer certificates.
+List of DER encoded trusted certificates.
+DER encoded user certificate.
+Path to the PEM encoded user certificate file. May also contain the private key.
+List of ciphers that clients are allowed to use.
+Whether to allow client-initiated renegotiation.
+Customize the module used to cache Certificate Revocation Lists.
+Whether to perform CRL check on all certificates in the chain during validation.
+Maximum of intermediate certificates allowed in the certification path.
+DER encoded Diffie-Hellman parameters.
+Path to the PEM encoded Diffie-Hellman parameters file.
+Whether to refuse the connection if the client sends an empty certificate.
+Time in ms after which SSL socket processes go into hibernation to reduce memory usage.
+If true, use the server's preference for cipher selection. If false, use the client's preference.
+DER encoded user private key.
+Path to the PEM encoded private key file, if different than the certfile.
+If false, error reports will not be displayed.
+List of protocols to send to the client if it supports the Next Protocol extension.
+Whether to enable TCP_NODELAY.
+Allow disabling the block cipher padding check for TLS-1.0 to be able to interoperate with legacy software.
+Claim an intermediate CA in the chain as trusted.
+Password to the private key file, if password protected.
+Provide the given PSK identity hint to the client during the handshake.
+Custom policy to decide whether a session should be reused.
+Whether to allow session reuse.
+Whether to reject renegotiation attempts that do not conform to RFC5746.
+The TLS signature algorithm extension may be used, from TLS 1.2, to negotiate which signature algorithm to use during the TLS handshake.
+Function called when the client requests a host using Server Name Indication. Returns options to apply.
+Options to apply for the host that matches what the client requested with Server Name Indication.
+Function called to determine the shared secret when using PSK, or provide parameters when using SRP.
+Accept clients that send hello messages in SSL-2.0 format while offering supported SSL/TLS versions.
+Use verify_peer
to request a certificate from the client.
Custom policy to decide whether a client certificate is valid.
+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.
None.
None.
+ @@ -475,6 +264,8 @@ greater control over the client certificate validation. +ranch_tcp - TCP transport module
ranch_tcp - TCP transport module
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.
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.
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.
+List of listen options.
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.
- 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.
Max length of the queue of pending connections.
- Size of the buffer used by the Erlang driver. Default is system-dependent. -
+Size of the buffer used by the Erlang driver. Default is system-dependent.
- Always queue packets before sending, to send fewer, larger packets over the network. -
+Always queue packets before sending, to send fewer, larger packets over the network.
- Don’t send via a gateway, only send to directly connected hosts. -
+Don't send via a gateway, only send to directly connected hosts.
- Disable to allow sending data after a close has been detected. -
+Disable to allow sending data after a close has been detected.
- File descriptor of the socket, if it was opened externally. -
+File descriptor of the socket, if it was opened externally.
- Limit in the amount of data in the socket message queue before the socket queue becomes busy. -
+Limit in the amount of data in the socket message queue before the socket queue becomes busy.
- Limit in the amount of data in the ERTS socket implementation’s queue before the socket becomes busy. -
+Limit in the amount of data in the ERTS socket implementation's queue before the socket becomes busy.
- Set up the socket for IPv4. -
+Set up the socket for IPv4.
- Set up the socket for IPv6. -
+Set up the socket for IPv6.
- Interface to listen on. Listen on all interfaces by default. -
+Interface to listen on. Listen on all interfaces by default.
- Listen on IPv4 and IPv6 (false) or only on IPv6 (true). Use with inet6. -
+Listen on IPv4 and IPv6 (false) or only on IPv6 (true). Use with inet6.
- Enable sending of keep-alive messages. -
+Enable sending of keep-alive messages.
- Whether to wait and how long to flush data sent before closing the socket. -
+Whether to wait and how long to flush data sent before closing the socket.
- Amount of data in the socket message queue before the socket queue leaves busy state. -
+Amount of data in the socket message queue before the socket queue leaves busy state.
- Amount of data in the ERTS socket implementation’s queue before the socket leaves busy state. -
+Amount of data in the ERTS socket implementation's queue before the socket leaves busy state.
- Whether to enable TCP_NODELAY. -
+Whether to enable TCP_NODELAY.
- TCP port number to listen on. 0 means a random port will be used. -
+TCP port number to listen on. 0 means a random port will be used.
- Priority value for all packets to be sent by this socket. -
+Priority value for all packets to be sent by this socket.
- Minimum size of the socket’s receive buffer. Default is system-dependent. -
+Minimum size of the socket's receive buffer. Default is system-dependent.
- How long the send call may wait for confirmation before returning. -
+How long the send call may wait for confirmation before returning.
- Whether to close the socket when the confirmation wasn’t received. -
+Whether to close the socket when the confirmation wasn't received.
- Minimum size of the socket’s send buffer. Default is system-dependent. -
+Minimum size of the socket's send buffer. Default is system-dependent.
- Value for the IP_TOS IP level option. Use with caution. -
+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.
None.
None.
+ @@ -373,6 +217,8 @@ portable. Use with caution. +ranch_transport - behaviour for transport modules
ranch_transport - behaviour for transport modules
The ranch_transport
behaviour defines the interface used
-by Ranch transports.
The ranch_transport
behaviour defines the interface used by Ranch transports.
Options used by the sendfile function and callbacks.
Allows configuring the chunk size, in bytes. Defaults to 8191 bytes.
Options used by the sendfile function and callbacks.
+Allows configuring the chunk size, in bytes. Defaults to 8191 bytes.
-Listening socket. -
--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.
-Socket for this connection. -
--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.
-Socket opened with listen/1 or accept/2. -
-Close the given socket.
-Socket opened with listen/1 or accept/2. -
--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.
-Transport options. -
--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.
-Tuple names. -
-Return the atoms used to identify messages sent in active mode.
-Transport module name. -
-Return the name of the transport.
-Socket for this connection. -
--IP of the remote endpoint. -
--Port of the remote endpoint. -
-Return the IP and port of the remote endpoint.
-Socket for this connection. -
--Requested length. -
--Receive timeout. -
--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.
-Socket for this connection. -
--Data to be sent. -
-Send data to the given socket.
Alias of ranch_transport:sendfile/5
.
Alias of ranch_transport:sendfile/5
.
-Socket for this connection. -
--Filename or file descriptor for the file to be sent. -
--Begin sending at this position in the file. -
--Send this many bytes. -
--This many bytes were sent. -
--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.
-Socket for this connection. -
--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.
-Socket for this connection. -
--Which side(s) of the socket to close. -
-Immediately close the socket in one or two directions.
-Socket opened with listen/1 or accept/2. -
--IP of the local endpoint. -
--Port of the local endpoint. -
-Return the IP and port of the local endpoint.
Listening socket.
+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.
Socket for this connection.
+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.
+Socket opened with listen/1 or accept/2.
+Close the given socket.
+Socket opened with listen/1 or accept/2.
+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.
+Transport options.
+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.
+Tuple names.
+Return the atoms used to identify messages sent in active mode.
+Transport module name.
+Return the name of the transport.
+Socket for this connection.
+IP of the remote endpoint.
+Port of the remote endpoint.
+Return the IP and port of the remote endpoint.
+Socket for this connection.
+Requested length.
+Receive timeout.
+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.
Socket for this connection.
+Data to be sent.
+Send data to the given socket.
+Alias of ranch_transport:sendfile/5
.
Alias of ranch_transport:sendfile/5
.
Socket for this connection.
+Filename or file descriptor for the file to be sent.
+Begin sending at this position in the file.
+Send this many bytes.
+This many bytes were sent.
+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.
Socket for this connection.
+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.
+Socket for this connection.
+Which side(s) of the socket to close.
+Immediately close the socket in one or two directions.
+Socket opened with listen/1 or accept/2.
+IP of the local endpoint.
+Port of the local endpoint.
+Return the IP and port of the local endpoint.
-Transport module for this socket. -
--Socket for this connection. -
--Filename or file descriptor for the file to be sent. -
--Begin sending at this position in the file. -
--Send this many bytes. -
--This many bytes were sent. -
--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.
Transport module for this socket.
+Socket for this connection.
+Filename or file descriptor for the file to be sent.
+Begin sending at this position in the file.
+Send this many bytes.
+This many bytes were sent.
+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.
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.
+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.
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.
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.
+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.
+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.
+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.
+{raw, 6, 9, << 30:32/native >>}+
It means go on layer 6, turn on option 9 with the given integer parameter.
+ + + + + + + + + + + + + + + + +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.
+It is assumed the developer already knows Erlang and has some experience with socket programming and TCP protocols.
+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 uses Semantic Versioning 2.0.0
+ + + + + + + + + + + + + + + + +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.
+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:
+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.
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.
{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:
$ 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.
$ telnet localhost 5555 +Trying 127.0.0.1... +Connected to localhost. +Escape character is '^]'. +Hello! +Hello! +It works! +It works! +^] + +telnet> quit +Connection closed.+
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.
ranch:stop_listener(tcp_echo).+
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.
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
.
{ok, _} = ranch:start_listener(tcp_echo, + ranch_tcp, [{port, 0}], + echo_protocol, [] +). +Port = ranch:get_port(tcp_echo).+
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.
+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.
+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.
{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
.
{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.
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.
ranch:set_max_connections(tcp_echo, MaxConns).+
The change will occur immediately.
+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.
+{ok, _} = ranch:start_listener(tcp_echo, + ranch_tcp, [{port, 5555}, {num_acceptors, 42}], + echo_protocol, [] +).+
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.
+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 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.
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
.
Opts = ranch:get_protocol_options(tcp_echo).+
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.
ranch:info().+
The ranch:procs/2
function will return all acceptor or listener processes for a given listener.
ranch:procs(tcp_echo, acceptors).+
ranch:procs(tcp_echo, connections).+
There are three kinds of 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.
+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}
.
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.
+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.
+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.
+<< 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.
+ + + + + + + + + + + + + + + + +A protocol handler starts a connection process and defines the protocol logic executed in this process.
+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.
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/
.
-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.+
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.
-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.
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
.
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.
+You can optionally save the certificate for later use, for example to extract the IssuerID
information as will be detailed later on.
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.
{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.
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.
+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.
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.
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.
+The TCP transport is a thin wrapper around gen_tcp
.
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.
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:
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.
+{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.
{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.
{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.
+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:
{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
:
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:
+{ok, RawFile} = file:open(Filename, [raw, read, binary]), +{ok, SentBytes} = Transport:sendfile(Socket, RawFile, Offset, Bytes, Opts).+
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 - socket acceptor pool
+The ranch
module provides functions for starting and manipulating Ranch listeners.
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() = {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.
+Unique name used to refer to a listener.
+None of the options are required.
+Maximum allowed time for the ranch:accept_ack/1
call to finish.
Type of process that will handle the connection.
+Maximum number of active connections. Soft limit. Using infinity
will disable the limit entirely.
Number of processes that accept connections.
+Maximum allowed time for children to stop on listener shutdown.
+Listening socket opened externally to be used instead of calling Transport:listen/1
.
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.
+Listener name.
+Number of acceptor processes.
+Transport module.
+Transport options.
+Protocol module.
+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.
+Listener name.
+IP of the interface used by this listener.
+Port number used by this listener.
+Return the IP address and port for the given listener.
+Listener name.
+Current maximum number of connections.
+Return the max number of connections allowed for the given listener.
+Listener name.
+Port number used by this listener.
+Return the port for the given listener.
+Listener name.
+Current protocol options.
+Return the protocol options set for the given listener.
+Listener name.
+Information key.
+Information value.
+Return detailed information about all Ranch listeners.
+The following keys are defined:
+Pid of the listener's top-level supervisor.
+Interface Ranch listens on.
+Port number Ranch listens on.
+Number of acceptor processes.
+Maximum number of connections.
+Number of active connections.
+Number of connections, including those removed from the count.
+Transport module.
+Transport options.
+Protocol module.
+Protocol options.
+Listener name.
+Return all acceptor or connection processes for one listener.
+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.
+Listener name.
+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.
+Listener name.
+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.
+Listener name.
+Number of acceptor processes.
+Transport module.
+Transport options.
+Protocol module.
+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.
+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 - Socket acceptor pool for TCP protocols.
+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 defines one application environment configuration parameter.
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_protocol - behaviour for protocol modules
+The ranch_protocol
behaviour defines the interface used by Ranch protocols.
None.
+Listener name.
+Socket for this connection.
+Transport module for this socket.
+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_ssl - SSL transport module
+The ranch_ssl
module implements an SSL Ranch transport.
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.
+Listen options.
+List of listen options.
+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.
+Perform Application-Layer Protocol Negotiation with the given list of preferred protocols.
+Change the BEAST mitigation strategy for SSL-3.0 and TLS-1.0 to interoperate with legacy software.
+Path to PEM encoded trusted certificates file used to verify peer certificates.
+List of DER encoded trusted certificates.
+DER encoded user certificate.
+Path to the PEM encoded user certificate file. May also contain the private key.
+List of ciphers that clients are allowed to use.
+Whether to allow client-initiated renegotiation.
+Customize the module used to cache Certificate Revocation Lists.
+Whether to perform CRL check on all certificates in the chain during validation.
+Maximum of intermediate certificates allowed in the certification path.
+DER encoded Diffie-Hellman parameters.
+Path to the PEM encoded Diffie-Hellman parameters file.
+Whether to refuse the connection if the client sends an empty certificate.
+Time in ms after which SSL socket processes go into hibernation to reduce memory usage.
+If true, use the server's preference for cipher selection. If false, use the client's preference.
+DER encoded user private key.
+Path to the PEM encoded private key file, if different than the certfile.
+If false, error reports will not be displayed.
+List of protocols to send to the client if it supports the Next Protocol extension.
+Whether to enable TCP_NODELAY.
+Allow disabling the block cipher padding check for TLS-1.0 to be able to interoperate with legacy software.
+Claim an intermediate CA in the chain as trusted.
+Password to the private key file, if password protected.
+Provide the given PSK identity hint to the client during the handshake.
+Custom policy to decide whether a session should be reused.
+Whether to allow session reuse.
+Whether to reject renegotiation attempts that do not conform to RFC5746.
+The TLS signature algorithm extension may be used, from TLS 1.2, to negotiate which signature algorithm to use during the TLS handshake.
+Function called when the client requests a host using Server Name Indication. Returns options to apply.
+Options to apply for the host that matches what the client requested with Server Name Indication.
+Function called to determine the shared secret when using PSK, or provide parameters when using SRP.
+Accept clients that send hello messages in SSL-2.0 format while offering supported SSL/TLS versions.
+Use verify_peer
to request a certificate from the client.
Custom policy to decide whether a client certificate is valid.
+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.
None.
+ + + + + + +ranch_tcp - TCP transport module
+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.
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.
+List of listen options.
+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.
Max length of the queue of pending connections.
+Size of the buffer used by the Erlang driver. Default is system-dependent.
+Always queue packets before sending, to send fewer, larger packets over the network.
+Don't send via a gateway, only send to directly connected hosts.
+Disable to allow sending data after a close has been detected.
+File descriptor of the socket, if it was opened externally.
+Limit in the amount of data in the socket message queue before the socket queue becomes busy.
+Limit in the amount of data in the ERTS socket implementation's queue before the socket becomes busy.
+Set up the socket for IPv4.
+Set up the socket for IPv6.
+Interface to listen on. Listen on all interfaces by default.
+Listen on IPv4 and IPv6 (false) or only on IPv6 (true). Use with inet6.
+Enable sending of keep-alive messages.
+Whether to wait and how long to flush data sent before closing the socket.
+Amount of data in the socket message queue before the socket queue leaves busy state.
+Amount of data in the ERTS socket implementation's queue before the socket leaves busy state.
+Whether to enable TCP_NODELAY.
+TCP port number to listen on. 0 means a random port will be used.
+Priority value for all packets to be sent by this socket.
+Minimum size of the socket's receive buffer. Default is system-dependent.
+How long the send call may wait for confirmation before returning.
+Whether to close the socket when the confirmation wasn't received.
+Minimum size of the socket's send buffer. Default is system-dependent.
+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.
None.
+ + + + + + +ranch_transport - behaviour for transport modules
+The ranch_transport
behaviour defines the interface used by Ranch transports.
Options used by the sendfile function and callbacks.
+Allows configuring the chunk size, in bytes. Defaults to 8191 bytes.
+Listening socket.
+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.
Socket for this connection.
+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.
+Socket opened with listen/1 or accept/2.
+Close the given socket.
+Socket opened with listen/1 or accept/2.
+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.
+Transport options.
+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.
+Tuple names.
+Return the atoms used to identify messages sent in active mode.
+Transport module name.
+Return the name of the transport.
+Socket for this connection.
+IP of the remote endpoint.
+Port of the remote endpoint.
+Return the IP and port of the remote endpoint.
+Socket for this connection.
+Requested length.
+Receive timeout.
+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.
Socket for this connection.
+Data to be sent.
+Send data to the given socket.
+Alias of ranch_transport:sendfile/5
.
Alias of ranch_transport:sendfile/5
.
Socket for this connection.
+Filename or file descriptor for the file to be sent.
+Begin sending at this position in the file.
+Send this many bytes.
+This many bytes were sent.
+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.
Socket for this connection.
+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.
+Socket for this connection.
+Socket option names.
+Socket options.
+Get options for the given socket.
+Socket for this connection.
+Socket statistics.
+Get statistics for the given socket.
+Socket for this connection.
+Socket statistic names.
+Socket statistics.
+Get statistics for the given socket.
+Socket for this connection.
+Which side(s) of the socket to close.
+Immediately close the socket in one or two directions.
+Socket opened with listen/1 or accept/2.
+IP of the local endpoint.
+Port of the local endpoint.
+Return the IP and port of the local endpoint.
+Transport module for this socket.
+Socket for this connection.
+Filename or file descriptor for the file to be sent.
+Begin sending at this position in the file.
+Send this many bytes.
+This many bytes were sent.
+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.
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 @@Donate to Loïc Hoguin because his work on Cowboy -and Erlang.mk is fantastic:
Donate to Loïc Hoguin because his work on Cowboy and Erlang.mk is fantastic:
Donate to Loïc Hoguin because his work on Cowboy -and Erlang.mk is fantastic:
Donate to Loïc Hoguin because his work on Cowboy and Erlang.mk is fantastic:
Feeling generous? Love reading?
-Crowdfund my salary
-or buy The Erlanger Playbook
Feeling generous? Love reading?
Crowdfund my salary or buy The Erlanger Playbook
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.
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:
+-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.
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:
+-the power to make me maintain older versions of my projects - (as long as they are sponsoring) -
+-priority when adding features or fixing bugs -
+-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.
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.
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. -Donate to Loïc Hoguin because his work on Cowboy -and Erlang.mk is fantastic:
Donate to Loïc Hoguin because his work on Cowboy and Erlang.mk is fantastic:
Feeling generous? Love reading?
-Crowdfund my salary
-or buy The Erlanger Playbook
Feeling generous? Love reading?
Crowdfund my salary or buy The Erlanger Playbook
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?
+ +