Better config handling with constants (#83)

This commit is contained in:
konrad 2019-07-06 20:12:26 +00:00 committed by Gitea
parent f1d21ea52b
commit 1f1a079fd3
17 changed files with 200 additions and 120 deletions

View File

@ -17,13 +17,13 @@
package cmd package cmd
import ( import (
"code.vikunja.io/api/pkg/config"
"code.vikunja.io/api/pkg/log" "code.vikunja.io/api/pkg/log"
"code.vikunja.io/api/pkg/routes" "code.vikunja.io/api/pkg/routes"
"code.vikunja.io/api/pkg/swagger" "code.vikunja.io/api/pkg/swagger"
"context" "context"
"fmt" "fmt"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper"
"os" "os"
"os/signal" "os/signal"
"time" "time"
@ -49,7 +49,7 @@ var webCmd = &cobra.Command{
routes.RegisterRoutes(e) routes.RegisterRoutes(e)
// Start server // Start server
go func() { go func() {
if err := e.Start(viper.GetString("service.interface")); err != nil { if err := e.Start(config.ServiceInterface.GetString()); err != nil {
e.Logger.Info("shutting down...") e.Logger.Info("shutting down...")
} }
}() }()

View File

@ -17,15 +17,98 @@
package config package config
import ( import (
"code.vikunja.io/api/pkg/log"
"crypto/rand" "crypto/rand"
"fmt" "fmt"
"github.com/spf13/viper" "log"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"time"
"github.com/spf13/viper"
) )
// Key is used as a config key
type Key string
// These constants hold all config value keys
const (
ServiceJWTSecret Key = `service.JWTSecret`
ServiceInterface Key = `service.interface`
ServiceFrontendurl Key = `service.frontendurl`
ServiceEnableCaldav Key = `service.enablecaldav`
ServiceRootpath Key = `service.rootpath`
ServicePageCount Key = `service.pagecount`
ServiceEnableMetrics Key = `service.enablemetrics`
DatabaseType Key = `database.type`
DatabaseHost Key = `database.host`
DatabaseUser Key = `database.user`
DatabasePassword Key = `database.password`
DatabaseDatabase Key = `database.database`
DatabasePath Key = `database.path`
DatabaseMaxOpenConnections Key = `database.maxopenconnections`
DatabaseMaxIdleConnections Key = `database.maxidleconnections`
DatabaseMaxConnectionLifetime Key = `database.maxconnectionlifetime`
CacheEnabled Key = `cache.enabled`
CacheType Key = `cache.type`
CacheMaxElementSize Key = `cache.maxelementsize`
MailerEnabled Key = `mailer.enabled`
MailerHost Key = `mailer.host`
MailerPort Key = `mailer.port`
MailerUsername Key = `mailer.username`
MailerPassword Key = `mailer.password`
MailerSkipTLSVerify Key = `mailer.skiptlsverify`
MailerFromEmail Key = `mailer.fromemail`
MailerQueuelength Key = `mailer.queuelength`
MailerQueueTimeout Key = `mailer.queuetimeout`
RedisEnabled Key = `redis.enabled`
RedisHost Key = `redis.host`
RedisPassword Key = `redis.password`
RedisDB Key = `redis.db`
LogEnabled Key = `log.enabled`
LogErrors Key = `log.errors`
LogStandard Key = `log.standard`
LogDatabase Key = `log.database`
LogHTTP Key = `log.echo`
LogEcho Key = `log.echo`
LogPath Key = `log.path`
)
// GetString returns a string config value
func (k Key) GetString() string {
return viper.GetString(string(k))
}
// GetBool returns a bool config value
func (k Key) GetBool() bool {
return viper.GetBool(string(k))
}
// GetInt returns an int config value
func (k Key) GetInt() int {
return viper.GetInt(string(k))
}
// GetDuration returns a duration config value
func (k Key) GetDuration() time.Duration {
return viper.GetDuration(string(k))
}
// Set sets a value
func (k Key) Set(i interface{}) {
viper.Set(string(k), i)
}
// sets the default config value
func (k Key) setDefault(i interface{}) {
viper.SetDefault(string(k), i)
}
// InitConfig initializes the config, sets defaults etc. // InitConfig initializes the config, sets defaults etc.
func InitConfig() { func InitConfig() {
@ -33,61 +116,61 @@ func InitConfig() {
// Service config // Service config
random, err := random(32) random, err := random(32)
if err != nil { if err != nil {
log.Log.Fatal(err.Error()) log.Fatal(err.Error())
} }
// Service // Service
viper.SetDefault("service.JWTSecret", random) ServiceJWTSecret.setDefault(random)
viper.SetDefault("service.interface", ":3456") ServiceInterface.setDefault(":3456")
viper.SetDefault("service.frontendurl", "") ServiceFrontendurl.setDefault("")
viper.SetDefault("service.enablecaldav", true) ServiceEnableCaldav.setDefault(true)
ex, err := os.Executable() ex, err := os.Executable()
if err != nil { if err != nil {
panic(err) panic(err)
} }
exPath := filepath.Dir(ex) exPath := filepath.Dir(ex)
viper.SetDefault("service.rootpath", exPath) ServiceRootpath.setDefault(exPath)
viper.SetDefault("service.pagecount", 50) ServicePageCount.setDefault(50)
viper.SetDefault("service.enablemetrics", false) ServiceEnableMetrics.setDefault(false)
// Database // Database
viper.SetDefault("database.type", "sqlite") DatabaseType.setDefault("sqlite")
viper.SetDefault("database.host", "localhost") DatabaseHost.setDefault("localhost")
viper.SetDefault("database.user", "vikunja") DatabaseUser.setDefault("vikunja")
viper.SetDefault("database.password", "") DatabasePassword.setDefault("")
viper.SetDefault("database.database", "vikunja") DatabaseDatabase.setDefault("vikunja")
viper.SetDefault("database.path", "./vikunja.db") DatabasePath.setDefault("./vikunja.db")
viper.SetDefault("database.maxopenconnections", 100) DatabaseMaxOpenConnections.setDefault(100)
viper.SetDefault("database.maxidleconnections", 50) DatabaseMaxIdleConnections.setDefault(50)
viper.SetDefault("database.maxconnectionlifetime", 10000) DatabaseMaxConnectionLifetime.setDefault(10000)
// Cacher // Cacher
viper.SetDefault("cache.enabled", false) CacheEnabled.setDefault(false)
viper.SetDefault("cache.type", "memory") CacheType.setDefault("memory")
viper.SetDefault("cache.maxelementsize", 1000) CacheMaxElementSize.setDefault(1000)
// Mailer // Mailer
viper.SetDefault("mailer.enabled", false) MailerEnabled.setDefault(false)
viper.SetDefault("mailer.host", "") MailerHost.setDefault("")
viper.SetDefault("mailer.port", "587") MailerPort.setDefault("587")
viper.SetDefault("mailer.user", "user") MailerUsername.setDefault("user")
viper.SetDefault("mailer.password", "") MailerPassword.setDefault("")
viper.SetDefault("mailer.skiptlsverify", false) MailerSkipTLSVerify.setDefault(false)
viper.SetDefault("mailer.fromemail", "mail@vikunja") MailerFromEmail.setDefault("mail@vikunja")
viper.SetDefault("mailer.queuelength", 100) MailerQueuelength.setDefault(100)
viper.SetDefault("mailer.queuetimeout", 30) MailerQueueTimeout.setDefault(30)
// Redis // Redis
viper.SetDefault("redis.enabled", false) RedisEnabled.setDefault(false)
viper.SetDefault("redis.host", "localhost:6379") RedisHost.setDefault("localhost:6379")
viper.SetDefault("redis.password", "") RedisPassword.setDefault("")
viper.SetDefault("redis.db", 0) RedisDB.setDefault(0)
// Logger // Logger
viper.SetDefault("log.enabled", true) LogEnabled.setDefault(true)
viper.SetDefault("log.errors", "stdout") LogErrors.setDefault("stdout")
viper.SetDefault("log.standard", "stdout") LogStandard.setDefault("stdout")
viper.SetDefault("log.database", "off") LogDatabase.setDefault(false)
viper.SetDefault("log.http", "stdout") LogHTTP.setDefault("stdout")
viper.SetDefault("log.echo", "off") LogEcho.setDefault("off")
viper.SetDefault("log.path", viper.GetString("service.rootpath")+"/logs") LogPath.setDefault(ServiceRootpath.GetString() + "/logs")
// Init checking for environment variables // Init checking for environment variables
viper.SetEnvPrefix("vikunja") viper.SetEnvPrefix("vikunja")
@ -95,15 +178,15 @@ func InitConfig() {
viper.AutomaticEnv() viper.AutomaticEnv()
// Load the config file // Load the config file
viper.AddConfigPath(viper.GetString("service.rootpath")) viper.AddConfigPath(ServiceRootpath.GetString())
viper.AddConfigPath("/etc/vikunja/") viper.AddConfigPath("/etc/vikunja/")
viper.AddConfigPath("~/.config/vikunja") viper.AddConfigPath("~/.config/vikunja")
viper.AddConfigPath(".") viper.AddConfigPath(".")
viper.SetConfigName("config") viper.SetConfigName("config")
err = viper.ReadInConfig() err = viper.ReadInConfig()
if err != nil { if err != nil {
log.Log.Info(err) log.Println(err.Error())
log.Log.Info("Using defaults.") log.Println("Using defaults.")
} }
} }

View File

@ -22,7 +22,6 @@ import (
"fmt" "fmt"
"github.com/go-xorm/core" "github.com/go-xorm/core"
"github.com/go-xorm/xorm" "github.com/go-xorm/xorm"
"github.com/spf13/viper"
"strconv" "strconv"
"time" "time"
@ -33,12 +32,12 @@ import (
// CreateDBEngine initializes a db engine from the config // CreateDBEngine initializes a db engine from the config
func CreateDBEngine() (engine *xorm.Engine, err error) { func CreateDBEngine() (engine *xorm.Engine, err error) {
// If the database type is not set, this likely means we need to initialize the config first // If the database type is not set, this likely means we need to initialize the config first
if viper.GetString("database.type") == "" { if config.DatabaseType.GetString() == "" {
config.InitConfig() config.InitConfig()
} }
// Use Mysql if set // Use Mysql if set
if viper.GetString("database.type") == "mysql" { if config.DatabaseType.GetString() == "mysql" {
engine, err = initMysqlEngine() engine, err = initMysqlEngine()
if err != nil { if err != nil {
return return
@ -52,7 +51,7 @@ func CreateDBEngine() (engine *xorm.Engine, err error) {
} }
engine.SetMapper(core.GonicMapper{}) engine.SetMapper(core.GonicMapper{})
engine.ShowSQL(viper.GetString("log.database") != "off") engine.ShowSQL(config.LogDatabase.GetString() != "off")
engine.SetLogger(xorm.NewSimpleLogger(log.GetLogWriter("database"))) engine.SetLogger(xorm.NewSimpleLogger(log.GetLogWriter("database")))
return return
@ -61,17 +60,17 @@ func CreateDBEngine() (engine *xorm.Engine, err error) {
func initMysqlEngine() (engine *xorm.Engine, err error) { func initMysqlEngine() (engine *xorm.Engine, err error) {
connStr := fmt.Sprintf( connStr := fmt.Sprintf(
"%s:%s@tcp(%s)/%s?charset=utf8&parseTime=true", "%s:%s@tcp(%s)/%s?charset=utf8&parseTime=true",
viper.GetString("database.user"), config.DatabaseUser.GetString(),
viper.GetString("database.password"), config.DatabasePassword.GetString(),
viper.GetString("database.host"), config.DatabaseHost.GetString(),
viper.GetString("database.database")) config.DatabaseDatabase.GetString())
engine, err = xorm.NewEngine("mysql", connStr) engine, err = xorm.NewEngine("mysql", connStr)
if err != nil { if err != nil {
return return
} }
engine.SetMaxOpenConns(viper.GetInt("database.maxopenconnections")) engine.SetMaxOpenConns(config.DatabaseMaxOpenConnections.GetInt())
engine.SetMaxIdleConns(viper.GetInt("database.maxidleconnections")) engine.SetMaxIdleConns(config.DatabaseMaxIdleConnections.GetInt())
max, err := time.ParseDuration(strconv.Itoa(viper.GetInt("database.maxconnectionlifetime")) + `ms`) max, err := time.ParseDuration(strconv.Itoa(config.DatabaseMaxConnectionLifetime.GetInt()) + `ms`)
if err != nil { if err != nil {
return return
} }
@ -80,7 +79,7 @@ func initMysqlEngine() (engine *xorm.Engine, err error) {
} }
func initSqliteEngine() (engine *xorm.Engine, err error) { func initSqliteEngine() (engine *xorm.Engine, err error) {
path := viper.GetString("database.path") path := config.DatabasePath.GetString()
if path == "" { if path == "" {
path = "./db.db" path = "./db.db"
} }

View File

@ -25,7 +25,6 @@ import (
"code.vikunja.io/web/handler" "code.vikunja.io/web/handler"
"github.com/dgrijalva/jwt-go" "github.com/dgrijalva/jwt-go"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@ -75,7 +74,7 @@ var (
func setupTestEnv() (e *echo.Echo, err error) { func setupTestEnv() (e *echo.Echo, err error) {
config.InitConfig() config.InitConfig()
models.SetupTests(viper.GetString("service.rootpath")) models.SetupTests(config.ServiceRootpath.GetString())
err = models.LoadFixtures() err = models.LoadFixtures()
if err != nil { if err != nil {
@ -114,7 +113,7 @@ func addTokenToContext(t *testing.T, user *models.User, c echo.Context) {
assert.NoError(t, err) assert.NoError(t, err)
// We send the string token through the parsing function to get a valid jwt.Token // We send the string token through the parsing function to get a valid jwt.Token
tken, err := jwt.Parse(token, func(t *jwt.Token) (interface{}, error) { tken, err := jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
return []byte(viper.GetString("service.JWTSecret")), nil return []byte(config.ServiceJWTSecret.GetString()), nil
}) })
assert.NoError(t, err) assert.NoError(t, err)
c.Set("user", tken) c.Set("user", tken)

View File

@ -17,6 +17,7 @@
package log package log
import ( import (
"code.vikunja.io/api/pkg/config"
"github.com/op/go-logging" "github.com/op/go-logging"
"github.com/spf13/viper" "github.com/spf13/viper"
"io" "io"
@ -39,18 +40,18 @@ var Log = logging.MustGetLogger("vikunja")
// InitLogger initializes the global log handler // InitLogger initializes the global log handler
func InitLogger() { func InitLogger() {
if !viper.GetBool("log.enabled") { if !config.LogEnabled.GetBool() {
// Disable all logging when loggin in general is disabled, overwriting everything a user might have set. // Disable all logging when loggin in general is disabled, overwriting everything a user might have set.
viper.Set("log.errors", "off") config.LogErrors.Set("off")
viper.Set("log.standard", "off") config.LogStandard.Set("off")
viper.Set("log.database", "off") config.LogDatabase.Set("off")
viper.Set("log.http", "off") config.LogHTTP.Set("off")
viper.Set("log.echo", "off") config.LogEcho.Set("off")
return return
} }
if viper.GetString("log.errors") == "file" || viper.GetString("log.standard") == "file" { if config.LogErrors.GetString() == "file" || config.LogStandard.GetString() == "file" {
err := os.Mkdir(viper.GetString("log.path"), 0744) err := os.Mkdir(config.LogPath.GetString(), 0744)
if err != nil && !os.IsExist(err) { if err != nil && !os.IsExist(err) {
log.Fatal("Could not create log folder: ", err.Error()) log.Fatal("Could not create log folder: ", err.Error())
} }
@ -59,7 +60,7 @@ func InitLogger() {
var logBackends []logging.Backend var logBackends []logging.Backend
// We define our two backends // We define our two backends
if viper.GetString("log.standard") != "off" { if config.LogStandard.GetString() != "off" {
stdWriter := GetLogWriter("standard") stdWriter := GetLogWriter("standard")
stdBackend := logging.NewLogBackend(stdWriter, "", 0) stdBackend := logging.NewLogBackend(stdWriter, "", 0)
@ -67,7 +68,7 @@ func InitLogger() {
logBackends = append(logBackends, logging.NewBackendFormatter(stdBackend, logging.MustStringFormatter(Fmt+"\n"))) logBackends = append(logBackends, logging.NewBackendFormatter(stdBackend, logging.MustStringFormatter(Fmt+"\n")))
} }
if viper.GetString("log.error") != "off" { if config.LogErrors.GetString() != "off" {
errWriter := GetLogWriter("error") errWriter := GetLogWriter("error")
errBackend := logging.NewLogBackend(errWriter, "", 0) errBackend := logging.NewLogBackend(errWriter, "", 0)
@ -86,7 +87,7 @@ func GetLogWriter(logfile string) (writer io.Writer) {
writer = os.Stderr // Set the default case to prevent nil pointer panics writer = os.Stderr // Set the default case to prevent nil pointer panics
switch viper.GetString("log." + logfile) { switch viper.GetString("log." + logfile) {
case "file": case "file":
f, err := os.OpenFile(viper.GetString("log.path")+"/"+logfile+".log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) f, err := os.OpenFile(config.LogPath.GetString()+"/"+logfile+".log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }

View File

@ -17,9 +17,9 @@
package mail package mail
import ( import (
"code.vikunja.io/api/pkg/config"
"code.vikunja.io/api/pkg/log" "code.vikunja.io/api/pkg/log"
"crypto/tls" "crypto/tls"
"github.com/spf13/viper"
"gopkg.in/gomail.v2" "gopkg.in/gomail.v2"
"time" "time"
) )
@ -29,20 +29,20 @@ var Queue chan *gomail.Message
// StartMailDaemon starts the mail daemon // StartMailDaemon starts the mail daemon
func StartMailDaemon() { func StartMailDaemon() {
Queue = make(chan *gomail.Message, viper.GetInt("mailer.queuelength")) Queue = make(chan *gomail.Message, config.MailerQueuelength.GetInt())
if !viper.GetBool("mailer.enabled") { if !config.MailerEnabled.GetBool() {
return return
} }
if viper.GetString("mailer.host") == "" { if config.MailerHost.GetString() == "" {
log.Log.Warning("Mailer seems to be not configured! Please see the config docs for more details.") log.Log.Warning("Mailer seems to be not configured! Please see the config docs for more details.")
return return
} }
go func() { go func() {
d := gomail.NewDialer(viper.GetString("mailer.host"), viper.GetInt("mailer.port"), viper.GetString("mailer.username"), viper.GetString("mailer.password")) d := gomail.NewDialer(config.MailerHost.GetString(), config.MailerPort.GetInt(), config.MailerUsername.GetString(), config.MailerPassword.GetString())
d.TLSConfig = &tls.Config{InsecureSkipVerify: viper.GetBool("mailer.skiptlsverify")} d.TLSConfig = &tls.Config{InsecureSkipVerify: config.MailerSkipTLSVerify.GetBool()}
var s gomail.SendCloser var s gomail.SendCloser
var err error var err error
@ -64,7 +64,7 @@ func StartMailDaemon() {
} }
// Close the connection to the SMTP server if no email was sent in // Close the connection to the SMTP server if no email was sent in
// the last 30 seconds. // the last 30 seconds.
case <-time.After(viper.GetDuration("mailer.queuetimeout") * time.Second): case <-time.After(config.MailerQueueTimeout.GetDuration() * time.Second):
if open { if open {
if err := s.Close(); err != nil { if err := s.Close(); err != nil {
log.Log.Error("Error closing the mail server connection: %s\n", err) log.Log.Error("Error closing the mail server connection: %s\n", err)

View File

@ -18,9 +18,9 @@ package mail
import ( import (
"bytes" "bytes"
"code.vikunja.io/api/pkg/config"
"code.vikunja.io/api/pkg/utils" "code.vikunja.io/api/pkg/utils"
"github.com/labstack/gommon/log" "github.com/labstack/gommon/log"
"github.com/spf13/viper"
"gopkg.in/gomail.v2" "gopkg.in/gomail.v2"
"text/template" "text/template"
) )
@ -54,7 +54,7 @@ type header struct {
// SendMail puts a mail in the queue // SendMail puts a mail in the queue
func SendMail(opts *Opts) { func SendMail(opts *Opts) {
m := gomail.NewMessage() m := gomail.NewMessage()
m.SetHeader("From", viper.GetString("mailer.fromemail")) m.SetHeader("From", config.MailerFromEmail.GetString())
m.SetHeader("To", opts.To) m.SetHeader("To", opts.To)
m.SetHeader("Subject", opts.Subject) m.SetHeader("Subject", opts.Subject)
for _, h := range opts.Headers { for _, h := range opts.Headers {
@ -85,13 +85,13 @@ func SendMailWithTemplate(to, subject, tpl string, data map[string]interface{})
var plainContent bytes.Buffer var plainContent bytes.Buffer
t := &Template{ t := &Template{
Templates: template.Must(template.ParseGlob(viper.GetString("service.rootpath") + "/templates/mail/*.tmpl")), Templates: template.Must(template.ParseGlob(config.ServiceRootpath.GetString() + "/templates/mail/*.tmpl")),
} }
boundary := "np" + utils.MakeRandomString(13) boundary := "np" + utils.MakeRandomString(13)
data["Boundary"] = boundary data["Boundary"] = boundary
data["FrontendURL"] = viper.GetString("service.frontendurl") data["FrontendURL"] = config.ServiceFrontendurl.GetString()
if err := t.Templates.ExecuteTemplate(&htmlContent, tpl+".html.tmpl", data); err != nil { if err := t.Templates.ExecuteTemplate(&htmlContent, tpl+".html.tmpl", data); err != nil {
log.Error(3, "Template: %v", err) log.Error(3, "Template: %v", err)

View File

@ -17,12 +17,12 @@
package metrics package metrics
import ( import (
"code.vikunja.io/api/pkg/config"
"code.vikunja.io/api/pkg/log" "code.vikunja.io/api/pkg/log"
"code.vikunja.io/api/pkg/red" "code.vikunja.io/api/pkg/red"
"github.com/go-redis/redis" "github.com/go-redis/redis"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto" "github.com/prometheus/client_golang/prometheus/promauto"
"github.com/spf13/viper"
) )
var r *redis.Client var r *redis.Client
@ -112,7 +112,7 @@ func SetCount(count int64, key string) error {
// UpdateCount updates a count with a given amount // UpdateCount updates a count with a given amount
func UpdateCount(update int64, key string) { func UpdateCount(update int64, key string) {
if !viper.GetBool("service.enablemetrics") { if !config.ServiceEnableMetrics.GetBool() {
return return
} }
oldtotal, err := GetCount(key) oldtotal, err := GetCount(key)

View File

@ -17,12 +17,12 @@
package migration package migration
import ( import (
"code.vikunja.io/api/pkg/config"
"code.vikunja.io/api/pkg/db" "code.vikunja.io/api/pkg/db"
"code.vikunja.io/api/pkg/log" "code.vikunja.io/api/pkg/log"
"code.vikunja.io/api/pkg/models" "code.vikunja.io/api/pkg/models"
"github.com/go-xorm/xorm" "github.com/go-xorm/xorm"
"github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter"
"github.com/spf13/viper"
"os" "os"
"sort" "sort"
"src.techknowlogick.com/xormigrate" "src.techknowlogick.com/xormigrate"
@ -103,7 +103,7 @@ func Rollback(migrationID string) {
// Deletes a column from a table. All arguments are strings, to let them be standalone and not depending on any struct. // Deletes a column from a table. All arguments are strings, to let them be standalone and not depending on any struct.
func dropTableColum(x *xorm.Engine, tableName, col string) error { func dropTableColum(x *xorm.Engine, tableName, col string) error {
switch viper.GetString("database.type") { switch config.DatabaseType.GetString() {
case "sqlite": case "sqlite":
log.Log.Warning("Unable to drop columns in SQLite") log.Log.Warning("Unable to drop columns in SQLite")
case "mysql": case "mysql":

View File

@ -18,11 +18,10 @@ package models
import ( import (
"code.vikunja.io/api/pkg/config" "code.vikunja.io/api/pkg/config"
"github.com/spf13/viper"
"testing" "testing"
) )
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
config.InitConfig() config.InitConfig()
MainTest(m, viper.GetString("service.rootpath")) MainTest(m, config.ServiceRootpath.GetString())
} }

View File

@ -17,6 +17,7 @@
package models package models
import ( import (
"code.vikunja.io/api/pkg/config"
"code.vikunja.io/api/pkg/db" "code.vikunja.io/api/pkg/db"
"code.vikunja.io/api/pkg/log" "code.vikunja.io/api/pkg/log"
"encoding/gob" "encoding/gob"
@ -24,7 +25,6 @@ import (
"github.com/go-xorm/xorm" "github.com/go-xorm/xorm"
xrc "github.com/go-xorm/xorm-redis-cache" xrc "github.com/go-xorm/xorm-redis-cache"
_ "github.com/mattn/go-sqlite3" // Because. _ "github.com/mattn/go-sqlite3" // Because.
"github.com/spf13/viper"
) )
var ( var (
@ -61,13 +61,13 @@ func SetEngine() (err error) {
// Cache // Cache
// We have to initialize the cache here to avoid import cycles // We have to initialize the cache here to avoid import cycles
if viper.GetBool("cache.enabled") { if config.CacheEnabled.GetBool() {
switch viper.GetString("cache.type") { switch config.CacheType.GetString() {
case "memory": case "memory":
cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), viper.GetInt("cache.maxelementsize")) cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), config.CacheMaxElementSize.GetInt())
x.SetDefaultCacher(cacher) x.SetDefaultCacher(cacher)
case "redis": case "redis":
cacher := xrc.NewRedisCacher(viper.GetString("redis.host"), viper.GetString("redis.password"), xrc.DEFAULT_EXPIRATION, x.Logger()) cacher := xrc.NewRedisCacher(config.RedisEnabled.GetString(), config.RedisPassword.GetString(), xrc.DEFAULT_EXPIRATION, x.Logger())
x.SetDefaultCacher(cacher) x.SetDefaultCacher(cacher)
gob.Register(GetTables()) gob.Register(GetTables())
default: default:
@ -85,7 +85,7 @@ func getLimitFromPageIndex(page int) (limit, start int) {
return 0, 0 return 0, 0
} }
limit = viper.GetInt("service.pagecount") limit = config.ServicePageCount.GetInt()
start = limit * (page - 1) start = limit * (page - 1)
return return
} }

View File

@ -24,7 +24,6 @@ import (
"fmt" "fmt"
"github.com/go-xorm/core" "github.com/go-xorm/core"
"github.com/go-xorm/xorm" "github.com/go-xorm/xorm"
"github.com/spf13/viper"
"gopkg.in/testfixtures.v2" "gopkg.in/testfixtures.v2"
"os" "os"
"path/filepath" "path/filepath"
@ -71,7 +70,7 @@ func createTestEngine(fixturesDir string) error {
return err return err
} }
if viper.GetString("database.type") == "mysql" { if config.DatabaseType.GetString() == "mysql" {
fixturesHelper = &testfixtures.MySQL{} fixturesHelper = &testfixtures.MySQL{}
} }
} else { } else {

View File

@ -17,10 +17,10 @@
package models package models
import ( import (
"code.vikunja.io/api/pkg/config"
"code.vikunja.io/api/pkg/mail" "code.vikunja.io/api/pkg/mail"
"code.vikunja.io/api/pkg/metrics" "code.vikunja.io/api/pkg/metrics"
"code.vikunja.io/api/pkg/utils" "code.vikunja.io/api/pkg/utils"
"github.com/spf13/viper"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
@ -69,7 +69,7 @@ func CreateUser(user User) (newUser User, err error) {
} }
newUser.IsActive = true newUser.IsActive = true
if viper.GetBool("mailer.enabled") { if config.MailerEnabled.GetBool() {
// The new user should not be activated until it confirms his mail address // The new user should not be activated until it confirms his mail address
newUser.IsActive = false newUser.IsActive = false
// Generate a confirm token // Generate a confirm token
@ -99,7 +99,7 @@ func CreateUser(user User) (newUser User, err error) {
} }
// Dont send a mail if we're testing // Dont send a mail if we're testing
if !viper.GetBool("mailer.enabled") { if !config.MailerEnabled.GetBool() {
return newUserOut, err return newUserOut, err
} }

View File

@ -17,9 +17,9 @@
package models package models
import ( import (
"code.vikunja.io/api/pkg/config"
"code.vikunja.io/api/pkg/mail" "code.vikunja.io/api/pkg/mail"
"code.vikunja.io/api/pkg/utils" "code.vikunja.io/api/pkg/utils"
"github.com/spf13/viper"
) )
// PasswordReset holds the data to reset a password // PasswordReset holds the data to reset a password
@ -62,7 +62,7 @@ func UserPasswordReset(reset *PasswordReset) (err error) {
} }
// Dont send a mail if we're testing // Dont send a mail if we're testing
if !viper.GetBool("mailer.enabled") { if !config.MailerEnabled.GetBool() {
return return
} }
@ -103,7 +103,7 @@ func RequestUserPasswordResetToken(tr *PasswordTokenRequest) (err error) {
} }
// Dont send a mail if we're testing // Dont send a mail if we're testing
if !viper.GetBool("mailer.enabled") { if !config.MailerEnabled.GetBool() {
return return
} }

View File

@ -17,27 +17,27 @@
package red package red
import ( import (
"code.vikunja.io/api/pkg/config"
"code.vikunja.io/api/pkg/log" "code.vikunja.io/api/pkg/log"
"github.com/go-redis/redis" "github.com/go-redis/redis"
"github.com/spf13/viper"
) )
var r *redis.Client var r *redis.Client
// InitRedis initializes a redis connection // InitRedis initializes a redis connection
func InitRedis() { func InitRedis() {
if !viper.GetBool("redis.enabled") { if !config.RedisEnabled.GetBool() {
return return
} }
if viper.GetString("redis.host") == "" { if config.RedisHost.GetString() == "" {
log.Log.Fatal("No redis host provided.") log.Log.Fatal("No redis host provided.")
} }
r = redis.NewClient(&redis.Options{ r = redis.NewClient(&redis.Options{
Addr: viper.GetString("redis.host"), Addr: config.RedisHost.GetString(),
Password: viper.GetString("redis.password"), Password: config.RedisPassword.GetString(),
DB: viper.GetInt("redis.db"), DB: config.RedisDB.GetInt(),
}) })
err := r.Ping().Err() err := r.Ping().Err()

View File

@ -17,11 +17,11 @@
package v1 package v1
import ( import (
"code.vikunja.io/api/pkg/config"
"code.vikunja.io/api/pkg/models" "code.vikunja.io/api/pkg/models"
"code.vikunja.io/web/handler" "code.vikunja.io/web/handler"
"github.com/dgrijalva/jwt-go" "github.com/dgrijalva/jwt-go"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/spf13/viper"
"net/http" "net/http"
"time" "time"
) )
@ -77,5 +77,5 @@ func CreateNewJWTTokenForUser(user *models.User) (token string, err error) {
claims["avatar"] = user.AvatarURL claims["avatar"] = user.AvatarURL
// Generate encoded token and send it as response. // Generate encoded token and send it as response.
return t.SignedString([]byte(viper.GetString("service.JWTSecret"))) return t.SignedString([]byte(config.ServiceJWTSecret.GetString()))
} }

View File

@ -39,6 +39,7 @@
package routes package routes
import ( import (
"code.vikunja.io/api/pkg/config"
"code.vikunja.io/api/pkg/log" "code.vikunja.io/api/pkg/log"
"code.vikunja.io/api/pkg/metrics" "code.vikunja.io/api/pkg/metrics"
"code.vikunja.io/api/pkg/models" "code.vikunja.io/api/pkg/models"
@ -52,7 +53,6 @@ import (
"github.com/labstack/echo/v4/middleware" "github.com/labstack/echo/v4/middleware"
elog "github.com/labstack/gommon/log" elog "github.com/labstack/gommon/log"
"github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/spf13/viper"
"strings" "strings"
) )
@ -88,7 +88,7 @@ func NewEcho() *echo.Echo {
e.HideBanner = true e.HideBanner = true
if l, ok := e.Logger.(*elog.Logger); ok { if l, ok := e.Logger.(*elog.Logger); ok {
if viper.GetString("log.echo") == "off" { if config.LogEcho.GetString() == "off" {
l.SetLevel(elog.OFF) l.SetLevel(elog.OFF)
} }
l.EnableColor() l.EnableColor()
@ -97,7 +97,7 @@ func NewEcho() *echo.Echo {
} }
// Logger // Logger
if viper.GetString("log.http") != "off" { if config.LogHTTP.GetString() != "off" {
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
Format: log.WebFmt + "\n", Format: log.WebFmt + "\n",
Output: log.GetLogWriter("http"), Output: log.GetLogWriter("http"),
@ -121,7 +121,7 @@ func NewEcho() *echo.Echo {
// RegisterRoutes registers all routes for the application // RegisterRoutes registers all routes for the application
func RegisterRoutes(e *echo.Echo) { func RegisterRoutes(e *echo.Echo) {
if viper.GetBool("service.enablecaldav") { if config.ServiceEnableCaldav.GetBool() {
// Caldav routes // Caldav routes
wkg := e.Group("/.well-known") wkg := e.Group("/.well-known")
wkg.Use(middleware.BasicAuth(caldavBasicAuth)) wkg.Use(middleware.BasicAuth(caldavBasicAuth))
@ -155,9 +155,9 @@ func registerAPIRoutes(a *echo.Group) {
a.GET("/docs", apiv1.RedocUI) a.GET("/docs", apiv1.RedocUI)
// Prometheus endpoint // Prometheus endpoint
if viper.GetBool("service.enablemetrics") { if config.ServiceEnableMetrics.GetBool() {
if !viper.GetBool("redis.enabled") { if !config.RedisEnabled.GetBool() {
log.Log.Fatal("You have to enable redis in order to use metrics") log.Log.Fatal("You have to enable redis in order to use metrics")
} }
@ -217,10 +217,10 @@ func registerAPIRoutes(a *echo.Group) {
// ===== Routes with Authetification ===== // ===== Routes with Authetification =====
// Authetification // Authetification
a.Use(middleware.JWT([]byte(viper.GetString("service.JWTSecret")))) a.Use(middleware.JWT([]byte(config.ServiceJWTSecret.GetString())))
// Middleware to collect metrics // Middleware to collect metrics
if viper.GetBool("service.enablemetrics") { if config.ServiceJWTSecret.GetBool() {
a.Use(func(next echo.HandlerFunc) echo.HandlerFunc { a.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error { return func(c echo.Context) error {