Skip to content

Commit

Permalink
Merge pull request #21 from isd-sgcu/JOH-37/migrate-to-env
Browse files Browse the repository at this point in the history
[JOH-37] Migrate from Config to Envs
  • Loading branch information
bookpanda authored Jan 17, 2024
2 parents 5eda981 + c4b6e3c commit bf89949
Show file tree
Hide file tree
Showing 11 changed files with 225 additions and 139 deletions.
22 changes: 22 additions & 0 deletions .env.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
APP_PORT=3004
APP_ENV=development
APP_SECRET=secret

DB_URL=postgres://root:root@localhost:5432/johnjud_db

JWT_SECRET=secret
JWT_EXPIRES_IN=3600
JWT_REFRESH_TOKEN_TTL=604800
JWT_ISSUER=issuer
JWT_RESET_TOKEN_TTL=900

REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=

AUTH_CLIENT_URL=http://localhost:3000

SENDGRID_API_KEY=api_key
SENDGRID_NAME=johnjud
[email protected]

6 changes: 0 additions & 6 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,6 @@ COPY . .
# Build the application
RUN go build -o server ./cmd/main.go

# Copy config files
COPY ./config ./config

# Adding the grpc_health_probe
RUN GRPC_HEALTH_PROBE_VERSION=v0.3.1 && \
wget -qO/bin/grpc_health_probe https://github.com/grpc-ecosystem/grpc-health-probe/releases/download/${GRPC_HEALTH_PROBE_VERSION}/grpc_health_probe-linux-amd64 && \
Expand All @@ -36,9 +33,6 @@ COPY --from=base /bin/grpc_health_probe ./
# Copy execute file
COPY --from=base /app/server ./

# Copy config files
COPY --from=base /app/config ./config

# Set ENV to production
ENV GO_ENV production

Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
server:
go run ./cmd/.
. ./tools/export-env.sh ; go run ./cmd/.

mock-gen:
mockgen -source ./pkg/repository/cache/cache.repository.go -destination ./mocks/repository/cache/cache.mock.go
Expand Down
125 changes: 85 additions & 40 deletions cfgldr/config.go
Original file line number Diff line number Diff line change
@@ -1,74 +1,119 @@
package cfgldr

import (
"github.com/pkg/errors"
"github.com/spf13/viper"
)

type Database struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Name string `mapstructure:"name"`
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
SSL string `mapstructure:"ssl"`
Url string `mapstructure:"URL"`
}

type App struct {
Port int `mapstructure:"port"`
Debug bool `mapstructure:"debug"`
Secret string `mapstructure:"secret"`
Port int `mapstructure:"PORT"`
Env string `mapstructure:"ENV"`
Secret string `mapstructure:"SECRET"`
}

type Jwt struct {
Secret string `mapstructure:"secret"`
ExpiresIn int `mapstructure:"expires_in"`
RefreshTokenTTL int `mapstructure:"refresh_token_ttl"`
Issuer string `mapstructure:"issuer"`
ResetTokenTTL int `mapstructure:"reset_token_ttl"`
Secret string `mapstructure:"SECRET"`
ExpiresIn int `mapstructure:"EXPIRES_IN"`
RefreshTokenTTL int `mapstructure:"REFRESH_TOKEN_TTL"`
Issuer string `mapstructure:"ISSUER"`
ResetTokenTTL int `mapstructure:"RESET_TOKEN_TTL"`
}

type Redis struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Password string `mapstructure:"password"`
Host string `mapstructure:"HOST"`
Port int `mapstructure:"PORT"`
Password string `mapstructure:"PASSWORD"`
}

type Auth struct {
ClientURL string `mapstructure:"client_url"`
ClientURL string `mapstructure:"CLIENT_URL"`
}

type Sendgrid struct {
ApiKey string `mapstructure:"api_key"`
Name string `mapstructure:"name"`
Address string `mapstructure:"address"`
ApiKey string `mapstructure:"API_KEY"`
Name string `mapstructure:"NAME"`
Address string `mapstructure:"ADDRESS"`
}

type Config struct {
App App `mapstructure:"app"`
Database Database `mapstructure:"database"`
Jwt Jwt `mapstructure:"jwt"`
Redis Redis `mapstructure:"redis"`
Auth Auth `mapstructure:"auth"`
Sendgrid Sendgrid `mapstructure:"sendgrid"`
App App
Database Database
Jwt Jwt
Redis Redis
Auth Auth
Sendgrid Sendgrid
}

