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?

2
  • 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 Commented May 19, 2022 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. Commented May 19, 2022 at 19:43

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.