Commit 54549428 authored by Artemis's avatar Artemis

Moved to using Viper for configuration

parent 29129658
......@@ -9,6 +9,7 @@ Small temp redis-based pastebin server.
Environment variables
=====================
- ``HTTP_HOST`` (default ``127.0.0.1:1234``): HTTP listening interface host
- ``REDIS_ADDR`` (default ``127.0.0.1:6379``): Redis URL
- ``REDIS_PASS`` (default ""): Redis password
- ``HttpHost`` (default ``127.0.0.1:1234``): HTTP listening interface host
- ``RedisAddress`` (default ``127.0.0.1:6379``): Redis URL
- ``RedisPassword`` (default ""): Redis password
- ``RedisDatabase`` (default 0): Redis database
package main
import (
"github.com/spf13/viper"
)
var ConfigName = "paste"
func SetupConfig() error {
viper.SetConfigName(ConfigName)
// Sources
viper.AddConfigPath("/etc")
viper.AddConfigPath("/etc/" + ConfigName)
viper.AddConfigPath("$HOME")
viper.AddConfigPath("$HOME/." + ConfigName)
viper.AddConfigPath(".")
viper.AutomaticEnv()
// Default values
viper.SetDefault("RedisAddress", "127.0.0.1:6379")
viper.SetDefault("RedisPassword", "")
viper.SetDefault("RedisDatabase", 0)
viper.SetDefault("HttpHost", "127.0.0.1:1234")
// Tries to load the config, and fails otherwise. Returns the error, or nil.
return viper.ReadInConfig()
}
......@@ -5,22 +5,13 @@ import (
"github.com/elgs/gostrgen"
"github.com/go-redis/redis"
"github.com/husobee/vestigo"
"github.com/spf13/viper"
"html/template"
"log"
"net/http"
"os"
"time"
)
func getEnvDefault(key string, defaultVal string) string {
val := os.Getenv(key)
if len(val) == 0 {
val = defaultVal
}
return val
}
func GetNewKey() (error, string) {
key, err := gostrgen.RandGen(6, gostrgen.LowerUpper, "", "")
if err != nil {
......@@ -50,10 +41,15 @@ type Content struct {
var NotFoundErr = "This document could not be found. Maybe it expired? Remember that documents have a 1-hour expiry time."
func main() {
err := SetupConfig()
if err != nil {
panic(err)
}
backend := redis.NewClient(&redis.Options{
Addr: getEnvDefault("REDIS_ADDR", "127.0.0.1:6379"),
Password: getEnvDefault("REDIS_PASS", ""),
DB: 0,
Addr: viper.GetString("RedisAddress"),
Password: viper.GetString("RedisPassword"),
DB: viper.GetInt("RedisDatabase"),
})
res := backend.Ping()
if err := res.Err(); err != nil {
......@@ -163,7 +159,7 @@ func main() {
http.ServeFile(w, req, "privacy.html")
})
host := getEnvDefault("HTTP_HOST", "127.0.0.1:1234")
host := viper.GetString("HttpHost")
fmt.Printf("HTTP server about to start listening on %s\n", host)
log.Fatal(http.ListenAndServe(host, r))
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment