Esempio n. 1
0
func RegisterShortlink(origin, token string) (string, error) {
	//Check origin
	_, err := http.Get(origin)
	if err != nil {
		return "", err
	}

	//Store in Redis
	if token == "" {
		token = RandomString()
	} else {
		if len(token) > configuration.TokenMaxSize {
			return "", errors.New("token is too long")
		}
	}

	//check if key is already used
	if redisClient.Get(token).Val() != "" {
		log.WithFields(log.Fields{"token": token}).Warn("token already used")
		i := 0
		for ; redisClient.Get(token+strconv.Itoa(i)).Val() != ""; i++ {
			log.WithFields(log.Fields{"token": token + strconv.Itoa(i)}).Warn("token already used")
		}
		token = token + strconv.Itoa(i)
	}

	// Save Shortlink in Redis
	log.WithFields(log.Fields{"origin": origin, "token": token}).Info("creation")
	uuid, _ := newUUID()
	CreateShortlink(Shortlink{uuid, token, origin, time.Now().Unix(), 0})
	return token, nil
}
Esempio n. 2
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)
	}
}