-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
202 lines (168 loc) · 6.3 KB
/
main.go
File metadata and controls
202 lines (168 loc) · 6.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package main
import (
"context"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/go-redis/redis/v8"
"github.com/joho/godotenv"
"github.com/stripe/stripe-go/v82"
"payment-gateway/internal/config"
"payment-gateway/internal/handlers"
"payment-gateway/internal/kafka"
"payment-gateway/internal/logger"
"payment-gateway/internal/middleware"
rediswrap "payment-gateway/internal/redis"
"payment-gateway/internal/services"
"payment-gateway/internal/storage"
"github.com/gin-gonic/gin"
)
// Global logger instance
var log *logger.Logger
func main() {
log = logger.NewLogger()
defer log.Close()
// Load environment variables from .env file
if err := godotenv.Load(); err != nil {
log.Warn("ENV", "Error loading .env file, using environment variables")
}
log.LogProcess("STARTUP", "Payment Gateway starting up...")
log.Info("SYSTEM", "Initializing components...")
// Load configuration
cfg := config.Load()
log.Info("CONFIG", "Configuration loaded successfully")
log.LogProcess("DATABASE", "Initializing MySQL database...")
store, err := storage.NewMySQLStore(cfg.Database, log)
if err != nil {
log.Fatal("DATABASE", "Failed to initialize MySQL: "+err.Error())
}
defer store.Close()
log.LogDatabase("INIT", "mysql", "MySQL storage initialized successfully")
// Initialize Kafka
log.LogProcess("KAFKA", "Initializing Kafka producer...")
kafkaProducer, err := kafka.NewProducer(cfg.Kafka.Brokers, true, log)
if err != nil {
log.Fatal("KAFKA", "Failed to create Kafka producer: "+err.Error())
}
defer kafkaProducer.Close()
log.LogKafka("INIT", "producer", "Kafka producer initialized successfully")
log.LogProcess("KAFKA", "Initializing Kafka consumer...")
kafkaConsumer, err := kafka.NewConsumer(cfg.Kafka.Brokers, cfg.Kafka.GroupID)
if err != nil {
log.Fatal("KAFKA", "Failed to create Kafka consumer: "+err.Error())
}
defer kafkaConsumer.Close()
log.LogKafka("INIT", "consumer", "Kafka consumer initialized successfully")
redisAddr := os.Getenv("REDIS_ADDR")
redisClient := redis.NewClient(&redis.Options{
Addr: redisAddr,
})
log.LogProcess("SERVICE", " Redis connection successful")
// Initialize Stripe with API key
stripeKey := os.Getenv("STRIPE_SECRET_KEY")
if stripeKey == "" {
log.Warn("STRIPE", "STRIPE_SECRET_KEY environment variable not set")
log.Warn("STRIPE", "Please set a valid Stripe API key in your .env file")
// Don't set a default key here, let the service fail if no key is provided
} else {
stripe.Key = stripeKey
log.LogProcess("STRIPE", "Stripe API initialized with key")
}
// Initialize services
paymentService := services.NewPaymentService(store, kafkaProducer, log, rediswrap.NewRedis(redisClient))
log.LogProcess("SERVICE", "Payment service initialized")
// Initialize Stripe service
stripeService, err := services.NewStripeService(log)
if err != nil {
log.Fatal("STRIPE", "Failed to initialize Stripe service: "+err.Error())
}
log.LogProcess("SERVICE", "Stripe service initialized")
// Initialize handlers
paymentHandler := handlers.NewPaymentHandler(paymentService)
stripeHandler := handlers.NewStripeHandler(stripeService, paymentService)
log.LogProcess("HANDLER", "All handlers initialized")
// Start Kafka consumer in background
go func() {
log.LogKafka("START", "consumer", "Starting Kafka consumer goroutine")
if err := kafkaConsumer.ConsumePayments(context.Background(), paymentService.ProcessPaymentEvent); err != nil {
log.Error("KAFKA", "Consumer error: "+err.Error())
}
}()
// Setup router
router := setupRouter(paymentHandler, stripeHandler)
log.LogProcess("ROUTER", "HTTP router configured")
// Create server
srv := &http.Server{
Addr: ":8085",
Handler: router,
ReadTimeout: cfg.Server.ReadTimeout,
WriteTimeout: cfg.Server.WriteTimeout,
IdleTimeout: cfg.Server.IdleTimeout,
}
// Start server in goroutine
go func() {
log.LogProcess("SERVER", "Starting HTTP server on port "+cfg.Server.Port)
log.Info("STARTUP", "🚀 Payment Gateway is ready to accept requests!")
log.Info("STARTUP", "📊 Health check available at: http://localhost"+cfg.Server.Port+"/health")
log.Info("STARTUP", "💳 Payment API available at: http://localhost"+cfg.Server.Port+"/api/v1/payments")
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal("SERVER", "Server failed to start: "+err.Error())
}
}()
// Wait for interrupt signal to gracefully shutdown
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Warn("SHUTDOWN", "Received shutdown signal, initiating graceful shutdown...")
// Graceful shutdown with timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("SHUTDOWN", "Server forced to shutdown: "+err.Error())
}
log.Info("SHUTDOWN", "✅ Payment Gateway shutdown completed successfully")
}
func setupRouter(paymentHandler *handlers.PaymentHandler, stripeHandler *handlers.StripeHandler) *gin.Engine {
gin.SetMode(gin.ReleaseMode)
router := gin.New()
router.Use(middleware.EnhancedLogger(log))
router.Use(middleware.Recovery(log))
router.Use(middleware.CORS())
router.Use(middleware.RateLimit(log))
// Health check
router.GET("/health", func(c *gin.Context) {
log.LogAPI("GET", "/health", "200", "0ms")
c.JSON(http.StatusOK, gin.H{
"status": "healthy",
"timestamp": time.Now().UTC(),
"service": "payment-gateway",
"version": "1.0.0",
})
})
// API routes
v1 := router.Group("/api/v1")
{
payments := v1.Group("/payments")
{
payments.POST("/process", paymentHandler.ProcessPayment)
payments.GET("/:id", paymentHandler.GetPayment)
payments.GET("/:id/status", paymentHandler.GetPaymentStatus)
payments.POST("/:id/refund", paymentHandler.RefundPayment)
payments.POST("/OTP", paymentHandler.OTP)
payments.POST("/validate", paymentHandler.ValidateOTP)
}
// Stripe-specific routes
stripe := v1.Group("/stripe")
{
stripe.POST("/validate-card", stripeHandler.ValidateCard)
stripe.POST("/payment", stripeHandler.ProcessPayment)
stripe.POST("/refund", stripeHandler.RefundPayment)
stripe.GET("/payment/:id", stripeHandler.GetPaymentDetails)
stripe.POST("/webhook", stripeHandler.HandleStripeWebhook)
}
}
log.LogProcess("ROUTER", "All routes registered successfully")
return router
}