fcamuso

Un assaggio di Go - Video 12

Jul 11th, 2025
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.20 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "encoding/json" // Per lavorare con JSON
  5.     "fmt"
  6.     "log"      // Per i log degli errori
  7.     "net/http" // Il pacchetto per il server HTTP
  8.     "sync"     // Per proteggere la slice di prodotti in caso di accesso concorrente
  9. )
  10.  
  11. // Prodotto rappresenta la struttura di un prodotto
  12. type Prodotto struct {
  13.     ID     string  `json:"id"`
  14.     Nome   string  `json:"nome"`
  15.     Prezzo float64 `json:"prezzo"`
  16. }
  17.  
  18. // In questo esempio, usiamo una slice in memoria per i nostri "prodotti".
  19. // In un'applicazione reale useremmo un vero database .
  20. var (
  21.     Prodotti []Prodotto
  22.     // Usiamo una mutex per proteggere l'accesso allo slice Prodotti'
  23.     // in caso di richieste POST concorrenti.
  24.     ProdottiMutex  sync.Mutex
  25.     nextProdottoID = 1
  26. )
  27.  
  28. // getProdottiHandler gestisce le richieste GET Prodotti
  29. func getProdottiHandler(writer http.ResponseWriter, request *http.Request) {
  30.  
  31.     // Blocca l'accesso alla slice prima di leggerla
  32.     ProdottiMutex.Lock()
  33.     defer ProdottiMutex.Unlock() // Sblocca alla fine della funzione
  34.  
  35.     // Imposta l'intestazione Content-Type a application/json
  36.     writer.Header().Set("Content-Type", "application/json")
  37.     // Codifica la slice di prodotti in JSON e la invia come risposta
  38.     if err := json.NewEncoder(writer).Encode(Prodotti); err != nil {
  39.         http.Error(writer, "Errore nella codifica JSON", http.StatusInternalServerError)
  40.         log.Printf("Errore codifica JSON in getProdottiHandler: %v", err)
  41.     }
  42. }
  43.  
  44. // createProdottoHandler gestisce le richieste POST Prodotti
  45. func createProdottoHandler(writer http.ResponseWriter, request *http.Request) {
  46.  
  47.     var newProdotto Prodotto
  48.     // Decodifica il corpo della richiesta JSON nel nostro struct Prodotto
  49.     if err := json.NewDecoder(request.Body).Decode(&newProdotto); err != nil {
  50.         http.Error(writer, "Richiesta JSON non valida", http.StatusBadRequest)
  51.         log.Printf("Errore decodifica JSON in createProdottoHandler: %v", err)
  52.         return
  53.     }
  54.  
  55.     // Genera un ID unico e aggiungi il prodotto
  56.     ProdottiMutex.Lock()
  57.     newProdotto.ID = fmt.Sprintf("prod%d", nextProdottoID)
  58.     nextProdottoID++
  59.  
  60.     Prodotti = append(Prodotti, newProdotto)
  61.     ProdottiMutex.Unlock()
  62.  
  63.     // Imposta lo status HTTP a 201 Created
  64.     writer.WriteHeader(http.StatusCreated)
  65.     writer.Header().Set("Content-Type", "application/json")
  66.  
  67.     // Invia il prodotto creato come risposta (con il suo ID generato)
  68.     if err := json.NewEncoder(writer).Encode(newProdotto); err != nil {
  69.         http.Error(writer, "Errore nella codifica JSON della risposta",
  70.             http.StatusInternalServerError)
  71.         log.Printf("Errore codifica JSON risposta in createProdottoHandler: %v", err)
  72.     }
  73.  
  74.     log.Printf("Prodotto aggiunto: %s - %s (%.2f)", newProdotto.ID,
  75.         newProdotto.Nome, newProdotto.Prezzo)
  76. }
  77.  
  78. func main() {
  79.     // Inizializziamo alcuni prodotti di esempio
  80.     Prodotti = append(Prodotti, Prodotto{ID: "prod1", Nome: "Notebook", Prezzo: 850.00})
  81.     Prodotti = append(Prodotti, Prodotto{ID: "prod2", Nome: "Mouse", Prezzo: 25.50})
  82.  
  83.     // Registra i gestori per i percorsi specifici
  84.     http.HandleFunc("/prodotti", func(writer http.ResponseWriter, request *http.Request) {
  85.         switch request.Method {
  86.         case http.MethodGet:
  87.             getProdottiHandler(writer, request)
  88.         case http.MethodPost:
  89.             createProdottoHandler(writer, request)
  90.         default:
  91.             http.Error(writer, "Metodo HTTP non supportato per questo endpoint",
  92.                 http.StatusMethodNotAllowed)
  93.         }
  94.     })
  95.  
  96.     // Avvia il server HTTP sulla porta 8080
  97.     // Ascolta su localhost (127.0.0.1) sulla porta 8080
  98.     fmt.Println("Server API avviato su http://localhost:8080")
  99.     log.Fatal(http.ListenAndServe(":8080", nil)) // nil significa usare il DefaultServeMux
  100. }
  101.  
  102. //PARTE C#
  103. using System;
  104. using System.Net.Http;
  105. using System.Net.Http.Headers;
  106. using System.Text;
  107. using System.Threading.Tasks;
  108. using System.Text.Json; // Necessario per lavorare con JSON
  109.  
  110. namespace GoApiTester
  111. {
  112.     public class Product
  113.     {
  114.         public string id { get; set; }
  115.         public string nome { get; set; }
  116.         public double prezzo { get; set; }
  117.     }
  118.  
  119.     class Program
  120.     {
  121.         private static readonly HttpClient client = new HttpClient();
  122.         private const string ApiBaseUrl = "http://localhost:8080/prodotti";
  123.  
  124.         static async Task Main(string[] args)
  125.         {
  126.             Console.WriteLine("--- Test dell'API Go con C# ---");
  127.  
  128.             // Configura l'HttpClient
  129.             client.DefaultRequestHeaders.Accept.Clear();
  130.             client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  131.  
  132.             // 1. Esegui la richiesta GET
  133.             Console.WriteLine("\nEffettuo GET /products...");
  134.             await GetProductsAsync();
  135.  
  136.             // 2. Esegui la richiesta POST
  137.             Console.WriteLine("\nEffettuo POST /products...");
  138.             await CreateProductAsync();
  139.  
  140.             // 3. Esegui un'altra richiesta GET per vedere il prodotto aggiunto
  141.             Console.WriteLine("\nEffettuo un altro GET /products per verificare...");
  142.             await GetProductsAsync();
  143.  
  144.             Console.WriteLine("\nTest completato. Premi un tasto per uscire.");
  145.             Console.ReadKey();
  146.         }
  147.  
  148.         static async Task GetProductsAsync()
  149.         {
  150.             try
  151.             {
  152.                 HttpResponseMessage response = await client.GetAsync(ApiBaseUrl);
  153.                 response.EnsureSuccessStatusCode(); // Lancia un'eccezione se lo status code è un errore HTTP
  154.  
  155.                 string responseBody = await response.Content.ReadAsStringAsync();
  156.                 Console.WriteLine("Risposta GET:");
  157.                 Console.WriteLine(responseBody);               
  158.             }
  159.             catch (HttpRequestException e)
  160.             {
  161.                 Console.WriteLine($"\nErrore durante la richiesta GET: {e.Message}");
  162.             }
  163.         }
  164.  
  165.         static async Task CreateProductAsync()
  166.         {
  167.             var newProduct = new Product
  168.             {
  169.                 nome = "Webcam HD",
  170.                 prezzo = 59.99
  171.             };
  172.  
  173.             // Serializza l'oggetto Product in una stringa JSON
  174.             string jsonContent = JsonSerializer.Serialize(newProduct);
  175.             var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
  176.  
  177.             try
  178.             {
  179.                 HttpResponseMessage response = await client.PostAsync(ApiBaseUrl, content);
  180.                 response.EnsureSuccessStatusCode(); // Lancia un'eccezione se lo status code è un errore HTTP
  181.  
  182.                 string responseBody = await response.Content.ReadAsStringAsync();
  183.                 Console.WriteLine("Risposta POST:");
  184.                 Console.WriteLine(responseBody);
  185.             }
  186.             catch (HttpRequestException e)
  187.             {
  188.                 Console.WriteLine($"\nErrore durante la richiesta POST: {e.Message}");
  189.             }
  190.         }
  191.     }
  192. }
  193.  
Advertisement
Add Comment
Please, Sign In to add comment