在Go的http包中,如何在POST请求中获取查询字符串? [英] In Go's http package, how do I get the query string on a POST request?
问题描述
我使用Go的 http
包来处理POST请求。我如何从 Request
对象访问和分析查询字符串的内容?我无法从官方文档中找到答案。
I'm using the http
package from Go to deal with POST request. How can I access and parse the content of the query string from the Request
object ? I can't find the answer from the official documentation.
推荐答案
QueryString是,按定义,在URL中。您可以使用 req.URL
( DOC )。 URL对象有一个 Query()
方法(值类型,它只是一个 map [string] [] string
QueryString参数。
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.
如果您要查找的是POST数据由HTML表单提交,那么这通常是请求主体中的键值对。你在答案中是正确的,你可以调用 ParseForm()
,然后使用 req.Form
字段来获取键值对的映射,但您也可以调用 FormValue(key)
来获取特定键的值。如果需要,这将调用 ParseForm()
,并且无论它们是如何被发送的(即在查询字符串中或在请求体中),都会获取值。
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).
这篇关于在Go的http包中,如何在POST请求中获取查询字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!