Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate query string in golang?

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 ?

like image 939
JavaDeveloper Avatar asked Oct 19 '25 02:10

JavaDeveloper


1 Answers

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.

like image 199
volker Avatar answered Oct 21 '25 18:10

volker