Beispiel #1
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)
}
Beispiel #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)
	}
}