summaryrefslogblamecommitdiffstats
path: root/docs/en/cowboy/1.0/guide/req/index.html
blob: 7005d09b0288b2c9be0da77ba2d960d69bc708f5 (plain) (tree)












































                                                                                                                                    
                                                                                                                                            








                                                                                                                                                                                      
                                                                                                                













































































































































































































































































































































                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Nine Nines Support: Cowboy User Guide</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Change them or set them up as you like -->
    <meta name="description" content="">
    <meta name="author" content="(Soft10) Pol Cámara">

    <!-- Stylesheets -->    
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700,400italic' rel='stylesheet' type='text/css'>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="/css/99s.css" rel="stylesheet">
<!--    <link href="js/google-code-prettify/prettify.css" rel="stylesheet"> -->
    <link href="/css/sh99s.css"  rel="stylesheet"/>

    <!-- Enables html5 support on older browsers, other js is placed at the end of the page to speed up loading -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->

    <link rel="shortcut icon" href="/img/ico/favicon.ico">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="/img/ico/apple-touch-icon-114.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="/img/ico/apple-touch-icon-72.png">
    <link rel="apple-touch-icon-precomposed" href="/img/ico/apple-touch-icon-57.png">
	<link rel="alternate" href="/feeds/atom.xml" type="application/atom+xml" title="Nine Nines Atom Feed">
  </head>

  <body class="big_text docs">
    <header id="page-head">
      <div id="topbar" class="container">
          <div class="row">
            <div class="span2">
              <h1 id="logo"><a href="/" title="99s">99s</a></h1>
            </div>
            <div class="span10">
              <!-- Top navigation and social icons-->
              <div id="side-header">
                <nav>
                  <ul>
					<li><a title="Erlang training" href="/training">Training</a></li>
                    <li><a title="Technical publications" href="/articles">Articles</a></li>
					<li><a title="Our talks" href="/talks">Talks</a></li>
					<li class="active"><a title="Our services" href="/support">Pricing &amp; Sponsoring</a></li>
					<li><a title="Community support" href="https://ninenines.eu/archives/extend/">Mailing Lists</a></li>
                    <li><a title="Contact us" href="mailto:[email protected]">Contact</a></li>
                  </ul>
                </nav> 
                <ul id="social">
                  <li>
                    <a href="https://github.com/ninenines" title="Check our Github repositories"><img src="/img/ico_github.png" data-hover="/img/ico_github_alt.png" alt="Github"></a>
                  </li>
                  <li class="dropdown" id="twitter-links">
                    <a href="#twitter-links" class="dropdown-toggle" data-toggle="dropdown"  title="Follow us on Twitter">
                        <img src="/img/ico_microblog.png" data-hover="/img/ico_microblog_alt.png" alt="Twitter">
                    </a>                 
                    <ul class="dropdown-menu">
                      <li><a title="Visit Loïc Hoguin's Twitter Account" href="http://twitter.com/lhoguin">@lhoguin</a></li>
                      <!-- <li class="divider"></li>
                      <li><a title="Visit our official Twitter account" href="#">@99s</a></li> -->
                    </ul>
                  </li>
                  <!-- <li>
                    <a href="/css/" title="Add us on Linkedin"><img src="/img/ico_linkedin.png" data-hover="img/ico_linkedin_alt.png" alt="Linkedin"></a>
                  </li> -->
                </ul>
              </div>
            </div>
          </div>
      </div>


    </header>


<div id="contents" class="two_col">
<div class="container">
<div class="row">
<div id="docs" class="span9 maincol">

<h1 class="lined-header"><span>The Req object</span></h1>

<p>The Req object is this variable that you will use to obtain information about a request, read the body of the request and send a response.</p>

<h2 id="a_special_variable">A special variable</h2>

<p>While we call it an "object", it is not an object in the OOP sense of the term. In fact it is completely opaque to you and the only way you can perform operations using it is by calling the functions from the <code>cowboy_req</code> module.</p>

