Coffeescript snippet for accessing Google's URL-shortening service (not actually a question)

You must Login before you can answer or comment on any questions.

This isn't really large enough to warrant putting in git or whatever, so I'm just posting it here in case it's of use to anyone.

Coffeescript to generate a short url using Google's Goo.gl service. You need a Google API key to use this.

Written by Tony Hursh, awh@acm.org

MIT license.

Parameters url: the URL to shorten as a text string success_callback: a two-argument function to call if the call succeeds.

      First arg is the HTTP request status, second is the 
      response text.

error_callback: a two-argument function that's called if a network error occurs. Args are the same as success_callback

A successful call returns JSON-formatted text with the following layout:

{

  kind: urlshortener#url,

  id: (your shortened URL is here),

  longUrl: (the original URL is here)

}

apikey = "YOUR GOOGLE API KEY GOES HERE"
 
shorten_url = (url, success_callback, error_callback) ->
 
  xhr = Titanium.Network.createHTTPClient()
  xhr.open "POST", "https://www.googleapis.com/urlshortener/v1/url?key=" + apikey
  xhr.setRequestHeader "Content-type", "application/json"
  xhr.onload = () -> success_callback xhr.status, xhr.responseText
  xhr.onerror = () -> error_callback xhr.status, xhr.responseText
  content =  "{\"longUrl\": \"#{url}\"}"
  xhr.send content

Your Answer

Think you can help? Login to answer this question!