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

rest_pastebin example: Add a constraint for lang parameter

This commit is contained in:
Loïc Hoguin 2019-09-05 18:05:44 +02:00
parent 094387a08f
commit d5814a59f4
No known key found for this signature in database
GPG key ID: 8A9DF795F6FED764

View file

@ -56,17 +56,25 @@ create_paste(Req, State) ->
paste_html(Req, index) -> paste_html(Req, index) ->
{read_file("index.html"), Req, index}; {read_file("index.html"), Req, index};
paste_html(Req, Paste) -> paste_html(Req, Paste) ->
#{lang := Lang} = cowboy_req:match_qs([{lang, [], plain}], Req), #{lang := Lang} = cowboy_req:match_qs([{lang, [fun lang_constraint/2], plain}], Req),
{format_html(Paste, Lang), Req, Paste}. {format_html(Paste, Lang), Req, Paste}.
paste_text(Req, index) -> paste_text(Req, index) ->
{read_file("index.txt"), Req, index}; {read_file("index.txt"), Req, index};
paste_text(Req, Paste) -> paste_text(Req, Paste) ->
#{lang := Lang} = cowboy_req:match_qs([{lang, [], plain}], Req), #{lang := Lang} = cowboy_req:match_qs([{lang, [fun lang_constraint/2], plain}], Req),
{format_text(Paste, Lang), Req, Paste}. {format_text(Paste, Lang), Req, Paste}.
% Private % Private
lang_constraint(forward, Bin) ->
case re:run(Bin, "^[a-z0-9_]+$", [{capture, none}]) of
match -> {ok, Bin};
nomatch -> {error, bad_lang}
end;
lang_constraint(format_error, {bad_lang, _}) ->
"Invalid lang parameter.".
read_file(Name) -> read_file(Name) ->
{ok, Binary} = file:read_file(full_path(Name)), {ok, Binary} = file:read_file(full_path(Name)),
Binary. Binary.