Darth.Vader
Darth.Vader

Reputation: 6271

golang passing data payload from HTTP client

I have an HTTPS endpoint that works fine with a cURL command like this:

curl -k -u xyz:pqr \
  --data "grant_type=client_credentials" \
  https://my-url

Now I am trying to use golang to call the same API endpoint like this:

data := url.Values{}
data.Set("grant_type", "client_credentials")
req, err := http.NewRequestWithContext(
  ctx,
  "POST",
  "https://my-url",
  strings.NewReader(data.Encode())
)

It fails with the error body:

  {
     "error_description":"grant_type is required",
      "error":"invalid_request"
  }

I am already passing grant_type as the last argument to the http.NewRequestWithContext() function.

What am I missing?

Upvotes: 0

Views: 629

Answers (1)

Steven Masley
Steven Masley

Reputation: 697

You are not translating the curl correctly. This tool might be helpful: https://mholt.github.io/curl-to-go/

Essentially you need to add user auth.

req.SetBasicAuth("xyz", "pqr")
// Might help to set the `Content-Type` too
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

-k on curl seems to be reading some curl arguments from a file too. You are going to want to make sure you translate those over as well. I cannot see what they are from your example.

Upvotes: 1

Related Questions