first commit

This commit is contained in:
2025-09-24 18:42:16 +07:00
commit daffbc67dc
72 changed files with 40710 additions and 0 deletions

86
cmd/api/main.go Normal file
View File

@@ -0,0 +1,86 @@
package main
import (
"context"
"fmt"
"log"
"net/http"
"os/signal"
"syscall"
"time"
"api-service/internal/server"
"github.com/joho/godotenv" // Import the godotenv package
_ "api-service/docs"
)
// @title API Service
// @version 1.0.0
// @description A comprehensive Go API service with Swagger documentation
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /api/v1
// @schemes http https
func gracefulShutdown(apiServer *http.Server, done chan bool) {
// Create context that listens for the interrupt signal from the OS.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
// Listen for the interrupt signal.
<-ctx.Done()
log.Println("shutting down gracefully, press Ctrl+C again to force")
stop() // Allow Ctrl+C to force shutdown
// The context is used to inform the server it has 5 seconds to finish
// the request it is currently handling
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := apiServer.Shutdown(ctx); err != nil {
log.Printf("Server forced to shutdown with error: %v", err)
}
log.Println("Server exiting")
// Notify the main goroutine that the shutdown is complete
done <- true
}
func main() {
log.Println("Starting API Service...")
// Load environment variables from .env file
if err := godotenv.Load(); err != nil {
log.Printf("Warning: .env file not found or could not be loaded: %v", err)
log.Println("Continuing with system environment variables...")
}
server := server.NewServer()
// Create a done channel to signal when the shutdown is complete
done := make(chan bool, 1)
// Run graceful shutdown in a separate goroutine
go gracefulShutdown(server, done)
log.Printf("Server starting on port %s", server.Addr)
err := server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
panic(fmt.Sprintf("http server error: %s", err))
}
// Wait for the graceful shutdown to complete
<-done
log.Println("Graceful shutdown complete.")
}

109
cmd/logging/main.go Normal file
View File

@@ -0,0 +1,109 @@
package main
import (
"fmt"
"log"
"time"
"api-service/pkg/logger"
)
func main() {
fmt.Println("Testing Dynamic Logging Functions...")
fmt.Println("====================================")
// Test fungsi penyimpanan log dinamis
testDynamicLogging()
// Tunggu sebentar untuk memastikan goroutine selesai
time.Sleep(500 * time.Millisecond)
fmt.Println("\n====================================")
fmt.Println("Dynamic logging test completed!")
fmt.Println("Check the log files in pkg/logger/data/ directory")
}
func testDynamicLogging() {
// Buat logger instance
loggerInstance := logger.New("test-app", logger.DEBUG, false)
// Test 1: Log dengan penyimpanan otomatis
fmt.Println("\n1. Testing automatic log saving...")
loggerInstance.LogAndSave(logger.INFO, "Application started successfully", map[string]interface{}{
"version": "1.0.0",
"build_date": time.Now().Format("2006-01-02"),
"environment": "development",
})
// Test 2: Log dengan request context
fmt.Println("\n2. Testing log with request context...")
requestLogger := loggerInstance.WithRequestID("req-001").WithCorrelationID("corr-001")
requestLogger.LogAndSave(logger.INFO, "User login attempt", map[string]interface{}{
"username": "john_doe",
"ip": "192.168.1.100",
"success": true,
})
// Test 3: Error logging
fmt.Println("\n3. Testing error logging...")
loggerInstance.LogAndSave(logger.ERROR, "Database connection failed", map[string]interface{}{
"error": "connection timeout",
"retry_count": 3,
"host": "db.example.com:5432",
})
// Test 4: Manual log entry saving
fmt.Println("\n4. Testing manual log entry saving...")
manualEntry := logger.LogEntry{
Timestamp: time.Now().Format(time.RFC3339),
Level: "DEBUG",
Service: "manual-test",
Message: "Manual log entry created",
RequestID: "manual-req-001",
CorrelationID: "manual-corr-001",
File: "main.go",
Line: 42,
Fields: map[string]interface{}{
"custom_field": "test_value",
"number": 123,
"active": true,
},
}
// Simpan manual ke berbagai format
if err := logger.SaveLogText(manualEntry); err != nil {
log.Printf("Error saving text log: %v", err)
} else {
fmt.Println("✓ Text log saved successfully")
}
if err := logger.SaveLogJSON(manualEntry); err != nil {
log.Printf("Error saving JSON log: %v", err)
} else {
fmt.Println("✓ JSON log saved successfully")
}
if err := logger.SaveLogToDatabase(manualEntry); err != nil {
log.Printf("Error saving database log: %v", err)
} else {
fmt.Println("✓ Database log saved successfully")
}
// Test 5: Performance logging dengan durasi
fmt.Println("\n5. Testing performance logging...")
start := time.Now()
// Simulasi proses yang memakan waktu
time.Sleep(200 * time.Millisecond)
duration := time.Since(start)
loggerInstance.LogAndSave(logger.INFO, "Data processing completed", map[string]interface{}{
"operation": "data_import",
"duration": duration.String(),
"duration_ms": duration.Milliseconds(),
"records": 1000,
"throughput": fmt.Sprintf("%.2f records/ms", 1000/float64(duration.Milliseconds())),
})
fmt.Println("\n✓ All logging tests completed successfully!")
}