<p>Almost all the calls to the <code>cowboy_req</code> module will return an updated request object. Just like you would keep the updated <code>State</code> variable in a gen_server, you MUST keep the updated <code>Req</code> variable in a Cowboy handler. Cowboy will use this object to know whether a response has been sent when the handler has finished executing.</p>

<p>The Req object allows accessing both immutable and mutable state. This means that calling some of the functions twice will not produce the same result. For example, when streaming the request body, the function will return the body by chunks, one at a time, until there is none left.</p>

<p>It also caches the result of operations performed on the immutable state. That means that some calls will give a result much faster when called many times.</p>

<h2 id="overview_of_the_cowboy_req_interface">Overview of the cowboy_req interface</h2>

<p>The <code>cowboy_req</code> interface is divided in four groups of functions, each having a well defined return type signature common to the entire group.</p>

<p>The first group, access functions, will always return <code>{Value, Req}</code>. The group includes all the following functions: <code>binding/{2,3}</code>, <code>bindings/1</code>, <code>body_length/1</code>, <code>cookie/{2,3}</code>, <code>cookies/1</code>, <code>header/{2,3}</code>, <code>headers/1</code>, <code>host/1</code>, <code>host_info/1</code>, <code>host_url/1</code>, <code>meta/{2,3}</code>, <code>method/1</code>, <code>path/1</code>, <code>path_info/1</code>, <code>peer/1</code>, <code>port/1</code>, <code>qs/1</code>, <code>qs_val/{2,3}</code>, <code>qs_vals/1</code>, <code>url/1</code>, <code>version/1</code>.</p>

<p>The second group, question functions, will always return a <code>boolean()</code>. The group includes the following three functions: <code>has_body/1</code>, <code>has_resp_body/1</code>, <code>has_resp_header/2</code>.</p>

<p>The third group contains the functions that manipulate the socket or perform operations that may legitimately fail. They may return <code>{Result, Req}</code>, <code>{Result, Value, Req}</code> or <code>{error, atom()}</code>. This includes the following functions: <code>body/{1,2}</code>, <code>body_qs/{1,2}</code>, <code>chunked_reply/{2,3}</code>, <code>parse_header/{2,3}</code>, <code>part/{1,2}</code>, <code>part_body/{1,2}</code> and <code>reply/{2,3,4}</code>. Finally, the group also includes the <code>chunk/2</code> and <code>continue/1</code> functions which always return <code>ok</code>.</p>

<p>The final group modifies the Req object state without performing any immediate operations. As these functions can't fail, they always return a new <code>Req</code> directly. This includes the following functions: <code>compact/1</code>, <code>delete_resp_header/2</code>, <code>set_meta/3</code>, <code>set_resp_body/2</code>, <code>set_resp_body_fun/{2,3}</code>, <code>set_resp_cookie/4</code>, <code>set_resp_header/3</code>.</p>

<p>This chapter covers most of the first group, plus a few other functions. The next few chapters cover cookies handling, reading the request body and sending a response.</p>

<h2 id="request">Request</h2>

<p>When a client performs a request, it first sends a few required values. They are sent differently depending on the protocol being used, but the intent is the same. They indicate to the server the type of action it wants to do and how to locate the resource to perform it on.</p>

<p>The method identifies the action. Standard methods include GET, HEAD, OPTIONS, PATCH, POST, PUT, DELETE. Method names are case sensitive.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{Method, Req2} = cowboy_req:method(Req).
]]></script>

<p>The host, port and path parts of the URL identify the resource being accessed. The host and port information may not be available if the client uses HTTP/1.0.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{Host, Req2} = cowboy_req:host(Req),
{Port, Req3} = cowboy_req:port(Req2),
{Path, Req4} = cowboy_req:path(Req3).
]]></script>

<p>The version used by the client can of course also be obtained.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{Version, Req2} = cowboy_req:version(Req).
]]></script>

<p>Do note however that clients claiming to implement one version of the protocol does not mean they implement it fully, or even properly.</p>

<h2 id="bindings">Bindings</h2>

<p>After routing the request, bindings are available. Bindings are these parts of the host or path that you chose to extract when defining the routes of your application.</p>

