Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "encoding/json" // Per lavorare con JSON
- "fmt"
- "log" // Per i log degli errori
- "net/http" // Il pacchetto per il server HTTP
- "sync" // Per proteggere la slice di prodotti in caso di accesso concorrente
- )
- // Prodotto rappresenta la struttura di un prodotto
- type Prodotto struct {
- ID string `json:"id"`
- Nome string `json:"nome"`
- Prezzo float64 `json:"prezzo"`
- }
- // In questo esempio, usiamo una slice in memoria per i nostri "prodotti".
- // In un'applicazione reale useremmo un vero database .
- var (
- Prodotti []Prodotto
- // Usiamo una mutex per proteggere l'accesso allo slice Prodotti'
- // in caso di richieste POST concorrenti.
- ProdottiMutex sync.Mutex
- nextProdottoID = 1
- )
- // getProdottiHandler gestisce le richieste GET Prodotti
- func getProdottiHandler(writer http.ResponseWriter, request *http.Request) {
- // Blocca l'accesso alla slice prima di leggerla
- ProdottiMutex.Lock()
- defer ProdottiMutex.Unlock() // Sblocca alla fine della funzione
- // Imposta l'intestazione Content-Type a application/json
- writer.Header().Set("Content-Type", "application/json")
- // Codifica la slice di prodotti in JSON e la invia come risposta
- if err := json.NewEncoder(writer).Encode(Prodotti); err != nil {
- http.Error(writer, "Errore nella codifica JSON", http.StatusInternalServerError)
- log.Printf("Errore codifica JSON in getProdottiHandler: %v", err)
- }
- }
- // createProdottoHandler gestisce le richieste POST Prodotti
- func createProdottoHandler(writer http.ResponseWriter, request *http.Request) {
- var newProdotto Prodotto
- // Decodifica il corpo della richiesta JSON nel nostro struct Prodotto
- if err := json.NewDecoder(request.Body).Decode(&newProdotto); err != nil {
- http.Error(writer, "Richiesta JSON non valida", http.StatusBadRequest)
- log.Printf("Errore decodifica JSON in createProdottoHandler: %v", err)
- return
- }
- // Genera un ID unico e aggiungi il prodotto
- ProdottiMutex.Lock()
- newProdotto.ID = fmt.Sprintf("prod%d", nextProdottoID)
- nextProdottoID++
- Prodotti = append(Prodotti, newProdotto)
- ProdottiMutex.Unlock()
- // Imposta lo status HTTP a 201 Created
- writer.WriteHeader(http.StatusCreated)
- writer.Header().Set("Content-Type", "application/json")
- // Invia il prodotto creato come risposta (con il suo ID generato)
- if err := json.NewEncoder(writer).Encode(newProdotto); err != nil {
- http.Error(writer, "Errore nella codifica JSON della risposta",
- http.StatusInternalServerError)
- log.Printf("Errore codifica JSON risposta in createProdottoHandler: %v", err)
- }
- log.Printf("Prodotto aggiunto: %s - %s (%.2f)", newProdotto.ID,
- newProdotto.Nome, newProdotto.Prezzo)
- }
- func main() {
- // Inizializziamo alcuni prodotti di esempio
- Prodotti = append(Prodotti, Prodotto{ID: "prod1", Nome: "Notebook", Prezzo: 850.00})
- Prodotti = append(Prodotti, Prodotto{ID: "prod2", Nome: "Mouse", Prezzo: 25.50})
- // Registra i gestori per i percorsi specifici
- http.HandleFunc("/prodotti", func(writer http.ResponseWriter, request *http.Request) {
- switch request.Method {
- case http.MethodGet:
- getProdottiHandler(writer, request)
- case http.MethodPost:
- createProdottoHandler(writer, request)
- default:
- http.Error(writer, "Metodo HTTP non supportato per questo endpoint",
- http.StatusMethodNotAllowed)
- }
- })
- // Avvia il server HTTP sulla porta 8080
- // Ascolta su localhost (127.0.0.1) sulla porta 8080
- fmt.Println("Server API avviato su http://localhost:8080")
- log.Fatal(http.ListenAndServe(":8080", nil)) // nil significa usare il DefaultServeMux
- }
- //PARTE C#
- using System;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Text;
- using System.Threading.Tasks;
- using System.Text.Json; // Necessario per lavorare con JSON
- namespace GoApiTester
- {
- public class Product
- {
- public string id { get; set; }
- public string nome { get; set; }
- public double prezzo { get; set; }
- }
- class Program
- {
- private static readonly HttpClient client = new HttpClient();
- private const string ApiBaseUrl = "http://localhost:8080/prodotti";
- static async Task Main(string[] args)
- {
- Console.WriteLine("--- Test dell'API Go con C# ---");
- // Configura l'HttpClient
- client.DefaultRequestHeaders.Accept.Clear();
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- // 1. Esegui la richiesta GET
- Console.WriteLine("\nEffettuo GET /products...");
- await GetProductsAsync();
- // 2. Esegui la richiesta POST
- Console.WriteLine("\nEffettuo POST /products...");
- await CreateProductAsync();
- // 3. Esegui un'altra richiesta GET per vedere il prodotto aggiunto
- Console.WriteLine("\nEffettuo un altro GET /products per verificare...");
- await GetProductsAsync();
- Console.WriteLine("\nTest completato. Premi un tasto per uscire.");
- Console.ReadKey();
- }
- static async Task GetProductsAsync()
- {
- try
- {
- HttpResponseMessage response = await client.GetAsync(ApiBaseUrl);
- response.EnsureSuccessStatusCode(); // Lancia un'eccezione se lo status code è un errore HTTP
- string responseBody = await response.Content.ReadAsStringAsync();
- Console.WriteLine("Risposta GET:");
- Console.WriteLine(responseBody);
- }
- catch (HttpRequestException e)
- {
- Console.WriteLine($"\nErrore durante la richiesta GET: {e.Message}");
- }
- }
- static async Task CreateProductAsync()
- {
- var newProduct = new Product
- {
- nome = "Webcam HD",
- prezzo = 59.99
- };
- // Serializza l'oggetto Product in una stringa JSON
- string jsonContent = JsonSerializer.Serialize(newProduct);
- var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
- try
- {
- HttpResponseMessage response = await client.PostAsync(ApiBaseUrl, content);
- response.EnsureSuccessStatusCode(); // Lancia un'eccezione se lo status code è un errore HTTP
- string responseBody = await response.Content.ReadAsStringAsync();
- Console.WriteLine("Risposta POST:");
- Console.WriteLine(responseBody);
- }
- catch (HttpRequestException e)
- {
- Console.WriteLine($"\nErrore durante la richiesta POST: {e.Message}");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment