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 कमांड्स

यहां कुछ सामान्य curl कमांड्स हैं जिन्हें आप Go कोड में बदल सकते हैं:

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. टाइमआउट के लिए कॉन्टेक्स्ट का उपयोग करें

// 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 बनाना और इसे अनुरोधों में पुन: उपयोग करना कनेक्शन पूलिंग की अनुमति देता है और प्रदर्शन में सुधार करता है। क्लाइंट कॉन्करेंसी-सेफ है और अतिरिक्त सिंक्रोनाइज़ेशन के बिना गोरूटीन के बीच साझा किया जा सकता है।

प्रश्न: मैं 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 कमांड रेफरेंस

प्रभावी 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. टाइमआउट और कैंसलेशन कंट्रोल के लिए कॉन्टेक्स्ट का उपयोग करें

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