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.

4
  • 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? Commented May 11, 2018 at 1:38
  • @ThunderCat As query paramaters Commented May 11, 2018 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 Commented May 11, 2018 at 13:22
  • @nos does a form imply the data is in the body? Commented May 11, 2018 at 13:35

2 Answers 2

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())) 
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, The net/url Values was the missing link! Also, this one is shorter than the duplicate answers
-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) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.