<p>You can fetch a single binding. The value will be <code>undefined</code> if the binding doesn't exist.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{Binding, Req2} = cowboy_req:binding(my_binding, Req).
]]></script>

<p>If you need a different value when the binding doesn't exist, you can change the default.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{Binding, Req2} = cowboy_req:binding(my_binding, Req, 42).
]]></script>

<p>You can also obtain all bindings in one call. They will be returned as a list of key/value tuples.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{AllBindings, Req2} = cowboy_req:bindings(Req).
]]></script>

<p>If you used <code>...</code> at the beginning of the route's pattern for the host, you can retrieve the matched part of the host. The value will be <code>undefined</code> otherwise.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{HostInfo, Req2} = cowboy_req:host_info(Req).
]]></script>

<p>Similarly, if you used <code>...</code> at the end of the route's pattern for the path, you can retrieve the matched part, or get <code>undefined</code> otherwise.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{PathInfo, Req2} = cowboy_req:path_info(Req).
]]></script>

<h2 id="query_string">Query string</h2>

<p>The query string can be obtained directly.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{Qs, Req2} = cowboy_req:qs(Req).
]]></script>

<p>You can also requests only one value.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{QsVal, Req2} = cowboy_req:qs_val(<<"lang">>, Req).
]]></script>

<p>If that value is optional, you can define a default to simplify your task.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{QsVal, Req2} = cowboy_req:qs_val(<<"lang">>, Req, <<"en">>).
]]></script>

<p>Finally, you can obtain all query string values.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{AllValues, Req2} = cowboy_req:qs_vals(Req).
]]></script>

<h2 id="request_url">Request URL</h2>

<p>You can reconstruct the full URL of the resource.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{URL, Req2} = cowboy_req:url(Req).
]]></script>

<p>You can also obtain only the base of the URL, excluding the path and query string.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{BaseURL, Req2} = cowboy_req:host_url(Req).
]]></script>

<h2 id="headers">Headers</h2>

<p>Cowboy allows you to obtain the header values as string, or parsed into a more meaningful representation.</p>

<p>This will get the string value of a header.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{HeaderVal, Req2} = cowboy_req:header(<<"content-type">>, Req).
]]></script>

<p>You can of course set a default in case the header is missing.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{HeaderVal, Req2}
    = cowboy_req:header(<<"content-type">>, Req, <<"text/plain">>).
]]></script>

<p>And also obtain all headers.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{AllHeaders, Req2} = cowboy_req:headers(Req).
]]></script>

<p>To parse the previous header, simply call <code>parse_header/{2,3}</code> where you would call <code>header/{2,3}</code> otherwise. Note that the return value changes and includes the result of the operation as the first element of the returned tuple. A successful parse returns <code>ok</code>.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{ok, ParsedVal, Req2} = cowboy_req:parse_header(<<"content-type">>, Req).
]]></script>

<p>When Cowboy doesn't know how to parse the given header, the result of the operation will be <code>undefined</code> and the string value will be returned instead.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{undefined, HeaderVal, Req2}
    = cowboy_req:parse_header(<<"unicorn-header">>, Req).
]]></script>

<p>When parsing fails, <code>{error, Reason}</code> is returned instead.</p>

<p>You can of course define a default value. Note that the default value you specify here is the parsed value you'd like to get by default.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{ok, ParsedVal, Req2}
    = cowboy_req:parse_header(<<"content-type">>, Req,
    {<<"text">>, <<"plain">>, []}).
]]></script>

<p>The list of known headers and default values is defined in the manual. Also note that the result of parsing is cached, so calling this function multiple times for the same values will not have a significant performance impact.</p>

<h2 id="meta">Meta</h2>

<p>Cowboy will sometimes associate some meta information with the request. Built-in meta values are listed in the manual for their respective modules.</p>

<p>This will get a meta value. The returned value will be <code>undefined</code> if it isn't defined.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{MetaVal, Req2} = cowboy_req:meta(websocket_version, Req).
]]></script>

