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"])
}
Create a free account and build your private vault. Share publicly whenever you want.