package main import ( "fmt" "io/ioutil" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Error reading request body", http.StatusInternalServerError) return } fmt.Printf("Request Body: %s", string(body)) } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }
package main import ( "bytes" "encoding/json" "fmt" "net/http" ) type Person struct { Name string `json:"name"` Age int `json:"age"` Address string `json:"address"` } func main() { person := Person{"John Doe", 30, "123 Main St."} payload, _ := json.Marshal(person) req, err := http.NewRequest(http.MethodPost, "http://localhost:8080", bytes.NewBuffer(payload)) if err != nil { fmt.Println("Error creating request:", err) return } client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer resp.Body.Close() fmt.Printf("Response Status: %s\n", resp.Status) }In the second example, we also use the bytes package to create a buffer containing the JSON payload. The net/http package is used to create an HTTP request with the payload and send it to a server. We then print out the response status to the console. The package used for both examples is "net/http".