.
Apps Script Url Shortener
This script actually uses goo.gl url shortening service.
However, having an apps script to carry out the shortening service gives an advantage of a custom API that can be called by other web or mobile apps.
Edit Script
Util.gs
function shortenUrls(urls){
/*urls items are separated by a space*/ output=[] var pattern = new RegExp(/(http|ftp|https):\/\/(?!goo.gl)([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/g); var matches = urls.match(pattern); if (matches != null) { for ( var x = 0 ; x < matches.length ; x++) { var match = matches[x]; var url = UrlShortener.Url.insert({ longUrl: match }); output.push({longurl:match,shorturl:url.id}); } } return output } function testShortenUrls1(){ var urls='http://bernama.com http://www.cnn.com'; Logger.log(shortenUrls(urls)) } function testShortenUrls2(){ var urls='http://bernama.com'; Logger.log(shortenUrls(urls)) } |
WebApp.gs
/* web request listeners */
function doGet(e) {
return handleResponse(e);
}
function doPost(e) {
return handleResponse(e);
}
/* handle action request */
function handleResponse(e) {
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
var cmd = e.parameter.cmd || "";
if (cmd == "") {
return TaskMan("default", e);
} else if (cmd == "shorten") {
if (e.parameter.passcode=='12345'){
return TaskMan("shorten", e);
}else{
return TaskMan("default", e);
}
}
} catch (e) { /*if error return this*/
return ContentService.createTextOutput(JSON.stringify({
"result": "error",
"error": e
})).setMimeType(ContentService.MimeType.JSON);
} finally { /*release lock*/
lock.releaseLock();
}
}
|
TaskMan.gs
/*taskManager*/
function TaskMan(cmd, e) {
var output = {rescode:0,resdesc:'',reslong:'',resshort:''};
switch (cmd) {
case "default":
var output = {rescode:0,resdesc:'none'};
break;
case "shorten":
var strLongUrl = e.parameter.longurl || '';
if (strLongUrl!=''){
var result = shortenUrls(strLongUrl)[0];
output.reslong = result.longurl;
output.resshort=result.shorturl;
output.rescode=100;
output.resdesc='shorten successful';
}
break;
} /*switch*/
var output = ContentService.createTextOutput(JSON.stringify({
"result": "success",
"content": output
})).setMimeType(ContentService.MimeType.JSON);
return output;
}
|
When you deploy the code as Web Apps, you will get an error message saying your project id needs to be enabled on Google Developer Console.
Go to Google Developer Console.
Browse for the project id.
Click the ENABLE button.
Test
using www.resttesttest.com
REFERENCE:
.