Example #1
0
func InitRedisClient() {
	log.Info("Setting up Redis client")
	redisHost := os.Getenv("DB_PORT_6379_TCP_ADDR")
	redisPort := os.Getenv("DB_PORT_6379_TCP_PORT")
	if redisHost == "" {
		redisHost = viper.GetString("redisHost")
	}
	if redisPort == "" {
		redisPort = viper.GetString("redisPort")
	}
	redisAddr := redisHost + ":" + redisPort
	log.Info("Connecting to " + redisAddr)
	redisClient = redis.NewClient(&redis.Options{
		Addr:     redisAddr,
		Password: viper.GetString("redisPassword"),
		DB:       int64(viper.GetInt("redisDB")),
	})
	pong, err := redisClient.Ping().Result()
	if pong == "PONG" {
		log.Info("Redis client is up and running")
	} else {
		log.WithFields(log.Fields{"err": err}).Fatal("Redis could not start")
		os.Exit(1)
	}
}
Example #2
0
func main() {
	viper.SetConfigName("conf")
	viper.AddConfigPath("conf/")
	viper.SetConfigType("yaml")
	err := viper.ReadInConfig() // Find and read the config file
	if err != nil {             // Handle errors reading the config file
		log.Fatal("Could not read config file: %s \n", err)
	}

	f, err := os.OpenFile(viper.GetString("logfile")+time.Now().Format("20060102")+".log", os.O_WRONLY|os.O_CREATE, 0755)
	if err != nil {
		log.Fatal("Could not create log file: %s \n", err)
	}
	log.SetOutput(f)
	switch viper.GetString("loglevel") {

	case "DEBUG":
		log.SetLevel(log.DebugLevel)
	case "WARN":
		fmt.Println(log.WarnLevel)
	case "INFO":
		fmt.Println(log.InfoLevel)
	case "ERROR":
		fmt.Println(log.ErrorLevel)
	}

	log.Info("Starting up!")

	configuration.Port = viper.GetInt("port")
	configuration.DataTTL = viper.GetInt("dataTTL")
	configuration.TokenMaxSize = viper.GetInt("tokenMaxSize")

	// INIT Redis
	InitRedisClient()

	// INIT Server
	r := mux.NewRouter()
	log.Info("Registering RedirectionHandler on /{value}")
	r.HandleFunc("/{value}", RedirectionHandler).
		Methods("GET")

	log.Info("Registering ShortlinkCreationHandler on /shortlink/{value}")
	r.HandleFunc("/shortlink/{value}", ShortlinkCreationHandler).
		Methods("GET")

	log.Info("Registering AdvancedShortlinkCreationHandler on /shortlink")
	r.HandleFunc("/shortlink", AdvancedShortlinkCreationHandler).
		Methods("POST")

	log.Info("Registering MonitoringHandler on /admin/{value}")
	r.HandleFunc("/admin/{value}", MonitoringHandler).
		Methods("GET")

	http.Handle("/", r)
	http.ListenAndServe(":"+strconv.Itoa(configuration.Port), r)
}
Example #3
0
func RedirectionHandler(w http.ResponseWriter, r *http.Request) {
	log.Debug("RedirectionHandler")

	// Extract request parameters
	vars := mux.Vars(r)
	token := vars["value"]

	// Fetch Shortlink in Redis
	shortlink, err := ReadFromRedis(token)
	if err != nil {
		http.Error(w, "Token not found", 404)
		return
	}

	// Increment
	shortlink.Count++
	UpdateShortlink(shortlink)

	log.Info("Redirecting http://" + r.Host + "/" + shortlink.Token + " to " + shortlink.Origin)
	// Redirect
	http.Redirect(w, r, shortlink.Origin, http.StatusFound)
}