Curl から Go へのコンバーター

curl コマンドを Go コードに変換 - API リクエスト用のすぐに使用可能な Go net/http コードを生成

プライバシー通知: このプロフェッショナルツールは、エンタープライズグレードのプライバシー保護で Go コードへの安全な変換を提供します。送信されたデータは一切保存されず、API 開発作業の完全な機密性を確保します。

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

Go API テスト用の一般的な curl コマンド

Go コードに変換できる一般的な curl コマンドをいくつか紹介します:

Go HTTP の例

Go の net/http パッケージは、HTTP リクエストを行うための強力で効率的な方法を提供します。以下は一般的な Go HTTP パターンです:

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

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

Go コードコンバーターの使い方

1. 基本的な使用方法

curl コマンドをコピー → 入力ボックスに貼り付け → Go コードを即座に取得

2. 適切なエラー処理を実装する

// 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. タイムアウトには Context を使用する

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

Go HTTP リクエストに関するよくある質問

Q: Go の HTTP クライアントは curl とどのように異なりますか?

A: curl は HTTP リクエストを行うためのコマンドラインツールですが、Go の net/http パッケージはプログラム的な API を提供します。Go は強力な型付け、組み込みの並行性サポート、アプリケーションコードとの優れた統合を提供しますが、curl は迅速なアドホックテストとスクリプティングに優れています。

Q: なぜ Go ではレスポンスボディを閉じるために defer を使用するのですか?

A: Go では defer resp.Body.Close() を使用して、関数内の後の部分でエラーが発生しても確実にリソースが適切に解放されるようにします。このパターンは Go の慣用的な書き方であり、すべての可能なコードパスでボディを閉じることを忘れた場合に発生する可能性のあるリソースリークを防ぎます。

Q: Go でストリーミングレスポンスを処理するにはどうすればよいですか?

A: ioutil.ReadAll() を使用する代わりに、io.Copy() を使用するか、バッファでチャンクを読み取ることでレスポンスボディをストリームとして処理できます。これは、ボディ全体をメモリにロードすることが非効率的な大きなレスポンスに特に役立ちます。

Q: Go で HTTP クライアントを再利用できますか?

A: はい、そして推奨されています!単一の http.Client を作成してリクエスト間で再利用することで、接続プーリングが可能になり、パフォーマンスが向上します。クライアントは並行性に対して安全であり、追加の同期なしでゴルーチン間で共有できます。

Q: Go でリクエストのキャンセルを実装するにはどうすればよいですか?

A: Go の context パッケージはエレガントなリクエストキャンセルを提供します。context.WithCancel() または context.WithTimeout() でコンテキストを作成し、それを http.NewRequestWithContext() に渡します。キャンセル関数を呼び出すことで、いつでもリクエストをキャンセルできます。

Q: Go における curl の -k/--insecure フラグに相当するものは何ですか?

A: TLS 証明書検証をスキップするには(curl の -k フラグのように)、HTTP クライアントでカスタム Transport を設定します:client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}} ただし、これはセキュリティチェックをバイパスするため、テスト目的でのみ使用してください。

Q: curl と比較して Go でリダイレクトを処理するにはどうすればよいですか?

A: Go の HTTP クライアントは curl と同様に自動的にリダイレクトをフォローします(デフォルトで最大 10 回)。この動作をカスタマイズするには、HTTP クライアントにカスタム CheckRedirect 関数を設定して、リダイレクト処理を制御するか、リダイレクトを完全に防止します。

Go API テスト用の Curl コマンドリファレンス

効果的な Go API テストには curl コマンドを理解することが不可欠です。以下は、当社のコンバーターがサポートする一般的な curl オプションのクイックリファレンスです:

基本的な curl 構文

curl [options] [URL]

一般的な curl オプション

複雑な curl コマンドの変換

当社の Go コンバーターは、複数のヘッダー、認証、データペイロード、さまざまなオプションを含む複雑な curl コマンドを処理します。curl コマンドを貼り付けるだけで、net/http パッケージを使用したクリーンでモダンな Go コードを取得できます。

Go HTTP のベストプラクティス

Go の net/http パッケージを使用する際は、効率的で安全な API 連携のために以下のベストプラクティスに従ってください:

1. 常にレスポンスボディを閉じる

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

2. カスタム HTTP クライアントを使用する

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. 包括的なエラー処理を実装する

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. タイムアウトとキャンセル制御には Context を使用する

// 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. 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)