feat: config files
This commit is contained in:
4
.gitignore
vendored
4
.gitignore
vendored
@@ -114,4 +114,6 @@ fabric.properties
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/goland+all,go
|
||||
|
||||
build
|
||||
build
|
||||
|
||||
config.json
|
||||
@@ -2,7 +2,12 @@ package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"git.brettb.xyz/goinv/server/internal/config"
|
||||
"github.com/knadh/koanf/parsers/json"
|
||||
"github.com/knadh/koanf/providers/env"
|
||||
"github.com/knadh/koanf/providers/file"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"git.brettb.xyz/goinv/server/internal/api"
|
||||
"git.brettb.xyz/goinv/server/internal/storage"
|
||||
@@ -13,9 +18,22 @@ func main() {
|
||||
seed := flag.Bool("seed", false, "seed the database")
|
||||
flag.Parse()
|
||||
|
||||
datastore, err := storage.NewDataStorePG("127.0.0.1", "postgres", "password", "em_test", "disable") // TODO: CONFIGURATION
|
||||
config.LoadConfig(file.Provider("config.json"), json.Parser())
|
||||
config.LoadConfig(env.Provider("GOINV_SRV_", ".", func(s string) string {
|
||||
return strings.Replace(strings.ToLower(
|
||||
strings.TrimPrefix(s, "GOINV_SRV_")), "_", ".", -1,
|
||||
)
|
||||
}), nil)
|
||||
|
||||
var cfg config.Config
|
||||
err := config.Unmarshal(&cfg)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
log.Fatalf("could not load config: %v", err)
|
||||
}
|
||||
|
||||
datastore, err := storage.NewDataStorePG(cfg.DB.Host, cfg.DB.Username, cfg.DB.Password, cfg.DB.Database, cfg.DB.SSLMode)
|
||||
if err != nil {
|
||||
log.Fatalf("could not connect to database: %v", err)
|
||||
}
|
||||
|
||||
if *seed {
|
||||
|
||||
9
config.example.json
Normal file
9
config.example.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"db": {
|
||||
"host": "127.0.0.1",
|
||||
"username": "postgres",
|
||||
"password": "password",
|
||||
"database": "em_test",
|
||||
"ssl_mode": "disable"
|
||||
}
|
||||
}
|
||||
25
internal/config/config.go
Normal file
25
internal/config/config.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package config
|
||||
|
||||
import "github.com/knadh/koanf"
|
||||
|
||||
var (
|
||||
K = koanf.New(".")
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
DB struct {
|
||||
Host string `koanf:"host"`
|
||||
Username string `koanf:"username"`
|
||||
Password string `koanf:"password"`
|
||||
Database string `koanf:"database"`
|
||||
SSLMode string `koanf:"ssl_mode"`
|
||||
} `koanf:"db"`
|
||||
}
|
||||
|
||||
func LoadConfig(provider koanf.Provider, parser koanf.Parser) error {
|
||||
return K.Load(provider, parser)
|
||||
}
|
||||
|
||||
func Unmarshal(o interface{}) error {
|
||||
return K.Unmarshal("", o)
|
||||
}
|
||||
Reference in New Issue
Block a user