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 請求的常見問題

問:Go 的 HTTP 客戶端與 curl 有何不同?

答:雖然 curl 是用於發出 HTTP 請求的命令行工具,但 Go 的 net/http 套件提供了程式化 API。Go 提供更強的類型檢查、內建並發支援和更好的應用程式程式碼整合,而 curl 則擅長快速臨時測試和腳本編寫。

問:為什麼 Go 使用 defer 來關閉回應主體?

答:Go 使用 defer resp.Body.Close() 來確保即使函數後面發生錯誤,資源也能正確釋放。這種模式在 Go 中很常見,可防止在所有可能的程式碼路徑中忘記關閉主體而導致的資源洩漏。

問:如何在 Go 中處理流式回應?

答:不使用 ioutil.ReadAll(),您可以使用 io.Copy() 將回應主體作為流處理,或使用緩衝區分塊讀取。這對於大型回應特別有用,因為將整個主體載入記憶體會效率低下。

問:我可以在 Go 中重複使用 HTTP 客戶端嗎?

答:是的,而且建議這樣做!創建單個 http.Client 並在請求之間重複使用它可以實現連接池化並提高性能。客戶端是並發安全的,可以在 goroutine 之間共享而無需額外同步。

問:如何在 Go 中實現請求取消?

答:Go 的 context 套件提供了優雅的請求取消。使用 context.WithCancel()context.WithTimeout() 創建上下文,然後將其傳遞給 http.NewRequestWithContext()。您可以隨時通過調用取消函數來取消請求。

問:Go 中與 curl 的 -k/--insecure 標誌等效的是什麼?

答:要跳過 TLS 憑證驗證(如 curl 的 -k 標誌),請在您的 HTTP 客戶端中配置自訂 Transport:client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}} 但是,這應該只用於測試,因為它會繞過安全檢查。

問:與 curl 相比,如何在 Go 中處理重定向?

答:Go 的 HTTP 客戶端會自動跟隨重定向(默認最多 10 次),類似於 curl。要自訂此行為,請在您的 HTTP 客戶端中設置自訂 CheckRedirect 函數,以控制重定向處理或完全防止重定向。

Go API 測試的 Curl 命令參考

了解 curl 命令對於有效的 Go API 測試至關重要。以下是我們的轉換器支援的常見 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)