curl कमांड्स को Go कोड में बदलें - API अनुरोधों के लिए तुरंत उपयोग करने योग्य Go net/http कोड जनरेट करें
// 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)) }
यहां कुछ सामान्य curl कमांड्स हैं जिन्हें आप Go कोड में बदल सकते हैं:
curl https://api.example.com/users
curl -X POST -H "Content-Type: application/json" -d '{"name":"John","email":"[email protected]"}' https://api.example.com/users
curl -X PUT -H "Authorization: Bearer token123" -d '{"status":"active"}' https://api.example.com/users/1
curl -X DELETE https://api.example.com/users/1
curl -H "X-API-Key: abc123" -H "Accept: application/json" https://api.example.com/data
Go का net/http पैकेज HTTP अनुरोध करने का एक शक्तिशाली और कुशल तरीका प्रदान करता है। यहां कुछ सामान्य Go HTTP पैटर्न हैं:
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)) }
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) }
अपना curl कमांड कॉपी करें → इनपुट बॉक्स में पेस्ट करें → तुरंत Go कोड प्राप्त करें
// 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 }
// 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 }
उत्तर: जबकि curl HTTP अनुरोध करने के लिए एक कमांड-लाइन टूल है, Go का net/http पैकेज एक प्रोग्रामेटिक API प्रदान करता है। Go मजबूत टाइपिंग, बिल्ट-इन कॉन्करेंसी सपोर्ट और आपके एप्लिकेशन कोड के साथ बेहतर इंटीग्रेशन प्रदान करता है, जबकि curl त्वरित एड-हॉक टेस्टिंग और स्क्रिप्टिंग में उत्कृष्ट है।
उत्तर: Go defer resp.Body.Close() का उपयोग यह सुनिश्चित करने के लिए करता है कि फंक्शन में बाद में त्रुटियां होने पर भी संसाधन ठीक से जारी किए जाएं। यह पैटर्न Go में आदर्श है और संसाधन लीक को रोकता है जो सभी संभावित कोड पाथ में बॉडी को बंद करना भूलने पर हो सकता है।
उत्तर: ioutil.ReadAll()
का उपयोग करने के बजाय, आप io.Copy()
का उपयोग करके या एक बफर के साथ चंक्स पढ़कर रिस्पॉन्स बॉडी को स्ट्रीम के रूप में प्रोसेस कर सकते हैं। यह विशेष रूप से बड़े रिस्पॉन्स के लिए उपयोगी है जहां पूरी बॉडी को मेमोरी में लोड करना अकुशल होगा।
उत्तर: हां, और यह अनुशंसित है! एक http.Client
बनाना और इसे अनुरोधों में पुन: उपयोग करना कनेक्शन पूलिंग की अनुमति देता है और प्रदर्शन में सुधार करता है। क्लाइंट कॉन्करेंसी-सेफ है और अतिरिक्त सिंक्रोनाइज़ेशन के बिना गोरूटीन के बीच साझा किया जा सकता है।
उत्तर: Go का context पैकेज एलिगेंट रिक्वेस्ट कैंसलेशन प्रदान करता है। context.WithCancel()
या context.WithTimeout()
के साथ एक कॉन्टेक्स्ट बनाएं, फिर इसे http.NewRequestWithContext()
को पास करें। आप किसी भी समय कैंसल फंक्शन को कॉल करके रिक्वेस्ट को कैंसल कर सकते हैं।
उत्तर: TLS सर्टिफिकेट वेरिफिकेशन को स्किप करने के लिए (curl के -k फ्लैग की तरह), अपने HTTP क्लाइंट में एक कस्टम Transport कॉन्फिगर करें: client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}}
हालांकि, इसका उपयोग केवल टेस्टिंग के लिए किया जाना चाहिए, क्योंकि यह सुरक्षा जांच को बायपास करता है।
उत्तर: Go का HTTP क्लाइंट स्वचालित रूप से रीडायरेक्ट्स का पालन करता है (डिफ़ॉल्ट रूप से 10 तक), curl के समान। इस व्यवहार को कस्टमाइज़ करने के लिए, रीडायरेक्ट हैंडलिंग को नियंत्रित करने या रीडायरेक्ट्स को पूरी तरह से रोकने के लिए अपने HTTP क्लाइंट में एक कस्टम CheckRedirect
फंक्शन सेट करें।
प्रभावी Go API टेस्टिंग के लिए curl कमांड्स को समझना आवश्यक है। यहां सामान्य curl विकल्पों का एक त्वरित संदर्भ है जिसे हमारा कन्वर्टर समर्थित करता है:
curl [options] [URL]
-X, --request METHOD
: Specify request method (GET, POST, PUT, DELETE, etc.)-H, --header LINE
: Add header to the request-d, --data DATA
: Send data in POST request-F, --form CONTENT
: Submit form data-u, --user USER:PASSWORD
: Server user and password-k, --insecure
: Allow insecure server connections-I, --head
: Show document info only-v, --verbose
: Make the operation more verbose-s, --silent
: Silent mode--connect-timeout SECONDS
: Maximum time for connectionहमारा Go कन्वर्टर मल्टीपल हेडर्स, ऑथेंटिकेशन, डेटा पेलोड और विभिन्न विकल्पों सहित जटिल curl कमांड्स को संभालता है। बस अपना curl कमांड पेस्ट करें और net/http पैकेज का उपयोग करके क्लीन, मॉडर्न Go कोड प्राप्त करें।
Go के net/http पैकेज के साथ काम करते समय, कुशल और सुरक्षित API इंटरैक्शन के लिए इन बेस्ट प्रैक्टिसेज का पालन करें:
resp, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer resp.Body.Close() // Important: prevents resource leaks
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 }
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 }
// 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...
// 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)