[Go] Send a POST request with a JSON body

Created on November 30, 2026

You can use Go's encoding/json and net/http packages to send a JSON document in an HTTP POST request. Replace the example URL with the endpoint that accepts your JSON payload.

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "log"
    "net/http"
    "os"
    "time"
)

type Message struct {
    Text string `json:"text"`
}

func main() {
    body, err := json.Marshal(Message{Text: "Hello"})
    if err != nil {
        log.Fatal(err)
    }

    req, err := http.NewRequest(http.MethodPost, "https://example.com/messages", bytes.NewReader(body))
    if err != nil {
        log.Fatal(err)
    }
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{Timeout: 10 * time.Second}
    resp, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    fmt.Println(resp.Status)
    if _, err := io.Copy(os.Stdout, resp.Body); err != nil {
        log.Print(err)
    }
}
  • json.Marshal encodes the message as {"text":"Hello"}, and bytes.NewReader makes those bytes available as the request body.
  • http.NewRequest creates the POST request. The Content-Type header tells the server that the body contains JSON.
  • client.Do sends the request. The example prints the HTTP status and copies the response body to standard output.
Go