package main import ( "context" "encoding/json" "log" "net/http" "os" "os/signal" "syscall" "time" "github.com/gorilla/mux" "github.com/jobs-scraper/api/app" _ "github.com/jobs-scraper/docs" "github.com/jobs-scraper/infrastructure" httpHandler "github.com/jobs-scraper/infrastructure/http" "github.com/jobs-scraper/infrastructure/nats" "github.com/jobs-scraper/internal/domain" "github.com/joho/godotenv" httpSwagger "github.com/swaggo/http-swagger" ) // @title Jobs Scraper API // @version 1.0 // @description API for managing job scraping operations // @BasePath / func main() { // Try to load .local.env first, then fallback to .env if err := godotenv.Load("../.local.env"); err != nil { log.Println("No .local.env file found, trying .env") if err := godotenv.Load("../.env"); err != nil { log.Println("No .env file found, using system environment variables") } } dbConfig := infrastructure.LoadConfigFromEnv() db, err := infrastructure.NewConnection(dbConfig) if err != nil { log.Fatal("Error connecting to db") } err = db.Ping() if err != nil { log.Fatal("Error pinging db") } log.Println("Successfully connected to db") nc, err := nats.NewNatsClient() if err != nil { log.Fatal("Failed to create nats client") } defer nc.Close() // Run database migrations if err := infrastructure.RunMigrations(db); err != nil { log.Fatalf("Failed to run migrations: %v", err) } router := mux.NewRouter() // Swagger endpoint router.PathPrefix("/swagger/").Handler(httpSwagger.WrapHandler) router.Use(httpHandler.CORSMiddleware) router.Use(httpHandler.LogsMiddleware) app := app.NewApplication(router, db) jobHandler := httpHandler.NewJobHandler(app.JobCommands) jobHandler.RegisterRoutes(router) jobRequest := domain.SearchQuery{ Keywords: "Javascript", Location: "US", FWT: "2,3", } // Marshal to JSON with error handling jsonData, err := json.Marshal(jobRequest) if err != nil { log.Printf("Error marshaling JSON: %v", err) } else { // Publish with error handling if err := nc.Publish(nats.LinkedInSubTopic, jsonData); err != nil { log.Printf("Error publishing message: %v", err) } else { log.Printf("Published job request: %s", string(jsonData)) } } go func() { log.Printf("Server running on http %s\n", "8080") if err := app.Server.Start(); err != nil && err != http.ErrServerClosed { log.Fatalf("Could not listen on http %s: %v\n", "8080", err) } }() stopChan := make(chan os.Signal, 1) signal.Notify( stopChan, os.Interrupt, syscall.SIGTERM, ) <-stopChan ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() app.Server.Stop(ctx) log.Println("Server shutting down") os.Exit(0) }