This weekend's project is a URL redirecter/shortner.

Written in golang, this cloud-native app will make it easy to redirect URLs.

Let's dive in

Exploring what's involved with writing a URL shortner

// manage starting of webserver
func HandleWebserver() {
...
router.HandleFunc(/{link:[a-zA-Z0-9]+}, APIshortLink)

...

(#1) In code block #1, the HandleWebserver function the router is handling any path from / as a variable. Referring to what's passed in as link, requiring it to only have lower, and upper characters as well as numbers.

// handle the url variables on /{link}
func APIshortLink(w http.ResponseWriter, r *http.Request) {
	configYAML := ReadConfigYAML()
	vars := mux.Vars(r)
	redirectURL := configYAML.Routes[vars["link"]]
	if redirectURL == "" {
		w.WriteHeader(404)
		return
	}
	http.Redirect(w, r, redirectURL, 302)
}

(#2) Now that we've got the link variable from the request, we need to check to see if it's available in our data store config.yaml. In code block #2, the config YAML is loaded and the link variable is entered as the key, if anything returns, it'll redirect it to the given link. If it doesn't exist, it will return a 404 status code.

The result

With the code snippits in mind, let's say you're hosting an instance at https://s.mydomain.com and your config looks like

s.mydomain.com:
  routes:
    duck: https://duckduckgo.com
    gitlab: https://gitlab.com

Then, if you visit https://s.mydomain.com/duck the request will be redirected to https://duckduckgo.com.

Deployment ideas

If deployed in Kubernetes and config.yaml is a ConfigMap, a separate service might deal to handling the ConfigMap and what it's contents are – with kubernetes/client-go.

Final thoughts

Thank you, if you've made it this far.Hope you've enjoy this insight!

Feel free to contribute, fork, and use this project. Links: