Convertitore da Curl a Go

Converti comandi curl in codice Go - Genera codice Go net/http pronto all'uso per richieste API

Informativa sulla Privacy: Questo strumento professionale fornisce conversione sicura in codice Go con protezione della privacy di livello enterprise. Non memorizziamo alcun dato che invii, garantendo completa riservatezza per il tuo lavoro di sviluppo API.

Generatore di Codice Go

// Go code will appear here
// Example:
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	url := "https://api.example.com/data"
	
	// Create request payload
	payload := map[string]interface{}{
		"name": "test",
	}
	
	jsonData, err := json.Marshal(payload)
	if err != nil {
		fmt.Println("Error marshaling JSON:", err)
		return
	}
	
	// Create request
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}
	
	// Add headers
	req.Header.Set("Content-Type", "application/json")
	
	// Send request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()
	
	// Read response
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return
	}
	
	fmt.Println("Status:", resp.Status)
	fmt.Println("Response:", string(body))
}

Comandi curl Comuni per Test API Go

Ecco alcuni comandi curl comuni che puoi convertire in codice Go:

Esempi HTTP Go

Il pacchetto net/http di Go fornisce un modo potente ed efficiente per effettuare richieste HTTP. Ecco alcuni pattern HTTP Go comuni:

Caricamento File con Go

package main

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
)

func main() {
	url := "https://api.example.com/upload"
	
	// Create a buffer to store the multipart form
	var requestBody bytes.Buffer
	multipartWriter := multipart.NewWriter(&requestBody)
	
	// Open the file
	file, err := os.Open("document.pdf")
	if err != nil {
		fmt.Println("Error opening file:", err)
		return
	}
	defer file.Close()
	
	// Create a form file field
	fileWriter, err := multipartWriter.CreateFormFile("file", filepath.Base("document.pdf"))
	if err != nil {
		fmt.Println("Error creating form file:", err)
		return
	}
	
	// Copy the file content to the form field
	_, err = io.Copy(fileWriter, file)
	if err != nil {
		fmt.Println("Error copying file to form:", err)
		return
	}
	
	// Add other form fields if needed
	multipartWriter.WriteField("description", "Sample document upload")
	
	// Close the multipart writer
	multipartWriter.Close()
	
	// Create request
	req, err := http.NewRequest("POST", url, &requestBody)
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}
	
	// Set the content type with the boundary
	req.Header.Set("Content-Type", multipartWriter.FormDataContentType())
	req.Header.Set("Authorization", "Bearer YOUR_TOKEN_HERE")
	
	// Send request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()
	
	// Read response
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return
	}
	
	fmt.Println("Status:", resp.Status)
	fmt.Println("Response:", string(body))
}

Go HTTP con Timeout e Gestione Errori

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

func main() {
	// Create a context with timeout
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	
	// Create request
	req, err := http.NewRequestWithContext(ctx, "GET", "https://api.example.com/data", nil)
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}
	
	// Send request
	client := &http.Client{}
	resp, err := client.Do(req)
	
	// Handle errors
	if err != nil {
		if ctx.Err() == context.DeadlineExceeded {
			fmt.Println("Request timed out")
		} else {
			fmt.Println("Error sending request:", err)
		}
		return
	}
	defer resp.Body.Close()
	
	// Check status code
	if resp.StatusCode != http.StatusOK {
		fmt.Printf("Server returned non-200 status: %s\n", resp.Status)
		body, _ := ioutil.ReadAll(resp.Body)
		fmt.Println("Response body:", string(body))
		return
	}
	
	// Read and parse response
	var data map[string]interface{}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return
	}
	
	err = json.Unmarshal(body, &data)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		fmt.Println("Raw response:", string(body))
		return
	}
	
	fmt.Println("Successfully received data:", data)
}

Come Utilizzare il Convertitore di Codice Go

1. Utilizzo Base

Copia il tuo comando curl → Incolla nella casella di input → Ottieni codice Go istantaneamente

2. Implementa una Corretta Gestione degli Errori

// Always check for errors in Go
resp, err := client.Do(req)
if err != nil {
	fmt.Println("Error sending request:", err)
	return
}
defer resp.Body.Close()

// Check status code
if resp.StatusCode != http.StatusOK {
	fmt.Printf("Server returned non-200 status: %s\n", resp.Status)
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println("Response body:", string(body))
	return
}

3. Usa Context per i Timeout

// Create a context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

// Create request with context
req, err := http.NewRequestWithContext(ctx, "GET", "https://api.example.com/data", nil)
if err != nil {
	fmt.Println("Error creating request:", err)
	return
}

// Send request
client := &http.Client{}
resp, err := client.Do(req)

// Check for timeout
if err != nil {
	if ctx.Err() == context.DeadlineExceeded {
		fmt.Println("Request timed out")
	} else {
		fmt.Println("Error sending request:", err)
	}
	return
}

Domande Frequenti sulle Richieste HTTP Go

D: In cosa differisce il client HTTP di Go da curl?

R: Mentre curl è uno strumento da riga di comando per effettuare richieste HTTP, il pacchetto net/http di Go fornisce un'API programmatica. Go offre tipizzazione più forte, supporto integrato per la concorrenza e migliore integrazione con il codice dell'applicazione, mentre curl eccelle nei test ad hoc rapidi e negli script.

D: Perché Go usa defer per chiudere i body delle risposte?