<p>You can change the default value if needed.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{MetaVal, Req2} = cowboy_req:meta(websocket_version, Req, 13).
]]></script>

<p>You can also define your own meta values. The name must be an <code>atom()</code>.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
Req2 = cowboy_req:set_meta(the_answer, 42, Req).
]]></script>

<h2 id="peer">Peer</h2>

<p>You can obtain the peer address and port number. This is not necessarily the actual IP and port of the client, but rather the one of the machine that connected to the server.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
{{IP, Port}, Req2} = cowboy_req:peer(Req).
]]></script>

<h2 id="reducing_the_memory_footprint">Reducing the memory footprint</h2>

<p>When you are done reading information from the request object and know you are not going to access it anymore, for example when using long-polling or Websocket, you can use the <code>compact/1</code> function to remove most of the data from the request object and free memory.</p>

<script type="syntaxhighlighter" class="brush: erlang"><![CDATA[
Req2 = cowboy_req:compact(Req).
]]></script>

<p>You will still be able to send a reply if needed.</p>


<!-- a.code -->
</div>

<div class="span3 sidecol">
<div class="input-append">
<form id="form-search" class="form-search" action="#">
	<input id="input-search" type="text" placeholder="Function search" autocomplete="off" autofocus class="input-medium search-query span2">
	<button type="submit" class="btn btn-success">Go</button>
</form>
</div>

<h3 id="docs-nav">Navigation</h3>

<h3>See also</h3><ul><li><a href="/docs/en/cowboy/1.0/manual/">Function Reference</a></li><li><a href="/docs/en/cowboy/1.0/index.html">README</a></li></ul>

<h3>Version select</h3>
<ul>

	<li><a href="/docs/en/cowboy/1.0/guide/"><strong>1.0</strong></a></li>

	<li><a href="/docs/en/cowboy/HEAD/guide/"><strong>HEAD</strong></a></li>

</ul>

</div>
</div>
</div>
</div>


      <footer>
        <div class="container">
          <div class="row">
            <div class="span6">
              <p id="scroll-top"><a href="#">↑ Scroll to top</a></p>
              <nav>
                <ul>
                  <li><a href="mailto:[email protected]" title="Contact us">Contact us</a></li><li><a href="https://github.com/ninenines/ninenines.github.io" title="Github repository">Contribute to this site</a></li>
                </ul>
              </nav>
            </div>
            <div class="span6 credits">
               <p><img src="/img/footer_logo.png"></p>
               <p>Copyright &copy; Nine Nines 2012-2014</p>
            </div>
          </div>
        </div>
      </footer>

    <!-- Javascript -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="/js/bootstrap-carousel.js"></script>
    <script src="/js/bootstrap-dropdown.js"></script>
    <script src="/js/custom.js"></script>


<script type="text/javascript" src="/js/shCore.js"></script>
<script type="text/javascript" src="/js/shlang/shBrushBash.js"></script>
<script type="text/javascript" src="/js/shlang/shBrushErlang.js"></script>
<script type="text/javascript" src="/js/shlang/shBrushJScript.js"></script>
<script type="text/javascript" src="/js/shlang/shBrushPlain.js"></script>
<script type="text/javascript">SyntaxHighlighter.all();</script>

<script type="text/javascript" src="/js/fuse.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	var f;

	$.getJSON("/docs/db.json", function(data){
		f = new Fuse(data, {keys: ["n"], threshold: 0.3});
		$("<ul id=\"search-results\">").insertAfter("#form-search");
	});

	$("#input-search").keyup(function(e){if(f){if (e.which != 13 ){
		var results = f.search($(this).val());
		if (results.length == 0){
			$("#form-search").attr("action", "#");
		}else{
			$("#form-search").attr("action", results[0].l);
		}

		$("#search-results").empty();
		for (var i = 0; i < 10 && i < results.length; i++){
			$("<li><a href=\"" + results[i].l + "\">" + results[i].n + "</a></li>")
				.appendTo("#search-results");
		}
	}}});
});
</script>

  </body>
</html>