0
Fork 0
mirror of https://github.com/ninenines/cowboy.git synced 2025-07-14 20:30:23 +00:00

Add automatic ranged request handling for bytes units

Returning the atom auto instead of a callback informs Cowboy
that it needs to handle range requests automatically. This
changes the behavior so that the ProvideCallback function
is called and then Cowboy splits the data on its own and
sends the response without any other user involvement other
than defining the ranges_provided/2 callback.

This is a quick and dirty way to add range request support
to resources, and will be good enough for many cases including
for cowboy_static as it also works when the normal response
body is a sendfile tuple.
This commit is contained in:
Loïc Hoguin 2018-11-11 13:57:26 +01:00
parent d7b7580b39
commit dd0fbab6b7
No known key found for this signature in database
GPG key ID: 8A9DF795F6FED764
4 changed files with 357 additions and 24 deletions

View file

@ -0,0 +1,27 @@
%% This module defines the ranges_provided callback
%% which returns the auto option for bytes ranges
%% and the normal ProvideCallback that returns
%% something different depending on query string.
-module(ranges_provided_auto_h).
-export([init/2]).
-export([content_types_provided/2]).
-export([ranges_provided/2]).
-export([get_text_plain/2]).
init(Req, State) ->
{cowboy_rest, Req, State}.
content_types_provided(Req, State) ->
{[{{<<"text">>, <<"plain">>, []}, get_text_plain}], Req, State}.
ranges_provided(Req, State) ->
{[{<<"bytes">>, auto}], Req, State}.
get_text_plain(Req=#{qs := <<"data">>}, State) ->
{<<"This is ranged REST!">>, Req, State};
get_text_plain(Req=#{qs := <<"sendfile">>}, State) ->
Path = code:lib_dir(cowboy) ++ "/ebin/cowboy.app",
Size = filelib:file_size(Path),
{{sendfile, 0, Size, Path}, Req, State}.