49 lines
1011 B
Go
49 lines
1011 B
Go
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."`
|
|
DatabaseFilePath string `toml:"database_file_path" comment:"Path to sqlite database file."`
|
|
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", DatabaseFilePath: "plm.db", 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
|
|
}
|