-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
108 lines (93 loc) · 2.57 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"fmt"
"github.com/caarlos0/env/v6"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type AppConfig struct {
Name string `env:"APP_NAME" envDefault:"mochi"`
Host string `env:"APP_HOST" envDefault:"localhost"`
Port int `env:"APP_PORT" envDefault:"8080"`
LogLevel string `env:"LOG_LEVEL" envDefault:"debug"`
TimeZone string `env:"TIME_ZONE" envDefault:"Asia/Jakarta"`
Profile bool `env:"PROFILE_ENABLED" envDefault:"false"`
}
type DatabaseDialect string
const (
DialectMySQL DatabaseDialect = "mysql"
DialectPostgres DatabaseDialect = "postgres"
)
type DatabaseConfig struct {
Host string `env:"DATABASE_HOST"`
Port int `env:"DATABASE_PORT" envDefault:"3306"`
Username string `env:"DATABASE_USERNAME" envDefault:"root"`
Password string `env:"DATABASE_PASSWORD"`
Schema string `env:"DATABASE_SCHEMA"`
Debug bool `env:"DATABASE_DEBUG" envDefault:"false"`
Dialect string `env:"DATABASE_DIALECT"`
}
func (d DatabaseConfig) GetDialector() gorm.Dialector {
switch d.Dialect {
case string(DialectMySQL):
dsn := fmt.Sprintf(
"%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
d.Username,
d.Password,
d.Host,
d.Port,
d.Schema,
)
return mysql.Open(dsn)
case string(DialectPostgres):
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=Asia/Jakarta",
d.Host,
d.Username,
d.Password,
d.Schema,
d.Port,
)
return postgres.Open(dsn)
default:
return nil
}
}
type RedisConfig struct {
Host string `env:"REDIS_HOST"`
Port int `env:"REDIS_PORT" envDefault:"6379"`
Password string `env:"REDIS_PASSWORD"`
DB int `env:"REDIS_DB" envDefault:"0"`
}
type MeilisearchConfig struct {
Host string `env:"MEILISEARCH_HOST" envDefault:"http://localhost:7700"`
MasterKey string `env:"MEILISEARCH_MASTER_KEY" envDefault:""`
}
func (r RedisConfig) GetAddress() string {
return fmt.Sprintf("%s:%d", r.Host, r.Port)
}
type GoroutineConfig struct {
Channel string `env:"CHANNEL" envDefault:""`
Workers int `env:"WORKERS" envDefault:"10"`
}
type PPROF struct {
Host string `env:"PPROF_HOST" envDefault:"localhost"`
Port string `env:"PPROF_PORT" envDefault:"6060"`
IsEnabled bool `env:"PPROF_ENABLED" envDefault:"false"`
}
func (p *PPROF) Address() string {
return fmt.Sprintf("%s:%s", p.Host, p.Port)
}
type Config struct {
AppConfig
DatabaseConfig
RedisConfig
MeilisearchConfig
GoroutineConfig
PPROF
}
func GetConfig() (*Config, error) {
cfg := Config{}
err := env.Parse(&cfg)
return &cfg, err
}