← All tools

cURL to Go

Turn any curl command into Go net/http code.
Try
POSThttps://api.example.com/v1/customers
HEADERS · 2
AuthorizationBearer sk_t••••••→ API_TOKEN
Content-Typeapplication/json
BODY · JSON
{
  "email": "ada@example.com",
  "name": "Ada Lovelace",
  "metadata": {
    "plan": "pro",
    "seats": 3
  }
}
Gonet/http
package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
)

func main() {
	body := strings.NewReader(`{
	  "email": "ada@example.com",
	  "name": "Ada Lovelace",
	  "metadata": {
	    "plan": "pro",
	    "seats": 3
	  }
	}`)
	req, err := http.NewRequest("POST", "https://api.example.com/v1/customers", body)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("API_TOKEN"))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	data, err := io.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println(resp.Status)
	fmt.Println(string(data))
}
40 linesReads secrets with os.Getenv
● Parsed in this tab-X -H -d --json -F -u -b -G -L -k -m and moreTokens and keys are never sent

How curl maps to net/http

What the generated code does.

  • http.NewRequestMethod, URL and body go in one call; headers are set with req.Header.Set.
  • SetBasicAuth-u user:pass becomes req.SetBasicAuth — Go handles the Base64.
  • multipart.Writer-F uploads are built with mime/multipart, including the right Content-Type.
  • Client timeout-m 30 becomes http.Client{Timeout: …}. The default client never times out.

Questions

The short answers.

Decode the response into a struct?

Paste a sample response into JSON → Go to get the struct, then use json.NewDecoder(resp.Body).Decode(&v).

Why defer resp.Body.Close()?

Go keeps the connection open until the body is closed. Forgetting it leaks connections.

Cancel a request?

Use http.NewRequestWithContext with a context that has a deadline.

Does the code compile as it is?

Yes. It's a complete main package with its imports, every error is checked, and several file uploads each get their own variables.

Where do tokens and passwords go?

With “Secrets as env variables” on, they're read with os.Getenv, so they stay out of your code.

See all →