Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,21 @@

### 로컬 DB 실행
```bash
./dev-db.sh
./script/dev-db.sh
```

### 테스트용 DB 실행
```bash
./test-db.sh
./script/test-db.sh
```

## DB 마이그레이션

[ent, atlas migration 가이드](https://entgo.io/docs/versioned-migrations#generating-versioned-migration-files)

schema 작성 후 아래 스크립트 실행
```bash
./script/create_migration.sh <migration_name>
```
- atlas 설치 필요
- migration파일 생성 후 필요에 따라 migratin 파일 수정시 atlas migrate hash로 적용 필요
36 changes: 20 additions & 16 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,33 @@ package main

import (
"fmt"
"os"
"log"

"github.com/techbloghub/server/config"
"github.com/techbloghub/server/internal/database"

"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
)

func main() {
godotenv.Load(".env")
cfg, cfgErr := config.NewConfig()
if cfgErr != nil {
log.Fatalf("failed to load config: %v", cfgErr)
}

// DB 연결
client, errPg := database.ConnectDatabase(cfg)
if errPg != nil {
log.Fatalf("failed to connect database: %v", errPg)
}
defer client.Close()

// PORT 환경변수에서 가져오기
// 후에 이런 config값 관리할것들 많아지면 후에 Config struct등으로 분리 고려
port := getEnvWithDefault("PORT", "8080")
// 서버 실행
r := setRouter()
err := r.Run(":" + port)
if err != nil {
fmt.Println("Error while running server: ", err)
routerErr := r.Run(":" + cfg.ServerConfig.Port)
if routerErr != nil {
fmt.Println("Error while running server: ", cfgErr)
return
}
}
Expand All @@ -29,10 +40,3 @@ func setRouter() *gin.Engine {
})
return r
}

func getEnvWithDefault(key, defaultValue string) string {
if value := os.Getenv(key); value != "" {
return value
}
return defaultValue
}
97 changes: 97 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package config
Copy link
Member

@iamjooon2 iamjooon2 Jan 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저는 지금 config.go로도 괜찮은 것 같습니당

고랭 컨셉이 일단 짜고보는(?) 걸 지향하다보니
오히려 직관적이라는 생각이 드네용

config 개수가 늘어나거나(4~5개) 설정파일 뎁스가 늘어나면(config -> Aconfig -> BConfig 식으로 의존하게된다면) 그때 고민해봐도 좋을 것 같아요!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ㅋㅋㅋㅋㅋㅋㅋ good good .
사실 만들면서 처음엔 자프링하듯이 디비랑 서버 config분리해서 만들다가 이게 맞나...? 하고 그냥 롤백하고 하나로 합쳐서 작업했슴다.

일단 그냥 만들기 말은 편한데 계속 이게 맞나 고미이 드면서 아직 어렵네용


import (
"fmt"
"log"
"os"

"github.com/joho/godotenv"
)

type Config struct {
PostgresConfig
ServerConfig
}

type PostgresConfig struct {
Host string
Port string
User string
Password string
Db string
}

type ServerConfig struct {
Port string
Env string
}

func (cfg *PostgresConfig) ToMap() map[string]string {
return map[string]string{
"HOST": cfg.Host,
"PORT": cfg.Port,
"USER": cfg.User,
"PASSWORD": cfg.Password,
"DB": cfg.Db,
}
}

func (cfg *ServerConfig) ToMap() map[string]string {
return map[string]string{
"PORT": cfg.Port,
"ENV": cfg.Env,
}
}

func NewConfig() (*Config, error) {
errEnv := godotenv.Load(".env")
if errEnv != nil {
log.Print("failed to reading .env", errEnv)
}

postgresConf := PostgresConfig{
Host: os.Getenv("POSTGRES_HOST"),
Port: os.Getenv("POSTGRES_PORT"),
User: os.Getenv("POSTGRES_USER"),
Password: os.Getenv("POSTGRES_PASSWORD"),
Db: os.Getenv("POSTGRES_DB"),
}

serverConf := ServerConfig{
Port: os.Getenv("PORT"),
Env: os.Getenv("ENV"),
}

cfg := &Config{
PostgresConfig: postgresConf,
ServerConfig: serverConf,
}

if err := validateEnvs(cfg); err != nil {
return nil, err
}

return cfg, nil
}

func validateEnvs(cfg *Config) error {
missingEnvs := []string{}

missingEnvs = append(missingEnvs, findEmptyValueKeys(cfg.PostgresConfig.ToMap())...)
missingEnvs = append(missingEnvs, findEmptyValueKeys(cfg.ServerConfig.ToMap())...)

if len(missingEnvs) > 0 {
return fmt.Errorf("missing envs: %v", missingEnvs)
}
return nil
}

func findEmptyValueKeys(m map[string]string) []string {
keys := []string{}
for k, v := range m {
if v == "" {
keys = append(keys, k)
}
}
return keys
}
Loading
Loading