In Go's http package, how do I get the query string on a POST request?

Fabien picture Fabien · Mar 14, 2013 · Viewed 158.1k times · Source

I'm using the httppackage from Go to deal with POST request. How can I access and parse the content of the query string from the Requestobject ? I can't find the answer from the official documentation.

Answer

mna picture mna · Mar 14, 2013

A QueryString is, by definition, in the URL. You can access the URL of the request using req.URL (doc). The URL object has a Query() method (doc) that returns a Values type, which is simply a map[string][]string of the QueryString parameters.

If what you're looking for is the POST data as submitted by an HTML form, then this is (usually) a key-value pair in the request body. You're correct in your answer that you can call ParseForm() and then use req.Form field to get the map of key-value pairs, but you can also call FormValue(key) to get the value of a specific key. This calls ParseForm() if required, and gets values regardless of how they were sent (i.e. in query string or in the request body).