API Keyを使った中継CGI
中継CGI。LWP (libwww-perl)で取りに行きます。httpsなので Crypt::SSLeay がインストールされていないとコケます。
APIキーを取りましょう!
別に、無くてもいいんですが、Getting Startedでも
Note: An API key is highly recommended.となっているので、取得してください。そのリンク先にも、取得するメリットが書かれています。
Why you should get a key
- Higher usage limits. Without an API key, we don't know who you are, and we're pretty shy. You'll be subject to anonymous usage limits, and those are very, very low. Your requests will fail when you exceed your limits. With an API key, you'll have very high usage limits — high enough to accomodate most applications' needs.
- Traffic reports. With an API key, you also get access to fun graphs of your API usage on the APIs Console.
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;