« blib/lib/auto/share/dist/Cmd-Dwarf/app/lib/Dwarf/Pragma.pm
↑ Summary
blib/lib/auto/share/dist/Cmd-Dwarf/app/lib/Dwarf/Plugin/Error.pm »
| 1 | package Dwarf::Plugin::CORS; | ||
| 2 | use Dwarf::Pragma; | ||
| 3 | use Dwarf::Util qw/add_method/; | ||
| 4 | |||
| 5 | sub init { | ||
| 6 | my ($class, $c, $conf) = @_; | ||
| 7 | $conf ||= {}; | ||
| 8 | die "conf must be HASH" unless ref $conf eq 'HASH'; | ||
| 9 | |||
| 10 | $conf->{origin} ||= '*'; | ||
| 11 | $conf->{methods} ||= [qw/GET PUT POST DELETE HEAD OPTIONS PATCH/]; | ||
| 12 | $conf->{headers} ||= [qw/X-Requested-With/]; | ||
| 13 | $conf->{credentials} ||= 0; | ||
| 14 | $conf->{maxage} ||= 7200; | ||
| 15 | |||
| 16 | $c->add_trigger(AFTER_DISPATCH => sub { | ||
| 17 | my ($self, $res) = @_; | ||
| 18 | |||
| 19 | $self->header('Access-Control-Allow-Origin' => $conf->{origin}); | ||
| 20 | $self->header('Access-Control-Allow-Methods' => join ',', @{ $conf->{methods} }); | ||
| 21 | $self->header('Access-Control-Allow-Headers' => join ',', @{ $conf->{headers} }); | ||
| 22 | |||
| 23 | if ($conf->{credentials}) { | ||
| 24 | $self->header('Access-Control-Allow-Credentials' => 'true'); | ||
| 25 | } | ||
| 26 | |||
| 27 | if ($self->method eq 'OPTIONS' and $conf->{maxage}) { | ||
| 28 | # preflight なリクエストには 200 を返してしまう | ||
| 29 | $self->response->status(200); | ||
| 30 | $self->response->body(""); | ||
| 31 | $self->header('Access-Control-Max-Age' => $conf->{maxage}); | ||
| 32 | } | ||
| 33 | }); | ||
| 34 | } | ||
| 35 | |||
| 36 | 1; |