0

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?

Darth.Vader
  • 5,079
  • 7
  • 50
  • 90
  • not knowing the specifics of the endpoint you're calling, one can only guess, but you're probably missing the `Content-Type`, or user auth – blackgreen May 19 '22 at 19:31
  • You have `-u xyz:pqr` in your curl command setting a user:pass auth. You need to do that in the golang too. – Steven Masley May 19 '22 at 19:43

1 Answers1

1

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.

Steven Masley
  • 634
  • 2
  • 9