main.go


SUBMITTED BY: Guest

DATE: Oct. 17, 2024, 9:34 p.m.

FORMAT: Text only

SIZE: 2.5 kB

HITS: 100

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "os"
  8. "sync"
  9. )
  10. func main() {
  11. // Check if the correct number of arguments is passed
  12. if len(os.Args) < 2 {
  13. fmt.Println("Usage: go run main.go <input_file>")
  14. return
  15. }
  16. // Get the input file from command line arguments
  17. inputFile := os.Args[1]
  18. // Open the input file
  19. file, err := os.Open(inputFile)
  20. if err != nil {
  21. log.Fatalf("Failed to open file: %v\n", err)
  22. }
  23. defer file.Close()
  24. // Create output files for works and failed URLs
  25. worksFile, err := os.Create("works.txt")
  26. if err != nil {
  27. log.Fatalf("Failed to create works.txt: %v\n", err)
  28. }
  29. defer worksFile.Close()
  30. failedFile, err := os.Create("failed.txt")
  31. if err != nil {
  32. log.Fatalf("Failed to create failed.txt: %v\n", err)
  33. }
  34. defer failedFile.Close()
  35. // Create a scanner to read the input file line by line
  36. scanner := bufio.NewScanner(file)
  37. // Channels for results
  38. worksChan := make(chan string)
  39. failedChan := make(chan string)
  40. // WaitGroup to wait for all goroutines to finish
  41. var wg sync.WaitGroup
  42. // Worker function to check URL
  43. checkURL := func(url string) {
  44. defer wg.Done() // Decrease the counter when the goroutine completes
  45. // Check if the URL is accessible
  46. resp, err := http.Get(url)
  47. if err != nil || resp.StatusCode != http.StatusOK {
  48. // If there's an error or the status is not 200 OK, send to failed channel
  49. failedChan <- url
  50. } else {
  51. // If the URL is successful, send to works channel
  52. worksChan <- url
  53. }
  54. // Close the response body if the request was successful
  55. if resp != nil {
  56. resp.Body.Close()
  57. }
  58. }
  59. // Goroutine to handle writing to works.txt
  60. go func() {
  61. for url := range worksChan {
  62. worksFile.WriteString(url + "\n")
  63. }
  64. }()
  65. // Goroutine to handle writing to failed.txt
  66. go func() {
  67. for url := range failedChan {
  68. failedFile.WriteString(url + "\n")
  69. }
  70. }()
  71. // Iterate through each line (URL) in the file and start a goroutine for each
  72. for scanner.Scan() {
  73. url := scanner.Text()
  74. wg.Add(1) // Increase the counter for each goroutine
  75. go checkURL(url)
  76. }
  77. // Wait for all goroutines to finish
  78. wg.Wait()
  79. // Close the channels once all URLs have been processed
  80. close(worksChan)
  81. close(failedChan)
  82. // Check for any scanner errors
  83. if err := scanner.Err(); err != nil {
  84. log.Fatalf("Error reading file: %v\n", err)
  85. }
  86. fmt.Println("URL check completed. See works.txt and failed.txt for results.")
  87. }

comments powered by Disqus