package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
func main() {
// The URL to which you want to send the JSON data
url := "https://example.com/api/endpoint"
// Data to be sent as JSON in the request body
data := map[string]interface{}{
"key1": "value1",
"key2": "value2",
}
// Convert data to JSON format
jsonData, err := json.Marshal(data)
if err != nil {
fmt.Println("Error converting data to JSON:", err)
return
}
// Create a new HTTP request
request, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set the request header to indicate JSON data
request.Header.Set("Content-Type", "application/json")
// Create an HTTP client and send the request
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer response.Body.Close()
// Check the response status code
if response.StatusCode != http.StatusOK {
fmt.Println("Unexpected response status code:", response.StatusCode)
return
}
// Read the response body
var responseData map[string]interface{}
err = json.NewDecoder(response.Body).Decode(&responseData)
if err != nil {
fmt.Println("Error decoding response:", err)
return
}
// Process the response data as needed
fmt.Println("Response:", responseData)
}
コメント
コメントを投稿