且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Go的http包中,如何在POST请求中获取查询字符串?

更新时间:2023-11-07 17:07:16

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).