API Keyを使った中継CGI
中継CGI。LWP (libwww-perl)で取りに行きます。httpsなので Crypt::SSLeay がインストールされていないとコケます。
APIキーを取りましょう!
別に、無くてもいいんですが、Getting Startedでも
Note: An API key is highly recommended.となっているので、取得しときましょ!
shortener.cgi (API Key版)
#!/usr/bin/perl # 対象URLが longUrl=http%3A%2F%2Fwww%2Egoogle%2Ecom%2F のように来ていると仮定 $apikey = 'API key'; use CGI; my $q = CGI->new; use LWP::UserAgent; my $ua = LWP::UserAgent->new; my $res = $ua->post( "https://www.googleapis.com/urlshortener/v1/url?key=$apikey", "Content-Type" => "application/json", "Content" => '{"longUrl":"'.$q->param("longUrl").'"}' ); print "Content-type: " . $res->header("Content-type") . "\n\n"; print $res->content; exit;
このままだとアクセスされ放題なので、適宜入力チェックをしましょう。
# ・自サイトのみ対象とする場合
unless ($q->param("longUrl") =~ /$ENV{SERVER_NAME}/) {
print "Status: 400\n\n";
exit;
}
# ・リファラチェック
unless ($ENV{HTTP_REFERER} =~ /$ENV{SERVER_NAME}/) {
print "Status: 400\n\n";
exit;
}
APIキーを使わない場合
オススメはされませんが、将来的には…!?
#!/usr/bin/perl
# 対象URLが longUrl=http%3A%2F%2Fwww%2Egoogle%2Ecom%2F のように来ていると仮定
use CGI;
my $q = CGI->new;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $res = $ua->post(
"https://www.googleapis.com/urlshortener/v1/url",
"Content-Type" => "application/json",
"Content" => '{"longUrl":"'.$q->param(longUrl).'"}';
);
print "Content-type: " . $res->header("Content-type") . "\n\n";
print $res->content;
exit;