ColdFusion UDFs for Google URL Shortening service

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:

<cffunction name="googleURLShorten" output="false" returnType="string"> <cfargument name="url" type="string" required="true"> <cfset var httpResult = ""> <cfset var result = ""> <cfset var body = {"longUrl"=arguments.url}> <cfset body = serializeJson(body)> <cfhttp url="https://www.googleapis.com/urlshortener/v1/url" method="post" result="httpResult"> <cfhttpparam type="header" name="Content-Type" value="application/json"> <cfhttpparam type="body" value="#body#"> </cfhttp> <cfset result = httpResult.filecontent.toString()> <cfreturn deserializeJSON(result).id> </cffunction>

And then the reverse:

<cffunction name="googleURLExpand" output="false" returnType="string"> <cfargument name="url" type="string" required="true"> <cfset var httpResult = ""> <cfset var result = ""> <cfhttp url="https://www.googleapis.com/urlshortener/v1/url?shortUrl=#urlEncodedFormat(arguments.url)#" method="get" result="httpResult"></cfhttp> <cfset result = httpResult.filecontent.toString()> <cfreturn deserializeJSON(result).longUrl> </cffunction>

And a quick test script:

<cfset sampleURL = "http://www.raymondcamden.com/index.cfm/2011/1/10/jQuery-based-example-of-simple-shopping-cart-UI"> <cfset test = googleURLShorten(sampleURL)> <cfoutput> I shorteneded #sampleURL# to #test#.<br/> </cfoutput> <cfset reversed = googleURLExpand(test)> <cfoutput> I expanded it to #reversed#. </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. ;)

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments