fcamuso

Un assaggio di Go - Video 11

Jul 9th, 2025
454
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 3.96 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "os/exec"
  6.     "runtime" // Importa il pacchetto runtime per rilevare il sistema operativo
  7.     "sync"
  8. )
  9.  
  10. func executePing(host string, wg *sync.WaitGroup) bool {
  11.     defer wg.Done() // Decrementa il contatore del WaitGroup quando la goroutine termina
  12.  
  13.     var cmd *exec.Cmd
  14.  
  15.     // Adatta il comando ping in base al sistema operativo
  16.     if runtime.GOOS == "windows" {
  17.         // Per Windows: -n 1 (count), -w 1000 (timeout in ms)
  18.         cmd = exec.Command("ping", "-n", "1", "-w", "1000", host)
  19.     } else {
  20.         // Per Linux/macOS: -c 1 (count), -W 1 (timeout in secondi)
  21.         cmd = exec.Command("ping", "-c", "1", "-W", "1", host)
  22.     }
  23.  
  24.     err := cmd.Run()
  25.     return err == nil
  26. }
  27.  
  28. func main() {
  29.     // Lista di host affidabili per i ping, più alcuni per dimostrare i fallimenti
  30.     hosts := []string{
  31.         "8.8.8.8",
  32.         "1.1.1.1",
  33.         "github.com",
  34.         "example.com",
  35.         "nonexistent.domain",
  36.         "192.0.2.1",
  37.     }
  38.  
  39.     fmt.Println("--- Monitor di Ping  ---")
  40.     var wg sync.WaitGroup
  41.  
  42.     // Avvia le goroutine
  43.     for _, host := range hosts {
  44.         wg.Add(1)
  45.         go func(h string) { // h è una copia del valore di host per evitare race conditions
  46.             if executePing(h, &wg) {
  47.                 fmt.Printf("Ping di %s: SUCCESS\n", h)
  48.             } else {
  49.                 fmt.Printf("Ping di %s: FAILED\n", h)
  50.             }
  51.         }(host)
  52.     }
  53.  
  54.     wg.Wait()
  55.  
  56.     fmt.Println("\nTutti i ping sono stati elaborati e il programma è terminato.")
  57. }
  58.  
  59.  
  60. //SECONDO MAIN, CON CHANNEL
  61. package main
  62.  
  63. import (
  64.     "fmt"
  65.     "os/exec"
  66.     "runtime" // Importa il pacchetto runtime per rilevare il sistema operativo
  67.     "sync"
  68. )
  69.  
  70. // PingResult struttura per contenere il risultato del ping.
  71. type PingResult struct {
  72.     Host    string
  73.     Success bool
  74.     Error   error
  75. }
  76.  
  77. // executePing esegue un comando ping e invia il risultato a un channel.
  78. func executePing(host string, results chan<- PingResult, wg *sync.WaitGroup) {
  79.     defer wg.Done() // Decrementa il contatore del WaitGroup quando la goroutine termina
  80.  
  81.     var cmd *exec.Cmd
  82.  
  83.     // Adatta il comando ping in base al sistema operativo
  84.     if runtime.GOOS == "windows" {
  85.         // Per Windows: -n 1 (count), -w 1000 (timeout in ms)
  86.         cmd = exec.Command("ping", "-n", "1", "-w", "1000", host)
  87.     } else {
  88.         // Per Linux/macOS: -c 1 (count), -W 1 (timeout in secondi)
  89.         cmd = exec.Command("ping", "-c", "1", "-W", "1", host)
  90.     }
  91.  
  92.     err := cmd.Run()
  93.  
  94.     result := PingResult{
  95.         Host:    host,
  96.         Success: err == nil,
  97.         Error:   err,
  98.     }
  99.     results <- result // Invia il risultato al channel
  100. }
  101.  
  102. func main() {
  103.     // Lista di host affidabili per i ping, più alcuni per dimostrare i fallimenti
  104.     hosts := []string{
  105.         "8.8.8.8",            // Google Public DNS (molto affidabile)
  106.         "1.1.1.1",            // Cloudflare Public DNS (molto affidabile)
  107.         "github.com",         // Di solito risponde
  108.         "example.com",        // Un dominio di esempio che quasi sempre risponde
  109.         "nonexistent.domain", // Questo dovrebbe fallire
  110.         "192.0.2.1",          // Indirizzo IP riservato per la documentazione, dovrebbe fallire
  111.     }
  112.  
  113.     resultsChan := make(chan PingResult) // Canale per inviare PingResult
  114.     var wg sync.WaitGroup                // Dichiarazione del WaitGroup
  115.  
  116.     fmt.Println("--- Monitor di Ping  ---")
  117.  
  118.     // Avvia le goroutine
  119.     for _, host := range hosts {
  120.         wg.Add(1) // Incrementa il contatore del WaitGroup per ogni goroutine lanciata
  121.         go executePing(host, resultsChan, &wg)
  122.     }
  123.  
  124.     // Goroutine separata per chiudere il channel una volta che tutte le goroutine sono terminate.
  125.     go func() {
  126.         wg.Wait()          // Blocca finché il contatore del WaitGroup non torna a zero
  127.         close(resultsChan) // Chiude il channel, segnalando che non ci saranno più invii
  128.     }()
  129.  
  130.     // Ricevi i risultati dal channel usando `range`.
  131.     for result := range resultsChan {
  132.         if result.Success {
  133.             fmt.Printf("Ping di %-18s: SUCCESS\n", result.Host) // Formattazione per allineare
  134.         } else {
  135.             fmt.Printf("Ping di %-18s: FAILED   (%v)\n", result.Host, result.Error)
  136.         }
  137.     }
  138.  
  139.     fmt.Println("\nTutti i ping sono stati elaborati e il programma è terminato.")
  140. }
  141.  
Advertisement
Add Comment
Please, Sign In to add comment