Skip to content

Instantly share code, notes, and snippets.

@qubyte
Last active December 27, 2015 19:59
Show Gist options
  • Save qubyte/7381197 to your computer and use it in GitHub Desktop.
Save qubyte/7381197 to your computer and use it in GitHub Desktop.
Super simple URL unshortener in Go
// Package unshortener takes a single parameter (url) and sends back an unshortened version.
//
// This version is in vanilla go, and requires no packages to be installed.
package main
import (
"encoding/json"
"io"
"log"
"net/http"
"net/url"
)
// Handler function looks for a "url" query parameter in the request, and uses
// it to make a request and ultimately resolve an unshortened URL.
func Handler(w http.ResponseWriter, r *http.Request) {
vals, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
http.Error(w, "No query parameters.", 400)
return
}
// Get the short URL from the query parameters.
urlParam := vals.Get("url")
if urlParam == "" {
http.Error(w, "No URL given.", 400)
return
}
// Make a request with the URL
res, err := http.Head(urlParam)
if err != nil {
http.Error(w, "Received error from external server.", 500)
return
}
// Close the response body later.
defer res.Body.Close()
resolvedUrl := res.Request.URL.String()
log.Printf("Unshortened %q to %q", urlParam, resolvedUrl)
// Build a response containing the original and resolved URLs.
reponse, err := json.Marshal(map[string]string{"original": urlParam, "resolved": resolvedUrl})
if err != nil {
http.Error(w, "Unable to marshal response.", 500)
}
// Set the response header and respond with JSON.
w.Header().Set("Content-Type", "application/json; charset=utf-8")
io.WriteString(w, string(reponse))
}
func main() {
http.HandleFunc("/", Handler)
log.Printf("Server listening...")
log.Fatal(http.ListenAndServe("localhost:8080", nil))
}
@qubyte
Copy link
Author

qubyte commented Nov 9, 2013

Extremely crude, but does the job. I wanted to compare it to a similar utility I wrote in Node.js today. Example use (the url parameter is http://youtu.be/JPBRbIvs5lc encoded):

GET localhost:8080?url=http%3A%2F%2Fyoutu.be%2FJPBRbIvs5lc

which responds with

{
    "original": "http://youtu.be/JPBRbIvs5lc",
    "resolved": "http://www.youtube.com/watch?v=JPBRbIvs5lc&feature=youtu.be"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment