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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With