Convertidor de Curl a Go

Convierte comandos curl a código Go - Genera código Go net/http listo para usar para peticiones API

Aviso de Privacidad: Esta herramienta profesional proporciona conversión segura a código Go con protección de privacidad de nivel empresarial. No almacenamos ningún dato que envíes, asegurando completa confidencialidad para tu trabajo de desarrollo API.

Generador de código 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))
}

Comandos curl Comunes para Pruebas de API en Go

Aquí hay algunos comandos curl comunes que puedes convertir a código Go:

Ejemplos de HTTP en Go

El paquete net/http de Go proporciona una forma potente y eficiente de hacer peticiones HTTP. Aquí hay algunos patrones comunes de HTTP en Go:

Subida de Archivos 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))
}

HTTP en Go con Timeout y Manejo de Errores

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)
}

Cómo Usar el Convertidor de Código Go

1. Uso Básico

Copia tu comando curl → Pégalo en la caja de entrada → Obtén código Go instantáneamente

2. Implementa un Manejo de Errores Adecuado

// 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 para Timeouts

// 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
}

Preguntas Frecuentes sobre Peticiones HTTP en Go

P: ¿En qué se diferencia el cliente HTTP de Go de curl?

R: Mientras que curl es una herramienta de línea de comandos para hacer peticiones HTTP, el paquete net/http de Go proporciona una API programática. Go ofrece tipado fuerte, soporte de concurrencia incorporado y mejor integración con el código de tu aplicación, mientras que curl sobresale en pruebas ad-hoc rápidas y scripting.

P: ¿Por qué Go usa defer para cerrar cuerpos de respuesta?

R: Go usa defer resp.Body.Close() para asegurar que los recursos se liberen adecuadamente incluso si ocurren errores más adelante en la función. Este patrón es idiomático en Go y previene fugas de recursos que podrían ocurrir si olvidas cerrar el cuerpo en todos los posibles caminos de código.

P: ¿Cómo manejo respuestas en streaming en Go?

R: En lugar de usar ioutil.ReadAll(), puedes procesar el cuerpo de la respuesta como un stream usando io.Copy() o leyendo fragmentos con un buffer. Esto es especialmente útil para respuestas grandes donde cargar todo el cuerpo en memoria sería ineficiente.

P: ¿Puedo reutilizar clientes HTTP en Go?

R: ¡Sí, y es recomendable! Crear un único http.Client y reutilizarlo entre peticiones permite el agrupamiento de conexiones y mejora el rendimiento. El cliente es seguro para concurrencia y puede compartirse entre goroutines sin sincronización adicional.

P: ¿Cómo implemento la cancelación de peticiones en Go?

R: El paquete context de Go proporciona una elegante cancelación de peticiones. Crea un contexto con context.WithCancel() o context.WithTimeout(), luego pásalo a http.NewRequestWithContext(). Puedes cancelar la petición en cualquier momento llamando a la función cancel.

P: ¿Cuál es el equivalente de la bandera -k/--insecure de curl en Go?

R: Para omitir la verificación de certificados TLS (como la bandera -k de curl), configura un Transport personalizado en tu cliente HTTP: client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}} Sin embargo, esto solo debe usarse para pruebas, ya que omite las comprobaciones de seguridad.

P: ¿Cómo manejo redirecciones en Go comparado con curl?

R: El cliente HTTP de Go sigue redirecciones automáticamente (hasta 10 por defecto), similar a curl. Para personalizar este comportamiento, establece una función personalizada CheckRedirect en tu cliente HTTP para controlar el manejo de redirecciones o evitarlas por completo.

Referencia de Comandos Curl para Pruebas de API en Go

Entender los comandos curl es esencial para pruebas efectivas de API con Go. Aquí hay una referencia rápida de opciones comunes de curl que nuestro convertidor soporta:

Sintaxis Básica de curl

curl [options] [URL]

Opciones Comunes de curl

Convertir Comandos curl Complejos

Nuestro convertidor de Go maneja comandos curl complejos incluyendo múltiples cabeceras, autenticación, cargas de datos y varias opciones. Simplemente pega tu comando curl y obtén código Go limpio y moderno usando el paquete net/http.

Mejores Prácticas para HTTP en Go

Cuando trabajes con el paquete net/http de Go, sigue estas mejores prácticas para interacciones API eficientes y seguras:

1. Siempre Cierra el Cuerpo de la Respuesta

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 Cliente HTTP Personalizado

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 Manejo de Errores Completo

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 para Control de Timeout y Cancelación

// 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 Structs para Serialización y Deserialización 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)