Conversor de Curl para Go

Converta comandos curl para código Go - Gere código Go net/http pronto para uso para requisições de API

Aviso de Privacidade: Esta ferramenta profissional fornece conversão segura para código Go com proteção de privacidade de nível empresarial. Não armazenamos nenhum dado que você envie, garantindo confidencialidade completa para seu trabalho de desenvolvimento de API.

Gerador 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 Comuns para Teste de API Go

Aqui estão alguns comandos curl comuns que você pode converter para código Go:

Exemplos HTTP Go

O pacote net/http do Go fornece uma maneira poderosa e eficiente de fazer requisições HTTP. Aqui estão alguns padrões HTTP Go comuns:

Upload de Arquivo com 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 Go com Timeout e Tratamento de Erros

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

Como Usar o Conversor de Código Go

1. Uso Básico

Copie seu comando curl → Cole na caixa de entrada → Obtenha código Go instantaneamente

2. Implemente Tratamento de Erros Adequado

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

Perguntas Frequentes sobre Requisições HTTP Go

P: Como o cliente HTTP do Go difere do curl?

R: Enquanto curl é uma ferramenta de linha de comando para fazer requisições HTTP, o pacote net/http do Go fornece uma API programática. Go oferece tipagem forte, suporte a concorrência integrado e melhor integração com seu código de aplicação, enquanto curl se destaca em testes ad-hoc rápidos e scripts.

P: Por que Go usa defer para fechar corpos de resposta?

R: Go usa defer resp.Body.Close() para garantir que os recursos sejam liberados adequadamente mesmo se ocorrerem erros posteriormente na função. Este padrão é idiomático em Go e previne vazamentos de recursos que poderiam ocorrer se você esquecesse de fechar o corpo em todos os caminhos de código possíveis.

P: Como lidar com respostas de streaming em Go?

R: Em vez de usar ioutil.ReadAll(), você pode processar o corpo da resposta como um stream usando io.Copy() ou lendo chunks com um buffer. Isso é especialmente útil para respostas grandes onde carregar o corpo inteiro na memória seria ineficiente.

P: Posso reutilizar clientes HTTP em Go?

R: Sim, e é recomendado! Criar um único http.Client e reutilizá-lo entre requisições permite pooling de conexões e melhora o desempenho. O cliente é seguro para concorrência e pode ser compartilhado entre goroutines sem sincronização adicional.

P: Como implementar cancelamento de requisição em Go?

R: O pacote context do Go fornece cancelamento de requisição elegante. Crie um contexto com context.WithCancel() ou context.WithTimeout(), então passe-o para http.NewRequestWithContext(). Você pode cancelar a requisição a qualquer momento chamando a função cancel.

P: Qual é o equivalente da flag -k/--insecure do curl em Go?

R: Para pular a verificação de certificado TLS (como a flag -k do curl), configure um Transport personalizado em seu cliente HTTP: client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}} No entanto, isso deve ser usado apenas para testes, pois ignora verificações de segurança.

P: Como lidar com redirecionamentos em Go comparado ao curl?

R: O cliente HTTP do Go segue redirecionamentos automaticamente (até 10 por padrão), similar ao curl. Para personalizar este comportamento, defina uma função CheckRedirect personalizada em seu cliente HTTP para controlar o tratamento de redirecionamento ou impedir redirecionamentos completamente.

Referência de Comandos Curl para Teste de API Go

Entender comandos curl é essencial para teste eficaz de API com Go. Aqui está uma referência rápida de opções curl comuns que nosso conversor suporta:

Sintaxe curl Básica

curl [options] [URL]

Opções curl Comuns

Convertendo Comandos curl Complexos

Nosso conversor Go lida com comandos curl complexos incluindo múltiplos cabeçalhos, autenticação, payloads de dados e várias opções. Simplesmente cole seu comando curl e obtenha código Go limpo e moderno usando o pacote net/http.

Melhores Práticas HTTP Go

Ao trabalhar com o pacote net/http do Go, siga estas melhores práticas para interações de API eficientes e seguras:

1. Sempre Feche o Corpo da Resposta

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

2. Use 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. Implemente Tratamento de Erros Abrangente

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. Use Context para Controle de Timeout e Cancelamento

// 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. Use Structs para Serialização e Desserialização 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)