Skip to content

Commit

Permalink
Updated posgres connection logic, added a folder for handlers, improv…
Browse files Browse the repository at this point in the history
…ed docker-compose to restart app container unless stopped. Reduced COPY steps in dockerfile
  • Loading branch information
aswinbennyofficial committed Sep 15, 2024
1 parent 1061367 commit 115789f
Show file tree
Hide file tree
Showing 7 changed files with 67 additions and 51 deletions.
13 changes: 5 additions & 8 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ RUN go mod download
# Copy the source code and config
COPY . .

# Build the application
RUN go build -o main .
# Build the application with multi-core parallelism
RUN GOMAXPROCS=$(nproc) go build -o main .

# Final stage
FROM alpine:3.14
Expand All @@ -24,11 +24,8 @@ COPY --from=builder /app/main .
# Copy the config directory
COPY config ./config

# Create logs directory
RUN mkdir -p /app/logs && chmod 777 /app/logs

# Create Migration directory
RUN mkdir -p /app/migrations && chmod 777 /app/migrations
# Create logs and migration directories
RUN mkdir -p /app/logs /app/migrations && chmod 777 /app/logs /app/migrations

# Copy the migrations
COPY src/db/migrations ./migrations
Expand All @@ -37,4 +34,4 @@ COPY src/db/migrations ./migrations
EXPOSE 8080

# Command to run
CMD ["./main"]
CMD ["./main"]
16 changes: 12 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
.PHONY: build run
.PHONY: build up run kill

build:
podman-compose build
@echo "Building Docker image..."
podman build .

run: build
podman-compose up
up:
@echo "Running container..."
podman-compose up

run: build up

kill:
@echo "Stopping containers..."
podman-compose down


2 changes: 1 addition & 1 deletion docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ services:
depends_on:
- db
- redis
restart: on-failure
restart: unless-stopped

db:
image: bitnami/postgresql
Expand Down
24 changes: 14 additions & 10 deletions src/db/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,32 +9,36 @@ import (
"github.com/rs/zerolog"
)


func NewPostgresConnection(config utils.PostgresConfig, log zerolog.Logger) (*pgxpool.Pool, error) {
dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s pool_max_conns=10",
dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s pool_max_conns=10",
config.Host, config.Port, config.User, config.Password, config.DBName)


log.Info().Msgf("Attempting to connect to database at %s:%d", config.Host, config.Port)

// Initial delay to allow database to start up
time.Sleep(30 * time.Second)

var db *pgxpool.Pool
var err error

// Retry logic for database connection
for i := 0; i < 30; i++ { // Retry up to 30 times (5 minutes total)
for i := 0; i < 60; i++ { // Retry up to 60 times (10 minutes total)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
db, err = pgxpool.New(ctx, dsn)
cancel()

if err == nil {
break
}

log.Warn().Err(err).Msgf("Failed to connect to database, retrying (%d/30)...", i+1)
log.Error().Err(err).Msgf("Failed to connect to database, retrying (%d/60)...", i+1)
time.Sleep(10 * time.Second) // Wait 10 seconds before retrying
}

if err != nil {
log.Fatal().Err(err).Msg("Failed to connect to database after retries")
return nil, err
}

// Test the connection
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
Expand All @@ -43,7 +47,7 @@ func NewPostgresConnection(config utils.PostgresConfig, log zerolog.Logger) (*pg
log.Fatal().Err(err).Msg("Failed to ping database")
return nil, err
}

log.Info().Msg("Connected to database successfully")
return db, nil
}
27 changes: 27 additions & 0 deletions src/server/handlers/handles.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package handlers

import (
"fmt"
"myapp/src/utils"
"net/http"

"github.com/rs/zerolog"
)

// HomeHandler handles the home route
func HomeHandler(app *utils.App, logger zerolog.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Extract user ID from JWT
userID, err := utils.ExtractClaim(r.Context(), "user_id")
if err != nil {
logger.Error().Err(err).Msg("Failed to extract user_id from token")
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}

// Log and respond with a message
logger.Info().Str("user_id", userID).Msg("Home page accessed")
response := fmt.Sprintf("Welcome to MyApp, %s!", userID)
w.Write([]byte(response))
}
}
22 changes: 0 additions & 22 deletions src/server/handles.go

This file was deleted.

14 changes: 8 additions & 6 deletions src/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import (
"fmt"
"net/http"

"myapp/src/server/handlers"
"myapp/src/server/middleware"
"myapp/src/utils"

"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/jwtauth/v5"
"github.com/rs/zerolog"

)

type Server struct {
Expand All @@ -29,19 +29,21 @@ func NewServer(app *utils.App) *Server {
func (s *Server) Start() {
r := chi.NewRouter()


tokenAuth := middlewares.InitJWTAuth(s.App.Config.Auth.JWTSecret)

r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middlewares.ZerologRequestLogger(s.Logger))
r.Use(middleware.Recoverer)

r.Use(jwtauth.Verifier(tokenAuth))
r.Use(jwtauth.Authenticator(tokenAuth))


r.Get("/", s.HomeHandler)
// Add more routes as needed
r.Route("/api/v1", func(r chi.Router) {
r.Use(jwtauth.Verifier(tokenAuth))
r.Use(jwtauth.Authenticator(tokenAuth))

r.Get("/home", handlers.HomeHandler(s.App, s.Logger))
})

addr := fmt.Sprintf(":%d", s.App.Config.App.Port)
s.App.Logger.Info().Msgf("Starting server on %s", addr)
Expand Down

0 comments on commit 115789f

Please sign in to comment.