[Laravel4] 短网址之API
我们提供三种格式的API, txt json jsonp
代码
路由
Route::get('short.txt', 'ShortController@txt');
Route::get('short.json', 'ShortController@json');
Route::get('short.jsonp', 'ShortController@jsonp');
控制器
public function txt() {
$validator = Validator::make(Input::all(), [
'url' => 'required|max:255|url',
]);
if ($validator->fails()) {
return implode(PHP_EOL, $validator->errors()->all());
}
$url = Input::get('url');
$hash = md5($url);
$link = Link::whereHash($hash)->first();
if (!$link)
$link = Link::create(compact('url', 'hash'));
$shorten = \Lib\Base62::encode($link->id);
return 'http://usr.im/' . $shorten;
}
public function json() {
$resp = [];
$validator = Validator::make(Input::all(), [
'url' => 'required|max:255|url',
]);
if ($validator->fails()) {
return ['status' => 'failed', 'message' => $validator->errors()->all()];
}
$url = Input::get('url');
$hash = md5($url);
$link = Link::whereHash($hash)->first();
if (!$link)
$link = Link::create(compact('url', 'hash'));
$shorten = \Lib\Base62::encode($link->id);
return ['status' => 'success', 'content' => 'http://usr.im/' . $shorten];
}
public function jsonp() {
$resp = [];
Validator::extend('callback', function($attribute, $value, $parameters) {
return preg_match('/^[A-z_]\w*$/i', $value);
});
$validator = Validator::make(Input::all(), [
'url' => 'required|max:255|url',
'callback' => 'required|max:255|callback',
]);
if ($validator->fails()) {
return Response::json(['status' => 'failed', 'message' => $validator->errors()->all()])
->setCallback(Input::get('callback'));
}
$url = Input::get('url');
$hash = md5($url);
$link = Link::whereHash($hash)->first();
if (!$link)
$link = Link::create(compact('url', 'hash'));
$shorten = \Lib\Base62::encode($link->id);
return Response::json(['status' => 'success', 'content' => 'http://usr.im/' . $shorten])
->setCallback(Input::get('callback'));
}