aboutsummaryrefslogtreecommitdiff
path: root/common
diff options
context:
space:
mode:
Diffstat (limited to 'common')
-rw-r--r--common/config.go64
-rw-r--r--common/context.go51
2 files changed, 115 insertions, 0 deletions
diff --git a/common/config.go b/common/config.go
new file mode 100644
index 0000000..07cff8d
--- /dev/null
+++ b/common/config.go
@@ -0,0 +1,64 @@
+package common
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/pelletier/go-toml/v2"
+ "gorm.io/driver/postgres"
+ "gorm.io/gorm"
+)
+
+type Config struct {
+ Debug bool `toml:"debug"`
+ Author string `toml:"author"`
+ Database *PostgresConfig `toml:"database"`
+}
+
+type PostgresConfig struct {
+ Host string `toml:"host"`
+ User string `toml:"user"`
+ Password string `toml:"password"`
+ DBName string `toml:"db_name"`
+ Port int `toml:"port"`
+}
+
+func (p *PostgresConfig) SetDefaultValues() {
+ p.Host = "localhost"
+ p.User = ""
+ p.Password = ""
+ p.DBName = ""
+ p.Port = 5432
+}
+
+func (p *PostgresConfig) Connect() (*gorm.DB, error) {
+ db, err := gorm.Open(postgres.Open(p.generateDsn()), &gorm.Config{})
+ if err != nil {
+ return nil, err
+ }
+ return db, nil
+}
+
+// generateDsn for the connection to postgres using the given config.SQLCredentials
+func (p *PostgresConfig) generateDsn() string {
+ return fmt.Sprintf(
+ "host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=Europe/Paris",
+ p.Host, p.User, p.Password, p.DBName, p.Port,
+ )
+}
+
+func (c *Config) SetDefaultValues() {
+ c.Debug = false
+ c.Author = "anhgelus"
+ c.Database = &PostgresConfig{}
+ c.Database.SetDefaultValues()
+}
+
+func LoadConfig(path string) (*Config, error) {
+ b, err := os.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+ var cfg Config
+ return &cfg, toml.Unmarshal(b, &cfg)
+}
diff --git a/common/context.go b/common/context.go
new file mode 100644
index 0000000..3a79264
--- /dev/null
+++ b/common/context.go
@@ -0,0 +1,51 @@
+package common
+
+import (
+ "context"
+
+ "gorm.io/gorm"
+)
+
+type key uint8
+
+const (
+ keyDB key = 0
+ keyDebug key = 1
+ keyAuthor key = 2
+)
+
+func SetDB(ctx context.Context, db *gorm.DB) context.Context {
+ return context.WithValue(ctx, keyDB, db)
+}
+
+func GetDB(ctx context.Context) *gorm.DB {
+ raw := ctx.Value(keyDB)
+ if raw == nil {
+ return nil
+ }
+ return raw.(*gorm.DB)
+}
+
+func SetDebug(ctx context.Context, b bool) context.Context {
+ return context.WithValue(ctx, keyDebug, b)
+}
+
+func IsDebug(ctx context.Context) bool {
+ raw := ctx.Value(keyDebug)
+ if raw == nil {
+ return false
+ }
+ return raw.(bool)
+}
+
+func SetAuthor(ctx context.Context, s string) context.Context {
+ return context.WithValue(ctx, keyAuthor, s)
+}
+
+func GetAuthor(ctx context.Context) string {
+ raw := ctx.Value(keyAuthor)
+ if raw == nil {
+ return ""
+ }
+ return raw.(string)
+}