Created
February 20, 2022 09:53
-
-
Save imyaman/69bc68b98b6948e799db74a9a128008e to your computer and use it in GitHub Desktop.
Dancer2, webhook, event type에 따른 처리
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use JSON qw(from_json to_json); | |
use URI::Encode qw(uri_decode); | |
use Data::Dumper; | |
use Dancer2; | |
post '/webhook-test' => sub { | |
my $self = shift; | |
my ($rbody, $evtype); | |
my @evtypes = ("postCreated", "postSubjectChanged"); | |
my @evprocessors = (\&postCreated, \&postSubjectChanged); | |
headers 'content-type' => 'application/json'; | |
# request->body 는 string 입니다. | |
# $rbody 는 hashref 입니다. | |
# request payload가 json이 아니면 바로 응답합니다. eval을 쓰지 않으면 500 에러가 발생하고 HTML로 응답합니다. | |
eval { $rbody = from_json(request->body); }; | |
if($@){ | |
debug $@; return to_json( {"result" => "Not OK. It's not json"} ); | |
}; | |
# dooray는 웹훅을 두 가지 포맷으로 보낼 수 있습니다. Slack을 위한 포맷이면 바로 응답합니다. | |
if($rbody->{channel}){ | |
debug "It's for Slack, not for me."; return to_json( {"result" => "Not OK. It's for Slack"} ); | |
} | |
# dooray는 이벤트 타입을 알 수 없으면 바로 응답합니다. | |
$evtype = $rbody->{hookEventType}; | |
if(not defined $evtype or $evtype eq ""){ | |
debug "It's not for an event"; return to_json( {"result" => "Not OK. It's not for an event"} ); | |
}; | |
# debug Dumper($rbody); return to_json( {"result"=>"OK"} ); | |
for(my $i=0; $i<$#evtypes; $i++){ | |
if($evtype eq $evtypes[$i]){ | |
# $rbody 는 hashref 입니다, 위에 말했듯이. | |
# 함수 안에서 my ($body)=@_; 하면 $body와 $rbody는 같은 hashref 입니다. | |
# 함수 안에서 hash를 return 한 걸 클라이언트에게 응답으로 줍니다. | |
return $evprocessors[$i]($rbody); | |
last; | |
} | |
} | |
return to_json( {"result"=>"OK. Nothing to do for the event: $evtype"} ); | |
}; | |
sub postCreated { | |
my ($body)=@_; | |
return to_json({"result" => "OK. postCreated"}); | |
} | |
sub postSubjectChanged { | |
my ($body)=@_; | |
return to_json({"result" => "OK. postSubjectChanged"}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment