first commit
This commit is contained in:
49
internal/config/config.go
Normal file
49
internal/config/config.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/pelletier/go-toml"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Port string `toml:"port" comment:"The port to listen on for the server."`
|
||||
DemoDataPath string `toml:"demo_data_path" comment:"The path to the sql file to load for demo data."`
|
||||
|
||||
}
|
||||
|
||||
func defaultConfig() Config {
|
||||
return Config{Port: "8080", DemoDataPath: ""}
|
||||
}
|
||||
|
||||
|
||||
func LoadConfig(configPath string) Config {
|
||||
f, err := os.ReadFile(configPath)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return initConfig(configPath)
|
||||
}
|
||||
log.Fatal(err)
|
||||
}
|
||||
var cfg Config
|
||||
err = toml.Unmarshal(f, &cfg)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
func initConfig(configPath string) Config {
|
||||
cfg := defaultConfig()
|
||||
b, err := toml.Marshal(cfg)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
err = os.WriteFile(configPath, b, 0666)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
43
internal/db/init.go
Normal file
43
internal/db/init.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"git.artlef.fr/PersonalLibraryManager/internal/model"
|
||||
)
|
||||
|
||||
func Initdb(databaseDir string) *gorm.DB {
|
||||
createDbFolderIfMissing(databaseDir)
|
||||
db, err := gorm.Open(
|
||||
sqlite.Open(
|
||||
fmt.Sprintf(
|
||||
"%s/plm.db", databaseDir)), &gorm.Config{})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
// Migrate the schema
|
||||
db.AutoMigrate(&model.Book{})
|
||||
return db
|
||||
}
|
||||
|
||||
func createDbFolderIfMissing(databaseDir string) {
|
||||
_, openFileErr := os.Open(databaseDir)
|
||||
if os.IsNotExist(openFileErr) {
|
||||
createNonExistingDbFolder(databaseDir)
|
||||
} else if openFileErr != nil {
|
||||
log.Fatal(openFileErr)
|
||||
}
|
||||
}
|
||||
|
||||
func createNonExistingDbFolder(databaseDir string) {
|
||||
log.Printf("Creating missing folder %s\n", databaseDir)
|
||||
err := os.MkdirAll(databaseDir, 0700)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
10
internal/model/model.go
Normal file
10
internal/model/model.go
Normal file
@@ -0,0 +1,10 @@
|
||||
package model
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
type Book struct {
|
||||
gorm.Model
|
||||
Title string `json:"title"`
|
||||
Author string `json:"author"`
|
||||
Rating int `json:"rating"`
|
||||
}
|
||||
Reference in New Issue
Block a user