How to Send JSON in an HTTP Request in Go

Web
Send JSON in Go by marshaling your struct to bytes and posting it with the application/json content type.

Use json.Marshal to convert your data to bytes, then pass it to http.Post with the "application/json" content type.

package main

import (
	"encoding/json"
	"fmt"
	"net/http"
)

type Payload struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	payload := Payload{Name: "Alice", Age: 30}
	jsonData, _ := json.Marshal(payload)
	resp, err := http.Post("https://api.example.com/users", "application/json", jsonData)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
}