package database import ( "errors" "os" "path/filepath" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" "github.com/rs/zerolog/log" "github.com/spf13/viper" ) type Manager struct { db *gorm.DB } func New() *Manager { m := new(Manager) m.init() return m } func (m *Manager) init() { m.open() m.db.LogMode(false) if viper.GetBool("Debug") { m.db.LogMode(true) } } func mkdirp(p string) error { src, err := os.Stat(p) if os.IsNotExist(err) { errDir := os.MkdirAll(p, 0755) if errDir != nil { return err } return nil } if src.Mode().IsRegular() { return errors.New("file already exists at path") } return nil } func (m *Manager) open() { log.Info().Msg("opening database") dirname := filepath.Dir(viper.GetString("DbStorageLocation")) err := mkdirp(dirname) if err != nil { log.Panic(). Err(err). Msg("db path erro") } db, err := gorm.Open("sqlite3", viper.GetString("DbStorageLocation")) if err != nil { log.Panic(). Err(err). Msg("failed to open database") } m.db = db m.doMigrations() }