Friday, January 15, 2016

Code Snippet: A redirection service in Go

Recently, I've been very fascinated with Go. That language is so easy to write and as it's statically compiled, less changes of bugs too. So, I keep finding excuses to write Go code.

I needed a service to redirect clients which runs inside a docker container. One obvious option is to run apache inside docker with proper configs but as I enjoy writing Go code, I wrote this really simple program that acts like a redirection service. Later, I just copy this compiled binary into docker container.
  • Specify location and port from command-line to set the location to redirect to. 
  • Each client is handled in it's own goroutine, that means, it's scalable. 
  • That few lines of code are so elegant. I love Go.

Code:- ( https://github.com/shadyabhi/redirection_service )

package main

import (
	"flag"
	"log"
	"net/http"
	"strconv"

	"github.com/asaskevich/govalidator"
)

// redirect function does the redirection
func redirect(w http.ResponseWriter, r *http.Request, location string) {
	w.Header().Set("Location", location)
	w.WriteHeader(http.StatusFound)
}

func main() {
	// Handle cmdline arguments
	location := flag.String("location", "localhost:80", "The URI at which the ")
	port := flag.Int("port", 80, "Port at which the http server binds to")
	flag.Parse()

	// Validate
	isURL := govalidator.IsURL(*location)
	if !isURL {
		log.Fatal("The location you provided is not a valid URL")
	}

	log.Printf("Starting web server... Location: %s, Port: %d", *location, *port)

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		redirect(w, r, *location)
	})

	err := http.ListenAndServe(":"+strconv.Itoa(*port), nil)
	if err != nil {
		log.Fatal("Error starting web server. ", err)
	}
}

Usage:-

% ./redirection_service -h
Usage of ./redirection_service:
  -location string
        The URI at which the  (default "localhost:80")
  -port int
        Port at which the http server binds to (default 80)
% sudo ./redirection_service -location=https://abhijeetr.com
2016/01/15 09:33:54 Starting web server... Location: https://abhijeetr.com, Port: 80

No comments:

Post a Comment