R: Go utilizza defer resp.Body.Close() per garantire che le risorse vengano rilasciate correttamente anche se si verificano errori successivamente nella funzione. Questo pattern è idiomatico in Go e previene perdite di risorse che potrebbero verificarsi se ci si dimenticasse di chiudere il body in tutti i possibili percorsi di codice.

D: Come gestisco le risposte in streaming in Go?

R: Invece di usare ioutil.ReadAll(), puoi elaborare il body della risposta come stream utilizzando io.Copy() o leggendo blocchi con un buffer. Questo è particolarmente utile per risposte di grandi dimensioni dove caricare l'intero body in memoria sarebbe inefficiente.

D: Posso riutilizzare i client HTTP in Go?

R: Sì, ed è consigliato! Creare un singolo http.Client e riutilizzarlo tra le richieste consente il pooling delle connessioni e migliora le prestazioni. Il client è thread-safe e può essere condiviso tra goroutine senza sincronizzazione aggiuntiva.

D: Come implemento la cancellazione delle richieste in Go?

R: Il pacchetto context di Go fornisce un'elegante cancellazione delle richieste. Crea un contesto con context.WithCancel() o context.WithTimeout(), quindi passalo a http.NewRequestWithContext(). Puoi annullare la richiesta in qualsiasi momento chiamando la funzione di cancellazione.

D: Qual è l'equivalente del flag -k/--insecure di curl in Go?

R: Per saltare la verifica del certificato TLS (come il flag -k di curl), configura un Transport personalizzato nel tuo client HTTP: client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}} Tuttavia, questo dovrebbe essere usato solo per i test, poiché bypassa i controlli di sicurezza.

D: Come gestisco i reindirizzamenti in Go rispetto a curl?

R: Il client HTTP di Go segue automaticamente i reindirizzamenti (fino a 10 di default), simile a curl. Per personalizzare questo comportamento, imposta una funzione CheckRedirect personalizzata nel tuo client HTTP per controllare la gestione dei reindirizzamenti o impedirli completamente.

Riferimento Comandi Curl per Test API Go

Comprendere i comandi curl è essenziale per test API Go efficaci. Ecco un riferimento rapido delle opzioni curl comuni che il nostro convertitore supporta:

Sintassi curl di Base

curl [options] [URL]

Opzioni curl Comuni

Conversione di Comandi curl Complessi

Il nostro convertitore Go gestisce comandi curl complessi inclusi header multipli, autenticazione, payload di dati e varie opzioni. Basta incollare il tuo comando curl e ottenere codice Go pulito e moderno utilizzando il pacchetto net/http.

Migliori Pratiche HTTP Go

Quando lavori con il pacchetto net/http di Go, segui queste migliori pratiche per interazioni API efficienti e sicure:

1. Chiudi Sempre il Body della Risposta

resp, err := client.Do(req)
if err != nil {
	fmt.Println("Error sending request:", err)
	return
}
defer resp.Body.Close() // Important: prevents resource leaks

2. Usa Client HTTP Personalizzati

client := &http.Client{
	Timeout: 10 * time.Second,
	Transport: &http.Transport{
		MaxIdleConns:        100,
		MaxIdleConnsPerHost: 20,
		IdleConnTimeout:     90 * time.Second,
	},
}

resp, err := client.Do(req)
if err != nil {
	fmt.Println("Error sending request:", err)
	return
}

3. Implementa una Gestione Errori Completa

resp, err := client.Do(req)
if err != nil {
	var netErr net.Error
	if errors.As(err, &netErr) && netErr.Timeout() {
		fmt.Println("Request timed out")
	} else if errors.Is(err, context.DeadlineExceeded) {
		fmt.Println("Context deadline exceeded")
	} else {
		fmt.Println("Error sending request:", err)
	}
	return
}
defer resp.Body.Close()

// Check status code
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Printf("Error status: %d %s\n", resp.StatusCode, resp.Status)
	fmt.Printf("Response body: %s\n", string(body))
	return
}

// Read response
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
	fmt.Println("Error reading response body:", err)
	return
}

// Process response data
var result map[string]interface{}
if err := json.Unmarshal(body, &result); err != nil {
	fmt.Println("Error parsing JSON:", err)
	fmt.Println("Raw response:", string(body))
	return
}

4. Usa Context per il Controllo di Timeout e Cancellazione

// Create context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel() // Important: prevents context leaks

// Create request with context
req, err := http.NewRequestWithContext(ctx, "GET", "https://api.example.com/data", nil)
if err != nil {
	fmt.Println("Error creating request:", err)
	return
}

// Send request
resp, err := client.Do(req)
// Error handling...

5. Usa Struct per la Serializzazione e Deserializzazione JSON

// Define request and response structs
type User struct {
	ID    int    `json:"id,omitempty"`
	Name  string `json:"name"`
	Email string `json:"email"`
}

// Create request data
user := User{
	Name:  "John Doe",
	Email: "[email protected]",
}

// Serialize to JSON
jsonData, err := json.Marshal(user)
if err != nil {
	fmt.Println("Error marshaling JSON:", err)
	return
}

// Create request
req, err := http.NewRequest("POST", "https://api.example.com/users", bytes.NewBuffer(jsonData))
// Set headers, send request, etc...

// Deserialize response
var responseUser User
if err := json.Unmarshal(body, &responseUser); err != nil {
	fmt.Println("Error parsing JSON response:", err)
	return
}
fmt.Printf("Created user with ID: %d\n", responseUser.ID)