1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00

refactor: move config to separate package

chore: load config from main method
This commit is contained in:
Ferdinand Mütsch 2020-09-29 18:55:07 +02:00
parent 062a9c6f57
commit f843be8d12
20 changed files with 79 additions and 62 deletions

View File

@ -1,10 +1,11 @@
package models package config
import ( import (
"encoding/json" "encoding/json"
"github.com/gorilla/securecookie" "github.com/gorilla/securecookie"
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
"github.com/joho/godotenv" "github.com/joho/godotenv"
"github.com/muety/wakapi/models"
migrate "github.com/rubenv/sql-migrate" migrate "github.com/rubenv/sql-migrate"
"gopkg.in/ini.v1" "gopkg.in/ini.v1"
"io/ioutil" "io/ioutil"
@ -44,7 +45,7 @@ func (c *Config) IsDev() bool {
return IsDev(c.Env) return IsDev(c.Env)
} }
func (c *Config) GetMigrationFunc(dbDialect string) MigrationFunc { func (c *Config) GetMigrationFunc(dbDialect string) models.MigrationFunc {
switch dbDialect { switch dbDialect {
case "sqlite3": case "sqlite3":
return func(db *gorm.DB) error { return func(db *gorm.DB) error {
@ -63,19 +64,19 @@ func (c *Config) GetMigrationFunc(dbDialect string) MigrationFunc {
} }
default: default:
return func(db *gorm.DB) error { return func(db *gorm.DB) error {
db.AutoMigrate(&Alias{}) db.AutoMigrate(&models.Alias{})
db.AutoMigrate(&Summary{}) db.AutoMigrate(&models.Summary{})
db.AutoMigrate(&SummaryItem{}) db.AutoMigrate(&models.SummaryItem{})
db.AutoMigrate(&User{}) db.AutoMigrate(&models.User{})
db.AutoMigrate(&Heartbeat{}).AddForeignKey("user_id", "users(id)", "RESTRICT", "RESTRICT") db.AutoMigrate(&models.Heartbeat{}).AddForeignKey("user_id", "users(id)", "RESTRICT", "RESTRICT")
db.AutoMigrate(&SummaryItem{}).AddForeignKey("summary_id", "summaries(id)", "CASCADE", "CASCADE") db.AutoMigrate(&models.SummaryItem{}).AddForeignKey("summary_id", "summaries(id)", "CASCADE", "CASCADE")
db.AutoMigrate(&KeyStringValue{}) db.AutoMigrate(&models.KeyStringValue{})
return nil return nil
} }
} }
} }
func (c *Config) GetFixturesFunc(dbDialect string) MigrationFunc { func (c *Config) GetFixturesFunc(dbDialect string) models.MigrationFunc {
return func(db *gorm.DB) error { return func(db *gorm.DB) error {
migrations := &migrate.FileMigrationSource{ migrations := &migrate.FileMigrationSource{
Dir: "migrations/common/fixtures", Dir: "migrations/common/fixtures",
@ -96,14 +97,6 @@ func IsDev(env string) bool {
return env == "dev" || env == "development" return env == "dev" || env == "development"
} }
func SetConfig(config *Config) {
cfg = config
}
func GetConfig() *Config {
return cfg
}
func LookupFatal(key string) string { func LookupFatal(key string) string {
v, ok := os.LookupEnv(key) v, ok := os.LookupEnv(key)
if !ok { if !ok {
@ -127,7 +120,15 @@ func readVersion() string {
return string(bytes) return string(bytes)
} }
func readConfig() *Config { func Set(config *Config) {
cfg = config
}
func Get() *Config {
return cfg
}
func Load() *Config {
if err := godotenv.Load(); err != nil { if err := godotenv.Load(); err != nil {
log.Fatal(err) log.Fatal(err)
} }
@ -206,7 +207,7 @@ func readConfig() *Config {
securecookie.GenerateRandomKey(32), securecookie.GenerateRandomKey(32),
) )
return &Config{ Set(&Config{
Env: env, Env: env,
Version: version, Version: version,
Port: port, Port: port,
@ -225,5 +226,7 @@ func readConfig() *Config {
PasswordSalt: passwordSalt, PasswordSalt: passwordSalt,
CustomLanguages: customLangs, CustomLanguages: customLangs,
LanguageColors: colors, LanguageColors: colors,
} })
return Get()
} }

View File

@ -2,6 +2,7 @@ package main
import ( import (
"github.com/gorilla/handlers" "github.com/gorilla/handlers"
conf "github.com/muety/wakapi/config"
"log" "log"
"net/http" "net/http"
"strconv" "strconv"
@ -23,7 +24,7 @@ import (
var ( var (
db *gorm.DB db *gorm.DB
config *models.Config config *conf.Config
) )
var ( var (
@ -38,7 +39,7 @@ var (
// TODO: Refactor entire project to be structured after business domains // TODO: Refactor entire project to be structured after business domains
func main() { func main() {
config = models.GetConfig() config = conf.Load()
// Enable line numbers in logging // Enable line numbers in logging
if config.IsDev() { if config.IsDev() {

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
config2 "github.com/muety/wakapi/config"
"github.com/muety/wakapi/utils" "github.com/muety/wakapi/utils"
"log" "log"
"net/http" "net/http"
@ -17,7 +18,7 @@ import (
) )
type AuthenticateMiddleware struct { type AuthenticateMiddleware struct {
config *models.Config config *config2.Config
userSrvc *services.UserService userSrvc *services.UserService
cache *cache.Cache cache *cache.Cache
whitelistPaths []string whitelistPaths []string
@ -25,7 +26,7 @@ type AuthenticateMiddleware struct {
func NewAuthenticateMiddleware(userService *services.UserService, whitelistPaths []string) *AuthenticateMiddleware { func NewAuthenticateMiddleware(userService *services.UserService, whitelistPaths []string) *AuthenticateMiddleware {
return &AuthenticateMiddleware{ return &AuthenticateMiddleware{
config: models.GetConfig(), config: config2.Get(),
userSrvc: userService, userSrvc: userService,
cache: cache.New(1*time.Hour, 2*time.Hour), cache: cache.New(1*time.Hour, 2*time.Hour),
whitelistPaths: whitelistPaths, whitelistPaths: whitelistPaths,

View File

@ -1,5 +1,4 @@
package models package models
func init() { func init() {
SetConfig(readConfig())
} }

View File

@ -2,6 +2,7 @@ package v1
import ( import (
"github.com/gorilla/mux" "github.com/gorilla/mux"
config2 "github.com/muety/wakapi/config"
"github.com/muety/wakapi/models" "github.com/muety/wakapi/models"
v1 "github.com/muety/wakapi/models/compat/shields/v1" v1 "github.com/muety/wakapi/models/compat/shields/v1"
"github.com/muety/wakapi/services" "github.com/muety/wakapi/services"
@ -19,14 +20,14 @@ const (
type BadgeHandler struct { type BadgeHandler struct {
userSrvc *services.UserService userSrvc *services.UserService
summarySrvc *services.SummaryService summarySrvc *services.SummaryService
config *models.Config config *config2.Config
} }
func NewBadgeHandler(summaryService *services.SummaryService, userService *services.UserService) *BadgeHandler { func NewBadgeHandler(summaryService *services.SummaryService, userService *services.UserService) *BadgeHandler {
return &BadgeHandler{ return &BadgeHandler{
summarySrvc: summaryService, summarySrvc: summaryService,
userSrvc: userService, userSrvc: userService,
config: models.GetConfig(), config: config2.Get(),
} }
} }

View File

@ -2,6 +2,7 @@ package v1
import ( import (
"github.com/gorilla/mux" "github.com/gorilla/mux"
config2 "github.com/muety/wakapi/config"
"github.com/muety/wakapi/models" "github.com/muety/wakapi/models"
v1 "github.com/muety/wakapi/models/compat/wakatime/v1" v1 "github.com/muety/wakapi/models/compat/wakatime/v1"
"github.com/muety/wakapi/services" "github.com/muety/wakapi/services"
@ -13,13 +14,13 @@ import (
type AllTimeHandler struct { type AllTimeHandler struct {
summarySrvc *services.SummaryService summarySrvc *services.SummaryService
config *models.Config config *config2.Config
} }
func NewAllTimeHandler(summaryService *services.SummaryService) *AllTimeHandler { func NewAllTimeHandler(summaryService *services.SummaryService) *AllTimeHandler {
return &AllTimeHandler{ return &AllTimeHandler{
summarySrvc: summaryService, summarySrvc: summaryService,
config: models.GetConfig(), config: config2.Get(),
} }
} }

View File

@ -3,6 +3,7 @@ package v1
import ( import (
"errors" "errors"
"github.com/gorilla/mux" "github.com/gorilla/mux"
config2 "github.com/muety/wakapi/config"
"github.com/muety/wakapi/models" "github.com/muety/wakapi/models"
v1 "github.com/muety/wakapi/models/compat/wakatime/v1" v1 "github.com/muety/wakapi/models/compat/wakatime/v1"
"github.com/muety/wakapi/services" "github.com/muety/wakapi/services"
@ -14,13 +15,13 @@ import (
type SummariesHandler struct { type SummariesHandler struct {
summarySrvc *services.SummaryService summarySrvc *services.SummaryService
config *models.Config config *config2.Config
} }
func NewSummariesHandler(summaryService *services.SummaryService) *SummariesHandler { func NewSummariesHandler(summaryService *services.SummaryService) *SummariesHandler {
return &SummariesHandler{ return &SummariesHandler{
summarySrvc: summaryService, summarySrvc: summaryService,
config: models.GetConfig(), config: config2.Get(),
} }
} }

View File

@ -2,6 +2,7 @@ package routes
import ( import (
"encoding/json" "encoding/json"
config2 "github.com/muety/wakapi/config"
"net/http" "net/http"
"os" "os"
@ -12,13 +13,13 @@ import (
) )
type HeartbeatHandler struct { type HeartbeatHandler struct {
config *models.Config config *config2.Config
heartbeatSrvc *services.HeartbeatService heartbeatSrvc *services.HeartbeatService
} }
func NewHeartbeatHandler(heartbeatService *services.HeartbeatService) *HeartbeatHandler { func NewHeartbeatHandler(heartbeatService *services.HeartbeatService) *HeartbeatHandler {
return &HeartbeatHandler{ return &HeartbeatHandler{
config: models.GetConfig(), config: config2.Get(),
heartbeatSrvc: heartbeatService, heartbeatSrvc: heartbeatService,
} }
} }

View File

@ -3,6 +3,7 @@ package routes
import ( import (
"fmt" "fmt"
"github.com/gorilla/schema" "github.com/gorilla/schema"
config2 "github.com/muety/wakapi/config"
"github.com/muety/wakapi/middlewares" "github.com/muety/wakapi/middlewares"
"github.com/muety/wakapi/models" "github.com/muety/wakapi/models"
"github.com/muety/wakapi/services" "github.com/muety/wakapi/services"
@ -13,7 +14,7 @@ import (
) )
type IndexHandler struct { type IndexHandler struct {
config *models.Config config *config2.Config
userSrvc *services.UserService userSrvc *services.UserService
keyValueSrvc *services.KeyValueService keyValueSrvc *services.KeyValueService
} }
@ -23,7 +24,7 @@ var signupDecoder = schema.NewDecoder()
func NewIndexHandler(userService *services.UserService, keyValueService *services.KeyValueService) *IndexHandler { func NewIndexHandler(userService *services.UserService, keyValueService *services.KeyValueService) *IndexHandler {
return &IndexHandler{ return &IndexHandler{
config: models.GetConfig(), config: config2.Get(),
userSrvc: userService, userSrvc: userService,
keyValueSrvc: keyValueService, keyValueSrvc: keyValueService,
} }

View File

@ -2,7 +2,7 @@ package routes
import ( import (
"fmt" "fmt"
"github.com/muety/wakapi/models" "github.com/muety/wakapi/config"
"github.com/muety/wakapi/utils" "github.com/muety/wakapi/utils"
"html/template" "html/template"
"io/ioutil" "io/ioutil"
@ -25,10 +25,10 @@ func loadTemplates() {
"title": strings.Title, "title": strings.Title,
"capitalize": utils.Capitalize, "capitalize": utils.Capitalize,
"getBasePath": func() string { "getBasePath": func() string {
return models.GetConfig().BasePath return config.Get().BasePath
}, },
"getVersion": func() string { "getVersion": func() string {
return models.GetConfig().Version return config.Get().Version
}, },
"htmlSafe": func(html string) template.HTML { "htmlSafe": func(html string) template.HTML {
return template.HTML(html) return template.HTML(html)

View File

@ -3,6 +3,7 @@ package routes
import ( import (
"fmt" "fmt"
"github.com/gorilla/schema" "github.com/gorilla/schema"
config2 "github.com/muety/wakapi/config"
"github.com/muety/wakapi/models" "github.com/muety/wakapi/models"
"github.com/muety/wakapi/services" "github.com/muety/wakapi/services"
"github.com/muety/wakapi/utils" "github.com/muety/wakapi/utils"
@ -11,7 +12,7 @@ import (
) )
type SettingsHandler struct { type SettingsHandler struct {
config *models.Config config *config2.Config
userSrvc *services.UserService userSrvc *services.UserService
} }
@ -19,7 +20,7 @@ var credentialsDecoder = schema.NewDecoder()
func NewSettingsHandler(userService *services.UserService) *SettingsHandler { func NewSettingsHandler(userService *services.UserService) *SettingsHandler {
return &SettingsHandler{ return &SettingsHandler{
config: models.GetConfig(), config: config2.Get(),
userSrvc: userService, userSrvc: userService,
} }
} }

View File

@ -1,6 +1,7 @@
package routes package routes
import ( import (
config2 "github.com/muety/wakapi/config"
"github.com/muety/wakapi/models" "github.com/muety/wakapi/models"
"github.com/muety/wakapi/services" "github.com/muety/wakapi/services"
"github.com/muety/wakapi/utils" "github.com/muety/wakapi/utils"
@ -9,13 +10,13 @@ import (
type SummaryHandler struct { type SummaryHandler struct {
summarySrvc *services.SummaryService summarySrvc *services.SummaryService
config *models.Config config *config2.Config
} }
func NewSummaryHandler(summaryService *services.SummaryService) *SummaryHandler { func NewSummaryHandler(summaryService *services.SummaryService) *SummaryHandler {
return &SummaryHandler{ return &SummaryHandler{
summarySrvc: summaryService, summarySrvc: summaryService,
config: models.GetConfig(), config: config2.Get(),
} }
} }

View File

@ -1,6 +1,7 @@
package services package services
import ( import (
"github.com/muety/wakapi/config"
"log" "log"
"runtime" "runtime"
"time" "time"
@ -15,7 +16,7 @@ const (
) )
type AggregationService struct { type AggregationService struct {
Config *models.Config Config *config.Config
Db *gorm.DB Db *gorm.DB
UserService *UserService UserService *UserService
SummaryService *SummaryService SummaryService *SummaryService
@ -24,7 +25,7 @@ type AggregationService struct {
func NewAggregationService(db *gorm.DB, userService *UserService, summaryService *SummaryService, heartbeatService *HeartbeatService) *AggregationService { func NewAggregationService(db *gorm.DB, userService *UserService, summaryService *SummaryService, heartbeatService *HeartbeatService) *AggregationService {
return &AggregationService{ return &AggregationService{
Config: models.GetConfig(), Config: config.Get(),
Db: db, Db: db,
UserService: userService, UserService: userService,
SummaryService: summaryService, SummaryService: summaryService,

View File

@ -2,6 +2,7 @@ package services
import ( import (
"errors" "errors"
"github.com/muety/wakapi/config"
"sync" "sync"
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
@ -9,13 +10,13 @@ import (
) )
type AliasService struct { type AliasService struct {
Config *models.Config Config *config.Config
Db *gorm.DB Db *gorm.DB
} }
func NewAliasService(db *gorm.DB) *AliasService { func NewAliasService(db *gorm.DB) *AliasService {
return &AliasService{ return &AliasService{
Config: models.GetConfig(), Config: config.Get(),
Db: db, Db: db,
} }
} }

View File

@ -2,6 +2,7 @@ package services
import ( import (
"github.com/jasonlvhit/gocron" "github.com/jasonlvhit/gocron"
"github.com/muety/wakapi/config"
"github.com/muety/wakapi/utils" "github.com/muety/wakapi/utils"
"log" "log"
"time" "time"
@ -17,13 +18,13 @@ const (
) )
type HeartbeatService struct { type HeartbeatService struct {
Config *models.Config Config *config.Config
Db *gorm.DB Db *gorm.DB
} }
func NewHeartbeatService(db *gorm.DB) *HeartbeatService { func NewHeartbeatService(db *gorm.DB) *HeartbeatService {
return &HeartbeatService{ return &HeartbeatService{
Config: models.GetConfig(), Config: config.Get(),
Db: db, Db: db,
} }
} }

View File

@ -3,17 +3,18 @@ package services
import ( import (
"errors" "errors"
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
"github.com/muety/wakapi/config"
"github.com/muety/wakapi/models" "github.com/muety/wakapi/models"
) )
type KeyValueService struct { type KeyValueService struct {
Config *models.Config Config *config.Config
Db *gorm.DB Db *gorm.DB
} }
func NewKeyValueService(db *gorm.DB) *KeyValueService { func NewKeyValueService(db *gorm.DB) *KeyValueService {
return &KeyValueService{ return &KeyValueService{
Config: models.GetConfig(), Config: config.Get(),
Db: db, Db: db,
} }
} }

View File

@ -3,6 +3,7 @@ package services
import ( import (
"crypto/md5" "crypto/md5"
"errors" "errors"
"github.com/muety/wakapi/config"
"github.com/patrickmn/go-cache" "github.com/patrickmn/go-cache"
"math" "math"
"sort" "sort"
@ -14,7 +15,7 @@ import (
) )
type SummaryService struct { type SummaryService struct {
Config *models.Config Config *config.Config
Cache *cache.Cache Cache *cache.Cache
Db *gorm.DB Db *gorm.DB
HeartbeatService *HeartbeatService HeartbeatService *HeartbeatService
@ -23,7 +24,7 @@ type SummaryService struct {
func NewSummaryService(db *gorm.DB, heartbeatService *HeartbeatService, aliasService *AliasService) *SummaryService { func NewSummaryService(db *gorm.DB, heartbeatService *HeartbeatService, aliasService *AliasService) *SummaryService {
return &SummaryService{ return &SummaryService{
Config: models.GetConfig(), Config: config.Get(),
Cache: cache.New(24*time.Hour, 24*time.Hour), Cache: cache.New(24*time.Hour, 24*time.Hour),
Db: db, Db: db,
HeartbeatService: heartbeatService, HeartbeatService: heartbeatService,

View File

@ -3,19 +3,20 @@ package services
import ( import (
"errors" "errors"
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
"github.com/muety/wakapi/config"
"github.com/muety/wakapi/models" "github.com/muety/wakapi/models"
"github.com/muety/wakapi/utils" "github.com/muety/wakapi/utils"
uuid "github.com/satori/go.uuid" uuid "github.com/satori/go.uuid"
) )
type UserService struct { type UserService struct {
Config *models.Config Config *config.Config
Db *gorm.DB Db *gorm.DB
} }
func NewUserService(db *gorm.DB) *UserService { func NewUserService(db *gorm.DB) *UserService {
return &UserService{ return &UserService{
Config: models.GetConfig(), Config: config.Get(),
Db: db, Db: db,
} }
} }

View File

@ -5,6 +5,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/hex" "encoding/hex"
"errors" "errors"
"github.com/muety/wakapi/config"
"github.com/muety/wakapi/models" "github.com/muety/wakapi/models"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
"net/http" "net/http"
@ -45,7 +46,7 @@ func ExtractBearerAuth(r *http.Request) (key string, err error) {
return string(keyBytes), err return string(keyBytes), err
} }
func ExtractCookieAuth(r *http.Request, config *models.Config) (login *models.Login, err error) { func ExtractCookieAuth(r *http.Request, config *config.Config) (login *models.Login, err error) {
cookie, err := r.Cookie(models.AuthCookieKey) cookie, err := r.Cookie(models.AuthCookieKey)
if err != nil { if err != nil {
return nil, errors.New("missing authentication") return nil, errors.New("missing authentication")

View File

@ -3,10 +3,9 @@ package utils
import ( import (
"errors" "errors"
"fmt" "fmt"
"github.com/muety/wakapi/config"
"regexp" "regexp"
"time" "time"
"github.com/muety/wakapi/models"
) )
func ParseDate(date string) (time.Time, error) { func ParseDate(date string) (time.Time, error) {
@ -30,7 +29,7 @@ func ParseUserAgent(ua string) (string, string, error) {
return groups[0][1], groups[0][2], nil return groups[0][1], groups[0][2], nil
} }
func MakeConnectionString(config *models.Config) string { func MakeConnectionString(config *config.Config) string {
switch config.DbDialect { switch config.DbDialect {
case "mysql": case "mysql":
return mySqlConnectionString(config) return mySqlConnectionString(config)
@ -42,7 +41,7 @@ func MakeConnectionString(config *models.Config) string {
return "" return ""
} }
func mySqlConnectionString(config *models.Config) string { func mySqlConnectionString(config *config.Config) string {
//location, _ := time.LoadLocation("Local") //location, _ := time.LoadLocation("Local")
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=true&loc=%s&sql_mode=ANSI_QUOTES", return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=true&loc=%s&sql_mode=ANSI_QUOTES",
config.DbUser, config.DbUser,
@ -54,7 +53,7 @@ func mySqlConnectionString(config *models.Config) string {
) )
} }
func postgresConnectionString(config *models.Config) string { func postgresConnectionString(config *config.Config) string {
return fmt.Sprintf("host=%s port=%d user=%s dbname=%s password=%s sslmode=disable", return fmt.Sprintf("host=%s port=%d user=%s dbname=%s password=%s sslmode=disable",
config.DbHost, config.DbHost,
config.DbPort, config.DbPort,
@ -64,6 +63,6 @@ func postgresConnectionString(config *models.Config) string {
) )
} }
func sqliteConnectionString(config *models.Config) string { func sqliteConnectionString(config *config.Config) string {
return config.DbName return config.DbName
} }