Go

HTTP POST JSON Body

admin by @admin ADMIN
6d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Build a request with `http.NewRequestWithContext`, set headers, send via your client. The context plumbing is what lets callers cancel mid-request.
Go
Raw
package main

import (
    "bytes"
    "context"
    "encoding/json"
    "fmt"
    "net/http"
    "time"
)

func postJSON(ctx context.Context, url string, payload, out any) error {
    body, err := json.Marshal(payload)
    if err != nil { return err }

    req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))
    if err != nil { return err }
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Accept",       "application/json")

    resp, err := http.DefaultClient.Do(req)
    if err != nil { return err }
    defer resp.Body.Close()

    if resp.StatusCode >= 400 {
        return fmt.Errorf("http %d", resp.StatusCode)
    }
    return json.NewDecoder(resp.Body).Decode(out)
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    var resp map[string]any
    err := postJSON(ctx, "https://httpbin.org/post",
        map[string]string{"name": "Alice"}, &resp)
    fmt.Println(err, resp["json"])
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.