initial commit
This commit is contained in:
commit
ebd5bb09fd
30 changed files with 1920 additions and 0 deletions
89
internal/config/config.go
Normal file
89
internal/config/config.go
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Server ServerConfig
|
||||
Database DatabaseConfig
|
||||
JWT JWTConfig
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
Host string
|
||||
Port string
|
||||
}
|
||||
|
||||
type DatabaseConfig struct {
|
||||
URL string
|
||||
}
|
||||
|
||||
type JWTConfig struct {
|
||||
SecretKey string
|
||||
}
|
||||
|
||||
func LoadConfig(path string) (*Config, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading config file: %w", err)
|
||||
}
|
||||
|
||||
var cfg Config
|
||||
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||||
return nil, fmt.Errorf("parsing config file: %w", err)
|
||||
}
|
||||
|
||||
cfg.applyDefaults()
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
func LoadFromEnv() (*Config, error) {
|
||||
cfg := DefaultConfig()
|
||||
|
||||
if host := os.Getenv("GO_MAD_SERVER_HOST"); host != "" {
|
||||
cfg.Server.Host = host
|
||||
}
|
||||
if port := os.Getenv("GO_MAD_SERVER_PORT"); port != "" {
|
||||
cfg.Server.Port = port
|
||||
}
|
||||
if dbURL := os.Getenv("GO_MAD_DATABASE_URL"); dbURL != "" {
|
||||
cfg.Database.URL = dbURL
|
||||
}
|
||||
if jwtSecret := os.Getenv("GO_MAD_JWT_SECRET"); jwtSecret != "" {
|
||||
cfg.JWT.SecretKey = jwtSecret
|
||||
}
|
||||
|
||||
cfg.applyDefaults()
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func DefaultConfig() *Config {
|
||||
return &Config{
|
||||
Server: ServerConfig{
|
||||
Host: "0.0.0.0",
|
||||
Port: "8080",
|
||||
},
|
||||
Database: DatabaseConfig{
|
||||
URL: "postgres://mad:mad@localhost:5432/mad?sslmode=disable",
|
||||
},
|
||||
JWT: JWTConfig{
|
||||
SecretKey: "change-me-to-a-32-plus-char-secret",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Config) applyDefaults() {
|
||||
if c.Server.Port == "" {
|
||||
c.Server.Port = "8080"
|
||||
}
|
||||
if c.Database.URL == "" {
|
||||
c.Database.URL = "postgres://mad:mad@localhost:5432/mad?sslmode=disable"
|
||||
}
|
||||
if c.JWT.SecretKey == "" {
|
||||
c.JWT.SecretKey = "change-me-to-a-32-plus-char-secret"
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue