HTTP Client / API Call
🌐 HTTP CLIENT – API CALL (net/http)
আমি ধরে নিচ্ছি তুমি API call করবে যেমন:
https://jsonplaceholder.typicode.com
(learning-এর জন্য খুব common test API)
✅ 1️⃣ GET Request (Client Side)
📌 কাজ
Server থেকে data আনা
📄 Full Code – GET
package main
import (
"fmt"
"io"
"net/http"
)
func main() {
resp, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Println("Read Error:", err)
return
}
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println("Response Body:")
fmt.Println(string(body))
}
✅ 2️⃣ POST Request (Client Side)
📌 কাজ
Server-এ নতুন data পাঠানো
📄 Full Code – POST
package main
import (
"bytes"
"fmt"
"io"
"net/http"
)
func main() {
jsonData := []byte(`{
"title": "foo",
"body": "bar",
"userId": 1
}`)
resp, err := http.Post(
"https://jsonplaceholder.typicode.com/posts",
"application/json",
bytes.NewBuffer(jsonData),
)
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(body))
}
✅ 3️⃣ PUT Request (Client Side)
📌 কাজ
Existing data update করা
📄 Full Code – PUT
package main
import (
"bytes"
"fmt"
"io"
"net/http"
)
func main() {
jsonData := []byte(`{
"id": 1,
"title": "updated title",
"body": "updated body",
"userId": 1
}`)
req, err := http.NewRequest(
http.MethodPut,
"https://jsonplaceholder.typicode.com/posts/1",
bytes.NewBuffer(jsonData),
)
if err != nil {
fmt.Println("Error:", err)
return
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request Error:", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(body))
}
✅ 4️⃣ DELETE Request (Client Side)
📌 কাজ
Server-এর data delete করা
📄 Full Code – DELETE
package main
import (
"fmt"
"io"
"net/http"
)
func main() {
req, err := http.NewRequest(
http.MethodDelete,
"https://jsonplaceholder.typicode.com/posts/1",
nil,
)
if err != nil {
fmt.Println("Error:", err)
return
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request Error:", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println("Response:")
fmt.Println(string(body))
}
🧠 Important Concepts (খুব জরুরি)
কেন GET & POST আলাদা?
GET, POST → shortcut function আছে
PUT, DELETE →
http.NewRequest()ব্যবহার করতে হয়
🔑 Common Pattern (Interview Tip)
client := &http.Client{}
req, _ := http.NewRequest("METHOD", url, body)
resp, _ := client.Do(req)
defer resp.Body.Close()
📌 Summary Table
| Method | Function Used |
|---|---|
| GET | http.Get() |
| POST | http.Post() |
| PUT | http.NewRequest() |
| DELETE | http.NewRequest() |