func LoadConfig() (config *Config, err error) {
viper.AddConfigPath("./config")
viper.SetConfigName("config")
viper.SetConfigType("yaml")
func LoadConfig() (*Config, error) {
dbCfgLdr := viper.New()
dbCfgLdr.SetEnvPrefix("DB")
dbCfgLdr.AutomaticEnv()
dbCfgLdr.AllowEmptyEnv(false)
dbConfig := Database{}
if err := dbCfgLdr.Unmarshal(&dbConfig); err != nil {
return nil, err
}

appCfgLdr := viper.New()
appCfgLdr.SetEnvPrefix("APP")
appCfgLdr.AutomaticEnv()
appCfgLdr.AllowEmptyEnv(false)
appConfig := App{}
if err := appCfgLdr.Unmarshal(&appConfig); err != nil {
return nil, err
}

jwtCfgLdr := viper.New()
jwtCfgLdr.SetEnvPrefix("JWT")
jwtCfgLdr.AutomaticEnv()
jwtCfgLdr.AllowEmptyEnv(false)
jwtConfig := Jwt{}
if err := jwtCfgLdr.Unmarshal(&jwtConfig); err != nil {
return nil, err
}

viper.AutomaticEnv()
redisCfgLdr := viper.New()
redisCfgLdr.SetEnvPrefix("REDIS")
redisCfgLdr.AutomaticEnv()
redisCfgLdr.AllowEmptyEnv(false)
redisConfig := Redis{}
if err := redisCfgLdr.Unmarshal(&redisConfig); err != nil {
return nil, err
}

authCfgLdr := viper.New()
authCfgLdr.SetEnvPrefix("AUTH")
authCfgLdr.AutomaticEnv()
authCfgLdr.AllowEmptyEnv(false)
authConfig := Auth{}
if err := authCfgLdr.Unmarshal(&authConfig); err != nil {
return nil, err
}

err = viper.ReadInConfig()
if err != nil {
return nil, errors.Wrap(err, "error occurs while reading the config")
sendgridCfgLdr := viper.New()
sendgridCfgLdr.SetEnvPrefix("SENDRID")
sendgridCfgLdr.AutomaticEnv()
sendgridCfgLdr.AllowEmptyEnv(false)
sendgridConfig := Sendgrid{}
if err := sendgridCfgLdr.Unmarshal(&sendgridConfig); err != nil {
return nil, err
}

err = viper.Unmarshal(&config)
if err != nil {
return nil, errors.Wrap(err, "error occurs while unmarshal the config")
config := &Config{
Database: dbConfig,
App: appConfig,
Jwt: jwtConfig,
Redis: redisConfig,
Auth: authConfig,
Sendgrid: sendgridConfig,
}

return
return config, nil
}

func (ac *App) IsDevelopment() bool {
return ac.Env == "development"
}
15 changes: 8 additions & 7 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ package main
import (
"context"
"fmt"
"net"
"os"
"os/signal"
"sync"
"syscall"
"time"

"github.com/isd-sgcu/johnjud-auth/cfgldr"
"github.com/isd-sgcu/johnjud-auth/database"
authRp "github.com/isd-sgcu/johnjud-auth/internal/repository/auth"
Expand All @@ -13,12 +20,6 @@ import (
jwtSvc "github.com/isd-sgcu/johnjud-auth/internal/service/jwt"
tokenSvc "github.com/isd-sgcu/johnjud-auth/internal/service/token"
userSvc "github.com/isd-sgcu/johnjud-auth/internal/service/user"
"net"
"os"
"os/signal"
"sync"
"syscall"
"time"

"github.com/isd-sgcu/johnjud-auth/internal/strategy"
"github.com/isd-sgcu/johnjud-auth/internal/utils"
Expand Down Expand Up @@ -96,7 +97,7 @@ func main() {
Msg("Failed to load config")
}

db, err := database.InitPostgresDatabase(&conf.Database, conf.App.Debug)
db, err := database.InitPostgresDatabase(&conf.Database, conf.App.IsDevelopment())
if err != nil {
log.Fatal().
Err(err).
Expand Down
31 changes: 0 additions & 31 deletions config/config.example.yaml

This file was deleted.

6 changes: 1 addition & 5 deletions database/postgresql.connection.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,21 @@
package database

import (
"fmt"
"github.com/isd-sgcu/johnjud-auth/cfgldr"
"github.com/isd-sgcu/johnjud-auth/internal/domain/model"
"gorm.io/driver/postgres"
"gorm.io/gorm"
gormLogger "gorm.io/gorm/logger"
"strconv"
)

func InitPostgresDatabase(conf *cfgldr.Database, isDebug bool) (db *gorm.DB, err error) {
dsn := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s", conf.Host, strconv.Itoa(conf.Port), conf.Username, conf.Password, conf.Name, conf.SSL)

gormConf := &gorm.Config{TranslateError: true}

if !isDebug {
gormConf.Logger = gormLogger.Default.LogMode(gormLogger.Silent)
}

db, err = gorm.Open(postgres.Open(dsn), gormConf)
db, err = gorm.Open(postgres.Open(conf.Url), gormConf)
if err != nil {
return nil, err
}
Expand Down
56 changes: 56 additions & 0 deletions docker-compose-prod.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
version: "3"

services:
auth:
container_name: johnjud-auth
restart: unless-stopped
build: .
ports:
- 3002:3002
environment:
- APP_PORT=3004
- APP_ENV=production
- APP_SECRET=secret
- DB_URL=postgres://root:root@johnjud-local-db:5432/johnjud_db
- JWT_SECRET=secret
- JWT_EXPIRES_IN=3600
- JWT_REFRESH_TOKEN_TTL=604800
- JWT_ISSUER=issuer
- JWT_RESET_TOKEN_TTL=900
- REDIS_HOST=localhost
- REDIS_PORT=6379
- REDIS_PASSWORD=
- AUTH_CLIENT_URL=http://localhost:3000
- SENDGRID_API_KEY=api_key
- SENDGRID_NAME=johnjud
- [email protected]
networks:
- johnjud

local-db:
image: postgres:15.1-alpine3.17
container_name: johnjud-local-db
restart: unless-stopped
environment:
POSTGRES_USER: root
POSTGRES_PASSWORD: root
POSTGRES_DB: johnjud_db
volumes:
- postgres:/var/lib/postgresql/data
ports:
- "5432:5432"
networks:
- johnjud

cache:
image: redis
restart: unless-stopped
ports:
- "6379:6379"
networks:
- johnjud

volumes:
postgres:
networks:
johnjud:
Loading

0 comments on commit bf89949

Please sign in to comment.