0

I see there is an easy way to send a post with form values, but is there a function I could use to do essentially the same as PostForm but for a GET request?

-- edit --

Basically, I want to construct the URL: https://uri.com?key=value but without using string concatenation with unescaped keys and values.

Eaton Emmerich
  • 390
  • 3
  • 12
  • 3
    Do you want to send the form as the request body (which is usually ignored by a server for GET requests) or do you send the form as query parameters? – Cerise Limón May 11 '18 at 01:38
  • @ThunderCat As query paramaters – Eaton Emmerich May 11 '18 at 13:17
  • 1
    @EatonEmmerich Note that that is not called a Form or anything related to a post, you just want to construct a query string. See of [Go doing a GET request and building the Querystring](https://stackoverflow.com/questions/30652577/go-doing-a-get-request-and-building-the-querystring) – nos May 11 '18 at 13:22
  • @nos does a form imply the data is in the body? – Eaton Emmerich May 11 '18 at 13:35

2 Answers2

1

Encode the query parameters using Values.Encode. Concatenate the base URL and query parameters to get the actual URL.

resp, err := http.Get(fmt.Sprintf("%s?%s", baseURL, data.Encode()))
Cerise Limón
  • 88,331
  • 8
  • 164
  • 179
-1

As explained in this question, you probably don't actually want to do this. Most servers won't do anything useful with a form body in a GET request—and most that do will just treat it as synonymous with the same parameters sent in a query string, in which case you should just put them in the query string of your url.URL object in the first place.

However, if you do have a good reason to do this, you can. As the docs you linked explain, PostForm is just a thin convenience wrapper around NewRequest and Do. Just as you're expected to use NewRequest yourself if you want to add custom headers, you can use it to attach a body.

And if you look at the source to PostForm, it's pretty trivial:

return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))

Basically, instead of this:

resp, err := client.PostForm(url, data)

… you do this:

body := strings.NewReader(data.Encode())
req, err := http.NewRequest("GET", url, body)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
abarnert
  • 313,628
  • 35
  • 508
  • 596