Last active
December 27, 2015 19:59
-
-
Save qubyte/7381197 to your computer and use it in GitHub Desktop.
Super simple URL unshortener in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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):
which responds with