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

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.
27 lines
848 B
Erlang
27 lines
848 B
Erlang
%% 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}.
|