refactor: change structure project

This commit is contained in:
lorsan
2026-05-03 19:17:55 +03:00
parent e289365ce8
commit c44fedb488
38 changed files with 62 additions and 59 deletions
+56
View File
@@ -0,0 +1,56 @@
package config
import (
"fmt"
"log"
"github.com/ilyakaznacheev/cleanenv"
"github.com/rs/zerolog"
)
type Config struct {
DBHost string `env:"DB_HOST"`
DBPort int `env:"DB_PORT"`
DBPassword string `env:"DB_PASS"`
DBUser string `env:"DB_USER"`
DBName string `env:"DB_NAME"`
LogLevel string `env:"LOG_LEVEL" env-default:"INFO"`
Mode string `env:"MODE" env-default:"DEV"`
Port int `env:"PORT" env-default:"9000"`
}
func NewConfig() (*Config, error) {
var cfg Config
if err := cleanenv.ReadConfig(".env", &cfg); err != nil {
log.Printf("failed read config: %v", err)
if err = cleanenv.ReadEnv(&cfg); err != nil {
return nil, fmt.Errorf("env read failed: %v", err)
}
}
return &cfg, nil
}
func (c *Config) GetURLPostgres() string {
return fmt.Sprintf(
"postgres://%v:%v@%v:%v/%v?sslmode=disable",
c.DBUser,
c.DBPassword,
c.DBHost,
c.DBPort,
c.DBName)
}
func (c *Config) GetLogLevel() zerolog.Level {
level, err := zerolog.ParseLevel(c.LogLevel)
if err != nil {
return zerolog.InfoLevel
}
return level
}
func (c *Config) GetMode() string {
return c.Mode
}
+76
View File
@@ -0,0 +1,76 @@
package config
import (
"testing"
"github.com/rs/zerolog"
)
func TestConfig_GetLogLevel(t *testing.T) {
t.Parallel()
tests := []struct {
name string
cfg Config
wantLogLevel zerolog.Level
}{
{
name: "success",
cfg: Config{LogLevel: "DEBUG"},
wantLogLevel: zerolog.DebugLevel,
},
{
name: "failed parse",
cfg: Config{LogLevel: "TEST"},
wantLogLevel: zerolog.InfoLevel,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
logLevel := tt.cfg.GetLogLevel()
if logLevel != tt.wantLogLevel {
t.Fatalf("expected %v, got: %v", tt.wantLogLevel, logLevel)
}
})
}
}
func TestConfig_GetURLPostgres(t *testing.T) {
t.Parallel()
tests := []struct {
name string
cfg Config
wantURLPostgres string
}{
{
name: "success",
cfg: Config{
DBHost: "TestHost",
DBName: "TestName",
DBPassword: "TestPassword",
DBPort: 1234,
DBUser: "TestUser",
},
wantURLPostgres: "postgres://TestUser:TestPassword@TestHost:1234/TestName?sslmode=disable",
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
url := tt.cfg.GetURLPostgres()
if url != tt.wantURLPostgres {
t.Fatalf("expected %v, got: %v", tt.wantURLPostgres, url)
}
})
}
}