Twitter: raymondcamden


Address: Lafayette, LA, USA

ColdFusion UDFs for Google URL Shortening service

01-10-2011 4,982 views ColdFusion

I wrote this in about five minutes and it doesn't support auth tokens yet, but here are two UDFs that make use of Google's URL Shortening API. First, the shorten call:

view plain print about
1<cffunction name="googleURLShorten" output="false" returnType="string">
2    <cfargument name="url" type="string" required="true">
3    <cfset var httpResult = "">
4    <cfset var result = "">
5
6    <cfset var body = {"longUrl"=arguments.url}>
7
8    <cfset body = serializeJson(body)>
9    
10    <cfhttp url="https://www.googleapis.com/urlshortener/v1/url" method="post" result="httpResult">
11        <cfhttpparam type="header" name="Content-Type" value="application/json">
12        <cfhttpparam type="body" value="#body#">
13    </cfhttp>
14    <cfset result = httpResult.filecontent.toString()>
15    <cfreturn deserializeJSON(result).id>
16</cffunction>

And then the reverse:

view plain print about
1<cffunction name="googleURLExpand" output="false" returnType="string">
2    <cfargument name="url" type="string" required="true">
3    <cfset var httpResult = "">
4    <cfset var result = "">
5
6    <cfhttp url="https://www.googleapis.com/urlshortener/v1/url?shortUrl=#urlEncodedFormat(arguments.url)#" method="get" result="httpResult"></cfhttp>
7
8    <cfset result = httpResult.filecontent.toString()>
9    <cfreturn deserializeJSON(result).longUrl>
10</cffunction>

And a quick test script:

view plain print about
1<cfset sampleURL = "http://www.coldfusionjedi.com/index.cfm/2011/1/10/jQuery-based-example-of-simple-shopping-cart-UI">
2<cfset test = googleURLShorten(sampleURL)>
3<cfoutput>
4I shorteneded #sampleURL# to #test#.<br/>
5</cfoutput>
6
7<cfset reversed = googleURLExpand(test)>
8<cfoutput>
9I expanded it to #reversed#.
10</cfoutput>

When run, I get:

I shorteneded http://www.coldfusionjedi.com/index.cfm/2011/1/10/jQuery-based-example-of-simple-shopping-cart-UI to http://goo.gl/qeDBv. I expanded it to http://www.coldfusionjedi.com/index.cfm/2011/1/10/jQuery-based-example-of-simple-shopping-cart-UI.

Love that typo on the first line. Anyway, the UDFs could be improved with simple error checking and optional token support. But this is the best you get in five minutes. ;)