4

In my use-case, I need to post data to url, however the data itself is a query string. Example:

curl -POST -d "username=abc&rememberme=on&authtype=intenal" "https..somemdpoint"

What I have is a method which takes in 3 values

function makePostRequest(username string, rememberme string, authtype string, endpoint string) {
  // post a curl request.
} 

I am struggling to find any library that would return me a query string if I provided it with parameters.

I tried doing this:

q := req.URL.Query()
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foobar")
fmt.Print(q)

But realized it actually returns Values which is a map so its no good.

Is there any method in golang that creates a queryString ?

1
  • 1
    Your curl example would send the data as a application/x-www-form-urlencoded payload, are you sure you want it in the query string (as part of the URL)? Commented Jul 19, 2020 at 4:09

1 Answer 1

17

You almost got it. Call Values.Encode() to encode the map in URL-encoded form.

fmt.Print(q.Encode()) // another_thing=foobar&api_key=key_from_environment_or_flag

Create the map directly instead of using req.URL.Query() to return an empty map:

values := url.Values{}
values.Add("api_key", "key_from_environment_or_flag")
values.Add("another_thing", "foobar")
query := values.Encode()

Use strings.NewReader(query) to get an io.Reader for the POST request body.

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.